Files
pipelines/app/lib/features/chat/stack/mobile_chat_navigation.dart
T

100 lines
2.6 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
const mobileChatNavigationKey = 'pipelines.mobile-chat-navigation.v1';
/// How a phone-width layout moves between the open chats.
enum MobileChatNavigation {
quickSwitch(
'Quick switch',
'The next open chat peeks below the current one; tap it to swap.',
),
chatStack(
'Chat stack',
'A stack of the open chats floats above the composer; tap it to pick one.',
);
const MobileChatNavigation(this.label, this.description);
final String label;
final String description;
}
abstract interface class MobileChatNavigationStore {
Future<String?> load();
Future<bool> save(String value);
}
class SharedMobileChatNavigationStore implements MobileChatNavigationStore {
const SharedMobileChatNavigationStore();
@override
Future<String?> load() async {
try {
return (await SharedPreferences.getInstance()).getString(
mobileChatNavigationKey,
);
} catch (_) {
return null;
}
}
@override
Future<bool> save(String value) async {
try {
return await (await SharedPreferences.getInstance()).setString(
mobileChatNavigationKey,
value,
);
} catch (_) {
return false;
}
}
}
/// This device's choice of phone chat navigation, applied live.
class MobileChatNavigationController extends ChangeNotifier {
MobileChatNavigationController({MobileChatNavigationStore? store})
: _store = store ?? const SharedMobileChatNavigationStore();
static final instance = MobileChatNavigationController();
final MobileChatNavigationStore _store;
MobileChatNavigation _value = MobileChatNavigation.quickSwitch;
int _revision = 0;
bool _disposed = false;
bool saveFailed = false;
MobileChatNavigation get value => _value;
bool get stack => _value == MobileChatNavigation.chatStack;
Future<void> restore() async {
final revision = _revision;
final saved = await _store.load();
if (_disposed || revision != _revision) return;
for (final mode in MobileChatNavigation.values) {
if (mode.name == saved && mode != _value) {
_value = mode;
notifyListeners();
}
}
}
Future<void> setValue(MobileChatNavigation mode) async {
if (_disposed) return;
final revision = ++_revision;
_value = mode;
saveFailed = false;
notifyListeners();
final saved = await _store.save(mode.name);
if (_disposed || revision != _revision) return;
saveFailed = !saved;
notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}