Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

refactor: Create BaseInfoPage to eliminate code duplication

vishnukvmd1fe47117259f
diff --git a/mobile/apps/locker/lib/ui/pages/account_credentials_page.dart b/mobile/apps/locker/lib/ui/pages/account_credentials_page.dart
index ac6b75674a..19904d8726 100644
--- a/mobile/apps/locker/lib/ui/pages/account_credentials_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/account_credentials_page.dart
@@ -1,49 +1,33 @@
-import 'package:ente_ui/components/buttons/gradient_button.dart';
-import 'package:ente_ui/theme/ente_theme.dart';
import 'package:flutter/material.dart';
import 'package:locker/l10n/l10n.dart';
import 'package:locker/models/info/info_item.dart';
-import 'package:locker/services/collections/collections_service.dart';
-import 'package:locker/services/collections/models/collection.dart';
-import 'package:locker/services/info_file_service.dart';
-import 'package:locker/ui/components/collection_selection_widget.dart';
import 'package:locker/ui/components/form_text_input_widget.dart';
-import 'package:locker/ui/pages/home_page.dart';
+import 'package:locker/ui/pages/base_info_page.dart';
-class AccountCredentialsPage extends StatefulWidget {
- final AccountCredentialData? existingData;
-
- const AccountCredentialsPage({super.key, this.existingData});
+class AccountCredentialsPage extends BaseInfoPage<AccountCredentialData> {
+ const AccountCredentialsPage({super.key, super.existingData});
@override
State<AccountCredentialsPage> createState() => _AccountCredentialsPageState();
}
-class _AccountCredentialsPageState extends State<AccountCredentialsPage> {
+class _AccountCredentialsPageState
+ extends BaseInfoPageState<AccountCredentialData, AccountCredentialsPage> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _notesController = TextEditingController();
- final _formKey = GlobalKey<FormState>();
- bool _isLoading = false;
bool _passwordVisible = false;
- bool _showValidationErrors = false;
final _passwordFocusNode = FocusNode();
- bool _passwordInFocus = false;
-
- // Collection selection state
- List<Collection> _availableCollections = [];
- Set<int> _selectedCollectionIds = {};
@override
void initState() {
super.initState();
_passwordFocusNode.addListener(() {
setState(() {
- _passwordInFocus = _passwordFocusNode.hasFocus;
+ // Password focus state handling if needed
});
});
- _loadCollections();
_loadExistingData();
}
@@ -56,42 +40,6 @@ class _AccountCredentialsPageState extends State<AccountCredentialsPage> {
}
}
- Future<void> _loadCollections() async {
- try {
- final collections = await CollectionService.instance.getCollections();
- setState(() {
- _availableCollections = collections;
- // Pre-select a default collection if available
- if (collections.isNotEmpty) {
- final defaultCollection = collections.firstWhere(
- (c) => c.name == 'Information',
- orElse: () => collections.first,
- );
- _selectedCollectionIds = {defaultCollection.id};
- }
- });
- } catch (e) {
- // Handle error silently or show a message
- }
- }
-
- void _onToggleCollection(int collectionId) {
- setState(() {
- if (_selectedCollectionIds.contains(collectionId)) {
- _selectedCollectionIds.remove(collectionId);
- } else {
- // Allow multiple selections
- _selectedCollectionIds.add(collectionId);
- }
- });
- }
-
- void _onCollectionsUpdated(List<Collection> updatedCollections) {
- setState(() {
- _availableCollections = updatedCollections;
- });
- }
-
@override
void dispose() {
_nameController.dispose();
@@ -103,280 +51,91 @@ class _AccountCredentialsPageState extends State<AccountCredentialsPage> {
}
@override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text(
- context.l10n.accountCredentials,
- style: const TextStyle(fontWeight: FontWeight.bold),
- ),
- elevation: 0,
- backgroundColor: Theme.of(context).scaffoldBackgroundColor,
- foregroundColor: Theme.of(context).textTheme.bodyLarge?.color,
- ),
- body: Form(
- key: _formKey,
- child: Column(
- children: [
- Expanded(
- child: SingleChildScrollView(
- padding: const EdgeInsets.all(24),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- context.l10n.accountCredentialsDescription,
- style: getEnteTextTheme(context).body.copyWith(
- color: Colors.grey[600],
- ),
- ),
- const SizedBox(height: 32),
- FormTextInputWidget(
- controller: _nameController,
- labelText: context.l10n.credentialName,
- hintText: context.l10n.credentialNameHint,
- showValidationErrors: _showValidationErrors,
- validator: (value) {
- if (value == null || value.trim().isEmpty) {
- return context.l10n.pleaseEnterAccountName;
- }
- return null;
- },
- ),
- const SizedBox(height: 24),
- FormTextInputWidget(
- controller: _usernameController,
- labelText: context.l10n.username,
- hintText: context.l10n.usernameHint,
- showValidationErrors: _showValidationErrors,
- validator: (value) {
- if (value == null || value.trim().isEmpty) {
- return context.l10n.pleaseEnterUsername;
- }
- return null;
- },
- ),
- const SizedBox(height: 24),
- Text(context.l10n.password),
- const SizedBox(height: 4),
- Padding(
- padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
- child: TextFormField(
- controller: _passwordController,
- focusNode: _passwordFocusNode,
- obscureText: !_passwordVisible,
- keyboardType: TextInputType.visiblePassword,
- style: getEnteTextTheme(context).body,
- decoration: InputDecoration(
- fillColor: getEnteColorScheme(context).fillFaint,
- filled: true,
- hintText: context.l10n.passwordHint,
- hintStyle: getEnteTextTheme(context).body.copyWith(
- color: getEnteColorScheme(context).textMuted,
- ),
- contentPadding:
- const EdgeInsets.fromLTRB(16, 16, 16, 16),
- border: const UnderlineInputBorder(
- borderSide: BorderSide.none,
- ),
- enabledBorder: OutlineInputBorder(
- borderSide: BorderSide(
- color: getEnteColorScheme(context).strokeFaint,
- width: 1,
- ),
- borderRadius: BorderRadius.circular(8),
- ),
- focusedBorder: OutlineInputBorder(
- borderSide: BorderSide(
- color: getEnteColorScheme(context).primary500,
- width: 2,
- ),
- borderRadius: BorderRadius.circular(8),
- ),
- errorBorder: OutlineInputBorder(
- borderSide: BorderSide(
- color: getEnteColorScheme(context).warning500,
- width: 1,
- ),
- borderRadius: BorderRadius.circular(8),
- ),
- focusedErrorBorder: OutlineInputBorder(
- borderSide: BorderSide(
- color: getEnteColorScheme(context).warning500,
- width: 2,
- ),
- borderRadius: BorderRadius.circular(8),
- ),
- suffixIcon: _passwordInFocus
- ? IconButton(
- icon: Icon(
- _passwordVisible
- ? Icons.visibility
- : Icons.visibility_off,
- color: Theme.of(context).iconTheme.color,
- size: 20,
- ),
- onPressed: () {
- setState(() {
- _passwordVisible = !_passwordVisible;
- });
- },
- )
- : null,
- suffixIconConstraints: const BoxConstraints(
- maxHeight: 24,
- maxWidth: 48,
- minHeight: 24,
- minWidth: 48,
- ),
- ),
- validator: _showValidationErrors
- ? (value) {
- if (value == null || value.trim().isEmpty) {
- return context.l10n.pleaseEnterPassword;
- }
- return null;
- }
- : null,
- onChanged: (value) {
- if (_showValidationErrors) {
- setState(() {});
- }
- },
- ),
- ),
- const SizedBox(height: 24),
- FormTextInputWidget(
- controller: _notesController,
- labelText: context.l10n.credentialNotes,
- hintText: context.l10n.credentialNotesHint,
- maxLines: 5,
- showValidationErrors: _showValidationErrors,
- ),
- const SizedBox(height: 24),
- CollectionSelectionWidget(
- collections: _availableCollections,
- selectedCollectionIds: _selectedCollectionIds,
- onToggleCollection: _onToggleCollection,
- onCollectionsUpdated: _onCollectionsUpdated,
- ),
- ],
- ),
- ),
- ),
- Container(
- padding: const EdgeInsets.all(24),
- child: SizedBox(
- width: double.infinity,
- child: GradientButton(
- onTap: _isLoading ? null : _saveRecord,
- text: context.l10n.saveRecord,
- paddingValue: 16.0,
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }
-
- Future<void> _saveRecord() async {
- setState(() {
- _showValidationErrors = true;
- });
+ String get pageTitle => context.l10n.accountCredentials;
- if (!_formKey.currentState!.validate()) {
- return;
- }
-
- if (_selectedCollectionIds.isEmpty) {
- ScaffoldMessenger.of(context).showSnackBar(
- const SnackBar(
- content: Text('Please select at least one collection'),
- backgroundColor: Colors.red,
- ),
- );
- return;
- }
-
- setState(() {
- _isLoading = true;
- });
-
- try {
- // Create InfoItem for account credentials
- final credentialData = AccountCredentialData(
- name: _nameController.text.trim(),
- username: _usernameController.text.trim(),
- password: _passwordController.text.trim(),
- notes: _notesController.text.trim().isNotEmpty
- ? _notesController.text.trim()
- : null,
- );
-
- final infoItem = InfoItem(
- type: InfoType.accountCredential,
- data: credentialData,
- createdAt: DateTime.now(),
- );
-
- // Upload to all selected collections
- final selectedCollections = _availableCollections
- .where((c) => _selectedCollectionIds.contains(c.id))
- .toList();
-
- // Create and upload the info file to each selected collection
- for (final collection in selectedCollections) {
- await InfoFileService.instance.createAndUploadInfoFile(
- infoItem: infoItem,
- collection: collection,
- );
- }
+ @override
+ String get submitButtonText => context.l10n.saveRecord;
- // Trigger sync after successful save
- await CollectionService.instance.sync();
+ @override
+ InfoType get infoType => InfoType.accountCredential;
- if (mounted) {
- // Show success message
- final collectionCount = selectedCollections.length;
- final message = collectionCount == 1
- ? context.l10n.recordSavedSuccessfully
- : 'Record saved to $collectionCount collections successfully';
+ @override
+ bool validateForm() {
+ return _nameController.text.trim().isNotEmpty &&
+ _usernameController.text.trim().isNotEmpty &&
+ _passwordController.text.trim().isNotEmpty;
+ }
- // Navigate to home page and clear all previous routes
- await Navigator.of(context).pushAndRemoveUntil(
- MaterialPageRoute(builder: (context) => const HomePage()),
- (route) => false,
- );
+ @override
+ AccountCredentialData createInfoData() {
+ return AccountCredentialData(
+ name: _nameController.text.trim(),
+ username: _usernameController.text.trim(),
+ password: _passwordController.text.trim(),
+ notes: _notesController.text.trim().isEmpty
+ ? null
+ : _notesController.text.trim(),
+ );
+ }
- // Show success message after navigation
- Future.delayed(const Duration(milliseconds: 100), () {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text(message),
- backgroundColor: Colors.green,
- ),
- );
+ @override
+ List<Widget> buildFormFields() {
+ return [
+ const SizedBox(height: 20),
+ FormTextInputWidget(
+ labelText: context.l10n.credentialName,
+ hintText: context.l10n.credentialNameHint,
+ controller: _nameController,
+ validator: (value) {
+ if (value == null || value.trim().isEmpty) {
+ return context.l10n.pleaseEnterAccountName;
}
- });
- }
- } catch (e) {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text('${context.l10n.failedToSaveRecord}: $e'),
- backgroundColor: Colors.red,
+ return null;
+ },
+ ),
+ const SizedBox(height: 16),
+ FormTextInputWidget(
+ labelText: context.l10n.username,
+ hintText: context.l10n.usernameHint,
+ controller: _usernameController,
+ validator: (value) {
+ if (value == null || value.trim().isEmpty) {
+ return context.l10n.pleaseEnterUsername;
+ }
+ return null;
+ },
+ ),
+ const SizedBox(height: 16),
+ FormTextInputWidget(
+ labelText: context.l10n.password,
+ hintText: context.l10n.passwordHint,
+ controller: _passwordController,
+ obscureText: !_passwordVisible,
+ suffixIcon: IconButton(
+ icon: Icon(
+ _passwordVisible ? Icons.visibility : Icons.visibility_off,
),
- );
- }
- } finally {
- if (mounted) {
- setState(() {
- _isLoading = false;
- });
- }
- }
+ onPressed: () {
+ setState(() {
+ _passwordVisible = !_passwordVisible;
+ });
+ },
+ ),
+ validator: (value) {
+ if (value == null || value.trim().isEmpty) {
+ return context.l10n.pleaseEnterPassword;
+ }
+ return null;
+ },
+ ),
+ const SizedBox(height: 16),
+ FormTextInputWidget(
+ labelText: context.l10n.credentialNotes,
+ hintText: context.l10n.credentialNotesHint,
+ controller: _notesController,
+ maxLines: 3,
+ ),
+ const SizedBox(height: 24),
+ ];
}
}
diff --git a/mobile/apps/locker/lib/ui/pages/base_info_page.dart b/mobile/apps/locker/lib/ui/pages/base_info_page.dart
new file mode 100644
index 0000000000..ecff4d1d06
--- /dev/null
+++ b/mobile/apps/locker/lib/ui/pages/base_info_page.dart
@@ -0,0 +1,219 @@
+import 'package:ente_ui/components/buttons/gradient_button.dart';
+import 'package:ente_ui/theme/ente_theme.dart';
+import 'package:flutter/material.dart';
+import 'package:locker/l10n/l10n.dart';
+import 'package:locker/models/info/info_item.dart';
+import 'package:locker/services/collections/collections_service.dart';
+import 'package:locker/services/collections/models/collection.dart';
+import 'package:locker/services/info_file_service.dart';
+import 'package:locker/ui/components/collection_selection_widget.dart';
+import 'package:locker/ui/pages/home_page.dart';
+
+abstract class BaseInfoPage<T extends InfoData> extends StatefulWidget {
+ final T? existingData;
+
+ const BaseInfoPage({super.key, this.existingData});
+}
+
+abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
+ extends State<W> {
+ final _formKey = GlobalKey<FormState>();
+ bool _isLoading = false;
+
+ // Collection selection state
+ List<Collection> _availableCollections = [];
+ Set<int> _selectedCollectionIds = {};
+
+ // Abstract methods that subclasses must implement
+ String get pageTitle;
+ String get submitButtonText;
+ InfoType get infoType;
+ T createInfoData();
+ List<Widget> buildFormFields();
+ bool validateForm();
+
+ @override
+ void initState() {
+ super.initState();
+ _loadCollections();
+ loadExistingData();
+ }
+
+ void loadExistingData() {
+ // Override in subclasses if needed
+ }
+
+ Future<void> _loadCollections() async {
+ try {
+ final collections = await CollectionService.instance.getCollections();
+ setState(() {
+ _availableCollections = collections;
+ // Pre-select a default collection if available
+ if (collections.isNotEmpty) {
+ final defaultCollection = collections.firstWhere(
+ (c) => c.name == 'Information',
+ orElse: () => collections.first,
+ );
+ _selectedCollectionIds = {defaultCollection.id};
+ }
+ });
+ } catch (e) {
+ // Handle error silently or show a message
+ }
+ }
+
+ void _onToggleCollection(int collectionId) {
+ setState(() {
+ if (_selectedCollectionIds.contains(collectionId)) {
+ _selectedCollectionIds.remove(collectionId);
+ } else {
+ // Allow multiple selections
+ _selectedCollectionIds.add(collectionId);
+ }
+ });
+ }
+
+ void _onCollectionsUpdated(List<Collection> updatedCollections) {
+ setState(() {
+ _availableCollections = updatedCollections;
+ });
+ }
+
+ Future<void> _saveRecord() async {
+ if (!_formKey.currentState!.validate() || !validateForm()) {
+ return;
+ }
+
+ if (_selectedCollectionIds.isEmpty) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(
+ content: Text('Please select at least one collection'),
+ backgroundColor: Colors.red,
+ ),
+ );
+ return;
+ }
+
+ setState(() {
+ _isLoading = true;
+ });
+
+ try {
+ // Create InfoItem using the subclass implementation
+ final infoData = createInfoData();
+ final infoItem = InfoItem(
+ type: infoType,
+ data: infoData,
+ createdAt: DateTime.now(),
+ );
+
+ // Upload to all selected collections
+ final selectedCollections = _availableCollections
+ .where((c) => _selectedCollectionIds.contains(c.id))
+ .toList();
+
+ // Create and upload the info file to each selected collection
+ for (final collection in selectedCollections) {
+ await InfoFileService.instance.createAndUploadInfoFile(
+ infoItem: infoItem,
+ collection: collection,
+ );
+ }
+
+ // Trigger sync after successful save
+ await CollectionService.instance.sync();
+
+ if (mounted) {
+ // Show success message
+ final collectionCount = selectedCollections.length;
+ final message = collectionCount == 1
+ ? context.l10n.recordSavedSuccessfully
+ : 'Record saved to $collectionCount collections successfully';
+
+ // Navigate to home page and clear all previous routes
+ await Navigator.of(context).pushAndRemoveUntil(
+ MaterialPageRoute(builder: (context) => const HomePage()),
+ (route) => false,
+ );
+
+ // Show success message after navigation
+ Future.delayed(const Duration(milliseconds: 100), () {
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(
+ content: Text(message),
+ backgroundColor: Colors.green,
+ ),
+ );
+ }
+ });
+ }
+ } catch (e) {
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(
+ content: Text('${context.l10n.failedToSaveRecord}: $e'),
+ backgroundColor: Colors.red,
+ ),
+ );
+ }
+ } finally {
+ if (mounted) {
+ setState(() {
+ _isLoading = false;
+ });
+ }
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(
+ title: Text(pageTitle),
+ ),
+ body: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 20.0),
+ child: Form(
+ key: _formKey,
+ child: Column(
+ children: [
+ Expanded(
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Form fields implemented by subclass
+ ...buildFormFields(),
+ const SizedBox(height: 24),
+ // Collection selection
+ Text(
+ 'Select collections',
+ style: getEnteTextTheme(context).body,
+ ),
+ const SizedBox(height: 12),
+ CollectionSelectionWidget(
+ collections: _availableCollections,
+ selectedCollectionIds: _selectedCollectionIds,
+ onToggleCollection: _onToggleCollection,
+ onCollectionsUpdated: _onCollectionsUpdated,
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 20),
+ SizedBox(
+ width: double.infinity,
+ child: GradientButton(
+ onTap: _isLoading ? null : _saveRecord,
+ text: _isLoading ? context.l10n.pleaseWait : submitButtonText,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/locker/lib/ui/pages/emergency_contact_page.dart b/mobile/apps/locker/lib/ui/pages/emergency_contact_page.dart
index 50f7c859be..f831838896 100644
--- a/mobile/apps/locker/lib/ui/pages/emergency_contact_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/emergency_contact_page.dart
@@ -1,41 +1,26 @@
-import 'package:ente_ui/components/buttons/gradient_button.dart';
-import 'package:ente_ui/theme/ente_theme.dart';
import 'package:flutter/material.dart';
import 'package:locker/l10n/l10n.dart';
import 'package:locker/models/info/info_item.dart';
-import 'package:locker/services/collections/collections_service.dart';
-import 'package:locker/services/collections/models/collection.dart';
-import 'package:locker/services/info_file_service.dart';
-import 'package:locker/ui/components/collection_selection_widget.dart';
import 'package:locker/ui/components/form_text_input_widget.dart';
-import 'package:locker/ui/pages/home_page.dart';
+import 'package:locker/ui/pages/base_info_page.dart';
-class EmergencyContactPage extends StatefulWidget {
- final EmergencyContactData? existingData;
-
- const EmergencyContactPage({super.key, this.existingData});
+class EmergencyContactPage extends BaseInfoPage<EmergencyContactData> {
+ const EmergencyContactPage({super.key, super.existingData});
@override
State<EmergencyContactPage> createState() => _EmergencyContactPageState();
}
-class _EmergencyContactPageState extends State<EmergencyContactPage> {
+class _EmergencyContactPageState
+ extends BaseInfoPageState<EmergencyContactData, EmergencyContactPage> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _contactDetailsController =
TextEditingController();
final TextEditingController _notesController = TextEditingController();
- final _formKey = GlobalKey<FormState>();
- bool _isLoading = false;
- bool _showValidationErrors = false;
-
- // Collection selection state
- List<Collection> _availableCollections = [];
- Set<int> _selectedCollectionIds = {};
@override
void initState() {
super.initState();
- _loadCollections();
_loadExistingData();
}
@@ -47,42 +32,6 @@ class _EmergencyContactPageState extends State<EmergencyContactPage> {
}
}
- Future<void> _loadCollections() async {
- try {
- final collections = await CollectionService.instance.getCollections();
- setState(() {
- _availableCollections = collections;
- // Pre-select a default collection if available
- if (collections.isNotEmpty) {
- final defaultCollection = collections.firstWhere(
- (c) => c.name == 'Information',
- orElse: () => collections.first,
- );
- _selectedCollectionIds = {defaultCollection.id};
- }
- });
- } catch (e) {
- // Handle error silently or show a message
- }
- }
-
- void _onToggleCollection(int collectionId) {
- setState(() {
- if (_selectedCollectionIds.contains(collectionId)) {
- _selectedCollectionIds.remove(collectionId);
- } else {
- // Allow multiple selections
- _selectedCollectionIds.add(collectionId);
- }
- });
- }
-
- void _onCollectionsUpdated(List<Collection> updatedCollections) {
- setState(() {
- _availableCollections = updatedCollections;
- });
- }
-
@override
void dispose() {
_nameController.dispose();
@@ -92,191 +41,66 @@ class _EmergencyContactPageState extends State<EmergencyContactPage> {
}
@override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text(
- context.l10n.emergencyContact,
- style: const TextStyle(fontWeight: FontWeight.bold),
- ),
- elevation: 0,
- backgroundColor: Theme.of(context).scaffoldBackgroundColor,
- foregroundColor: Theme.of(context).textTheme.bodyLarge?.color,
- ),
- body: Form(
- key: _formKey,
- child: Column(
- children: [
- Expanded(
- child: SingleChildScrollView(
- padding: const EdgeInsets.all(24),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- context.l10n.emergencyContactDescription,
- style: getEnteTextTheme(context).body.copyWith(
- color: Colors.grey[600],
- ),
- ),
- const SizedBox(height: 32),
- FormTextInputWidget(
- controller: _nameController,
- labelText: context.l10n.contactName,
- hintText: context.l10n.contactNameHint,
- showValidationErrors: _showValidationErrors,
- validator: (value) {
- if (value == null || value.trim().isEmpty) {
- return context.l10n.pleaseEnterContactName;
- }
- return null;
- },
- ),
- const SizedBox(height: 24),
- FormTextInputWidget(
- controller: _contactDetailsController,
- labelText: context.l10n.contactDetails,
- hintText: context.l10n.contactDetailsHint,
- maxLines: 3,
- showValidationErrors: _showValidationErrors,
- validator: (value) {
- if (value == null || value.trim().isEmpty) {
- return context.l10n.pleaseEnterContactDetails;
- }
- return null;
- },
- ),
- const SizedBox(height: 24),
- FormTextInputWidget(
- controller: _notesController,
- labelText: context.l10n.contactNotes,
- hintText: context.l10n.contactNotesHint,
- maxLines: 4,
- showValidationErrors: _showValidationErrors,
- ),
- const SizedBox(height: 24),
- CollectionSelectionWidget(
- collections: _availableCollections,
- selectedCollectionIds: _selectedCollectionIds,
- onToggleCollection: _onToggleCollection,
- onCollectionsUpdated: _onCollectionsUpdated,
- ),
- ],
- ),
- ),
- ),
- Container(
- padding: const EdgeInsets.all(24),
- child: SizedBox(
- width: double.infinity,
- child: GradientButton(
- onTap: _isLoading ? null : _saveRecord,
- text: context.l10n.saveRecord,
- paddingValue: 16.0,
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }
-
- Future<void> _saveRecord() async {
- setState(() {
- _showValidationErrors = true;
- });
-
- if (!_formKey.currentState!.validate()) {
- return;
- }
-
- if (_selectedCollectionIds.isEmpty) {
- ScaffoldMessenger.of(context).showSnackBar(
- const SnackBar(
- content: Text('Please select at least one collection'),
- backgroundColor: Colors.red,
- ),
- );
- return;
- }
+ String get pageTitle => context.l10n.emergencyContact;
- setState(() {
- _isLoading = true;
- });
-
- try {
- // Create InfoItem for emergency contact
- final contactData = EmergencyContactData(
- name: _nameController.text.trim(),
- contactDetails: _contactDetailsController.text.trim(),
- notes: _notesController.text.trim().isNotEmpty
- ? _notesController.text.trim()
- : null,
- );
-
- final infoItem = InfoItem(
- type: InfoType.emergencyContact,
- data: contactData,
- createdAt: DateTime.now(),
- );
-
- // Upload to all selected collections
- final selectedCollections = _availableCollections
- .where((c) => _selectedCollectionIds.contains(c.id))
- .toList();
-
- // Create and upload the info file to each selected collection
- for (final collection in selectedCollections) {
- await InfoFileService.instance.createAndUploadInfoFile(
- infoItem: infoItem,
- collection: collection,
- );
- }
+ @override
+ String get submitButtonText => context.l10n.saveRecord;
- // Trigger sync after successful save
- await CollectionService.instance.sync();
+ @override
+ InfoType get infoType => InfoType.emergencyContact;
- if (mounted) {
- // Show success message
- final collectionCount = selectedCollections.length;
- final message = collectionCount == 1
- ? context.l10n.recordSavedSuccessfully
- : 'Record saved to $collectionCount collections successfully';
+ @override
+ bool validateForm() {
+ return _nameController.text.trim().isNotEmpty &&
+ _contactDetailsController.text.trim().isNotEmpty;
+ }
- // Navigate to home page and clear all previous routes
- await Navigator.of(context).pushAndRemoveUntil(
- MaterialPageRoute(builder: (context) => const HomePage()),
- (route) => false,
- );
+ @override
+ EmergencyContactData createInfoData() {
+ return EmergencyContactData(
+ name: _nameController.text.trim(),
+ contactDetails: _contactDetailsController.text.trim(),
+ notes: _notesController.text.trim().isEmpty
+ ? null
+ : _notesController.text.trim(),
+ );
+ }
- // Show success message after navigation
- Future.delayed(const Duration(milliseconds: 100), () {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text(message),
- backgroundColor: Colors.green,
- ),
- );
+ @override
+ List<Widget> buildFormFields() {
+ return [
+ const SizedBox(height: 20),
+ FormTextInputWidget(
+ labelText: context.l10n.contactName,
+ hintText: context.l10n.contactNameHint,
+ controller: _nameController,
+ validator: (value) {
+ if (value == null || value.trim().isEmpty) {
+ return context.l10n.pleaseEnterContactName;
}
- });
- }
- } catch (e) {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text('${context.l10n.failedToSaveRecord}: $e'),
- backgroundColor: Colors.red,
- ),
- );
- }
- } finally {
- if (mounted) {
- setState(() {
- _isLoading = false;
- });
- }
- }
+ return null;
+ },
+ ),
+ const SizedBox(height: 16),
+ FormTextInputWidget(
+ labelText: context.l10n.contactDetails,
+ hintText: context.l10n.contactDetailsHint,
+ controller: _contactDetailsController,
+ validator: (value) {
+ if (value == null || value.trim().isEmpty) {
+ return context.l10n.pleaseEnterContactDetails;
+ }
+ return null;
+ },
+ ),
+ const SizedBox(height: 16),
+ FormTextInputWidget(
+ labelText: context.l10n.contactNotes,
+ hintText: context.l10n.contactNotesHint,
+ controller: _notesController,
+ maxLines: 3,
+ ),
+ const SizedBox(height: 24),
+ ];
}
}
diff --git a/mobile/apps/locker/lib/ui/pages/personal_note_page.dart b/mobile/apps/locker/lib/ui/pages/personal_note_page.dart
index 79784249e2..155fb172f4 100644
--- a/mobile/apps/locker/lib/ui/pages/personal_note_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/personal_note_page.dart
@@ -1,39 +1,24 @@
-import 'package:ente_ui/components/buttons/gradient_button.dart';
-import 'package:ente_ui/theme/ente_theme.dart';
import 'package:flutter/material.dart';
import 'package:locker/l10n/l10n.dart';
import 'package:locker/models/info/info_item.dart';
-import 'package:locker/services/collections/collections_service.dart';
-import 'package:locker/services/collections/models/collection.dart';
-import 'package:locker/services/info_file_service.dart';
-import 'package:locker/ui/components/collection_selection_widget.dart';
import 'package:locker/ui/components/form_text_input_widget.dart';
-import 'package:locker/ui/pages/home_page.dart';
+import 'package:locker/ui/pages/base_info_page.dart';
-class PersonalNotePage extends StatefulWidget {
- final PersonalNoteData? existingData;
-
- const PersonalNotePage({super.key, this.existingData});
+class PersonalNotePage extends BaseInfoPage<PersonalNoteData> {
+ const PersonalNotePage({super.key, super.existingData});
@override
State<PersonalNotePage> createState() => _PersonalNotePageState();
}
-class _PersonalNotePageState extends State<PersonalNotePage> {
+class _PersonalNotePageState
+ extends BaseInfoPageState<PersonalNoteData, PersonalNotePage> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _contentController = TextEditingController();
- final _formKey = GlobalKey<FormState>();
- bool _isLoading = false;
- bool _showValidationErrors = false;
-
- // Collection selection state
- List<Collection> _availableCollections = [];
- Set<int> _selectedCollectionIds = {};
@override
void initState() {
super.initState();
- _loadCollections();
_loadExistingData();
}
@@ -44,42 +29,6 @@ class _PersonalNotePageState extends State<PersonalNotePage> {
}
}
- Future<void> _loadCollections() async {
- try {
- final collections = await CollectionService.instance.getCollections();
- setState(() {
- _availableCollections = collections;
- // Pre-select a default collection if available
- if (collections.isNotEmpty) {
- final defaultCollection = collections.firstWhere(
- (c) => c.name == 'Information',
- orElse: () => collections.first,
- );
- _selectedCollectionIds = {defaultCollection.id};
- }
- });
- } catch (e) {
- // Handle error silently or show a message
- }
- }
-
- void _onToggleCollection(int collectionId) {
- setState(() {
- if (_selectedCollectionIds.contains(collectionId)) {
- _selectedCollectionIds.remove(collectionId);
- } else {
- // Allow multiple selections
- _selectedCollectionIds.add(collectionId);
- }
- });
- }
-
- void _onCollectionsUpdated(List<Collection> updatedCollections) {
- setState(() {
- _availableCollections = updatedCollections;
- });
- }
-
@override
void dispose() {
_nameController.dispose();
@@ -88,180 +37,57 @@ class _PersonalNotePageState extends State<PersonalNotePage> {
}
@override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text(
- context.l10n.personalNote,
- style: const TextStyle(fontWeight: FontWeight.bold),
- ),
- elevation: 0,
- backgroundColor: Theme.of(context).scaffoldBackgroundColor,
- foregroundColor: Theme.of(context).textTheme.bodyLarge?.color,
- ),
- body: Form(
- key: _formKey,
- child: Column(
- children: [
- Expanded(
- child: SingleChildScrollView(
- padding: const EdgeInsets.all(24),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- context.l10n.personalNoteDescription,
- style: getEnteTextTheme(context).body.copyWith(
- color: Colors.grey[600],
- ),
- ),
- const SizedBox(height: 32),
- FormTextInputWidget(
- controller: _nameController,
- labelText: context.l10n.noteName,
- hintText: context.l10n.noteNameHint,
- showValidationErrors: _showValidationErrors,
- validator: (value) {
- if (value == null || value.trim().isEmpty) {
- return context.l10n.pleaseEnterNoteName;
- }
- return null;
- },
- ),
- const SizedBox(height: 24),
- FormTextInputWidget(
- controller: _contentController,
- labelText: context.l10n.noteContent,
- hintText: context.l10n.noteContentHint,
- maxLines: 6,
- showValidationErrors: _showValidationErrors,
- validator: (value) {
- if (value == null || value.trim().isEmpty) {
- return context.l10n.pleaseEnterNoteContent;
- }
- return null;
- },
- ),
- const SizedBox(height: 24),
- CollectionSelectionWidget(
- collections: _availableCollections,
- selectedCollectionIds: _selectedCollectionIds,
- onToggleCollection: _onToggleCollection,
- onCollectionsUpdated: _onCollectionsUpdated,
- ),
- ],
- ),
- ),
- ),
- Container(
- padding: const EdgeInsets.all(24),
- child: SizedBox(
- width: double.infinity,
- child: GradientButton(
- onTap: _isLoading ? null : _saveRecord,
- text: context.l10n.saveRecord,
- paddingValue: 16.0,
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }
-
- Future<void> _saveRecord() async {
- setState(() {
- _showValidationErrors = true;
- });
-
- if (!_formKey.currentState!.validate()) {
- return;
- }
-
- if (_selectedCollectionIds.isEmpty) {
- ScaffoldMessenger.of(context).showSnackBar(
- const SnackBar(
- content: Text('Please select at least one collection'),
- backgroundColor: Colors.red,
- ),
- );
- return;
- }
-
- setState(() {
- _isLoading = true;
- });
-
- try {
- // Create InfoItem for personal note
- final noteData = PersonalNoteData(
- title: _nameController.text.trim(),
- content: _contentController.text.trim(),
- );
-
- final infoItem = InfoItem(
- type: InfoType.note,
- data: noteData,
- createdAt: DateTime.now(),
- );
-
- // Upload to all selected collections
- final selectedCollections = _availableCollections
- .where((c) => _selectedCollectionIds.contains(c.id))
- .toList();
+ String get pageTitle => context.l10n.personalNote;
- // Create and upload the info file to each selected collection
- for (final collection in selectedCollections) {
- await InfoFileService.instance.createAndUploadInfoFile(
- infoItem: infoItem,
- collection: collection,
- );
- }
+ @override
+ String get submitButtonText => context.l10n.saveRecord;
- // Trigger sync after successful save
- await CollectionService.instance.sync();
+ @override
+ InfoType get infoType => InfoType.note;
- if (mounted) {
- // Show success message
- final collectionCount = selectedCollections.length;
- final message = collectionCount == 1
- ? context.l10n.recordSavedSuccessfully
- : 'Record saved to $collectionCount collections successfully';
+ @override
+ bool validateForm() {
+ return _nameController.text.trim().isNotEmpty &&
+ _contentController.text.trim().isNotEmpty;
+ }
- // Navigate to home page and clear all previous routes
- await Navigator.of(context).pushAndRemoveUntil(
- MaterialPageRoute(builder: (context) => const HomePage()),
- (route) => false,
- );
+ @override
+ PersonalNoteData createInfoData() {
+ return PersonalNoteData(
+ title: _nameController.text.trim(),
+ content: _contentController.text.trim(),
+ );
+ }
- // Show success message after navigation
- Future.delayed(const Duration(milliseconds: 100), () {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text(message),
- backgroundColor: Colors.green,
- ),
- );
+ @override
+ List<Widget> buildFormFields() {
+ return [
+ const SizedBox(height: 20),
+ FormTextInputWidget(
+ labelText: context.l10n.noteName,
+ hintText: context.l10n.noteNameHint,
+ controller: _nameController,
+ validator: (value) {
+ if (value == null || value.trim().isEmpty) {
+ return context.l10n.pleaseEnterNoteName;
}
- });
- }
- } catch (e) {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text('${context.l10n.failedToSaveRecord}: $e'),
- backgroundColor: Colors.red,
- ),
- );
- }
- } finally {
- if (mounted) {
- setState(() {
- _isLoading = false;
- });
- }
- }
+ return null;
+ },
+ ),
+ const SizedBox(height: 16),
+ FormTextInputWidget(
+ labelText: context.l10n.noteContent,
+ hintText: context.l10n.noteContentHint,
+ controller: _contentController,
+ maxLines: 5,
+ validator: (value) {
+ if (value == null || value.trim().isEmpty) {
+ return context.l10n.pleaseEnterNoteContent;
+ }
+ return null;
+ },
+ ),
+ const SizedBox(height: 24),
+ ];
}
}
diff --git a/mobile/apps/locker/lib/ui/pages/physical_records_page.dart b/mobile/apps/locker/lib/ui/pages/physical_records_page.dart
index 6047138236..c9f0e428c5 100644
--- a/mobile/apps/locker/lib/ui/pages/physical_records_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/physical_records_page.dart
@@ -1,40 +1,25 @@
-import 'package:ente_ui/components/buttons/gradient_button.dart';
-import 'package:ente_ui/theme/ente_theme.dart';
import 'package:flutter/material.dart';
import 'package:locker/l10n/l10n.dart';
import 'package:locker/models/info/info_item.dart';
-import 'package:locker/services/collections/collections_service.dart';
-import 'package:locker/services/collections/models/collection.dart';
-import 'package:locker/services/info_file_service.dart';
-import 'package:locker/ui/components/collection_selection_widget.dart';
import 'package:locker/ui/components/form_text_input_widget.dart';
-import 'package:locker/ui/pages/home_page.dart';
+import 'package:locker/ui/pages/base_info_page.dart';
-class PhysicalRecordsPage extends StatefulWidget {
- final PhysicalRecordData? existingData;
-
- const PhysicalRecordsPage({super.key, this.existingData});
+class PhysicalRecordsPage extends BaseInfoPage<PhysicalRecordData> {
+ const PhysicalRecordsPage({super.key, super.existingData});
@override
State<PhysicalRecordsPage> createState() => _PhysicalRecordsPageState();
}
-class _PhysicalRecordsPageState extends State<PhysicalRecordsPage> {
+class _PhysicalRecordsPageState
+ extends BaseInfoPageState<PhysicalRecordData, PhysicalRecordsPage> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _locationController = TextEditingController();
final TextEditingController _notesController = TextEditingController();
- final _formKey = GlobalKey<FormState>();
- bool _isLoading = false;
- bool _showValidationErrors = false;
-
- // Collection selection state
- List<Collection> _availableCollections = [];
- Set<int> _selectedCollectionIds = {};
@override
void initState() {
super.initState();
- _loadCollections();
_loadExistingData();
}
@@ -46,42 +31,6 @@ class _PhysicalRecordsPageState extends State<PhysicalRecordsPage> {
}
}
- Future<void> _loadCollections() async {
- try {
- final collections = await CollectionService.instance.getCollections();
- setState(() {
- _availableCollections = collections;
- // Pre-select a default collection if available
- if (collections.isNotEmpty) {
- final defaultCollection = collections.firstWhere(
- (c) => c.name == 'Information',
- orElse: () => collections.first,
- );
- _selectedCollectionIds = {defaultCollection.id};
- }
- });
- } catch (e) {
- // Handle error silently or show a message
- }
- }
-
- void _onToggleCollection(int collectionId) {
- setState(() {
- if (_selectedCollectionIds.contains(collectionId)) {
- _selectedCollectionIds.remove(collectionId);
- } else {
- // Allow multiple selections
- _selectedCollectionIds.add(collectionId);
- }
- });
- }
-
- void _onCollectionsUpdated(List<Collection> updatedCollections) {
- setState(() {
- _availableCollections = updatedCollections;
- });
- }
-
@override
void dispose() {
_nameController.dispose();
@@ -91,191 +40,66 @@ class _PhysicalRecordsPageState extends State<PhysicalRecordsPage> {
}
@override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text(
- context.l10n.physicalRecords,
- style: const TextStyle(fontWeight: FontWeight.bold),
- ),
- elevation: 0,
- backgroundColor: Theme.of(context).scaffoldBackgroundColor,
- foregroundColor: Theme.of(context).textTheme.bodyLarge?.color,
- ),
- body: Form(
- key: _formKey,
- child: Column(
- children: [
- Expanded(
- child: SingleChildScrollView(
- padding: const EdgeInsets.all(24),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- context.l10n.physicalRecordsDescription,
- style: getEnteTextTheme(context).body.copyWith(
- color: Colors.grey[600],
- ),
- ),
- const SizedBox(height: 32),
- FormTextInputWidget(
- controller: _nameController,
- labelText: context.l10n.recordName,
- hintText: context.l10n.recordNameHint,
- showValidationErrors: _showValidationErrors,
- validator: (value) {
- if (value == null || value.trim().isEmpty) {
- return context.l10n.pleaseEnterRecordName;
- }
- return null;
- },
- ),
- const SizedBox(height: 24),
- FormTextInputWidget(
- controller: _locationController,
- labelText: context.l10n.recordLocation,
- hintText: context.l10n.recordLocationHint,
- maxLines: 3,
- showValidationErrors: _showValidationErrors,
- validator: (value) {
- if (value == null || value.trim().isEmpty) {
- return context.l10n.pleaseEnterLocation;
- }
- return null;
- },
- ),
- const SizedBox(height: 24),
- FormTextInputWidget(
- controller: _notesController,
- labelText: context.l10n.recordNotes,
- hintText: context.l10n.recordNotesHint,
- maxLines: 5,
- showValidationErrors: _showValidationErrors,
- ),
- const SizedBox(height: 24),
- CollectionSelectionWidget(
- collections: _availableCollections,
- selectedCollectionIds: _selectedCollectionIds,
- onToggleCollection: _onToggleCollection,
- onCollectionsUpdated: _onCollectionsUpdated,
- ),
- ],
- ),
- ),
- ),
- Container(
- padding: const EdgeInsets.all(24),
- child: SizedBox(
- width: double.infinity,
- child: GradientButton(
- onTap: _isLoading ? null : _saveRecord,
- text: context.l10n.saveRecord,
- paddingValue: 16.0,
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }
-
- Future<void> _saveRecord() async {
- setState(() {
- _showValidationErrors = true;
- });
-
- if (!_formKey.currentState!.validate()) {
- return;
- }
-
- if (_selectedCollectionIds.isEmpty) {
- ScaffoldMessenger.of(context).showSnackBar(
- const SnackBar(
- content: Text('Please select at least one collection'),
- backgroundColor: Colors.red,
- ),
- );
- return;
- }
+ String get pageTitle => context.l10n.physicalRecords;
- setState(() {
- _isLoading = true;
- });
-
- try {
- // Create InfoItem for physical record
- final recordData = PhysicalRecordData(
- name: _nameController.text.trim(),
- location: _locationController.text.trim(),
- notes: _notesController.text.trim().isNotEmpty
- ? _notesController.text.trim()
- : null,
- );
-
- final infoItem = InfoItem(
- type: InfoType.physicalRecord,
- data: recordData,
- createdAt: DateTime.now(),
- );
-
- // Upload to all selected collections
- final selectedCollections = _availableCollections
- .where((c) => _selectedCollectionIds.contains(c.id))
- .toList();
-
- // Create and upload the info file to each selected collection
- for (final collection in selectedCollections) {
- await InfoFileService.instance.createAndUploadInfoFile(
- infoItem: infoItem,
- collection: collection,
- );
- }
+ @override
+ String get submitButtonText => context.l10n.saveRecord;
- // Trigger sync after successful save
- await CollectionService.instance.sync();
+ @override
+ InfoType get infoType => InfoType.physicalRecord;
- if (mounted) {
- // Show success message
- final collectionCount = selectedCollections.length;
- final message = collectionCount == 1
- ? context.l10n.recordSavedSuccessfully
- : 'Record saved to $collectionCount collections successfully';
+ @override
+ bool validateForm() {
+ return _nameController.text.trim().isNotEmpty &&
+ _locationController.text.trim().isNotEmpty;
+ }
- // Navigate to home page and clear all previous routes
- await Navigator.of(context).pushAndRemoveUntil(
- MaterialPageRoute(builder: (context) => const HomePage()),
- (route) => false,
- );
+ @override
+ PhysicalRecordData createInfoData() {
+ return PhysicalRecordData(
+ name: _nameController.text.trim(),
+ location: _locationController.text.trim(),
+ notes: _notesController.text.trim().isEmpty
+ ? null
+ : _notesController.text.trim(),
+ );
+ }
- // Show success message after navigation
- Future.delayed(const Duration(milliseconds: 100), () {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text(message),
- backgroundColor: Colors.green,
- ),
- );
+ @override
+ List<Widget> buildFormFields() {
+ return [
+ const SizedBox(height: 20),
+ FormTextInputWidget(
+ labelText: context.l10n.recordName,
+ hintText: context.l10n.recordNameHint,
+ controller: _nameController,
+ validator: (value) {
+ if (value == null || value.trim().isEmpty) {
+ return context.l10n.pleaseEnterRecordName;
}
- });
- }
- } catch (e) {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text('${context.l10n.failedToSaveRecord}: $e'),
- backgroundColor: Colors.red,
- ),
- );
- }
- } finally {
- if (mounted) {
- setState(() {
- _isLoading = false;
- });
- }
- }
+ return null;
+ },
+ ),
+ const SizedBox(height: 16),
+ FormTextInputWidget(
+ labelText: context.l10n.recordLocation,
+ hintText: context.l10n.recordLocationHint,
+ controller: _locationController,
+ validator: (value) {
+ if (value == null || value.trim().isEmpty) {
+ return context.l10n.pleaseEnterLocation;
+ }
+ return null;
+ },
+ ),
+ const SizedBox(height: 16),
+ FormTextInputWidget(
+ labelText: context.l10n.recordNotes,
+ hintText: context.l10n.recordNotesHint,
+ controller: _notesController,
+ maxLines: 3,
+ ),
+ const SizedBox(height: 24),
+ ];
}
}