Compare commits

..

2 Commits

3 changed files with 369 additions and 108 deletions
+40 -5
View File
@@ -19,6 +19,7 @@ import 'package:notas/widgets/app_title_bar.dart';
import 'package:notas/widgets/sync_status_indicator.dart'; import 'package:notas/widgets/sync_status_indicator.dart';
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:window_manager/window_manager.dart'; import 'package:window_manager/window_manager.dart';
enum _AppSection { enum _AppSection {
@@ -50,6 +51,7 @@ class _NotesAppState extends State<NotesApp>
static const Duration _screenTransitionDuration = Duration(milliseconds: 280); static const Duration _screenTransitionDuration = Duration(milliseconds: 280);
static const Duration _biometricInactivityTimeout = Duration(minutes: 5); static const Duration _biometricInactivityTimeout = Duration(minutes: 5);
static const Duration _syncInterval = Duration(minutes: 5); static const Duration _syncInterval = Duration(minutes: 5);
static const String _themeSeedColorKey = 'theme_seed_color_v1';
final LocalVaultService _vaultService = LocalVaultService.instance; final LocalVaultService _vaultService = LocalVaultService.instance;
final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey =
@@ -71,6 +73,7 @@ class _NotesAppState extends State<NotesApp>
SyncStatus _syncStatus = SyncStatus.idle; SyncStatus _syncStatus = SyncStatus.idle;
String? _syncErrorMessage; String? _syncErrorMessage;
int _homeRefreshToken = 0; int _homeRefreshToken = 0;
Color _themeSeedColor = Colors.amber;
@override @override
void initState() { void initState() {
@@ -80,6 +83,7 @@ class _NotesAppState extends State<NotesApp>
windowManager.addListener(this); windowManager.addListener(this);
windowManager.setPreventClose(true); windowManager.setPreventClose(true);
} }
_loadThemeSeedColor();
_bootstrapVault(); _bootstrapVault();
} }
@@ -96,6 +100,33 @@ class _NotesAppState extends State<NotesApp>
super.dispose(); super.dispose();
} }
Future<void> _loadThemeSeedColor() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final int? storedColorValue = prefs.getInt(_themeSeedColorKey);
if (storedColorValue == null || !mounted) {
return;
}
setState(() {
_themeSeedColor = Color(storedColorValue);
});
}
Future<void> _setThemeSeedColor(Color color) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt(_themeSeedColorKey, color.value);
if (!mounted) {
return;
}
setState(() {
_themeSeedColor = color;
});
}
ThemeData get _theme => AppTheme.theme(seedColor: _themeSeedColor);
@override @override
void didChangeAppLifecycleState(AppLifecycleState state) { void didChangeAppLifecycleState(AppLifecycleState state) {
if (_isUnlocking) { if (_isUnlocking) {
@@ -202,8 +233,9 @@ class _NotesAppState extends State<NotesApp>
// Start periodic sync // Start periodic sync
_startPeriodicSync(); _startPeriodicSync();
// Run an initial full sync immediately to pull server changes // Run an initial sync immediately and let the repository use the
unawaited(_performSync(forceFull: true)); // stored lastSyncAt when it exists.
unawaited(_performSync());
} catch (e) { } catch (e) {
// If the database file is not a valid SQLite DB (e.g., wrong key or corruption), // If the database file is not a valid SQLite DB (e.g., wrong key or corruption),
// reset the local vault so the app doesn't crash. The reset will delete DB files // reset the local vault so the app doesn't crash. The reset will delete DB files
@@ -668,7 +700,7 @@ class _NotesAppState extends State<NotesApp>
navigatorKey: _navigatorKey, navigatorKey: _navigatorKey,
title: 'Mis Notas', title: 'Mis Notas',
debugShowCheckedModeBanner: false, debugShowCheckedModeBanner: false,
theme: AppTheme.theme, theme: _theme,
home: const Scaffold( home: const Scaffold(
body: SafeArea( body: SafeArea(
child: Column( child: Column(
@@ -699,7 +731,7 @@ class _NotesAppState extends State<NotesApp>
title: 'Mis Notas', title: 'Mis Notas',
debugShowCheckedModeBanner: false, debugShowCheckedModeBanner: false,
scaffoldMessengerKey: _scaffoldMessengerKey, scaffoldMessengerKey: _scaffoldMessengerKey,
theme: AppTheme.theme, theme: _theme,
home: home, home: home,
); );
} }
@@ -720,6 +752,9 @@ class _NotesAppState extends State<NotesApp>
key: const ValueKey<String>('settings-screen'), key: const ValueKey<String>('settings-screen'),
onDeleteAllData: _resetLocalVaultData, onDeleteAllData: _resetLocalVaultData,
onBackToHome: _openHome, onBackToHome: _openHome,
onForceSync: () => _performSync(forceFull: true),
currentSeedColor: _themeSeedColor,
onThemeColorSelected: _setThemeSeedColor,
); );
return MaterialApp( return MaterialApp(
@@ -727,7 +762,7 @@ class _NotesAppState extends State<NotesApp>
title: 'Mis Notas', title: 'Mis Notas',
debugShowCheckedModeBanner: false, debugShowCheckedModeBanner: false,
scaffoldMessengerKey: _scaffoldMessengerKey, scaffoldMessengerKey: _scaffoldMessengerKey,
theme: AppTheme.theme, theme: _theme,
home: Shortcuts( home: Shortcuts(
shortcuts: <LogicalKeySet, Intent>{ shortcuts: <LogicalKeySet, Intent>{
LogicalKeySet(LogicalKeyboardKey.f5): const PerformSyncIntent(), LogicalKeySet(LogicalKeyboardKey.f5): const PerformSyncIntent(),
+319 -98
View File
@@ -8,10 +8,16 @@ class SettingsScreen extends StatefulWidget {
super.key, super.key,
required this.onDeleteAllData, required this.onDeleteAllData,
required this.onBackToHome, required this.onBackToHome,
required this.onForceSync,
required this.currentSeedColor,
required this.onThemeColorSelected,
}); });
final Future<void> Function() onDeleteAllData; final Future<void> Function() onDeleteAllData;
final VoidCallback onBackToHome; final VoidCallback onBackToHome;
final Future<void> Function() onForceSync;
final Color currentSeedColor;
final Future<void> Function(Color color) onThemeColorSelected;
@override @override
State<SettingsScreen> createState() => _SettingsScreenState(); State<SettingsScreen> createState() => _SettingsScreenState();
@@ -19,18 +25,30 @@ class SettingsScreen extends StatefulWidget {
class _SettingsScreenState extends State<SettingsScreen> { class _SettingsScreenState extends State<SettingsScreen> {
bool _isBusy = false; bool _isBusy = false;
bool _isSyncing = false;
bool _isThemeSaving = false;
final TextEditingController _endpointController = TextEditingController(); final TextEditingController _endpointController = TextEditingController();
final TextEditingController _encryptionKeyController = TextEditingController(); final TextEditingController _encryptionKeyController = TextEditingController();
bool _endpointLoading = true; bool _endpointLoading = true;
bool _encryptionKeyLoading = false; bool _encryptionKeyLoading = false;
bool _encryptionKeyVisible = false; bool _encryptionKeyVisible = false;
late Color _selectedSeedColor;
static const List<Color> _themeColorOptions = <Color>[
Colors.amber,
Colors.blue,
Colors.teal,
Colors.green,
Colors.pink,
Colors.purple,
];
Future<void> _confirmAndDeleteAll() async { Future<void> _confirmAndDeleteAll() async {
final bool? confirmed = await showDialog<bool>( final bool? confirmed = await showDialog<bool>(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Borrar todos los datos'), title: const Text('Borrar todos los datos'),
content: const Text('¿Estás seguro? Esta acción eliminará la base de datos local y la clave de cifrado. No se podrá recuperar.'), content: const Text('¿Estás seguro? Esta acción eliminará la base de datos local y la clave de cifrado. Asegúrate de tener una copia de seguridad si es necesario o cuenta sincronizada.'),
actions: [ actions: [
TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancelar')), TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancelar')),
TextButton(onPressed: () => Navigator.of(context).pop(true), child: const Text('Borrar', style: TextStyle(color: Colors.red))), TextButton(onPressed: () => Navigator.of(context).pop(true), child: const Text('Borrar', style: TextStyle(color: Colors.red))),
@@ -65,12 +83,88 @@ class _SettingsScreenState extends State<SettingsScreen> {
} }
} }
Future<void> _forceSync() async {
if (_isBusy || _isSyncing) {
return;
}
setState(() {
_isSyncing = true;
});
try {
await widget.onForceSync();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Sincronización forzada completada.')),
);
} catch (error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error al forzar la sincronización: $error')),
);
} finally {
if (!mounted) return;
setState(() {
_isSyncing = false;
});
}
}
Future<void> _selectThemeColor(Color color) async {
if (_isThemeSaving || _selectedSeedColor == color) {
return;
}
final Color previousColor = _selectedSeedColor;
setState(() {
_selectedSeedColor = color;
_isThemeSaving = true;
});
try {
await widget.onThemeColorSelected(color);
} catch (error) {
if (!mounted) {
return;
}
setState(() {
_selectedSeedColor = previousColor;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('No se pudo guardar el color: $error')),
);
} finally {
if (mounted) {
setState(() {
_isThemeSaving = false;
});
}
}
}
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_selectedSeedColor = widget.currentSeedColor;
_loadEndpoint(); _loadEndpoint();
} }
@override
void didUpdateWidget(covariant SettingsScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.currentSeedColor != widget.currentSeedColor &&
widget.currentSeedColor != _selectedSeedColor) {
_selectedSeedColor = widget.currentSeedColor;
}
}
Future<void> _loadEndpoint() async { Future<void> _loadEndpoint() async {
final String endpoint = await ApiConfig.getEndpoint(); final String endpoint = await ApiConfig.getEndpoint();
if (!mounted) return; if (!mounted) return;
@@ -125,6 +219,58 @@ class _SettingsScreenState extends State<SettingsScreen> {
}); });
} }
Widget _buildThemeColorButton(Color color) {
final bool isSelected = _selectedSeedColor.value == color.value;
final Color foregroundColor =
ThemeData.estimateBrightnessForColor(color) == Brightness.dark
? Colors.white
: Colors.black;
return Semantics(
button: true,
selected: isSelected,
label: 'Color ${color.value.toRadixString(16)}',
child: Tooltip(
message: isSelected ? 'Color actual' : 'Usar este color',
child: InkWell(
onTap: _isThemeSaving ? null : () => _selectThemeColor(color),
borderRadius: BorderRadius.circular(12),
child: AnimatedContainer(
duration: const Duration(milliseconds: 180),
width: 44,
height: 44,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: isSelected ? Colors.white : Colors.white24,
width: isSelected ? 2.5 : 1.2,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.25),
blurRadius: 8,
offset: const Offset(0, 3),
),
],
),
child: Stack(
alignment: Alignment.center,
children: [
if (isSelected)
Icon(
Icons.check,
size: 22,
color: foregroundColor,
),
],
),
),
),
),
);
}
@override @override
void dispose() { void dispose() {
_endpointController.dispose(); _endpointController.dispose();
@@ -151,6 +297,56 @@ class _SettingsScreenState extends State<SettingsScreen> {
_endpointController.text = endpoint; _endpointController.text = endpoint;
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Endpoint restaurado al valor por defecto'))); ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Endpoint restaurado al valor por defecto')));
} }
Widget _buildResponsiveInputActionsRow({
required Widget input,
required List<Widget> actions,
}) {
return LayoutBuilder(
builder: (context, constraints) {
final bool isCompact = constraints.maxWidth < 600;
if (isCompact) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(width: double.infinity, child: input),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerRight,
child: Wrap(
alignment: WrapAlignment.end,
spacing: 8,
runSpacing: 8,
children: actions,
),
),
],
);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(child: input),
const SizedBox(width: 8),
Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (int index = 0; index < actions.length; index++) ...[
if (index > 0) const SizedBox(width: 8),
actions[index],
],
],
),
),
],
);
},
);
}
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
body: Container( body: Container(
@@ -181,118 +377,143 @@ class _SettingsScreenState extends State<SettingsScreen> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
ElevatedButton.icon( Row(
style: ElevatedButton.styleFrom(backgroundColor: Colors.redAccent), children: [
onPressed: _isBusy ? null : _confirmAndDeleteAll, const Expanded(
icon: _isBusy ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)) : const Icon(Icons.delete_forever), child: Text('Borrar datos locales:'),
label: const Text('Borrar todos los datos'), ),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.redAccent,
foregroundColor: Colors.white,
textStyle: const TextStyle(fontWeight: FontWeight.w600),
),
onPressed: _isBusy ? null : _confirmAndDeleteAll,
icon: _isBusy
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.delete_forever),
label: const Text('Borrar'),
),
],
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
const Text('Esto cerrará el vault actual y eliminará la base de datos local junto con la clave de cifrado.'), Row(
children: [
const Expanded(
child: Text('Forzar sincronizacion total:'),
),
ElevatedButton.icon(
onPressed: (_isBusy || _isSyncing) ? null : _forceSync,
icon: _isSyncing
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.sync),
label: const Text('Sincronizar'),
),
],
),
const SizedBox(height: 24),
const Text('Color del esquema'),
const SizedBox(height: 8),
Wrap(
spacing: 12,
runSpacing: 12,
children: [
for (final Color color in _themeColorOptions)
_buildThemeColorButton(color),
],
),
const SizedBox(height: 24), const SizedBox(height: 24),
const Text('API endpoint (ej: http://localhost:3000/api)'), const Text('API endpoint (ej: http://localhost:3000/api)'),
const SizedBox(height: 8), const SizedBox(height: 8),
Row( _buildResponsiveInputActionsRow(
crossAxisAlignment: CrossAxisAlignment.start, input: _endpointLoading
children: [ ? const SizedBox(height: 48, child: Center(child: CircularProgressIndicator()))
Expanded( : TextField(
child: _endpointLoading controller: _endpointController,
? const SizedBox(height: 48, child: Center(child: CircularProgressIndicator())) style: const TextStyle(color: Colors.white),
: TextField( keyboardType: TextInputType.url,
controller: _endpointController, decoration: InputDecoration(
style: const TextStyle(color: Colors.white), labelText: 'API endpoint',
keyboardType: TextInputType.url, labelStyle: TextStyle(color: Colors.white.withValues(alpha: 0.7)),
decoration: InputDecoration( filled: true,
labelText: 'API endpoint', fillColor: Colors.white.withValues(alpha: 0.05),
labelStyle: TextStyle(color: Colors.white.withValues(alpha: 0.7)), border: OutlineInputBorder(
filled: true, borderRadius: BorderRadius.circular(14),
fillColor: Colors.white.withValues(alpha: 0.05), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.12)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.12)),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.12)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: Colors.amber, width: 1.2),
),
),
), ),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.12)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: Colors.amber, width: 1.2),
),
),
),
actions: [
ElevatedButton(
onPressed: _endpointLoading ? null : _saveEndpoint,
child: const Text('Guardar'),
), ),
const SizedBox(width: 8), OutlinedButton(
Column( onPressed: _endpointLoading ? null : _resetEndpoint,
mainAxisSize: MainAxisSize.min, child: const Text('Restaurar'),
children: [
ElevatedButton(
onPressed: _endpointLoading ? null : _saveEndpoint,
child: const Text('Guardar'),
),
const SizedBox(height: 8),
OutlinedButton(
onPressed: _endpointLoading ? null : _resetEndpoint,
child: const Text('Restaurar'),
),
],
), ),
], ],
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
const Text('Clave de cifrado local'), const Text('Clave de cifrado local'),
const SizedBox(height: 8), const SizedBox(height: 8),
Row( _buildResponsiveInputActionsRow(
crossAxisAlignment: CrossAxisAlignment.start, input: TextField(
children: [ controller: _encryptionKeyController,
Expanded( readOnly: true,
child: TextField( obscureText: !_encryptionKeyVisible,
controller: _encryptionKeyController, enableSuggestions: false,
readOnly: true, autocorrect: false,
obscureText: !_encryptionKeyVisible, style: const TextStyle(color: Colors.white),
enableSuggestions: false, decoration: InputDecoration(
autocorrect: false, labelText: _encryptionKeyVisible ? 'Clave de cifrado' : 'Oculta hasta pulsar mostrar',
style: const TextStyle(color: Colors.white), labelStyle: TextStyle(color: Colors.white.withValues(alpha: 0.7)),
decoration: InputDecoration( filled: true,
labelText: _encryptionKeyVisible ? 'Clave de cifrado' : 'Oculta hasta pulsar mostrar', fillColor: Colors.white.withValues(alpha: 0.05),
labelStyle: TextStyle(color: Colors.white.withValues(alpha: 0.7)), border: OutlineInputBorder(
filled: true, borderRadius: BorderRadius.circular(14),
fillColor: Colors.white.withValues(alpha: 0.05), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.12)),
border: OutlineInputBorder( ),
borderRadius: BorderRadius.circular(14), enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.12)), borderRadius: BorderRadius.circular(14),
), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.12)),
enabledBorder: OutlineInputBorder( ),
borderRadius: BorderRadius.circular(14), focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.12)), borderRadius: BorderRadius.circular(14),
), borderSide: const BorderSide(color: Colors.amber, width: 1.2),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: Colors.amber, width: 1.2),
),
),
), ),
), ),
const SizedBox(width: 8), ),
Column( actions: [
mainAxisSize: MainAxisSize.min, ElevatedButton(
children: [ onPressed: _encryptionKeyLoading ? null : _loadEncryptionKey,
ElevatedButton( child: _encryptionKeyLoading
onPressed: _encryptionKeyLoading ? null : _loadEncryptionKey, ? const SizedBox(
child: _encryptionKeyLoading width: 16,
? const SizedBox( height: 16,
width: 16, child: CircularProgressIndicator(strokeWidth: 2),
height: 16, )
child: CircularProgressIndicator(strokeWidth: 2), : const Text('Mostrar'),
) ),
: const Text('Mostrar'), OutlinedButton(
), onPressed: _encryptionKeyVisible ? _hideEncryptionKey : null,
const SizedBox(height: 8), child: const Text('Ocultar'),
OutlinedButton(
onPressed: _encryptionKeyVisible ? _hideEncryptionKey : null,
child: const Text('Ocultar'),
),
],
), ),
], ],
), ),
+10 -5
View File
@@ -1,17 +1,22 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class AppTheme { class AppTheme {
static ThemeData get theme { static ThemeData theme({Color seedColor = Colors.amber}) {
final Brightness foregroundBrightness =
ThemeData.estimateBrightnessForColor(seedColor);
final Color foregroundColor =
foregroundBrightness == Brightness.dark ? Colors.white : Colors.black;
return ThemeData( return ThemeData(
useMaterial3: true, useMaterial3: true,
scaffoldBackgroundColor: const Color.fromRGBO(31, 32, 33, 1), scaffoldBackgroundColor: const Color.fromRGBO(31, 32, 33, 1),
colorScheme: ColorScheme.fromSeed( colorScheme: ColorScheme.fromSeed(
seedColor: Colors.amber, seedColor: seedColor,
brightness: Brightness.dark, brightness: Brightness.dark,
), ),
floatingActionButtonTheme: const FloatingActionButtonThemeData( floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: Colors.amber, backgroundColor: seedColor,
foregroundColor: Colors.black, foregroundColor: foregroundColor,
), ),
); );
} }