mirror of
https://github.com/kuhyx/todo-app.git
synced 2026-11-28 23:49:08 +01:00
Migrate Sync settings to the shared sync_settings_ui package
Some checks failed
release-apk / release (APK) (push) Has been cancelled
Some checks failed
release-apk / release (APK) (push) Has been cancelled
Splits the old single Settings screen into two: "Enable advanced" plus links to a Sync settings route (Firebase + notes backup, now the shared sync_settings_ui package used across every kuhy app that syncs) and an Advanced sync (GitHub) route. GitHub stays app-local rather than moving into the shared package: connecting it here also triggers a real note sync via runSync(), not just a settings save, which the generic package intentionally doesn't do for any app. 313/313 tests passing, 100% line coverage on both new/changed screens, flutter analyze clean. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KdSp6Nbrs9xvsWkCMDN9a1
This commit is contained in:
parent
fd1865db78
commit
49a94c9550
368
lib/ui/github_mirror_screen.dart
Normal file
368
lib/ui/github_mirror_screen.dart
Normal file
@ -0,0 +1,368 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/sync/github_device_auth.dart';
|
||||||
|
import 'package:todo/sync/run_sync.dart';
|
||||||
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
|
|
||||||
|
/// The GitHub mirror screen: cutover-only sync transport, not a peer of
|
||||||
|
/// Firebase.
|
||||||
|
///
|
||||||
|
/// Kept app-local rather than folded into the shared `sync_settings_ui`
|
||||||
|
/// package because connecting here also triggers an actual note sync via
|
||||||
|
/// [runSync] -- unlike the shared package's Firebase/Backup sections, which
|
||||||
|
/// only save settings. See `lib/ui/settings_screen.dart` for the "Enable
|
||||||
|
/// advanced" toggle and the link to this screen and to the shared Sync
|
||||||
|
/// settings screen.
|
||||||
|
class GitHubMirrorScreen extends StatefulWidget {
|
||||||
|
/// Creates a [GitHubMirrorScreen] pre-filled with [initial] settings.
|
||||||
|
const GitHubMirrorScreen({
|
||||||
|
required this.initial,
|
||||||
|
required this.repository,
|
||||||
|
required this.appSettings,
|
||||||
|
this.analytics,
|
||||||
|
this.httpClient,
|
||||||
|
this.firebaseFactory,
|
||||||
|
this.stateStore,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The sync settings loaded when this screen was opened.
|
||||||
|
final SyncSettings initial;
|
||||||
|
|
||||||
|
/// The store a post-connect sync reads from and writes to.
|
||||||
|
final NoteRepository repository;
|
||||||
|
|
||||||
|
/// App-wide preferences, reconciled after a post-connect sync.
|
||||||
|
final ValueNotifier<AppSettings> appSettings;
|
||||||
|
|
||||||
|
/// Interaction-only usage analytics. Null in tests that don't exercise it.
|
||||||
|
final AnalyticsService? analytics;
|
||||||
|
|
||||||
|
/// Optional HTTP client for the GitHub calls (test-connection and device
|
||||||
|
/// flow). Injected by tests; production uses each client's default.
|
||||||
|
final http.Client? httpClient;
|
||||||
|
|
||||||
|
/// Builds the Firebase backend for the post-connect sync. Injected so
|
||||||
|
/// tests can supply a fake.
|
||||||
|
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
||||||
|
|
||||||
|
/// Revision cache. Injected so tests need no application-support directory.
|
||||||
|
final SyncStateStore? stateStore;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<GitHubMirrorScreen> createState() => _GitHubMirrorScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
||||||
|
late final TextEditingController _owner = TextEditingController(
|
||||||
|
text: widget.initial.owner,
|
||||||
|
);
|
||||||
|
late final TextEditingController _repo = TextEditingController(
|
||||||
|
text: widget.initial.repo,
|
||||||
|
);
|
||||||
|
late final TextEditingController _token = TextEditingController(
|
||||||
|
text: widget.initial.token,
|
||||||
|
);
|
||||||
|
late final TextEditingController _clientId = TextEditingController(
|
||||||
|
text: widget.initial.clientId,
|
||||||
|
);
|
||||||
|
|
||||||
|
bool _testing = false;
|
||||||
|
String? _status;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_owner.dispose();
|
||||||
|
_repo.dispose();
|
||||||
|
_token.dispose();
|
||||||
|
_clientId.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
SyncSettings get _current => SyncSettings(
|
||||||
|
owner: _owner.text.trim(),
|
||||||
|
repo: _repo.text.trim(),
|
||||||
|
token: _token.text.trim(),
|
||||||
|
clientId: _clientId.text.trim(),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Runs the OAuth device flow and, on success, fills in the token field.
|
||||||
|
Future<void> _connectGitHub() async {
|
||||||
|
final clientId = _clientId.text.trim();
|
||||||
|
if (clientId.isEmpty) {
|
||||||
|
setState(() => _status = 'Enter the OAuth App client id first.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final auth = GitHubDeviceAuth(
|
||||||
|
clientId: clientId,
|
||||||
|
httpClient: widget.httpClient,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
final device = await auth.requestDeviceCode();
|
||||||
|
if (!mounted) return;
|
||||||
|
final token = await showDialog<String>(
|
||||||
|
context: context,
|
||||||
|
barrierDismissible: false,
|
||||||
|
builder: (_) => _DeviceCodeDialog(device: device, auth: auth),
|
||||||
|
);
|
||||||
|
if (token != null && token.isNotEmpty) {
|
||||||
|
setState(() {
|
||||||
|
_token.text = token;
|
||||||
|
_status = 'Connected — syncing…';
|
||||||
|
});
|
||||||
|
await _current.save();
|
||||||
|
await _syncAfterConnect();
|
||||||
|
}
|
||||||
|
} on Exception catch (e) {
|
||||||
|
if (mounted) setState(() => _status = 'Could not start device flow: $e');
|
||||||
|
} finally {
|
||||||
|
auth.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a sync right after connecting so the user's notes download
|
||||||
|
/// immediately and they get clear confirmation it worked.
|
||||||
|
Future<void> _syncAfterConnect() async {
|
||||||
|
final s = _current;
|
||||||
|
try {
|
||||||
|
final run = await runSync(
|
||||||
|
widget.repository,
|
||||||
|
s,
|
||||||
|
appSettings: widget.appSettings.value,
|
||||||
|
analytics: widget.analytics,
|
||||||
|
httpClient: widget.httpClient,
|
||||||
|
firebaseFactory: widget.firebaseFactory,
|
||||||
|
stateStore: widget.stateStore,
|
||||||
|
);
|
||||||
|
widget.appSettings.value = widget.appSettings.value.adopt(
|
||||||
|
run.appSettings,
|
||||||
|
);
|
||||||
|
if (mounted) {
|
||||||
|
setState(
|
||||||
|
() => _status =
|
||||||
|
'Connected and synced (merged '
|
||||||
|
'${run.syncResult.mergedDevices} device(s)). Your notes are '
|
||||||
|
'up to date.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} on Exception catch (e) {
|
||||||
|
if (mounted) setState(() => _status = 'Connected, but sync failed: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _test() async {
|
||||||
|
setState(() {
|
||||||
|
_testing = true;
|
||||||
|
_status = null;
|
||||||
|
});
|
||||||
|
final s = _current;
|
||||||
|
final client = GitHubClient(
|
||||||
|
owner: s.owner,
|
||||||
|
repo: s.repo,
|
||||||
|
token: s.token,
|
||||||
|
httpClient: widget.httpClient,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
final ok = await client.canAccessRepo();
|
||||||
|
setState(
|
||||||
|
() => _status = ok
|
||||||
|
? 'Connected — repo is reachable.'
|
||||||
|
: 'Could not access ${s.owner}/${s.repo}. Check token scope.',
|
||||||
|
);
|
||||||
|
} on Exception catch (e) {
|
||||||
|
setState(() => _status = 'Error: $e');
|
||||||
|
} finally {
|
||||||
|
client.close();
|
||||||
|
if (mounted) setState(() => _testing = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _save() async {
|
||||||
|
final s = _current;
|
||||||
|
await s.save();
|
||||||
|
if (mounted) Navigator.of(context).pop(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(title: const Text('Advanced sync (GitHub)')),
|
||||||
|
body: ListView(
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'Authorize in your browser — no token to paste. Syncs to '
|
||||||
|
'kuhyx/syncs by default.',
|
||||||
|
style: Theme.of(context).textTheme.bodySmall,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: FilledButton.icon(
|
||||||
|
onPressed: _connectGitHub,
|
||||||
|
icon: const Icon(Icons.login),
|
||||||
|
label: const Text('Connect GitHub'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
TextField(
|
||||||
|
controller: _owner,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'GitHub owner',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextField(
|
||||||
|
controller: _repo,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Repository name',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextField(
|
||||||
|
controller: _clientId,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'OAuth App client id',
|
||||||
|
helperText: 'Leave as the baked-in default unless self-hosting',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextField(
|
||||||
|
controller: _token,
|
||||||
|
obscureText: true,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Access token (fallback)',
|
||||||
|
helperText: 'Contents: read/write on the sync repo only',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
OutlinedButton.icon(
|
||||||
|
onPressed: _testing ? null : _test,
|
||||||
|
icon: _testing
|
||||||
|
? const SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
)
|
||||||
|
: const Icon(Icons.wifi_tethering),
|
||||||
|
label: const Text('Test connection'),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
FilledButton.icon(
|
||||||
|
onPressed: _save,
|
||||||
|
icon: const Icon(Icons.save),
|
||||||
|
label: const Text('Save'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (_status != null) ...[
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dialog shown during the device flow: displays the user code, opens the
|
||||||
|
/// verification page, and polls until authorized — popping the token (or
|
||||||
|
/// null if cancelled / failed).
|
||||||
|
class _DeviceCodeDialog extends StatefulWidget {
|
||||||
|
const _DeviceCodeDialog({required this.device, required this.auth});
|
||||||
|
|
||||||
|
final DeviceCodeResponse device;
|
||||||
|
final GitHubDeviceAuth auth;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_DeviceCodeDialog> createState() => _DeviceCodeDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
|
||||||
|
String? _error;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
unawaited(_poll());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _poll() async {
|
||||||
|
try {
|
||||||
|
final token = await widget.auth.pollForToken(widget.device);
|
||||||
|
if (mounted) Navigator.of(context).pop(token);
|
||||||
|
} on Exception catch (e) {
|
||||||
|
if (mounted) setState(() => _error = '$e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openPage() async {
|
||||||
|
await Clipboard.setData(ClipboardData(text: widget.device.userCode));
|
||||||
|
await launchUrl(
|
||||||
|
Uri.parse(widget.device.verificationUri),
|
||||||
|
mode: LaunchMode.externalApplication,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: const Text('Authorize on GitHub'),
|
||||||
|
content: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
const Text('Enter this code on GitHub:'),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
SelectableText(
|
||||||
|
widget.device.userCode,
|
||||||
|
style: Theme.of(context).textTheme.headlineSmall,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
if (_error == null)
|
||||||
|
const Row(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
SizedBox(width: 12),
|
||||||
|
Expanded(child: Text('Waiting for authorization…')),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Text(
|
||||||
|
_error!,
|
||||||
|
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
child: const Text('Cancel'),
|
||||||
|
),
|
||||||
|
FilledButton.icon(
|
||||||
|
onPressed: _openPage,
|
||||||
|
icon: const Icon(Icons.open_in_new),
|
||||||
|
label: const Text('Open GitHub & copy code'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,33 +3,29 @@ import 'dart:async';
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:file_selector/file_selector.dart';
|
import 'package:file_selector/file_selector.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
import 'package:todo/analytics/analytics_event.dart';
|
import 'package:todo/analytics/analytics_event.dart';
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
import 'package:todo/data/app_settings.dart';
|
import 'package:todo/data/app_settings.dart';
|
||||||
import 'package:todo/data/note_repository.dart';
|
import 'package:todo/data/note_repository.dart';
|
||||||
import 'package:todo/sync/backlog_export.dart';
|
import 'package:todo/sync/backlog_export.dart';
|
||||||
import 'package:todo/sync/firebase_backend.dart';
|
import 'package:todo/sync/firebase_backend.dart';
|
||||||
import 'package:todo/sync/github_device_auth.dart';
|
|
||||||
import 'package:todo/sync/google_sign_in_backend.dart';
|
import 'package:todo/sync/google_sign_in_backend.dart';
|
||||||
import 'package:todo/sync/notes_markdown.dart';
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
import 'package:todo/sync/run_sync.dart';
|
|
||||||
import 'package:todo/sync/sync_settings.dart';
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
import 'package:url_launcher/url_launcher.dart';
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
|
||||||
/// Settings screen for sync configuration and note backup.
|
/// Settings screen: the "Enable advanced" toggle plus links to the two sync
|
||||||
|
/// surfaces.
|
||||||
///
|
///
|
||||||
/// Primary sync path: "Connect Firebase" signs in with the shared sync
|
/// "Sync settings" is the shared `sync_settings_ui` package (Firebase +
|
||||||
/// account, whose password is kept in the OS keystore. GitHub is only the
|
/// notes backup, identical in shape to every other kuhy app's Sync settings
|
||||||
/// cutover mirror, so its device-flow connection, owner/repo and token
|
/// screen). "Advanced sync (GitHub)" stays app-local
|
||||||
/// fallback all sit under "Advanced (GitHub mirror)" rather than competing
|
/// ([GitHubMirrorScreen]) because connecting it also triggers a real note
|
||||||
/// with Firebase as a visible choice.
|
/// sync, which the shared package does not do.
|
||||||
///
|
|
||||||
/// The Backup section exports/imports all notes as a single Markdown file
|
|
||||||
/// (see [NotesMarkdown]).
|
|
||||||
class SettingsScreen extends StatefulWidget {
|
class SettingsScreen extends StatefulWidget {
|
||||||
/// Creates a [SettingsScreen] pre-filled with [initial] settings.
|
/// Creates a [SettingsScreen].
|
||||||
const SettingsScreen({
|
const SettingsScreen({
|
||||||
required this.initial,
|
required this.initial,
|
||||||
required this.repository,
|
required this.repository,
|
||||||
@ -47,10 +43,11 @@ class SettingsScreen extends StatefulWidget {
|
|||||||
super.key,
|
super.key,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// The sync settings loaded when this screen was opened.
|
/// The GitHub sync settings loaded when this screen was opened.
|
||||||
final SyncSettings initial;
|
final SyncSettings initial;
|
||||||
|
|
||||||
/// The store backup export/import reads from and writes to.
|
/// The store backup export/import and post-connect sync read from and
|
||||||
|
/// write to.
|
||||||
final NoteRepository repository;
|
final NoteRepository repository;
|
||||||
|
|
||||||
/// App-wide preferences, currently just `advancedMode`. The "Enable
|
/// App-wide preferences, currently just `advancedMode`. The "Enable
|
||||||
@ -60,6 +57,11 @@ class SettingsScreen extends StatefulWidget {
|
|||||||
/// Interaction-only usage analytics. Null in tests that don't exercise it.
|
/// Interaction-only usage analytics. Null in tests that don't exercise it.
|
||||||
final AnalyticsService? analytics;
|
final AnalyticsService? analytics;
|
||||||
|
|
||||||
|
/// Optional HTTP client for the GitHub calls (test-connection and device
|
||||||
|
/// flow) on the linked [GitHubMirrorScreen]. Injected by tests; production
|
||||||
|
/// uses each client's default.
|
||||||
|
final http.Client? httpClient;
|
||||||
|
|
||||||
/// Builds the Firebase backend. Injected so tests can supply a fake, or
|
/// Builds the Firebase backend. Injected so tests can supply a fake, or
|
||||||
/// null to assert the pre-migration GitHub-only path still works.
|
/// null to assert the pre-migration GitHub-only path still works.
|
||||||
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
||||||
@ -90,296 +92,13 @@ class SettingsScreen extends StatefulWidget {
|
|||||||
final Future<void> Function()? accountClearer;
|
final Future<void> Function()? accountClearer;
|
||||||
|
|
||||||
/// Whether a Firebase session is stored. See [accountLoader].
|
/// Whether a Firebase session is stored. See [accountLoader].
|
||||||
///
|
|
||||||
/// Separate from [accountLoader] because the two answer different
|
|
||||||
/// questions: the account marker is bookkeeping, the session is the
|
|
||||||
/// credential. A device can hold the second without the first, and
|
|
||||||
/// reporting only the first is what made a syncing phone read as
|
|
||||||
/// "not connected".
|
|
||||||
final Future<bool> Function()? sessionProbe;
|
final Future<bool> Function()? sessionProbe;
|
||||||
|
|
||||||
/// Optional HTTP client for the GitHub calls (test-connection and device
|
|
||||||
/// flow). Injected by tests; production uses each client's default.
|
|
||||||
final http.Client? httpClient;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<SettingsScreen> createState() => _SettingsScreenState();
|
State<SettingsScreen> createState() => _SettingsScreenState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _SettingsScreenState extends State<SettingsScreen> {
|
class _SettingsScreenState extends State<SettingsScreen> {
|
||||||
late final TextEditingController _owner = TextEditingController(
|
|
||||||
text: widget.initial.owner,
|
|
||||||
);
|
|
||||||
late final TextEditingController _repo = TextEditingController(
|
|
||||||
text: widget.initial.repo,
|
|
||||||
);
|
|
||||||
late final TextEditingController _token = TextEditingController(
|
|
||||||
text: widget.initial.token,
|
|
||||||
);
|
|
||||||
late final TextEditingController _clientId = TextEditingController(
|
|
||||||
text: widget.initial.clientId,
|
|
||||||
);
|
|
||||||
|
|
||||||
final TextEditingController _email = TextEditingController();
|
|
||||||
final TextEditingController _password = TextEditingController();
|
|
||||||
|
|
||||||
bool _testing = false;
|
|
||||||
bool _busy = false;
|
|
||||||
bool _firebaseConnected = false;
|
|
||||||
String? _status;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
unawaited(_loadFirebaseAccount());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reflects a previously-stored account, so a returning user sees the real
|
|
||||||
/// state instead of an empty form that looks unconfigured.
|
|
||||||
Future<void> _loadFirebaseAccount() async {
|
|
||||||
final account = await (widget.accountLoader ?? loadAccount)();
|
|
||||||
// The stored session, not the account marker, decides "connected": a
|
|
||||||
// Google sign-in leaves a refresh token that authenticates every request
|
|
||||||
// even when no marker was written beside it.
|
|
||||||
final connected = await (widget.sessionProbe ?? isFirebaseConfigured)();
|
|
||||||
if (!mounted) return;
|
|
||||||
if (account != null) _email.text = account.email;
|
|
||||||
setState(() => _firebaseConnected = connected);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Stores the typed account and signs in immediately, so a typo surfaces
|
|
||||||
/// here rather than as a silent background failure on the next sync.
|
|
||||||
///
|
|
||||||
/// Without this the app could never reach Firebase at all: `openFirebase()`
|
|
||||||
/// reads an account nothing had ever written.
|
|
||||||
Future<void> _connectFirebase() async {
|
|
||||||
final email = _email.text.trim();
|
|
||||||
final password = _password.text;
|
|
||||||
if (email.isEmpty || password.isEmpty) {
|
|
||||||
setState(() => _status = 'Enter the sync account email and password.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setState(() {
|
|
||||||
_busy = true;
|
|
||||||
_status = 'Signing in…';
|
|
||||||
});
|
|
||||||
await (widget.accountSaver ?? saveAccount)(
|
|
||||||
FirebaseAccount(email: email, password: password),
|
|
||||||
);
|
|
||||||
final client = await (widget.firebaseFactory ?? openFirebase)();
|
|
||||||
if (!mounted) return;
|
|
||||||
if (client == null) {
|
|
||||||
await (widget.accountClearer ?? clearAccount)();
|
|
||||||
setState(() {
|
|
||||||
_busy = false;
|
|
||||||
_firebaseConnected = false;
|
|
||||||
_status = 'Firebase rejected that account.';
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
_password.clear();
|
|
||||||
setState(() {
|
|
||||||
_busy = false;
|
|
||||||
_firebaseConnected = true;
|
|
||||||
_status = 'Connected to Firebase.';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Signs in by picking a Google account -- the one-tap path.
|
|
||||||
///
|
|
||||||
/// Distinguishes three outcomes deliberately: a dismissed picker is not an
|
|
||||||
/// error and says nothing alarming; a wrong-account sign-in reports *why*,
|
|
||||||
/// because it is the failure that would otherwise look like a working sync
|
|
||||||
/// that never syncs; anything else is a plain failure.
|
|
||||||
Future<void> _connectGoogle() async {
|
|
||||||
setState(() {
|
|
||||||
_busy = true;
|
|
||||||
_status = 'Signing in…';
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
final client =
|
|
||||||
await (widget.googleFirebaseFactory ?? openFirebaseWithGoogle)();
|
|
||||||
if (!mounted) return;
|
|
||||||
if (client == null) {
|
|
||||||
setState(() {
|
|
||||||
_busy = false;
|
|
||||||
_status = 'Google sign-in was cancelled.';
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// The account is saved by openFirebaseWithGoogle, using the email
|
|
||||||
// Firebase reports -- not from _email, which is empty on the fresh
|
|
||||||
// install this path exists for. Reflect it so the connected row shows
|
|
||||||
// the address instead of a blank.
|
|
||||||
//
|
|
||||||
// storedAccount, not loadAccount: the latter falls back to the desktop
|
|
||||||
// wrapper's /sync-account route when the keystore looks empty, which on
|
|
||||||
// Android resolves to file:/// and throws. That threw here mid-sign-in
|
|
||||||
// on the phone, leaving the screen stuck on "Signing in..." even though
|
|
||||||
// the sign-in had actually succeeded.
|
|
||||||
final account = await (widget.accountLoader ?? storedAccount)();
|
|
||||||
// Report the persisted state, not the fact that the call returned a
|
|
||||||
// client: a non-null client only means sign-in succeeded in that
|
|
||||||
// moment, which is how four apps claimed "Connected" and then synced
|
|
||||||
// over GitHub after the next restart.
|
|
||||||
final connected = await (widget.sessionProbe ?? isFirebaseConfigured)();
|
|
||||||
if (!mounted) return;
|
|
||||||
if (account != null) _email.text = account.email;
|
|
||||||
setState(() {
|
|
||||||
_busy = false;
|
|
||||||
_firebaseConnected = connected;
|
|
||||||
_status = connected
|
|
||||||
? 'Connected to Firebase.'
|
|
||||||
: 'Signed in, but this device did not save the session - it will '
|
|
||||||
'sync over GitHub after a restart. Try connecting again.';
|
|
||||||
});
|
|
||||||
} on FirebaseAuthError catch (error) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_busy = false;
|
|
||||||
_firebaseConnected = false;
|
|
||||||
_status = error.message;
|
|
||||||
});
|
|
||||||
} on Object catch (error) {
|
|
||||||
// Broader than Exception on purpose: a missing platform binding raises
|
|
||||||
// an Error, and anything escaping here leaves the button disabled and
|
|
||||||
// the screen stuck on "Signing in..." forever -- which is exactly what
|
|
||||||
// happened on the phone. Always land in a state the user can retry from.
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_busy = false;
|
|
||||||
_firebaseConnected = false;
|
|
||||||
_status = 'Google sign-in failed: $error';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _disconnectFirebase() async {
|
|
||||||
await (widget.accountClearer ?? clearAccount)();
|
|
||||||
if (!mounted) return;
|
|
||||||
_email.clear();
|
|
||||||
_password.clear();
|
|
||||||
setState(() {
|
|
||||||
_firebaseConnected = false;
|
|
||||||
_status = 'Firebase disconnected.';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_owner.dispose();
|
|
||||||
_repo.dispose();
|
|
||||||
_token.dispose();
|
|
||||||
_clientId.dispose();
|
|
||||||
_email.dispose();
|
|
||||||
_password.dispose();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
SyncSettings get _current => SyncSettings(
|
|
||||||
owner: _owner.text.trim(),
|
|
||||||
repo: _repo.text.trim(),
|
|
||||||
token: _token.text.trim(),
|
|
||||||
clientId: _clientId.text.trim(),
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Runs the OAuth device flow and, on success, fills in the token field.
|
|
||||||
Future<void> _connectGitHub() async {
|
|
||||||
final clientId = _clientId.text.trim();
|
|
||||||
if (clientId.isEmpty) {
|
|
||||||
setState(() => _status = 'Enter the OAuth App client id first.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final auth = GitHubDeviceAuth(
|
|
||||||
clientId: clientId,
|
|
||||||
httpClient: widget.httpClient,
|
|
||||||
);
|
|
||||||
try {
|
|
||||||
final device = await auth.requestDeviceCode();
|
|
||||||
if (!mounted) return;
|
|
||||||
final token = await showDialog<String>(
|
|
||||||
context: context,
|
|
||||||
barrierDismissible: false,
|
|
||||||
builder: (_) => _DeviceCodeDialog(device: device, auth: auth),
|
|
||||||
);
|
|
||||||
if (token != null && token.isNotEmpty) {
|
|
||||||
setState(() {
|
|
||||||
_token.text = token;
|
|
||||||
_status = 'Connected — syncing…';
|
|
||||||
});
|
|
||||||
await _current.save();
|
|
||||||
await _syncAfterConnect();
|
|
||||||
}
|
|
||||||
} on Exception catch (e) {
|
|
||||||
if (mounted) setState(() => _status = 'Could not start device flow: $e');
|
|
||||||
} finally {
|
|
||||||
auth.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs a sync right after connecting so the user's notes download
|
|
||||||
/// immediately and they get clear confirmation it worked.
|
|
||||||
Future<void> _syncAfterConnect() async {
|
|
||||||
final s = _current;
|
|
||||||
try {
|
|
||||||
final run = await runSync(
|
|
||||||
widget.repository,
|
|
||||||
s,
|
|
||||||
appSettings: widget.appSettings.value,
|
|
||||||
analytics: widget.analytics,
|
|
||||||
httpClient: widget.httpClient,
|
|
||||||
firebaseFactory: widget.firebaseFactory,
|
|
||||||
stateStore: widget.stateStore,
|
|
||||||
);
|
|
||||||
widget.appSettings.value = widget.appSettings.value.adopt(
|
|
||||||
run.appSettings,
|
|
||||||
);
|
|
||||||
if (mounted) {
|
|
||||||
setState(
|
|
||||||
() => _status =
|
|
||||||
'Connected and synced (merged '
|
|
||||||
'${run.syncResult.mergedDevices} device(s)). Your notes are '
|
|
||||||
'up to date.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} on Exception catch (e) {
|
|
||||||
if (mounted) setState(() => _status = 'Connected, but sync failed: $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _test() async {
|
|
||||||
setState(() {
|
|
||||||
_testing = true;
|
|
||||||
_status = null;
|
|
||||||
});
|
|
||||||
final s = _current;
|
|
||||||
final client = GitHubClient(
|
|
||||||
owner: s.owner,
|
|
||||||
repo: s.repo,
|
|
||||||
token: s.token,
|
|
||||||
httpClient: widget.httpClient,
|
|
||||||
);
|
|
||||||
try {
|
|
||||||
final ok = await client.canAccessRepo();
|
|
||||||
setState(
|
|
||||||
() => _status = ok
|
|
||||||
? 'Connected — repo is reachable.'
|
|
||||||
: 'Could not access ${s.owner}/${s.repo}. Check token scope.',
|
|
||||||
);
|
|
||||||
} on Exception catch (e) {
|
|
||||||
setState(() => _status = 'Error: $e');
|
|
||||||
} finally {
|
|
||||||
client.close();
|
|
||||||
if (mounted) setState(() => _testing = false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _save() async {
|
|
||||||
final s = _current;
|
|
||||||
await s.save();
|
|
||||||
if (mounted) Navigator.of(context).pop(s);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Persists the "Enable advanced" toggle locally and, when a Firebase
|
/// Persists the "Enable advanced" toggle locally and, when a Firebase
|
||||||
/// session is available, best-effort mirrors it so the choice follows the
|
/// session is available, best-effort mirrors it so the choice follows the
|
||||||
/// user to their other devices.
|
/// user to their other devices.
|
||||||
@ -423,45 +142,65 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
/// system share sheet; on desktop it writes the canonical `~/todo/
|
/// system share sheet; on desktop it writes the canonical `~/todo/
|
||||||
/// BACKLOG.md` so a future tool/agent has a stable path to read.
|
/// BACKLOG.md` so a future tool/agent has a stable path to read.
|
||||||
Future<void> _export() async {
|
Future<void> _export() async {
|
||||||
try {
|
final notes = await widget.repository.listNotes();
|
||||||
final notes = await widget.repository.listNotes();
|
final markdown = NotesMarkdown.export(notes);
|
||||||
final markdown = NotesMarkdown.export(notes);
|
await exportBacklog(markdown, notes.length);
|
||||||
|
|
||||||
final outcome = await exportBacklog(markdown, notes.length);
|
|
||||||
if (mounted) setState(() => _status = outcome);
|
|
||||||
} on Exception catch (e) {
|
|
||||||
if (mounted) setState(() => _status = 'Export failed: $e');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Imports notes from a user-picked Markdown file, merging by id so a
|
/// Imports notes from a user-picked Markdown file, merging by id so a
|
||||||
/// stale backup never clobbers a newer local edit (see
|
/// stale backup never clobbers a newer local edit (see
|
||||||
/// [NoteRepository.importNotes]).
|
/// [NoteRepository.importNotes]).
|
||||||
Future<void> _import() async {
|
Future<void> _import() async {
|
||||||
try {
|
const group = XTypeGroup(
|
||||||
const group = XTypeGroup(
|
label: 'Markdown',
|
||||||
label: 'Markdown',
|
extensions: ['md', 'markdown', 'txt'],
|
||||||
extensions: ['md', 'markdown', 'txt'],
|
// UTIs/MIME so the picker accepts the file on iOS/Android too.
|
||||||
// UTIs/MIME so the picker accepts the file on iOS/Android too.
|
uniformTypeIdentifiers: ['net.daringfireball.markdown', 'public.text'],
|
||||||
uniformTypeIdentifiers: ['net.daringfireball.markdown', 'public.text'],
|
mimeTypes: ['text/markdown', 'text/plain'],
|
||||||
mimeTypes: ['text/markdown', 'text/plain'],
|
);
|
||||||
);
|
final file = await openFile(acceptedTypeGroups: const [group]);
|
||||||
final file = await openFile(acceptedTypeGroups: const [group]);
|
if (file == null) return; // user cancelled
|
||||||
if (file == null) return; // user cancelled
|
final content = await file.readAsString();
|
||||||
final content = await file.readAsString();
|
final notes = NotesMarkdown.parse(content);
|
||||||
|
await widget.repository.importNotes(notes);
|
||||||
|
}
|
||||||
|
|
||||||
final notes = NotesMarkdown.parse(content);
|
Future<void> _openSyncSettings() async {
|
||||||
final outcome = await widget.repository.importNotes(notes);
|
await Navigator.of(context).push<void>(
|
||||||
if (mounted) {
|
MaterialPageRoute(
|
||||||
setState(
|
builder: (_) => SyncSettingsScreen(
|
||||||
() => _status =
|
accountLoader: widget.accountLoader ?? loadAccount,
|
||||||
'Imported ${outcome.total}: ${outcome.added} new, '
|
accountSaver: widget.accountSaver ?? saveAccount,
|
||||||
'${outcome.updated} updated, ${outcome.skipped} unchanged',
|
accountClearer: widget.accountClearer ?? clearAccount,
|
||||||
);
|
sessionProbe: widget.sessionProbe ?? isFirebaseConfigured,
|
||||||
}
|
firebaseFactory: widget.firebaseFactory ?? openFirebase,
|
||||||
} on Exception catch (e) {
|
googleFirebaseFactory:
|
||||||
if (mounted) setState(() => _status = 'Import failed: $e');
|
widget.googleFirebaseFactory ?? openFirebaseWithGoogle,
|
||||||
}
|
googleAvailable: widget.googleAvailable ?? googleSignInSupported,
|
||||||
|
backup: BackupSlot(
|
||||||
|
label: 'notes',
|
||||||
|
export: _export,
|
||||||
|
import: _import,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openGitHubMirror() async {
|
||||||
|
await Navigator.of(context).push<SyncSettings>(
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (_) => GitHubMirrorScreen(
|
||||||
|
initial: widget.initial,
|
||||||
|
repository: widget.repository,
|
||||||
|
appSettings: widget.appSettings,
|
||||||
|
analytics: widget.analytics,
|
||||||
|
httpClient: widget.httpClient,
|
||||||
|
firebaseFactory: widget.firebaseFactory,
|
||||||
|
stateStore: widget.stateStore,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@ -485,310 +224,22 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
const Divider(),
|
const Divider(),
|
||||||
const SizedBox(height: 8),
|
ListTile(
|
||||||
Text(
|
contentPadding: EdgeInsets.zero,
|
||||||
'Firebase sync',
|
title: const Text('Sync settings'),
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
subtitle: const Text('Firebase sync and notes backup'),
|
||||||
|
trailing: const Icon(Icons.chevron_right),
|
||||||
|
onTap: () => unawaited(_openSyncSettings()),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
ListTile(
|
||||||
Text(
|
contentPadding: EdgeInsets.zero,
|
||||||
_firebaseConnected
|
title: const Text('Advanced sync (GitHub)'),
|
||||||
? 'Connected. Notes go to Firebase first, and still mirror '
|
subtitle: const Text('Cutover mirror — not recommended'),
|
||||||
'to GitHub until every device has moved.'
|
trailing: const Icon(Icons.chevron_right),
|
||||||
: 'Not connected — syncing over GitHub only. Enter the '
|
onTap: () => unawaited(_openGitHubMirror()),
|
||||||
'shared sync account to move this device over. The '
|
|
||||||
'password is kept in the device keystore, never in the '
|
|
||||||
'app or the repo.',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
|
||||||
// Once connected the account is read-only text: an editable email
|
|
||||||
// box beside an empty password box reads as "you still have to
|
|
||||||
// enter this", making a connected device look unconfigured.
|
|
||||||
if (_firebaseConnected)
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
const Icon(Icons.cloud_done, size: 20),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(child: Text(_email.text)),
|
|
||||||
TextButton(
|
|
||||||
onPressed: _busy ? null : _disconnectFirebase,
|
|
||||||
child: const Text('Disconnect'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
else ...[
|
|
||||||
// The whole point of this screen after a reinstall: one tap, no
|
|
||||||
// typing. The password form is kept but demoted, because on a
|
|
||||||
// phone keyboard it is the slow path.
|
|
||||||
//
|
|
||||||
// Hidden where the platform cannot sign in programmatically --
|
|
||||||
// the desktop build is the web build, and Google Identity
|
|
||||||
// Services only signs in through its own rendered button there.
|
|
||||||
// A visible button that always failed would be worse than none.
|
|
||||||
if (widget.googleAvailable ?? googleSignInSupported) ...[
|
|
||||||
Align(
|
|
||||||
alignment: Alignment.centerLeft,
|
|
||||||
child: FilledButton.icon(
|
|
||||||
onPressed: _busy ? null : _connectGoogle,
|
|
||||||
icon: const Icon(Icons.account_circle),
|
|
||||||
label: const Text('Sign in with Google'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
],
|
|
||||||
ExpansionTile(
|
|
||||||
// Expanded by default where Google is unavailable: on desktop
|
|
||||||
// the password form is the only way in, so hiding it behind a
|
|
||||||
// disclosure would look like there is no way to connect.
|
|
||||||
initiallyExpanded:
|
|
||||||
!(widget.googleAvailable ?? googleSignInSupported),
|
|
||||||
title: const Text('Use the account password instead'),
|
|
||||||
tilePadding: EdgeInsets.zero,
|
|
||||||
childrenPadding: const EdgeInsets.only(bottom: 8),
|
|
||||||
children: [
|
|
||||||
TextField(
|
|
||||||
controller: _email,
|
|
||||||
keyboardType: TextInputType.emailAddress,
|
|
||||||
autocorrect: false,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Sync account email',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
TextField(
|
|
||||||
controller: _password,
|
|
||||||
obscureText: true,
|
|
||||||
autocorrect: false,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Sync account password',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Align(
|
|
||||||
alignment: Alignment.centerLeft,
|
|
||||||
child: FilledButton.icon(
|
|
||||||
onPressed: _busy ? null : _connectFirebase,
|
|
||||||
icon: const Icon(Icons.cloud_done),
|
|
||||||
label: const Text('Connect Firebase'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Align(
|
|
||||||
alignment: Alignment.centerRight,
|
|
||||||
child: FilledButton.icon(
|
|
||||||
onPressed: _save,
|
|
||||||
icon: const Icon(Icons.save),
|
|
||||||
label: const Text('Save'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
const Divider(),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text('Backup', style: Theme.of(context).textTheme.titleMedium),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
'Export all notes to a single Markdown file, or import/merge a '
|
|
||||||
'file back (matching ids are merged, never duplicated).',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
OutlinedButton.icon(
|
|
||||||
onPressed: _export,
|
|
||||||
icon: const Icon(Icons.upload_file),
|
|
||||||
label: const Text('Export notes'),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
OutlinedButton.icon(
|
|
||||||
onPressed: _import,
|
|
||||||
icon: const Icon(Icons.download),
|
|
||||||
label: const Text('Import notes'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
const Divider(),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
// GitHub is the cutover mirror, not a choice competing with
|
|
||||||
// Firebase, so its whole setup lives behind one disclosure at the
|
|
||||||
// very bottom of the screen — last, not suggested as a normal
|
|
||||||
// option.
|
|
||||||
ExpansionTile(
|
|
||||||
title: const Text('Advanced (GitHub mirror)'),
|
|
||||||
tilePadding: EdgeInsets.zero,
|
|
||||||
childrenPadding: const EdgeInsets.only(bottom: 8),
|
|
||||||
children: [
|
|
||||||
Align(
|
|
||||||
alignment: Alignment.centerLeft,
|
|
||||||
child: Text(
|
|
||||||
'Authorize in your browser — no token to paste. Syncs to '
|
|
||||||
'kuhyx/syncs by default.',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Align(
|
|
||||||
alignment: Alignment.centerLeft,
|
|
||||||
child: FilledButton.icon(
|
|
||||||
onPressed: _connectGitHub,
|
|
||||||
icon: const Icon(Icons.login),
|
|
||||||
label: const Text('Connect GitHub'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
TextField(
|
|
||||||
controller: _owner,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'GitHub owner',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
TextField(
|
|
||||||
controller: _repo,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Repository name',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
TextField(
|
|
||||||
controller: _clientId,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'OAuth App client id',
|
|
||||||
helperText:
|
|
||||||
'Leave as the baked-in default unless self-hosting',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
TextField(
|
|
||||||
controller: _token,
|
|
||||||
obscureText: true,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Access token (fallback)',
|
|
||||||
helperText: 'Contents: read/write on the sync repo only',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Align(
|
|
||||||
alignment: Alignment.centerLeft,
|
|
||||||
child: OutlinedButton.icon(
|
|
||||||
onPressed: _testing ? null : _test,
|
|
||||||
icon: _testing
|
|
||||||
? const SizedBox(
|
|
||||||
width: 16,
|
|
||||||
height: 16,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
)
|
|
||||||
: const Icon(Icons.wifi_tethering),
|
|
||||||
label: const Text('Test connection'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
if (_status != null) ...[
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
|
|
||||||
],
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dialog shown during the device flow: displays the user code, opens the
|
|
||||||
/// verification page, and polls until authorized — popping the token (or
|
|
||||||
/// null if cancelled / failed).
|
|
||||||
class _DeviceCodeDialog extends StatefulWidget {
|
|
||||||
const _DeviceCodeDialog({required this.device, required this.auth});
|
|
||||||
|
|
||||||
final DeviceCodeResponse device;
|
|
||||||
final GitHubDeviceAuth auth;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_DeviceCodeDialog> createState() => _DeviceCodeDialogState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
|
|
||||||
String? _error;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
unawaited(_poll());
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _poll() async {
|
|
||||||
try {
|
|
||||||
final token = await widget.auth.pollForToken(widget.device);
|
|
||||||
if (mounted) Navigator.of(context).pop(token);
|
|
||||||
} on Exception catch (e) {
|
|
||||||
if (mounted) setState(() => _error = '$e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _openPage() async {
|
|
||||||
await Clipboard.setData(ClipboardData(text: widget.device.userCode));
|
|
||||||
await launchUrl(
|
|
||||||
Uri.parse(widget.device.verificationUri),
|
|
||||||
mode: LaunchMode.externalApplication,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return AlertDialog(
|
|
||||||
title: const Text('Authorize on GitHub'),
|
|
||||||
content: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
const Text('Enter this code on GitHub:'),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
SelectableText(
|
|
||||||
widget.device.userCode,
|
|
||||||
style: Theme.of(context).textTheme.headlineSmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
if (_error == null)
|
|
||||||
const Row(
|
|
||||||
children: [
|
|
||||||
SizedBox(
|
|
||||||
width: 16,
|
|
||||||
height: 16,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
),
|
|
||||||
SizedBox(width: 12),
|
|
||||||
Expanded(child: Text('Waiting for authorization…')),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
else
|
|
||||||
Text(
|
|
||||||
_error!,
|
|
||||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
|
||||||
child: const Text('Cancel'),
|
|
||||||
),
|
|
||||||
FilledButton.icon(
|
|
||||||
onPressed: _openPage,
|
|
||||||
icon: const Icon(Icons.open_in_new),
|
|
||||||
label: const Text('Open GitHub & copy code'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@ -814,6 +814,15 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.4.1"
|
version: "1.4.1"
|
||||||
|
sync_settings_ui:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
path: sync_settings_ui
|
||||||
|
ref: "sync_settings_ui-v0.1.0"
|
||||||
|
resolved-ref: "23c693da4e6fd6004df09829a7d75365dc086c2c"
|
||||||
|
url: "https://github.com/kuhyx/utils"
|
||||||
|
source: git
|
||||||
|
version: "0.1.0"
|
||||||
synchronized:
|
synchronized:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
12
pubspec.yaml
12
pubspec.yaml
@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
|||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
# In Windows, build-name is used as the major, minor, and patch parts
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
# of the product and file versions while build-number is used as the build suffix.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 1.0.7+1
|
version: 1.0.8+1
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.12.2
|
sdk: ^3.12.2
|
||||||
@ -61,6 +61,16 @@ dependencies:
|
|||||||
# Retained only to read the legacy on-device DB during the one-time
|
# Retained only to read the legacy on-device DB during the one-time
|
||||||
# migration in NoteRepository.open; remove once all devices are migrated.
|
# migration in NoteRepository.open; remove once all devices are migrated.
|
||||||
sqlite_crdt: ^3.0.4
|
sqlite_crdt: ^3.0.4
|
||||||
|
|
||||||
|
# Shared "Sync settings" screen (Firebase + local backup), reused across
|
||||||
|
# every kuhy app that syncs. GitHub mirror stays app-local (see
|
||||||
|
# lib/ui/github_mirror_screen.dart) since here it also triggers a note
|
||||||
|
# sync, not just a settings save.
|
||||||
|
sync_settings_ui:
|
||||||
|
git:
|
||||||
|
url: https://github.com/kuhyx/utils
|
||||||
|
ref: sync_settings_ui-v0.1.0
|
||||||
|
path: sync_settings_ui
|
||||||
url_launcher: ^6.3.2
|
url_launcher: ^6.3.2
|
||||||
uuid: ^4.5.3
|
uuid: ^4.5.3
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
|
|||||||
@ -13,6 +13,7 @@ import 'package:todo/data/note_template.dart';
|
|||||||
import 'package:todo/sync/local_backup.dart';
|
import 'package:todo/sync/local_backup.dart';
|
||||||
import 'package:todo/sync/notes_markdown.dart';
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
import 'package:todo/ui/capture_screen.dart';
|
import 'package:todo/ui/capture_screen.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
import 'package:todo/ui/settings_screen.dart';
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
|
|
||||||
import 'fake_note_repository.dart';
|
import 'fake_note_repository.dart';
|
||||||
@ -304,20 +305,27 @@ void main() {
|
|||||||
|
|
||||||
await tester.tap(find.byTooltip('Settings'));
|
await tester.tap(find.byTooltip('Settings'));
|
||||||
await tester.pumpAndSettle(); // route transition
|
await tester.pumpAndSettle(); // route transition
|
||||||
expect(find.text('Firebase sync'), findsOneWidget); // settings is up
|
expect(find.byType(SettingsScreen), findsOneWidget); // settings is up
|
||||||
|
|
||||||
// Saving pops a SyncSettings back to the capture screen (covers the
|
// GitHub sync settings (owner/repo/token) now live on the standalone
|
||||||
// result-adoption branch in _openSettings). Scope to the settings route —
|
// GitHubMirrorScreen, reached via a link from SettingsScreen. The pop
|
||||||
// the capture screen's own "Save" is still mounted behind it.
|
// value itself is discarded by SettingsScreen; _openSettings always
|
||||||
await tester.tap(
|
// reloads from storage instead (a device-flow "Connect" saves the token
|
||||||
find.descendant(
|
// without popping a result at all, so a stale in-memory value would be
|
||||||
of: find.byType(SettingsScreen),
|
// wrong there too). This exercises that reload-after-return path, then
|
||||||
matching: find.text('Save'),
|
// Back returns to capture.
|
||||||
),
|
await tester.tap(find.text('Advanced sync (GitHub)'));
|
||||||
);
|
await tester.pumpAndSettle(); // route transition
|
||||||
await tester.pumpAndSettle(); // save + pop transition
|
expect(find.byType(GitHubMirrorScreen), findsOneWidget);
|
||||||
|
|
||||||
expect(find.text('Firebase sync'), findsNothing); // back on capture
|
await tester.tap(find.text('Save'));
|
||||||
|
await tester.pumpAndSettle(); // save + pop transition back to Settings
|
||||||
|
expect(find.byType(SettingsScreen), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.pageBack();
|
||||||
|
await tester.pumpAndSettle(); // pop transition back to capture
|
||||||
|
|
||||||
|
expect(find.byType(SettingsScreen), findsNothing); // back on capture
|
||||||
expect(find.byTooltip('Settings'), findsOneWidget);
|
expect(find.byTooltip('Settings'), findsOneWidget);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
365
test/github_mirror_screen_test.dart
Normal file
365
test/github_mirror_screen_test.dart
Normal file
@ -0,0 +1,365 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:url_launcher_platform_interface/link.dart';
|
||||||
|
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
/// Stub launcher that records the URL instead of opening it, so `_openPage`
|
||||||
|
/// can be exercised without a real platform channel.
|
||||||
|
class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||||
|
with MockPlatformInterfaceMixin {
|
||||||
|
String? launched;
|
||||||
|
|
||||||
|
@override
|
||||||
|
final LinkDelegate? linkDelegate = null;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> supportsMode(PreferredLaunchMode mode) async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> launchUrl(String url, LaunchOptions options) async {
|
||||||
|
launched = url;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
Future<FakeNoteRepository> pumpMirror(
|
||||||
|
WidgetTester tester, {
|
||||||
|
SyncSettings initial = const SyncSettings(
|
||||||
|
owner: 'kuhyx',
|
||||||
|
repo: 'syncs',
|
||||||
|
token: 't',
|
||||||
|
),
|
||||||
|
http.Client? httpClient,
|
||||||
|
FakeNoteRepository? repository,
|
||||||
|
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
||||||
|
ValueNotifier<AppSettings>? appSettings,
|
||||||
|
}) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
installFakeSecureStorage();
|
||||||
|
tester.view.physicalSize = const Size(1200, 2800);
|
||||||
|
tester.view.devicePixelRatio = 1.0;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final repo = repository ?? FakeNoteRepository();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: GitHubMirrorScreen(
|
||||||
|
initial: initial,
|
||||||
|
repository: repo,
|
||||||
|
appSettings:
|
||||||
|
appSettings ??
|
||||||
|
ValueNotifier(const AppSettings(advancedMode: false)),
|
||||||
|
httpClient: httpClient,
|
||||||
|
firebaseFactory: firebaseFactory ?? () async => null,
|
||||||
|
stateStore: InMemorySyncStateStore(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
return repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('Connect GitHub without a client id shows guidance', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpMirror(tester);
|
||||||
|
await tester.tap(find.text('Connect GitHub'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(
|
||||||
|
find.textContaining('Enter the OAuth App client id'),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Test connection reports a reachable repo', (tester) async {
|
||||||
|
final mock = MockClient((_) async => http.Response('{}', 200));
|
||||||
|
await pumpMirror(tester, httpClient: mock);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Test connection'));
|
||||||
|
await tester.pump(); // start
|
||||||
|
await tester.pump(); // resolve future + rebuild
|
||||||
|
|
||||||
|
expect(find.textContaining('reachable'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Test connection reports an inaccessible repo', (tester) async {
|
||||||
|
final mock = MockClient((_) async => http.Response('', 404));
|
||||||
|
await pumpMirror(tester, httpClient: mock);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Test connection'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.textContaining('Could not access'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Test connection surfaces a network error', (tester) async {
|
||||||
|
final mock = MockClient((_) async => throw Exception('offline'));
|
||||||
|
await pumpMirror(tester, httpClient: mock);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Test connection'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.textContaining('Error:'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('device flow failure to start shows a message', (tester) async {
|
||||||
|
final mock = MockClient((_) async => http.Response('nope', 422));
|
||||||
|
await pumpMirror(
|
||||||
|
tester,
|
||||||
|
initial: const SyncSettings(
|
||||||
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: '',
|
||||||
|
clientId: 'cid',
|
||||||
|
),
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Connect GitHub'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.textContaining('Could not start device flow'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('device flow happy path saves the token', (tester) async {
|
||||||
|
final mock = MockClient((req) async {
|
||||||
|
if (req.url.path.contains('device/code')) {
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'device_code': 'dev123',
|
||||||
|
'user_code': 'WXYZ-1234',
|
||||||
|
'verification_uri': 'https://github.com/login/device',
|
||||||
|
'interval': 0,
|
||||||
|
'expires_in': 900,
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Token endpoint: authorize immediately.
|
||||||
|
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
await pumpMirror(
|
||||||
|
tester,
|
||||||
|
initial: const SyncSettings(
|
||||||
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: '',
|
||||||
|
clientId: 'cid',
|
||||||
|
),
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Connect GitHub'));
|
||||||
|
await tester.pump(); // requestDeviceCode
|
||||||
|
await tester.pump(); // dialog builds, shows the user code
|
||||||
|
expect(find.text('WXYZ-1234'), findsOneWidget);
|
||||||
|
|
||||||
|
// Let the dialog poll (interval 0) and resolve the token, then the
|
||||||
|
// post-connect sync runs against the mock (list → empty, then PUT).
|
||||||
|
await tester.pump(const Duration(milliseconds: 50));
|
||||||
|
for (var i = 0; i < 6; i++) {
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(find.textContaining('Connected and synced'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('device flow connects but surfaces a post-connect sync failure', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final mock = MockClient((req) async {
|
||||||
|
if (req.url.path.contains('device/code')) {
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'device_code': 'dev123',
|
||||||
|
'user_code': 'WXYZ-1234',
|
||||||
|
'verification_uri': 'https://github.com/login/device',
|
||||||
|
'interval': 0,
|
||||||
|
'expires_in': 900,
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (req.url.path.contains('login/oauth/access_token')) {
|
||||||
|
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
||||||
|
}
|
||||||
|
return http.Response('boom', 500); // the sync's repo calls fail
|
||||||
|
});
|
||||||
|
|
||||||
|
await pumpMirror(
|
||||||
|
tester,
|
||||||
|
initial: const SyncSettings(
|
||||||
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: '',
|
||||||
|
clientId: 'cid',
|
||||||
|
),
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Connect GitHub'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 50));
|
||||||
|
for (var i = 0; i < 6; i++) {
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(find.textContaining('sync failed'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Save persists the settings and closes the screen', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
installFakeSecureStorage();
|
||||||
|
tester.view.physicalSize = const Size(1200, 2800);
|
||||||
|
tester.view.devicePixelRatio = 1.0;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final repo = FakeNoteRepository();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
|
||||||
|
// Push GitHubMirrorScreen over a base route so _save's Navigator.pop has
|
||||||
|
// somewhere to return to (popping the root route is a no-op and hides
|
||||||
|
// the result).
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Builder(
|
||||||
|
builder: (context) => Scaffold(
|
||||||
|
body: Center(
|
||||||
|
child: ElevatedButton(
|
||||||
|
onPressed: () => Navigator.of(context).push(
|
||||||
|
MaterialPageRoute<SyncSettings>(
|
||||||
|
builder: (_) => GitHubMirrorScreen(
|
||||||
|
initial: const SyncSettings(
|
||||||
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: 'tok',
|
||||||
|
),
|
||||||
|
repository: repo,
|
||||||
|
appSettings: ValueNotifier(
|
||||||
|
const AppSettings(advancedMode: false),
|
||||||
|
),
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
stateStore: InMemorySyncStateStore(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: const Text('open'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('open'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 400)); // route transition
|
||||||
|
expect(find.byType(GitHubMirrorScreen), findsOneWidget); // screen is up
|
||||||
|
|
||||||
|
await tester.tap(find.text('Save'));
|
||||||
|
await tester.pump(); // run _save (persist + pop)
|
||||||
|
await tester.pump(const Duration(milliseconds: 400)); // pop transition
|
||||||
|
|
||||||
|
expect(find.text('open'), findsOneWidget); // back on the base route
|
||||||
|
final saved = await SyncSettings.load();
|
||||||
|
expect(saved.owner, 'o');
|
||||||
|
expect(saved.token, 'tok');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('device dialog: failed poll shows the error and Open launches', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final launcher = _FakeUrlLauncher();
|
||||||
|
UrlLauncherPlatform.instance = launcher;
|
||||||
|
|
||||||
|
// _openPage copies the code to the clipboard first; there's no
|
||||||
|
// clipboard plugin in the test host, so stub the channel to succeed.
|
||||||
|
final messenger =
|
||||||
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||||
|
messenger.setMockMethodCallHandler(
|
||||||
|
SystemChannels.platform,
|
||||||
|
(call) async => null,
|
||||||
|
);
|
||||||
|
addTearDown(
|
||||||
|
() => messenger.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||||
|
);
|
||||||
|
|
||||||
|
final mock = MockClient((req) async {
|
||||||
|
if (req.url.path.contains('device/code')) {
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'device_code': 'dev123',
|
||||||
|
'user_code': 'WXYZ-1234',
|
||||||
|
'verification_uri': 'https://github.com/login/device',
|
||||||
|
'interval': 0,
|
||||||
|
'expires_in': 900,
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Token endpoint: a terminal error ends the poll loop cleanly (no
|
||||||
|
// lingering timer to trip the tester's pending-timer guard).
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({'error': 'access_denied', 'error_description': 'nope'}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
await pumpMirror(
|
||||||
|
tester,
|
||||||
|
initial: const SyncSettings(
|
||||||
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: '',
|
||||||
|
clientId: 'cid',
|
||||||
|
),
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Connect GitHub'));
|
||||||
|
await tester.pump(); // requestDeviceCode
|
||||||
|
await tester.pump(); // dialog builds, poll starts (interval 0)
|
||||||
|
expect(find.text('WXYZ-1234'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.pump(const Duration(milliseconds: 1)); // _delay(0) fires
|
||||||
|
await tester.pump(); // token error throws → _error set
|
||||||
|
expect(find.textContaining('nope'), findsOneWidget); // error rendered
|
||||||
|
|
||||||
|
// Tap the "open on GitHub" action: copies the code and launches the URL.
|
||||||
|
// _openPage awaits Clipboard.setData then the launcher's supportsMode +
|
||||||
|
// launchUrl; pumpAndSettle drains them (no spinner is animating now
|
||||||
|
// that the error is shown, so it settles).
|
||||||
|
await tester.tap(find.byIcon(Icons.open_in_new));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(launcher.launched, 'https://github.com/login/device');
|
||||||
|
|
||||||
|
await tester.tap(find.text('Cancel'));
|
||||||
|
await tester.pumpAndSettle(); // finish the dialog pop animation
|
||||||
|
expect(find.text('WXYZ-1234'), findsNothing); // dialog dismissed
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -4,12 +4,12 @@ import 'dart:io';
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
|
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:http/testing.dart';
|
import 'package:http/testing.dart';
|
||||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
import 'package:todo/data/app_settings.dart';
|
import 'package:todo/data/app_settings.dart';
|
||||||
import 'package:todo/data/note.dart';
|
import 'package:todo/data/note.dart';
|
||||||
@ -17,9 +17,8 @@ import 'package:todo/data/note_repository.dart';
|
|||||||
import 'package:todo/sync/backlog_export_io.dart';
|
import 'package:todo/sync/backlog_export_io.dart';
|
||||||
import 'package:todo/sync/notes_markdown.dart';
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
import 'package:todo/sync/sync_settings.dart';
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
import 'package:todo/ui/settings_screen.dart';
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
import 'package:url_launcher_platform_interface/link.dart';
|
|
||||||
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
|
|
||||||
|
|
||||||
import 'fake_note_repository.dart';
|
import 'fake_note_repository.dart';
|
||||||
import 'fake_secure_storage.dart';
|
import 'fake_secure_storage.dart';
|
||||||
@ -59,25 +58,6 @@ class _ThrowingFileSelector extends FileSelectorPlatform
|
|||||||
}) async => throw Exception('picker blew up');
|
}) async => throw Exception('picker blew up');
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stub launcher that records the URL instead of opening it, so `_openPage`
|
|
||||||
/// can be exercised without a real platform channel.
|
|
||||||
class _FakeUrlLauncher extends UrlLauncherPlatform
|
|
||||||
with MockPlatformInterfaceMixin {
|
|
||||||
String? launched;
|
|
||||||
|
|
||||||
@override
|
|
||||||
final LinkDelegate? linkDelegate = null;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> supportsMode(PreferredLaunchMode mode) async => true;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> launchUrl(String url, LaunchOptions options) async {
|
|
||||||
launched = url;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
Future<FakeNoteRepository> pumpSettings(
|
Future<FakeNoteRepository> pumpSettings(
|
||||||
WidgetTester tester, {
|
WidgetTester tester, {
|
||||||
@ -90,19 +70,14 @@ void main() {
|
|||||||
List<Note> seed = const [],
|
List<Note> seed = const [],
|
||||||
FakeNoteRepository? repository,
|
FakeNoteRepository? repository,
|
||||||
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
||||||
Future<FirebaseRestClient?> Function()? googleFirebaseFactory,
|
|
||||||
bool? googleAvailable,
|
|
||||||
Future<FirebaseAccount?> Function()? accountLoader,
|
|
||||||
Future<void> Function(FirebaseAccount)? accountSaver,
|
|
||||||
Future<void> Function()? accountClearer,
|
|
||||||
Future<bool> Function()? sessionProbe,
|
|
||||||
ValueNotifier<AppSettings>? appSettings,
|
ValueNotifier<AppSettings>? appSettings,
|
||||||
AnalyticsService? analytics,
|
AnalyticsService? analytics,
|
||||||
}) async {
|
}) async {
|
||||||
SharedPreferences.setMockInitialValues({});
|
SharedPreferences.setMockInitialValues({});
|
||||||
installFakeSecureStorage();
|
installFakeSecureStorage();
|
||||||
// Tall surface so the whole settings ListView builds (its Backup section
|
// Tall surface so the whole settings ListView builds and the pushed
|
||||||
// is below the default 800×600 fold and would otherwise be lazy-skipped).
|
// Sync settings screen's Backup section (below the default 800×600
|
||||||
|
// fold) isn't lazy-skipped.
|
||||||
tester.view.physicalSize = const Size(1200, 2800);
|
tester.view.physicalSize = const Size(1200, 2800);
|
||||||
tester.view.devicePixelRatio = 1.0;
|
tester.view.devicePixelRatio = 1.0;
|
||||||
addTearDown(tester.view.resetPhysicalSize);
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
@ -120,23 +95,12 @@ void main() {
|
|||||||
ValueNotifier(const AppSettings(advancedMode: false)),
|
ValueNotifier(const AppSettings(advancedMode: false)),
|
||||||
analytics: analytics,
|
analytics: analytics,
|
||||||
httpClient: httpClient,
|
httpClient: httpClient,
|
||||||
// Both injected so the widget never reaches for the platform: the
|
// Injected so the widget never reaches for the platform: the real
|
||||||
// real factories want the OS keystore and an application-support
|
// factory wants the OS keystore, which doesn't exist under
|
||||||
// directory, neither of which exists under `flutter test`.
|
// `flutter test`.
|
||||||
firebaseFactory: firebaseFactory ?? () async => null,
|
firebaseFactory: firebaseFactory ?? () async => null,
|
||||||
googleFirebaseFactory: googleFirebaseFactory ?? () async => null,
|
accountLoader: () async => null,
|
||||||
googleAvailable: googleAvailable ?? true,
|
sessionProbe: () async => false,
|
||||||
accountLoader: accountLoader ?? () async => null,
|
|
||||||
accountSaver: accountSaver,
|
|
||||||
accountClearer: accountClearer,
|
|
||||||
// Defaults to whatever the injected account says, so a test that
|
|
||||||
// only stubs the account still describes one coherent device. The
|
|
||||||
// production probe consults the keystore, which these tests fake
|
|
||||||
// rather than provide, and would otherwise answer "no session" for
|
|
||||||
// a device the test just declared signed in.
|
|
||||||
sessionProbe:
|
|
||||||
sessionProbe ??
|
|
||||||
() async => await (accountLoader ?? () async => null)() != null,
|
|
||||||
stateStore: InMemorySyncStateStore(),
|
stateStore: InMemorySyncStateStore(),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@ -145,25 +109,6 @@ void main() {
|
|||||||
return repo;
|
return repo;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Expands "Use the account password instead".
|
|
||||||
///
|
|
||||||
/// Google sign-in is the primary path now, so the email/password form is
|
|
||||||
/// collapsed by default; a test that types credentials has to open it.
|
|
||||||
Future<void> openPasswordForm(WidgetTester tester) async {
|
|
||||||
await tester.tap(find.text('Use the account password instead'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Expands the "Advanced (GitHub mirror)" section.
|
|
||||||
///
|
|
||||||
/// GitHub is the cutover mirror rather than a choice the user makes, so
|
|
||||||
/// everything GitHub-facing is collapsed by default; a test that touches
|
|
||||||
/// those widgets has to open it first.
|
|
||||||
Future<void> openAdvanced(WidgetTester tester) async {
|
|
||||||
await tester.tap(find.text('Advanced (GitHub mirror)'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
}
|
|
||||||
|
|
||||||
testWidgets(
|
testWidgets(
|
||||||
'Enable advanced toggles and persists locally with no client',
|
'Enable advanced toggles and persists locally with no client',
|
||||||
(tester) async {
|
(tester) async {
|
||||||
@ -259,396 +204,50 @@ void main() {
|
|||||||
expect(prefs.getString('analytics.buffer'), contains('settings_toggle'));
|
expect(prefs.getString('analytics.buffer'), contains('settings_toggle'));
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('renders sync fields and the backup actions', (tester) async {
|
testWidgets('renders the two sync links and no inline sync fields', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
await pumpSettings(tester);
|
await pumpSettings(tester);
|
||||||
// GitHub is the mirror now: hidden until the disclosure is opened. The
|
// The slim screen only links out; neither sync surface's own widgets
|
||||||
// password form is likewise behind one, leaving Google as the only
|
// should be inlined here anymore.
|
||||||
// sign-in control on screen.
|
expect(find.text('Sync settings'), findsOneWidget);
|
||||||
|
expect(find.text('Advanced sync (GitHub)'), findsOneWidget);
|
||||||
expect(find.text('Connect GitHub'), findsNothing);
|
expect(find.text('Connect GitHub'), findsNothing);
|
||||||
expect(find.text('Connect Firebase'), findsNothing);
|
|
||||||
expect(find.text('Sign in with Google'), findsOneWidget);
|
|
||||||
await openAdvanced(tester);
|
|
||||||
expect(find.text('Connect GitHub'), findsOneWidget);
|
|
||||||
expect(find.text('Export notes'), findsOneWidget);
|
|
||||||
expect(find.text('Import notes'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('offers Google first and the password form behind it', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// Ordering is the feature: after a reinstall the one-tap path has to be
|
|
||||||
// the thing you see, with the phone-keyboard path available but demoted.
|
|
||||||
await pumpSettings(tester);
|
|
||||||
expect(find.text('Sign in with Google'), findsOneWidget);
|
|
||||||
expect(
|
|
||||||
find.widgetWithText(TextField, 'Sync account email'),
|
|
||||||
findsNothing,
|
|
||||||
reason: 'the password form starts collapsed',
|
|
||||||
);
|
|
||||||
|
|
||||||
await openPasswordForm(tester);
|
|
||||||
expect(
|
|
||||||
find.widgetWithText(TextField, 'Sync account email'),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
find.widgetWithText(TextField, 'Sync account password'),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
expect(find.text('Disconnect'), findsNothing);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('hides Google and opens the password form on desktop', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// The desktop build is the web build, where Google Identity Services only
|
|
||||||
// signs in through its own rendered button -- `authenticate()` throws
|
|
||||||
// UnimplementedError there, and not a GoogleSignInException, so it would
|
|
||||||
// not even have been caught. Offering a button that always crashed would
|
|
||||||
// be worse than offering none, and the password form has to be visible
|
|
||||||
// because it is then the only way in.
|
|
||||||
await pumpSettings(tester, googleAvailable: false);
|
|
||||||
|
|
||||||
expect(find.text('Sign in with Google'), findsNothing);
|
expect(find.text('Sign in with Google'), findsNothing);
|
||||||
expect(
|
|
||||||
find.widgetWithText(TextField, 'Sync account email'),
|
|
||||||
findsOneWidget,
|
|
||||||
reason: 'the password form is expanded when it is the only option',
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('Sign in with Google connects without typing anything', (
|
testWidgets('Tapping "Sync settings" navigates to SyncSettingsScreen', (
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// The whole feature in one test: no text entered anywhere, one tap, and
|
|
||||||
// the device ends up connected showing the account Google signed in as.
|
|
||||||
//
|
|
||||||
// The email comes from Firebase's response via openFirebaseWithGoogle,
|
|
||||||
// not from the form -- a fresh install has nothing in the form, which is
|
|
||||||
// exactly the scenario this path exists for. An earlier cut read the
|
|
||||||
// controller here and persisted an empty account; the next launch then
|
|
||||||
// took the password branch with '' and failed.
|
|
||||||
// Starts genuinely unconfigured -- a fresh install -- and only gains an
|
|
||||||
// account as a side effect of the Google sign-in itself.
|
|
||||||
FirebaseAccount? stored;
|
|
||||||
await pumpSettings(
|
|
||||||
tester,
|
|
||||||
googleFirebaseFactory: () async {
|
|
||||||
stored = const FirebaseAccount(
|
|
||||||
email: 'signed-in@example.com',
|
|
||||||
password: '',
|
|
||||||
);
|
|
||||||
return _stubClient();
|
|
||||||
},
|
|
||||||
accountLoader: () async => stored,
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sign in with Google'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.text('Connected to Firebase.'), findsOneWidget);
|
|
||||||
expect(find.text('signed-in@example.com'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a cancelled Google sign-in is not reported as an error', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// Dismissing the account picker is an ordinary thing to do; it must not
|
|
||||||
// look like a failure.
|
|
||||||
await pumpSettings(tester, googleFirebaseFactory: () async => null);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sign in with Google'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.text('Google sign-in was cancelled.'), findsOneWidget);
|
|
||||||
expect(find.text('Sign in with Google'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a wrong-account Google sign-in explains itself', (tester) async {
|
|
||||||
// The failure worth being loud about: authentication succeeds but the uid
|
|
||||||
// is not the one the security rules pin, so every read and write would be
|
|
||||||
// denied with no other symptom.
|
|
||||||
await pumpSettings(
|
|
||||||
tester,
|
|
||||||
googleFirebaseFactory: () async =>
|
|
||||||
throw FirebaseAuthError('signed in as the wrong account: uid X'),
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sign in with Google'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.textContaining('wrong account'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Connect Firebase with empty fields asks for credentials', (
|
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
await pumpSettings(tester);
|
await pumpSettings(tester);
|
||||||
await openPasswordForm(tester);
|
|
||||||
await tester.tap(find.text('Connect Firebase'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(
|
|
||||||
find.textContaining('Enter the sync account email and password'),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Connect Firebase stores the account and reports success', (
|
await tester.tap(find.text('Sync settings'));
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
FirebaseAccount? saved;
|
|
||||||
await pumpSettings(
|
|
||||||
tester,
|
|
||||||
accountSaver: (a) async => saved = a,
|
|
||||||
firebaseFactory: () async => _stubClient(),
|
|
||||||
);
|
|
||||||
await openPasswordForm(tester);
|
|
||||||
|
|
||||||
await tester.enterText(
|
|
||||||
find.widgetWithText(TextField, 'Sync account email'),
|
|
||||||
'sync@example.com',
|
|
||||||
);
|
|
||||||
await tester.enterText(
|
|
||||||
find.widgetWithText(TextField, 'Sync account password'),
|
|
||||||
'pw',
|
|
||||||
);
|
|
||||||
await tester.tap(find.text('Connect Firebase'));
|
|
||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
// saveAccount must actually be called: without it openFirebase() reads an
|
expect(find.byType(SyncSettingsScreen), findsOneWidget);
|
||||||
// account nothing ever wrote, and Firebase is a silent no-op forever.
|
|
||||||
expect(saved?.email, 'sync@example.com');
|
|
||||||
expect(saved?.password, 'pw');
|
|
||||||
expect(find.text('Connected to Firebase.'), findsOneWidget);
|
|
||||||
// Connected state is read-only text, not a form implying re-entry.
|
|
||||||
expect(find.text('sync@example.com'), findsOneWidget);
|
|
||||||
expect(find.text('Disconnect'), findsOneWidget);
|
|
||||||
expect(
|
|
||||||
find.widgetWithText(TextField, 'Sync account password'),
|
|
||||||
findsNothing,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('a rejected account is cleared rather than left half-stored', (
|
testWidgets(
|
||||||
tester,
|
'Tapping "Advanced sync (GitHub)" navigates to GitHubMirrorScreen with '
|
||||||
) async {
|
'the right params',
|
||||||
var cleared = false;
|
(tester) async {
|
||||||
await pumpSettings(
|
const initial = SyncSettings(owner: 'o', repo: 'r', token: 'tok');
|
||||||
tester,
|
final repo = await pumpSettings(tester, initial: initial);
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async => cleared = true,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
);
|
|
||||||
await openPasswordForm(tester);
|
|
||||||
|
|
||||||
await tester.enterText(
|
await tester.tap(find.text('Advanced sync (GitHub)'));
|
||||||
find.widgetWithText(TextField, 'Sync account email'),
|
await tester.pumpAndSettle();
|
||||||
'wrong@example.com',
|
|
||||||
);
|
|
||||||
await tester.enterText(
|
|
||||||
find.widgetWithText(TextField, 'Sync account password'),
|
|
||||||
'bad',
|
|
||||||
);
|
|
||||||
await tester.tap(find.text('Connect Firebase'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(cleared, isTrue);
|
expect(find.byType(GitHubMirrorScreen), findsOneWidget);
|
||||||
expect(find.text('Firebase rejected that account.'), findsOneWidget);
|
final screen = tester.widget<GitHubMirrorScreen>(
|
||||||
});
|
find.byType(GitHubMirrorScreen),
|
||||||
|
);
|
||||||
testWidgets('a stored account shows as connected on open, and disconnects', (
|
// Prove the hand-off actually carries the right values, not just that
|
||||||
tester,
|
// the right widget type appears — a dropped constructor arg is the
|
||||||
) async {
|
// failure mode a screen split like this one actually produces.
|
||||||
var cleared = false;
|
expect(screen.initial, initial);
|
||||||
await pumpSettings(
|
expect(screen.repository, repo);
|
||||||
tester,
|
},
|
||||||
accountLoader: () async =>
|
);
|
||||||
const FirebaseAccount(email: 'stored@example.com', password: 'pw'),
|
|
||||||
accountClearer: () async => cleared = true,
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.text('stored@example.com'), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Disconnect'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(cleared, isTrue);
|
|
||||||
expect(find.text('Firebase disconnected.'), findsOneWidget);
|
|
||||||
// Back to the not-connected state, which now leads with Google rather
|
|
||||||
// than with the email field.
|
|
||||||
expect(find.text('Sign in with Google'), findsOneWidget);
|
|
||||||
await openPasswordForm(tester);
|
|
||||||
expect(
|
|
||||||
find.widgetWithText(TextField, 'Sync account email'),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Connect GitHub without a client id shows guidance', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpSettings(tester);
|
|
||||||
await openAdvanced(tester);
|
|
||||||
await tester.tap(find.text('Connect GitHub'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(
|
|
||||||
find.textContaining('Enter the OAuth App client id'),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Test connection reports a reachable repo', (tester) async {
|
|
||||||
final mock = MockClient((_) async => http.Response('{}', 200));
|
|
||||||
await pumpSettings(tester, httpClient: mock);
|
|
||||||
|
|
||||||
await tester.tap(
|
|
||||||
find.text('Advanced (GitHub mirror)'),
|
|
||||||
); // Test connection lives here now
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
await tester.tap(find.text('Test connection'));
|
|
||||||
await tester.pump(); // start
|
|
||||||
await tester.pump(); // resolve future + rebuild
|
|
||||||
|
|
||||||
expect(find.textContaining('reachable'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Test connection reports an inaccessible repo', (tester) async {
|
|
||||||
final mock = MockClient((_) async => http.Response('', 404));
|
|
||||||
await pumpSettings(tester, httpClient: mock);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Advanced (GitHub mirror)'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
await tester.tap(find.text('Test connection'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Could not access'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Test connection surfaces a network error', (tester) async {
|
|
||||||
final mock = MockClient((_) async => throw Exception('offline'));
|
|
||||||
await pumpSettings(tester, httpClient: mock);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Advanced (GitHub mirror)'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
await tester.tap(find.text('Test connection'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Error:'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('device flow failure to start shows a message', (tester) async {
|
|
||||||
final mock = MockClient((_) async => http.Response('nope', 422));
|
|
||||||
await pumpSettings(
|
|
||||||
tester,
|
|
||||||
initial: const SyncSettings(
|
|
||||||
owner: 'o',
|
|
||||||
repo: 'r',
|
|
||||||
token: '',
|
|
||||||
clientId: 'cid',
|
|
||||||
),
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
await openAdvanced(tester);
|
|
||||||
await tester.tap(find.text('Connect GitHub'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Could not start device flow'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('device flow happy path saves the token', (tester) async {
|
|
||||||
final mock = MockClient((req) async {
|
|
||||||
if (req.url.path.contains('device/code')) {
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'device_code': 'dev123',
|
|
||||||
'user_code': 'WXYZ-1234',
|
|
||||||
'verification_uri': 'https://github.com/login/device',
|
|
||||||
'interval': 0,
|
|
||||||
'expires_in': 900,
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Token endpoint: authorize immediately.
|
|
||||||
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
|
||||||
});
|
|
||||||
|
|
||||||
await pumpSettings(
|
|
||||||
tester,
|
|
||||||
initial: const SyncSettings(
|
|
||||||
owner: 'o',
|
|
||||||
repo: 'r',
|
|
||||||
token: '',
|
|
||||||
clientId: 'cid',
|
|
||||||
),
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
await openAdvanced(tester);
|
|
||||||
await tester.tap(find.text('Connect GitHub'));
|
|
||||||
await tester.pump(); // requestDeviceCode
|
|
||||||
await tester.pump(); // dialog builds, shows the user code
|
|
||||||
expect(find.text('WXYZ-1234'), findsOneWidget);
|
|
||||||
|
|
||||||
// Let the dialog poll (interval 0) and resolve the token, then the
|
|
||||||
// post-connect sync runs against the mock (list → empty, then PUT).
|
|
||||||
await tester.pump(const Duration(milliseconds: 50));
|
|
||||||
for (var i = 0; i < 6; i++) {
|
|
||||||
await tester.pump();
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(find.textContaining('Connected and synced'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('device flow connects but surfaces a post-connect sync failure', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final mock = MockClient((req) async {
|
|
||||||
if (req.url.path.contains('device/code')) {
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'device_code': 'dev123',
|
|
||||||
'user_code': 'WXYZ-1234',
|
|
||||||
'verification_uri': 'https://github.com/login/device',
|
|
||||||
'interval': 0,
|
|
||||||
'expires_in': 900,
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (req.url.path.contains('login/oauth/access_token')) {
|
|
||||||
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
|
||||||
}
|
|
||||||
return http.Response('boom', 500); // the sync's repo calls fail
|
|
||||||
});
|
|
||||||
|
|
||||||
await pumpSettings(
|
|
||||||
tester,
|
|
||||||
initial: const SyncSettings(
|
|
||||||
owner: 'o',
|
|
||||||
repo: 'r',
|
|
||||||
token: '',
|
|
||||||
clientId: 'cid',
|
|
||||||
),
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
await openAdvanced(tester);
|
|
||||||
await tester.tap(find.text('Connect GitHub'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 50));
|
|
||||||
for (var i = 0; i < 6; i++) {
|
|
||||||
await tester.pump();
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(find.textContaining('sync failed'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('the default export home is the real HOME', () {
|
test('the default export home is the real HOME', () {
|
||||||
// Guards the production default, which every other test overrides so the
|
// Guards the production default, which every other test overrides so the
|
||||||
@ -656,252 +255,137 @@ void main() {
|
|||||||
expect(resolveExportHome(), Platform.environment['HOME']);
|
expect(resolveExportHome(), Platform.environment['HOME']);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('Export notes writes the backlog file (desktop)', (tester) async {
|
group('BackupSlot wiring through Sync settings', () {
|
||||||
// Redirect HOME: this test does real file I/O, and without the override it
|
// These prove the closures SettingsScreen builds for
|
||||||
// overwrites the user's canonical ~/todo/BACKLOG.md with the fake note
|
// SyncSettingsScreen's BackupSlot actually call todo's real
|
||||||
// below on every test run.
|
// export/import — the shared package's own suite covers the generic
|
||||||
// Sync creation: awaiting real file I/O under the widget tester's fake
|
// BackupSlot UI (button taps, status text), so these focus on the real
|
||||||
// clock never completes.
|
// behavior behind the closures instead of re-asserting status text.
|
||||||
final home = Directory.systemTemp.createTempSync('todo_export_home');
|
|
||||||
resolveExportHome = () => home.path;
|
testWidgets('Export notes writes the backlog file (desktop)', (
|
||||||
addTearDown(() {
|
tester,
|
||||||
resolveExportHome = () =>
|
) async {
|
||||||
Platform.environment['HOME'] ?? Directory.current.path;
|
// Redirect HOME: this test does real file I/O, and without the
|
||||||
home.deleteSync(recursive: true);
|
// override it overwrites the user's canonical ~/todo/BACKLOG.md with
|
||||||
|
// the fake note below on every test run.
|
||||||
|
final home = Directory.systemTemp.createTempSync('todo_export_home');
|
||||||
|
resolveExportHome = () => home.path;
|
||||||
|
addTearDown(() {
|
||||||
|
resolveExportHome = () =>
|
||||||
|
Platform.environment['HOME'] ?? Directory.current.path;
|
||||||
|
home.deleteSync(recursive: true);
|
||||||
|
});
|
||||||
|
|
||||||
|
await pumpSettings(
|
||||||
|
tester,
|
||||||
|
seed: [
|
||||||
|
Note(
|
||||||
|
id: 'n',
|
||||||
|
text: 'an idea',
|
||||||
|
priority: Priority.medium,
|
||||||
|
status: Status.todo,
|
||||||
|
createdAt: DateTime(2026, 6, 15),
|
||||||
|
updatedAt: DateTime(2026, 6, 15),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sync settings'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
// _export does real file I/O on desktop, so drive it under runAsync.
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await tester.tap(find.text('Export notes'));
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||||
|
});
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
final file = File('${home.path}/todo/BACKLOG.md');
|
||||||
|
expect(file.existsSync(), isTrue);
|
||||||
|
expect(file.readAsStringSync(), contains('an idea'));
|
||||||
});
|
});
|
||||||
|
|
||||||
await pumpSettings(
|
testWidgets('Export surfaces a failure when the repository read fails', (
|
||||||
tester,
|
tester,
|
||||||
seed: [
|
) async {
|
||||||
|
await pumpSettings(tester, repository: _ExplodingRepo());
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sync settings'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await tester.tap(find.text('Export notes'));
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||||
|
});
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.textContaining('Export failed'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Import notes reads the picked file and merges', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
// Round-trip a known note through the export format so the picked
|
||||||
|
// file is valid input the importer can parse and merge.
|
||||||
|
final markdown = NotesMarkdown.export([
|
||||||
Note(
|
Note(
|
||||||
id: 'n',
|
id: 'imported-1',
|
||||||
text: 'an idea',
|
text: 'an imported idea',
|
||||||
priority: Priority.medium,
|
priority: Priority.high,
|
||||||
status: Status.todo,
|
status: Status.inProgress,
|
||||||
createdAt: DateTime(2026, 6, 15),
|
createdAt: DateTime(2026, 6, 15),
|
||||||
updatedAt: DateTime(2026, 6, 15),
|
updatedAt: DateTime(2026, 6, 15),
|
||||||
),
|
),
|
||||||
],
|
]);
|
||||||
);
|
FileSelectorPlatform.instance = _FakeFileSelector(
|
||||||
|
XFile.fromData(utf8.encode(markdown), name: 'backlog.md'),
|
||||||
// _export does real file I/O on desktop, so drive it under runAsync.
|
|
||||||
await tester.runAsync(() async {
|
|
||||||
await tester.tap(find.text('Export notes'));
|
|
||||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
|
||||||
});
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Exported'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Export surfaces a failure when the repository read fails', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpSettings(tester, repository: _ExplodingRepo());
|
|
||||||
|
|
||||||
await tester.runAsync(() async {
|
|
||||||
await tester.tap(find.text('Export notes'));
|
|
||||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
|
||||||
});
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Export failed'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Save persists the settings and closes the screen', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
SharedPreferences.setMockInitialValues({});
|
|
||||||
installFakeSecureStorage();
|
|
||||||
tester.view.physicalSize = const Size(1200, 2800);
|
|
||||||
tester.view.devicePixelRatio = 1.0;
|
|
||||||
addTearDown(tester.view.resetPhysicalSize);
|
|
||||||
addTearDown(tester.view.resetDevicePixelRatio);
|
|
||||||
|
|
||||||
final repo = FakeNoteRepository();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
|
|
||||||
// Push Settings over a base route so _save's Navigator.pop has somewhere
|
|
||||||
// to return to (popping the root route is a no-op and hides the result).
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
home: Builder(
|
|
||||||
builder: (context) => Scaffold(
|
|
||||||
body: Center(
|
|
||||||
child: ElevatedButton(
|
|
||||||
onPressed: () => Navigator.of(context).push(
|
|
||||||
MaterialPageRoute<SyncSettings>(
|
|
||||||
builder: (_) => SettingsScreen(
|
|
||||||
initial: const SyncSettings(
|
|
||||||
owner: 'o',
|
|
||||||
repo: 'r',
|
|
||||||
token: 'tok',
|
|
||||||
),
|
|
||||||
repository: repo,
|
|
||||||
appSettings: ValueNotifier(
|
|
||||||
const AppSettings(advancedMode: false),
|
|
||||||
),
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
stateStore: InMemorySyncStateStore(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: const Text('open'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('open'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 400)); // route transition
|
|
||||||
expect(find.text('Firebase sync'), findsOneWidget); // settings is up
|
|
||||||
|
|
||||||
await tester.tap(find.text('Save'));
|
|
||||||
await tester.pump(); // run _save (persist + pop)
|
|
||||||
await tester.pump(const Duration(milliseconds: 400)); // pop transition
|
|
||||||
|
|
||||||
expect(find.text('open'), findsOneWidget); // back on the base route
|
|
||||||
final saved = await SyncSettings.load();
|
|
||||||
expect(saved.owner, 'o');
|
|
||||||
expect(saved.token, 'tok');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Import notes reads the picked file and merges', (tester) async {
|
|
||||||
// Round-trip a known note through the export format so the picked file is
|
|
||||||
// valid input the importer can parse and merge.
|
|
||||||
final markdown = NotesMarkdown.export([
|
|
||||||
Note(
|
|
||||||
id: 'imported-1',
|
|
||||||
text: 'an imported idea',
|
|
||||||
priority: Priority.high,
|
|
||||||
status: Status.inProgress,
|
|
||||||
createdAt: DateTime(2026, 6, 15),
|
|
||||||
updatedAt: DateTime(2026, 6, 15),
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
FileSelectorPlatform.instance = _FakeFileSelector(
|
|
||||||
XFile.fromData(utf8.encode(markdown), name: 'backlog.md'),
|
|
||||||
);
|
|
||||||
|
|
||||||
final repo = await pumpSettings(tester);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Import notes'));
|
|
||||||
await tester.pump(); // openFile resolves (in-memory)
|
|
||||||
await tester.pump(); // read + parse + merge + setState
|
|
||||||
|
|
||||||
expect(find.textContaining('Imported'), findsOneWidget);
|
|
||||||
expect((await repo.listNotes()).single.text, 'an imported idea');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Import shows nothing when the picker is cancelled', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
FileSelectorPlatform.instance = _FakeFileSelector(null); // user cancels
|
|
||||||
final repo = await pumpSettings(tester);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Import notes'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Imported'), findsNothing);
|
|
||||||
expect(await repo.listNotes(), isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Import surfaces a failure from the picker', (tester) async {
|
|
||||||
FileSelectorPlatform.instance = _ThrowingFileSelector();
|
|
||||||
final repo = await pumpSettings(tester);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Import notes'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Import failed'), findsOneWidget);
|
|
||||||
expect(await repo.listNotes(), isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('device dialog: failed poll shows the error and Open launches', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final launcher = _FakeUrlLauncher();
|
|
||||||
UrlLauncherPlatform.instance = launcher;
|
|
||||||
|
|
||||||
// _openPage copies the code to the clipboard first; there's no clipboard
|
|
||||||
// plugin in the test host, so stub the channel to succeed.
|
|
||||||
final messenger =
|
|
||||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
|
||||||
messenger.setMockMethodCallHandler(
|
|
||||||
SystemChannels.platform,
|
|
||||||
(call) async => null,
|
|
||||||
);
|
|
||||||
addTearDown(
|
|
||||||
() => messenger.setMockMethodCallHandler(SystemChannels.platform, null),
|
|
||||||
);
|
|
||||||
|
|
||||||
final mock = MockClient((req) async {
|
|
||||||
if (req.url.path.contains('device/code')) {
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'device_code': 'dev123',
|
|
||||||
'user_code': 'WXYZ-1234',
|
|
||||||
'verification_uri': 'https://github.com/login/device',
|
|
||||||
'interval': 0,
|
|
||||||
'expires_in': 900,
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Token endpoint: a terminal error ends the poll loop cleanly (no
|
|
||||||
// lingering timer to trip the tester's pending-timer guard).
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({'error': 'access_denied', 'error_description': 'nope'}),
|
|
||||||
200,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
final repo = await pumpSettings(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sync settings'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Import notes'));
|
||||||
|
await tester.pump(); // openFile resolves (in-memory)
|
||||||
|
await tester.pump(); // read + parse + merge + setState
|
||||||
|
|
||||||
|
expect((await repo.listNotes()).single.text, 'an imported idea');
|
||||||
});
|
});
|
||||||
|
|
||||||
await pumpSettings(
|
testWidgets('Import shows nothing when the picker is cancelled', (
|
||||||
tester,
|
tester,
|
||||||
initial: const SyncSettings(
|
) async {
|
||||||
owner: 'o',
|
FileSelectorPlatform.instance = _FakeFileSelector(null); // cancelled
|
||||||
repo: 'r',
|
final repo = await pumpSettings(tester);
|
||||||
token: '',
|
|
||||||
clientId: 'cid',
|
|
||||||
),
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
await openAdvanced(tester);
|
await tester.tap(find.text('Sync settings'));
|
||||||
await tester.tap(find.text('Connect GitHub'));
|
await tester.pumpAndSettle();
|
||||||
await tester.pump(); // requestDeviceCode
|
|
||||||
await tester.pump(); // dialog builds, poll starts (interval 0)
|
|
||||||
expect(find.text('WXYZ-1234'), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.pump(const Duration(milliseconds: 1)); // _delay(0) fires
|
await tester.tap(find.text('Import notes'));
|
||||||
await tester.pump(); // token error throws → _error set
|
await tester.pump();
|
||||||
expect(find.textContaining('nope'), findsOneWidget); // error rendered
|
await tester.pump();
|
||||||
|
|
||||||
// Tap the "open on GitHub" action: copies the code and launches the URL.
|
// The shared screen can't distinguish "cancelled" from "nothing
|
||||||
// _openPage awaits Clipboard.setData then the launcher's supportsMode +
|
// imported" — it reports "Imported notes." either way, since
|
||||||
// launchUrl; pumpAndSettle drains them (no spinner is animating now that
|
// BackupSlot.import() returns normally on cancel. The behavior that
|
||||||
// the error is shown, so it settles).
|
// actually matters, that nothing was merged, is what's asserted here.
|
||||||
await tester.tap(find.byIcon(Icons.open_in_new));
|
expect(await repo.listNotes(), isEmpty);
|
||||||
await tester.pumpAndSettle();
|
});
|
||||||
expect(launcher.launched, 'https://github.com/login/device');
|
|
||||||
|
|
||||||
await tester.tap(find.text('Cancel'));
|
testWidgets('Import surfaces a failure from the picker', (tester) async {
|
||||||
await tester.pumpAndSettle(); // finish the dialog pop animation
|
FileSelectorPlatform.instance = _ThrowingFileSelector();
|
||||||
expect(find.text('WXYZ-1234'), findsNothing); // dialog dismissed
|
final repo = await pumpSettings(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sync settings'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Import notes'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.textContaining('Import failed'), findsOneWidget);
|
||||||
|
expect(await repo.listNotes(), isEmpty);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A real [FirebaseRestClient] that is never called: the settings screen only
|
|
||||||
/// checks it for null, so no network or keystore is touched.
|
|
||||||
FirebaseRestClient _stubClient() => FirebaseRestClient(
|
|
||||||
databaseUrl: 'https://example.invalid',
|
|
||||||
auth: FirebaseTokenProvider(
|
|
||||||
apiKey: 'k',
|
|
||||||
store: InMemoryCredentialStore(),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user