Compare commits

...

5 Commits

Author SHA1 Message Date
gitea 9061470e9b improvements in ui
2 months ago
gitea 9743f9a8ec easing transactions
2 months ago
gitea ffd1ac5ddc new settings design
2 months ago
gitea 2db3339071 reconnect to relay if down
2 months ago
gitea a477271d5f better tag search and add
2 months ago

@ -9,11 +9,18 @@ class NostrRelay {
/// Whether the relay is enabled (should be used).
bool isEnabled;
/// Number of consecutive connection failures.
int retryCount;
/// Maximum number of retry attempts before disabling.
static const int maxRetryAttempts = 3;
/// Creates a [NostrRelay] instance.
NostrRelay({
required this.url,
this.isConnected = false,
this.isEnabled = true,
this.retryCount = 0,
});
/// Creates a [NostrRelay] from a URL string.
@ -23,7 +30,7 @@ class NostrRelay {
@override
String toString() {
return 'NostrRelay(url: $url, connected: $isConnected, enabled: $isEnabled)';
return 'NostrRelay(url: $url, connected: $isConnected, enabled: $isEnabled, retryCount: $retryCount)';
}
@override

@ -29,6 +29,9 @@ class NostrService {
final Map<String, StreamController<Map<String, dynamic>>>
_messageControllers = {};
/// Retry timers for relays that are attempting to reconnect.
final Map<String, Timer> _retryTimers = {};
/// Creates a [NostrService] instance.
NostrService();
@ -67,6 +70,9 @@ class NostrService {
orElse: () => throw NostrException('Relay not found: $relayUrl'),
);
relay.isEnabled = enabled;
if (enabled) {
relay.retryCount = 0; // Reset retry count when enabling
}
// If disabling, also disconnect
if (!enabled && relay.isConnected) {
@ -156,6 +162,7 @@ class NostrService {
// No errors occurred, connection is established
connectionConfirmed = true;
relay.isConnected = true;
relay.retryCount = 0; // Reset retry count on successful connection
Logger.info('Connection confirmed for relay: $relayUrl (no errors after 500ms)');
}
});
@ -167,6 +174,7 @@ class NostrService {
if (!connectionConfirmed) {
connectionConfirmed = true;
relay.isConnected = true;
relay.retryCount = 0; // Reset retry count on successful connection
Logger.info('Connection confirmed for relay: $relayUrl (first message received)');
connectionTimer?.cancel();
}
@ -207,9 +215,7 @@ class NostrService {
connectionTimer?.cancel();
Logger.error('WebSocket error for relay: $relayUrl', error);
relay.isConnected = false;
// Automatically disable relay when connection error occurs
relay.isEnabled = false;
Logger.warning('Relay $relayUrl disabled due to connection error');
_handleConnectionFailure(relayUrl, relay, controller, 'connection error');
controller.addError(NostrException('Relay error: $error'));
},
onDone: () {
@ -217,9 +223,7 @@ class NostrService {
connectionTimer?.cancel();
Logger.warning('WebSocket stream closed for relay: $relayUrl');
relay.isConnected = false;
// Automatically disable relay when connection closes
relay.isEnabled = false;
Logger.warning('Relay $relayUrl disabled due to stream closure');
_handleConnectionFailure(relayUrl, relay, controller, 'stream closure');
controller.close();
},
);
@ -230,6 +234,101 @@ class NostrService {
}
}
/// Handles connection failure with retry logic.
///
/// [relayUrl] - The URL of the relay that failed.
/// [relay] - The relay object.
/// [controller] - The stream controller for this relay.
/// [reason] - Reason for the failure (for logging).
void _handleConnectionFailure(
String relayUrl,
NostrRelay relay,
StreamController<Map<String, dynamic>> controller,
String reason,
) {
// Cancel any existing retry timer
_retryTimers[relayUrl]?.cancel();
_retryTimers.remove(relayUrl);
// Only retry if relay is enabled
if (!relay.isEnabled) {
Logger.info('Relay $relayUrl is disabled, skipping retry');
return;
}
relay.retryCount++;
Logger.warning('Relay $relayUrl failed ($reason), retry attempt ${relay.retryCount}/${NostrRelay.maxRetryAttempts}');
if (relay.retryCount >= NostrRelay.maxRetryAttempts) {
// Max retries reached - disable the relay
relay.isEnabled = false;
relay.retryCount = 0; // Reset for future attempts
Logger.warning('Relay $relayUrl disabled after ${NostrRelay.maxRetryAttempts} failed attempts');
} else {
// Schedule retry after delay (5 seconds)
_scheduleRetry(relayUrl, relay, controller, reason);
}
}
/// Schedules a retry attempt for a failed relay connection.
///
/// [relayUrl] - The URL of the relay to retry.
/// [relay] - The relay object.
/// [controller] - The stream controller for this relay.
/// [reason] - Reason for the retry (for logging).
void _scheduleRetry(
String relayUrl,
NostrRelay relay,
StreamController<Map<String, dynamic>> controller,
String reason,
) {
Logger.info('Scheduling retry for relay $relayUrl in 5 seconds (attempt ${relay.retryCount}/${NostrRelay.maxRetryAttempts})');
_retryTimers[relayUrl] = Timer(const Duration(seconds: 5), () {
_retryTimers.remove(relayUrl);
if (relay.isEnabled && !relay.isConnected) {
Logger.info('Retrying connection to relay: $relayUrl');
try {
// Clean up old connection
disconnectRelay(relayUrl);
// Attempt to reconnect
connectRelay(relayUrl).then((stream) {
// Reset retry count on successful connection
relay.retryCount = 0;
Logger.info('Relay $relayUrl reconnected successfully');
// Cancel the stream subscription as we're just testing the connection
stream.listen(null).cancel();
}).catchError((e) {
Logger.warning('Retry failed for relay $relayUrl: $e');
// Handle retry failure - check if we should retry again or disable
if (relay.isEnabled) {
if (relay.retryCount >= NostrRelay.maxRetryAttempts) {
relay.isEnabled = false;
relay.retryCount = 0;
Logger.warning('Relay $relayUrl disabled after ${NostrRelay.maxRetryAttempts} failed attempts');
} else {
// Schedule another retry (retryCount already incremented in _handleConnectionFailure)
_scheduleRetry(relayUrl, relay, controller, 'retry failure');
}
}
});
} catch (e) {
Logger.error('Error during retry for relay $relayUrl', e);
// Handle synchronous exception
if (relay.isEnabled) {
if (relay.retryCount >= NostrRelay.maxRetryAttempts) {
relay.isEnabled = false;
relay.retryCount = 0;
Logger.warning('Relay $relayUrl disabled after ${NostrRelay.maxRetryAttempts} failed attempts');
} else {
// Schedule another retry (retryCount already incremented in _handleConnectionFailure)
_scheduleRetry(relayUrl, relay, controller, 'synchronous retry failure');
}
}
}
}
});
}
/// Disconnects from a relay.
///
/// [relayUrl] - The URL of the relay to disconnect from.

@ -553,9 +553,12 @@ class _AddRecipeScreenState extends State<AddRecipeScreen> {
Future<void> _removeTag(String tag) async {
if (_recipeService == null || _recipe == null) return;
final currentRecipe = _currentRecipe ?? widget.recipe;
if (currentRecipe == null) return;
try {
final updatedTags = List<String>.from(_recipe!.tags)..remove(tag);
final updatedRecipe = _recipe!.copyWith(tags: updatedTags);
final updatedTags = List<String>.from(currentRecipe.tags)..remove(tag);
final updatedRecipe = currentRecipe.copyWith(tags: updatedTags);
await _recipeService!.updateRecipe(updatedRecipe);
if (mounted) {
@ -591,7 +594,7 @@ class _AddRecipeScreenState extends State<AddRecipeScreen> {
}
final existingTags = allTags.toList()..sort();
final result = await showDialog<String>(
final result = await showDialog<List<String>>(
context: context,
builder: (context) => _AddTagDialog(
tagController: tagController,
@ -604,8 +607,8 @@ class _AddRecipeScreenState extends State<AddRecipeScreen> {
tagController.dispose();
});
if (mounted && result != null && result.trim().isNotEmpty) {
await _addTag(result.trim());
if (mounted && result != null && result.isNotEmpty) {
await _addTags(result);
}
} catch (e) {
WidgetsBinding.instance.addPostFrameCallback((_) {
@ -614,17 +617,22 @@ class _AddRecipeScreenState extends State<AddRecipeScreen> {
}
}
Future<void> _addTag(String tag) async {
Future<void> _addTags(List<String> tags) async {
if (_recipeService == null || _recipe == null) return;
final trimmedTag = tag.trim();
if (trimmedTag.isEmpty) return;
final currentRecipe = _currentRecipe ?? widget.recipe;
if (currentRecipe == null) return;
final trimmedTags = tags.map((tag) => tag.trim()).where((tag) => tag.isNotEmpty).toList();
if (trimmedTags.isEmpty) return;
if (_recipe!.tags.contains(trimmedTag)) {
// Filter out tags that already exist
final newTags = trimmedTags.where((tag) => !currentRecipe.tags.contains(tag)).toList();
if (newTags.isEmpty) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Tag already exists'),
content: Text('All tags already exist'),
duration: Duration(seconds: 1),
),
);
@ -633,8 +641,8 @@ class _AddRecipeScreenState extends State<AddRecipeScreen> {
}
try {
final updatedTags = List<String>.from(_recipe!.tags)..add(trimmedTag);
final updatedRecipe = _recipe!.copyWith(tags: updatedTags);
final updatedTags = List<String>.from(currentRecipe.tags)..addAll(newTags);
final updatedRecipe = currentRecipe.copyWith(tags: updatedTags);
await _recipeService!.updateRecipe(updatedRecipe);
if (mounted) {
@ -643,16 +651,16 @@ class _AddRecipeScreenState extends State<AddRecipeScreen> {
_tagsController.text = updatedTags.join(', ');
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Tag added'),
duration: Duration(seconds: 1),
SnackBar(
content: Text('${newTags.length} tag${newTags.length > 1 ? 's' : ''} added'),
duration: const Duration(seconds: 1),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error adding tag: $e')),
SnackBar(content: Text('Error adding tags: $e')),
);
}
}
@ -1781,7 +1789,7 @@ class _AddTagDialogState extends State<_AddTagDialog> with SingleTickerProviderS
late AnimationController _animationController;
late Animation<double> _animation;
bool _isUserScrolling = false;
DateTime? _lastUserScrollTime;
final Set<String> _selectedTags = {};
@override
void initState() {
@ -1846,16 +1854,47 @@ class _AddTagDialogState extends State<_AddTagDialog> with SingleTickerProviderS
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.jumpTo(0);
_isUserScrolling = false;
_lastUserScrollTime = null;
// Don't restart auto-scroll if user has interacted
if (!_isUserScrolling) {
_startAutoScroll();
}
}
});
});
}
void _selectTag(String tag) {
Navigator.pop(context, tag);
// Stop auto-scroll permanently when user selects a tag
_isUserScrolling = true;
_animationController.stop();
setState(() {
if (_selectedTags.contains(tag)) {
_selectedTags.remove(tag);
} else {
_selectedTags.add(tag);
}
});
}
List<String> _getTagsToAdd() {
final tags = <String>[];
// Add selected tags from the list
tags.addAll(_selectedTags);
// Parse comma-separated tags from text field
final textTags = widget.tagController.text
.split(',')
.map((tag) => tag.trim())
.where((tag) => tag.isNotEmpty)
.toList();
tags.addAll(textTags);
// Remove duplicates and tags that already exist in the recipe
final uniqueTags = tags.toSet().where((tag) => !widget.currentTags.contains(tag)).toList();
return uniqueTags;
}
@override
@ -1877,16 +1916,11 @@ class _AddTagDialogState extends State<_AddTagDialog> with SingleTickerProviderS
controller: widget.tagController,
autofocus: true,
decoration: InputDecoration(
hintText: 'Enter tag name or select from existing',
hintText: 'Enter tags (comma-separated) or select from existing',
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.search),
),
textCapitalization: TextCapitalization.none,
onSubmitted: (value) {
if (value.trim().isNotEmpty) {
Navigator.pop(context, value.trim());
}
},
),
const SizedBox(height: 16),
// Existing tags scrollable list with fade hint
@ -1902,25 +1936,10 @@ class _AddTagDialogState extends State<_AddTagDialog> with SingleTickerProviderS
height: 50,
child: NotificationListener<ScrollNotification>(
onNotification: (notification) {
// Detect when user manually scrolls
// Detect when user manually scrolls - stop auto-scroll permanently
if (notification is ScrollStartNotification && notification.dragDetails != null) {
_isUserScrolling = true;
_lastUserScrollTime = DateTime.now();
_animationController.stop();
} else if (notification is ScrollEndNotification) {
// Resume auto-scroll after user stops scrolling for 3 seconds
_lastUserScrollTime = DateTime.now();
Future.delayed(const Duration(seconds: 3), () {
if (mounted && _lastUserScrollTime != null) {
final timeSinceLastScroll = DateTime.now().difference(_lastUserScrollTime!);
if (timeSinceLastScroll.inSeconds >= 3) {
setState(() {
_isUserScrolling = false;
});
_startAutoScroll();
}
}
});
}
return false;
},
@ -1931,11 +1950,34 @@ class _AddTagDialogState extends State<_AddTagDialog> with SingleTickerProviderS
itemBuilder: (context, index) {
final tag = _filteredTags[index];
final isAlreadyAdded = widget.currentTags.contains(tag);
final isSelected = _selectedTags.contains(tag);
return Padding(
padding: const EdgeInsets.only(right: 8),
child: FilterChip(
label: Text(tag),
selected: isAlreadyAdded,
label: Text(
tag,
style: TextStyle(
color: isSelected
? Colors.white
: (isAlreadyAdded
? (isDark ? Colors.white : Colors.black87)
: (isDark ? Colors.white : Colors.black87)),
fontWeight: isSelected
? FontWeight.w700
: (isAlreadyAdded ? FontWeight.w500 : FontWeight.normal),
fontSize: isSelected ? 14 : null,
shadows: isSelected
? [
Shadow(
color: Colors.black.withValues(alpha: 0.5),
offset: const Offset(0, 1),
blurRadius: 2,
),
]
: null,
),
),
selected: isSelected,
onSelected: isAlreadyAdded
? null
: (selected) {
@ -1946,12 +1988,24 @@ class _AddTagDialogState extends State<_AddTagDialog> with SingleTickerProviderS
backgroundColor: isDark
? Colors.grey[800]
: Colors.grey[200],
disabledColor: Colors.grey[400],
labelStyle: TextStyle(
color: isAlreadyAdded
? Colors.white
: (isDark ? Colors.white : Colors.black87),
),
disabledColor: isDark
? Colors.grey[600]
: Colors.grey[100],
side: isSelected
? BorderSide(
color: Colors.white.withValues(alpha: 0.5),
width: 2.5,
)
: (isAlreadyAdded
? BorderSide(
color: (isDark ? Colors.grey[500]! : Colors.grey[400]!),
width: 1,
)
: null),
elevation: isSelected ? 3 : 0,
padding: isSelected
? const EdgeInsets.symmetric(horizontal: 12, vertical: 8)
: null,
),
);
},
@ -1975,12 +2029,16 @@ class _AddTagDialogState extends State<_AddTagDialog> with SingleTickerProviderS
),
FilledButton(
onPressed: () {
final text = widget.tagController.text.trim();
if (text.isNotEmpty) {
Navigator.pop(context, text);
final tagsToAdd = _getTagsToAdd();
if (tagsToAdd.isNotEmpty) {
Navigator.pop(context, tagsToAdd);
} else {
Navigator.pop(context);
}
},
child: const Text('Add'),
child: Text(_selectedTags.isEmpty && widget.tagController.text.trim().isEmpty
? 'Add'
: 'Add (${_getTagsToAdd().length})'),
),
],
);

@ -23,12 +23,25 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
String? _errorMessage;
RecipeService? _recipeService;
bool _wasLoggedIn = false;
String _searchQuery = '';
final TextEditingController _searchController = TextEditingController();
@override
void initState() {
super.initState();
_checkLoginState();
_initializeService();
_searchController.addListener(() {
setState(() {
_searchQuery = _searchController.text.toLowerCase();
});
});
}
@override
void dispose() {
_searchController.dispose();
super.dispose();
}
@override
@ -123,6 +136,29 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
}
}
List<BookmarkCategory> _getFilteredCategories() {
if (_searchQuery.isEmpty) {
return _categories;
}
return _categories.where((category) {
final recipes = _recipesByCategory[category.id] ?? [];
return category.name.toLowerCase().contains(_searchQuery) ||
recipes.any((recipe) =>
recipe.title.toLowerCase().contains(_searchQuery) ||
(recipe.description?.toLowerCase().contains(_searchQuery) ?? false));
}).toList();
}
List<RecipeModel> _getFilteredRecipes(String categoryId) {
final recipes = _recipesByCategory[categoryId] ?? [];
if (_searchQuery.isEmpty) {
return recipes;
}
return recipes.where((recipe) =>
recipe.title.toLowerCase().contains(_searchQuery) ||
(recipe.description?.toLowerCase().contains(_searchQuery) ?? false)).toList();
}
void _viewRecipe(RecipeModel recipe) {
Navigator.push(
context,
@ -158,8 +194,36 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
if (!isLoggedIn) {
return Scaffold(
appBar: AppBar(title: const Text('Bookmarks')),
body: const Center(
child: Text('Please log in to view bookmarks'),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.bookmark_border,
size: 80,
color: Colors.grey.shade400,
),
const SizedBox(height: 24),
Text(
'Please log in to view bookmarks',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.grey.shade700,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
Text(
'Sign in to save and organize your favorite recipes',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.grey.shade600,
),
textAlign: TextAlign.center,
),
],
),
),
),
);
}
@ -175,86 +239,330 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
return Scaffold(
appBar: AppBar(title: const Text('Bookmarks')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_errorMessage!),
Icon(
Icons.error_outline,
size: 64,
color: Colors.red.shade300,
),
const SizedBox(height: 16),
ElevatedButton(
Text(
'Oops! Something went wrong',
style: Theme.of(context).textTheme.titleLarge,
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
Text(
_errorMessage!,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.grey.shade600,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: _loadBookmarks,
child: const Text('Retry'),
icon: const Icon(Icons.refresh),
label: const Text('Retry'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
),
],
),
),
),
);
}
if (_categories.isEmpty) {
return Scaffold(
appBar: AppBar(title: const Text('Bookmarks')),
body: const Center(
child: Text(
'No bookmark categories yet.\nBookmark a recipe to get started!',
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.bookmark_add_outlined,
size: 100,
color: Colors.grey.shade300,
),
const SizedBox(height: 24),
Text(
'No bookmark categories yet',
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
color: Colors.grey.shade700,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 12),
Text(
'Bookmark a recipe to organize your favorites into categories',
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Colors.grey.shade600,
),
textAlign: TextAlign.center,
),
],
),
),
),
);
}
final filteredCategories = _getFilteredCategories();
return Scaffold(
appBar: AppBar(
title: const Text('Bookmarks'),
actions: [
],
elevation: 0,
),
body: RefreshIndicator(
onRefresh: _loadBookmarks,
child: ListView.builder(
child: CustomScrollView(
slivers: [
// Search bar
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: TextField(
controller: _searchController,
decoration: InputDecoration(
hintText: 'Search bookmarks...',
prefixIcon: const Icon(Icons.search),
suffixIcon: _searchQuery.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.clear();
},
)
: null,
filled: true,
fillColor: Theme.of(context).brightness == Brightness.dark
? Colors.grey[800]
: Colors.grey[100],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
),
),
),
),
// Categories list
if (filteredCategories.isEmpty && _searchQuery.isNotEmpty)
SliverFillRemaining(
hasScrollBody: false,
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.search_off,
size: 64,
color: Colors.grey.shade400,
),
const SizedBox(height: 16),
Text(
'No results found',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.grey.shade700,
),
),
const SizedBox(height: 8),
Text(
'Try a different search term',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.grey.shade600,
),
),
],
),
),
),
)
else
SliverPadding(
padding: const EdgeInsets.all(16),
itemCount: _categories.length,
itemBuilder: (context, index) {
final category = _categories[index];
final recipes = _recipesByCategory[category.id] ?? [];
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final category = filteredCategories[index];
final recipes = _getFilteredRecipes(category.id);
return _CategoryCard(
category: category,
recipes: recipes,
categoryColor: category.color != null
? _parseColor(category.color!)
: Theme.of(context).primaryColor,
onRecipeTap: _viewRecipe,
onPhotoTap: _openPhotoGallery,
);
},
childCount: filteredCategories.length,
),
),
),
],
),
),
);
}
}
/// Modern category card widget
class _CategoryCard extends StatefulWidget {
final BookmarkCategory category;
final List<RecipeModel> recipes;
final Color categoryColor;
final Function(RecipeModel) onRecipeTap;
final Function(List<String>, int) onPhotoTap;
const _CategoryCard({
required this.category,
required this.recipes,
required this.categoryColor,
required this.onRecipeTap,
required this.onPhotoTap,
});
@override
State<_CategoryCard> createState() => _CategoryCardState();
}
class _CategoryCardState extends State<_CategoryCard> {
bool _isExpanded = false;
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.only(bottom: 16),
child: ExpansionTile(
leading: category.color != null
? Container(
width: 32,
height: 32,
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
child: Column(
children: [
InkWell(
onTap: () {
setState(() {
_isExpanded = !_isExpanded;
});
},
borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
// Category icon/color indicator
Container(
width: 48,
height: 48,
decoration: BoxDecoration(
color: _parseColor(category.color!),
shape: BoxShape.circle,
color: widget.categoryColor.withOpacity(0.2),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: widget.categoryColor,
width: 2,
),
),
child: Icon(
Icons.bookmark,
color: widget.categoryColor,
size: 24,
),
),
const SizedBox(width: 16),
// Category info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.category.name,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Row(
children: [
Icon(
Icons.restaurant_menu,
size: 16,
color: Colors.grey.shade600,
),
const SizedBox(width: 4),
Text(
'${widget.recipes.length} recipe${widget.recipes.length != 1 ? 's' : ''}',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.grey.shade600,
),
),
],
),
],
),
),
// Expand icon
Icon(
_isExpanded ? Icons.expand_less : Icons.expand_more,
color: Colors.grey.shade600,
),
],
),
),
),
// Recipes list
if (_isExpanded)
AnimatedSize(
duration: const Duration(milliseconds: 200),
child: widget.recipes.isEmpty
? Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Icon(
Icons.info_outline,
size: 20,
color: Colors.grey.shade400,
),
const SizedBox(width: 8),
Text(
'No recipes in this category',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.grey.shade600,
),
),
],
),
)
: const Icon(Icons.bookmark),
title: Text(
category.name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text('${recipes.length} recipe(s)'),
children: recipes.isEmpty
? [
const ListTile(
title: Text('No recipes in this category'),
)
]
: recipes.map((recipe) {
: Column(
children: widget.recipes.map((recipe) {
return _BookmarkRecipeItem(
recipe: recipe,
onTap: () => _viewRecipe(recipe),
onPhotoTap: (index) => _openPhotoGallery(
onTap: () => widget.onRecipeTap(recipe),
onPhotoTap: (index) => widget.onPhotoTap(
recipe.imageUrls,
index,
),
);
}).toList(),
),
);
},
),
],
),
);
}
@ -353,58 +661,130 @@ class _BookmarkRecipeItem extends StatelessWidget {
);
}
Color _getRatingColor(double rating) {
if (rating >= 4.5) return Colors.green;
if (rating >= 3.5) return Colors.orange;
if (rating >= 2.5) return Colors.amber;
return Colors.red;
}
@override
Widget build(BuildContext context) {
return ListTile(
leading: recipe.imageUrls.isNotEmpty
return InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Recipe image
recipe.imageUrls.isNotEmpty
? GestureDetector(
onTap: () => onPhotoTap(0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: 60,
height: 60,
borderRadius: BorderRadius.circular(12),
child: Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: Colors.grey.shade200,
borderRadius: BorderRadius.circular(12),
),
child: _buildRecipeImage(recipe.imageUrls.first),
),
),
)
: Container(
width: 60,
height: 60,
width: 80,
height: 80,
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(8),
color: Colors.grey.shade200,
borderRadius: BorderRadius.circular(12),
),
child: const Icon(Icons.restaurant_menu),
child: Icon(
Icons.restaurant_menu,
color: Colors.grey.shade400,
size: 32,
),
title: Text(
recipe.title,
style: const TextStyle(fontWeight: FontWeight.w500),
),
subtitle: Column(
const SizedBox(width: 16),
// Recipe info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (recipe.description != null && recipe.description!.isNotEmpty)
Text(
recipe.title,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
if (recipe.description != null && recipe.description!.isNotEmpty) ...[
const SizedBox(height: 6),
Text(
recipe.description!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.grey.shade600,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
],
const SizedBox(height: 8),
Row(
children: [
const Icon(Icons.star, size: 16, color: Colors.amber),
// Rating badge
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: _getRatingColor(recipe.rating.toDouble()).withOpacity(0.15),
borderRadius: BorderRadius.circular(12),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.star,
size: 14,
color: Colors.amber,
),
const SizedBox(width: 4),
Text(recipe.rating.toString()),
Text(
recipe.rating.toString(),
style: Theme.of(context).textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.bold,
color: _getRatingColor(recipe.rating.toDouble()),
),
),
],
),
),
if (recipe.isFavourite) ...[
const SizedBox(width: 12),
const Icon(Icons.favorite, size: 16, color: Colors.red),
const SizedBox(width: 8),
Icon(
Icons.favorite,
size: 16,
color: Colors.red.shade400,
),
],
],
),
],
),
onTap: onTap,
),
// Chevron icon
Icon(
Icons.chevron_right,
color: Colors.grey.shade400,
),
],
),
),
);
}
}

@ -7,6 +7,7 @@ import '../../data/recipes/recipe_service.dart';
import '../../data/recipes/models/recipe_model.dart';
import '../add_recipe/add_recipe_screen.dart';
import '../photo_gallery/photo_gallery_screen.dart';
import '../navigation/material3_page_route.dart';
/// Favourites screen displaying user's favorite recipes.
class FavouritesScreen extends StatefulWidget {
@ -165,8 +166,9 @@ class _FavouritesScreenState extends State<FavouritesScreen> {
void _viewRecipe(RecipeModel recipe) async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => AddRecipeScreen(recipe: recipe, viewMode: true),
Material3PageRoute(
child: AddRecipeScreen(recipe: recipe, viewMode: true),
useEmphasized: true, // Use emphasized easing for more fluid feel
),
);
// Reload favourites after viewing (in case favorite was toggled)
@ -177,8 +179,9 @@ class _FavouritesScreenState extends State<FavouritesScreen> {
void _editRecipe(RecipeModel recipe) async {
final result = await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => AddRecipeScreen(recipe: recipe),
Material3PageRoute(
child: AddRecipeScreen(recipe: recipe),
useEmphasized: true, // Use emphasized easing for more fluid feel
),
);
if (result == true || mounted) {

@ -6,6 +6,7 @@ import '../../data/recipes/models/recipe_model.dart';
import '../shared/primary_app_bar.dart';
import '../add_recipe/add_recipe_screen.dart';
import '../navigation/main_navigation_scaffold.dart';
import '../navigation/material3_page_route.dart';
import 'package:video_player/video_player.dart';
/// Home screen showing recipes overview, stats, tags, and favorites.
@ -90,8 +91,9 @@ class _HomeScreenState extends State<HomeScreen> {
void _navigateToRecipe(RecipeModel recipe) async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddRecipeScreen(recipe: recipe, viewMode: true),
Material3PageRoute(
child: AddRecipeScreen(recipe: recipe, viewMode: true),
useEmphasized: true, // Use emphasized easing for more fluid feel
),
);
// Reload data if recipe was edited

@ -0,0 +1,74 @@
import 'package:flutter/material.dart';
/// Material Design 3 easing curves
/// Reference: https://m3.material.io/styles/motion/easing-and-duration/applying-easing-and-duration
class Material3Easing {
/// Standard easing curve for entering animations
/// Cubic(0.2, 0, 0, 1)
static const Curve standardEnter = Cubic(0.2, 0, 0, 1);
/// Standard easing curve for exiting animations
/// Cubic(0, 0, 0.2, 1)
static const Curve standardExit = Cubic(0, 0, 0.2, 1);
/// Emphasized easing curve for entering animations
/// Cubic(0.2, 0, 0, 1)
static const Curve emphasizedEnter = Cubic(0.2, 0, 0, 1);
/// Emphasized easing curve for exiting animations
/// Cubic(0.05, 0.7, 0.1, 1)
static const Curve emphasizedExit = Cubic(0.05, 0.7, 0.1, 1);
}
/// Material Design 3 page route with custom easing animations.
///
/// Uses Material Design 3 motion guidelines for smooth, fluid transitions.
/// Reference: https://m3.material.io/styles/motion/easing-and-duration/applying-easing-and-duration
class Material3PageRoute<T> extends PageRouteBuilder<T> {
final Widget child;
final bool useEmphasized;
Material3PageRoute({
required this.child,
this.useEmphasized = false,
RouteSettings? settings,
}) : super(
pageBuilder: (context, animation, secondaryAnimation) => child,
transitionDuration: useEmphasized
? const Duration(milliseconds: 400)
: const Duration(milliseconds: 300),
reverseTransitionDuration: useEmphasized
? const Duration(milliseconds: 400)
: const Duration(milliseconds: 300),
settings: settings,
transitionsBuilder: (context, animation, secondaryAnimation, child) {
// Use Material Design 3 easing curves
final enterCurve = useEmphasized
? Material3Easing.emphasizedEnter
: Material3Easing.standardEnter;
final exitCurve = useEmphasized
? Material3Easing.emphasizedExit
: Material3Easing.standardExit;
// Apply easing curves to animations
final curvedAnimation = CurvedAnimation(
parent: animation,
curve: enterCurve,
reverseCurve: exitCurve,
);
// Slide transition with fade
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(0.0, 0.05), // Slight upward slide
end: Offset.zero,
).animate(curvedAnimation),
child: FadeTransition(
opacity: curvedAnimation,
child: child,
),
);
},
);
}

@ -9,6 +9,7 @@ import '../../data/local/models/item.dart';
import '../add_recipe/add_recipe_screen.dart';
import '../photo_gallery/photo_gallery_screen.dart';
import '../navigation/main_navigation_scaffold.dart';
import '../navigation/material3_page_route.dart';
import 'bookmark_dialog.dart';
import '../../data/recipes/models/bookmark_category_model.dart';
@ -28,7 +29,7 @@ class RecipesScreen extends StatefulWidget {
}
}
class _RecipesScreenState extends State<RecipesScreen> with WidgetsBindingObserver {
class _RecipesScreenState extends State<RecipesScreen> with WidgetsBindingObserver, SingleTickerProviderStateMixin {
List<RecipeModel> _recipes = [];
List<RecipeModel> _filteredRecipes = [];
bool _isLoading = false;
@ -41,6 +42,12 @@ class _RecipesScreenState extends State<RecipesScreen> with WidgetsBindingObserv
DateTime? _lastRefreshTime;
Set<String> _selectedTags = {}; // Currently selected tags for filtering
// Auto-scroll animation for tag filter bar
ScrollController? _tagScrollController;
AnimationController? _tagAnimationController;
Animation<double>? _tagAnimation;
bool _isUserScrollingTags = false;
@override
void initState() {
super.initState();
@ -49,15 +56,53 @@ class _RecipesScreenState extends State<RecipesScreen> with WidgetsBindingObserv
_checkLoginState();
_loadPreferences();
_searchController.addListener(_onSearchChanged);
// Initialize tag scroll animation
_tagScrollController = ScrollController();
_tagAnimationController = AnimationController(
vsync: this,
duration: const Duration(seconds: 8),
);
_tagAnimation = Tween<double>(begin: 0, end: 0.3).animate(
CurvedAnimation(parent: _tagAnimationController!, curve: Curves.easeInOut),
);
_startTagAutoScroll();
_tagAnimation?.addListener(_animateTagScroll);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_searchController.dispose();
_tagAnimationController?.dispose();
_tagScrollController?.dispose();
super.dispose();
}
void _startTagAutoScroll() {
if (!_isUserScrollingTags && _tagAnimationController != null) {
_tagAnimationController!.repeat(reverse: true);
}
}
void _animateTagScroll() {
if (!_isUserScrollingTags &&
_tagScrollController != null &&
_tagScrollController!.hasClients &&
_tagAnimation != null) {
final allTags = _getFilteredTags().toList();
if (allTags.length > 3) {
final maxScroll = _tagScrollController!.position.maxScrollExtent;
if (maxScroll > 0) {
final targetScroll = _tagAnimation!.value * maxScroll;
if ((_tagScrollController!.offset - targetScroll).abs() > 1) {
_tagScrollController!.jumpTo(targetScroll);
}
}
}
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
@ -169,6 +214,10 @@ class _RecipesScreenState extends State<RecipesScreen> with WidgetsBindingObserv
/// Handles tag selection for filtering
void _selectTag(String tag) {
// Stop auto-scroll permanently when user selects a tag
_isUserScrollingTags = true;
_tagAnimationController?.stop();
setState(() {
if (_selectedTags.contains(tag)) {
_selectedTags.remove(tag);
@ -334,8 +383,9 @@ class _RecipesScreenState extends State<RecipesScreen> with WidgetsBindingObserv
void _viewRecipe(RecipeModel recipe) async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => AddRecipeScreen(recipe: recipe, viewMode: true),
Material3PageRoute(
child: AddRecipeScreen(recipe: recipe, viewMode: true),
useEmphasized: true, // Use emphasized easing for more fluid feel
),
);
// Always reload recipes after viewing/editing to ensure UI is up-to-date
@ -491,7 +541,17 @@ class _RecipesScreenState extends State<RecipesScreen> with WidgetsBindingObserv
),
),
)
: ListView.builder(
: NotificationListener<ScrollNotification>(
onNotification: (notification) {
// Detect when user manually scrolls - stop auto-scroll permanently
if (notification is ScrollStartNotification && notification.dragDetails != null) {
_isUserScrollingTags = true;
_tagAnimationController?.stop();
}
return false;
},
child: ListView.builder(
controller: _tagScrollController ?? ScrollController(),
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 16),
itemCount: allTags.length,
@ -501,7 +561,15 @@ class _RecipesScreenState extends State<RecipesScreen> with WidgetsBindingObserv
return Padding(
padding: const EdgeInsets.only(right: 8),
child: FilterChip(
label: Text(tag),
label: Text(
tag,
style: TextStyle(
color: isSelected
? Colors.white
: (isDark ? Colors.white : Colors.black87),
fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
),
),
selected: isSelected,
onSelected: (selected) {
_selectTag(tag);
@ -511,16 +579,18 @@ class _RecipesScreenState extends State<RecipesScreen> with WidgetsBindingObserv
backgroundColor: isDark
? Colors.grey[800]
: Colors.grey[200],
labelStyle: TextStyle(
color: isSelected
? Colors.white
: (isDark ? Colors.white : Colors.black87),
),
side: isSelected
? BorderSide(
color: theme.primaryColor.withValues(alpha: 0.8),
width: 1.5,
)
: null,
),
);
},
),
),
),
);
}
@ -1103,7 +1173,10 @@ class _RecipeCard extends StatelessWidget {
Widget _buildRecipeImage(String imageUrl) {
final mediaService = ServiceLocator.instance.mediaService;
if (mediaService == null) {
return Image.network(imageUrl, fit: BoxFit.cover);
return _FadeInImageWidget(
imageUrl: imageUrl,
isNetwork: true,
);
}
// Try to extract asset ID from Immich URL (format: .../api/assets/{id}/original)
@ -1135,18 +1208,102 @@ class _RecipeCard extends StatelessWidget {
);
}
return Image.memory(
snapshot.data!,
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
return _FadeInImageWidget(
imageBytes: snapshot.data!,
);
},
);
}
return Image.network(
imageUrl,
return _FadeInImageWidget(
imageUrl: imageUrl,
isNetwork: true,
);
}
Widget _buildVideoThumbnail(String videoUrl) {
return _VideoThumbnailPreview(videoUrl: videoUrl);
}
Color _getRatingColor(int rating) {
if (rating >= 4) return Colors.green;
if (rating >= 2) return Colors.orange;
return Colors.red;
}
}
/// Widget that displays an image with a smooth fade-in animation.
class _FadeInImageWidget extends StatefulWidget {
final String? imageUrl;
final Uint8List? imageBytes;
final bool isNetwork;
const _FadeInImageWidget({
this.imageUrl,
this.imageBytes,
this.isNetwork = false,
}) : assert(imageUrl != null || imageBytes != null, 'Either imageUrl or imageBytes must be provided');
@override
State<_FadeInImageWidget> createState() => _FadeInImageWidgetState();
}
class _FadeInImageWidgetState extends State<_FadeInImageWidget>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _fadeAnimation;
bool _imageLoaded = false;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 500),
vsync: this,
);
_fadeAnimation = CurvedAnimation(
parent: _controller,
curve: Curves.easeOut,
);
// Start with opacity 0
_controller.value = 0.0;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _onImageLoaded() {
if (!_imageLoaded && mounted) {
_imageLoaded = true;
_controller.forward();
}
}
@override
Widget build(BuildContext context) {
Widget imageWidget;
if (widget.imageBytes != null) {
// For memory images, use frameBuilder to detect when image is ready
imageWidget = Image.memory(
widget.imageBytes!,
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
if ((wasSynchronouslyLoaded || frame != null) && !_imageLoaded) {
WidgetsBinding.instance.addPostFrameCallback((_) => _onImageLoaded());
}
return child;
},
);
} else if (widget.imageUrl != null) {
// For network images, use frameBuilder to detect when image is ready
imageWidget = Image.network(
widget.imageUrl!,
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
@ -1157,7 +1314,10 @@ class _RecipeCard extends StatelessWidget {
);
},
loadingBuilder: (context, child, loadingProgress) {
if (loadingProgress == null) return child;
if (loadingProgress == null) {
// Image is loaded, return child and let frameBuilder handle fade-in
return child;
}
return Container(
color: Colors.grey.shade200,
child: Center(
@ -1170,21 +1330,27 @@ class _RecipeCard extends StatelessWidget {
),
);
},
);
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
if ((wasSynchronouslyLoaded || frame != null) && !_imageLoaded) {
WidgetsBinding.instance.addPostFrameCallback((_) => _onImageLoaded());
}
Widget _buildVideoThumbnail(String videoUrl) {
return _VideoThumbnailPreview(videoUrl: videoUrl);
return child;
},
);
} else {
return Container(
color: Colors.grey.shade200,
child: const Icon(Icons.image_not_supported, size: 32, color: Colors.grey),
);
}
Color _getRatingColor(int rating) {
if (rating >= 4) return Colors.green;
if (rating >= 2) return Colors.orange;
return Colors.red;
return FadeTransition(
opacity: _fadeAnimation,
child: imageWidget,
);
}
}
/// Widget that displays a video thumbnail preview with a few seconds of playback.
class _VideoThumbnailPreview extends StatefulWidget {
final String videoUrl;

@ -56,6 +56,7 @@ class RelayManagementController extends ChangeNotifier {
url: relay.url,
isConnected: relay.isConnected,
isEnabled: relay.isEnabled,
retryCount: relay.retryCount,
)).toList();
notifyListeners();
}

@ -28,6 +28,7 @@ class RelayManagementScreen extends StatefulWidget {
class _RelayManagementScreenState extends State<RelayManagementScreen> {
final TextEditingController _urlController = TextEditingController();
final FocusNode _urlFocusNode = FocusNode();
bool _useNip05RelaysAutomatically = false;
bool _isDarkMode = false;
bool _isLoadingSetting = true;
@ -37,8 +38,6 @@ class _RelayManagementScreenState extends State<RelayManagementScreen> {
MultiMediaService? _multiMediaService;
List<MediaServerConfig> _mediaServers = [];
MediaServerConfig? _defaultMediaServer;
bool _mediaServersExpanded = false;
bool _settingsExpanded = true; // Settings expanded by default
// Store original values to detect changes
List<MediaServerConfig> _originalMediaServers = [];
@ -51,6 +50,16 @@ class _RelayManagementScreenState extends State<RelayManagementScreen> {
super.initState();
_initializeMultiMediaService();
_loadSetting();
_urlFocusNode.addListener(_onUrlFocusChanged);
}
void _onUrlFocusChanged() {
if (_urlFocusNode.hasFocus && _urlController.text.isEmpty) {
_urlController.text = 'wss://';
_urlController.selection = TextSelection.fromPosition(
TextPosition(offset: _urlController.text.length),
);
}
}
Future<void> _initializeMultiMediaService() async {
@ -71,7 +80,6 @@ class _RelayManagementScreenState extends State<RelayManagementScreen> {
_defaultMediaServer = _multiMediaService!.getDefaultServer();
_originalMediaServers = List.from(_mediaServers);
_originalDefaultServerId = _defaultMediaServer?.id;
_mediaServersExpanded = _mediaServers.isNotEmpty; // Auto-expand if servers exist
});
}
}
@ -133,6 +141,8 @@ class _RelayManagementScreenState extends State<RelayManagementScreen> {
@override
void dispose() {
_urlController.dispose();
_urlFocusNode.removeListener(_onUrlFocusChanged);
_urlFocusNode.dispose();
super.dispose();
}
@ -399,7 +409,7 @@ class _RelayManagementScreenState extends State<RelayManagementScreen> {
(s) => s.isDefault,
orElse: () => updatedServers.isNotEmpty ? updatedServers.first : result,
);
_mediaServersExpanded = true; // Expand to show the newly added server
// Server added successfully
});
Logger.info('Media server added. Total servers: ${_mediaServers.length}, Default: ${_defaultMediaServer?.baseUrl}');
@ -495,274 +505,142 @@ class _RelayManagementScreenState extends State<RelayManagementScreen> {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: const Text('Advanced Settings'),
actions: _hasUnsavedChanges
? [
TextButton.icon(
onPressed: _saveAllSettings,
icon: const Icon(Icons.save, size: 18),
label: const Text('Save'),
style: TextButton.styleFrom(
foregroundColor: Colors.green,
),
),
]
: null,
),
body: ListenableBuilder(
listenable: widget.controller,
builder: (context, child) {
return SingleChildScrollView(
child: Column(
children: [
// Settings section - Now using ExpansionTile for uniformity
ExpansionTile(
title: const Text('Settings'),
subtitle: _hasUnsavedChanges
? const Text('You have unsaved changes', style: TextStyle(color: Colors.orange))
: Text('${_useNip05RelaysAutomatically ? "NIP-05" : "Manual"} relays • ${_isDarkMode ? "Dark" : "Light"} mode'),
initiallyExpanded: _settingsExpanded,
trailing: _hasUnsavedChanges
? ElevatedButton.icon(
onPressed: _saveAllSettings,
icon: const Icon(Icons.save, size: 18),
label: const Text('Save'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
),
)
: null,
onExpansionChanged: (expanded) {
setState(() {
_settingsExpanded = expanded;
});
},
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (_isLoadingSetting)
const Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
SizedBox(width: 12),
Text('Loading settings...'),
],
// Preferences Section
_buildSectionCard(
context: context,
title: 'Preferences',
icon: Icons.settings_outlined,
child: _isLoadingSetting
? const Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
)
else ...[
SwitchListTile(
title: const Text('Use NIP-05 relays automatically'),
subtitle: const Text(
'Automatically replace relays with NIP-05 preferred relays upon login',
style: TextStyle(fontSize: 12),
),
value: _useNip05RelaysAutomatically,
onChanged: (value) {
_saveSetting('use_nip05_relays_automatically', value);
},
contentPadding: EdgeInsets.zero,
),
const SizedBox(height: 8),
SwitchListTile(
title: const Text('Dark Mode'),
subtitle: const Text(
'Enable dark theme for the app',
style: TextStyle(fontSize: 12),
),
: Column(
children: [
_buildSettingTile(
context: context,
title: 'Dark Mode',
subtitle: 'Enable dark theme for the app',
value: _isDarkMode,
onChanged: (value) {
_saveSetting('dark_mode', value);
},
contentPadding: EdgeInsets.zero,
icon: Icons.dark_mode_outlined,
),
const SizedBox(height: 16),
// Media Server Settings - Multiple Servers
],
),
),
const SizedBox(height: 8),
// Media Server Section
Builder(
builder: (context) {
final immichEnabled = dotenv.env['IMMICH_ENABLE']?.toLowerCase() != 'false';
final defaultBlossomServer = dotenv.env['BLOSSOM_SERVER'] ?? 'https://media.based21.com';
return ExpansionTile(
key: ValueKey('media-servers-${_mediaServers.length}-${_mediaServersExpanded}'),
title: const Text('Media Servers'),
subtitle: Text(_mediaServers.isEmpty
? 'No servers configured'
: '${_mediaServers.length} server(s)${_defaultMediaServer != null ? " • Default: ${_defaultMediaServer!.name ?? _defaultMediaServer!.type}" : ""}'),
initiallyExpanded: _mediaServersExpanded,
onExpansionChanged: (expanded) {
setState(() {
_mediaServersExpanded = expanded;
});
},
return _buildSectionCard(
context: context,
title: 'Media Server',
icon: Icons.storage_outlined,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Server list
if (_mediaServers.isEmpty)
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'No media servers configured. Add one to get started.',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.grey,
),
),
if (_defaultMediaServer != null)
_buildMediaServerTile(
context: context,
server: _defaultMediaServer!,
isDefault: true,
onEdit: () => _editMediaServer(_defaultMediaServer!),
onRemove: () => _removeMediaServer(_defaultMediaServer!),
)
else
...List.generate(_mediaServers.length, (index) {
final server = _mediaServers[index];
return ListTile(
key: ValueKey(server.id),
leading: Icon(
server.isDefault ? Icons.star : Icons.star_border,
color: server.isDefault ? Colors.amber : Colors.grey,
),
title: Text(server.name ?? '${server.type.toUpperCase()} Server'),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(server.baseUrl),
if (server.isDefault)
Padding(
padding: const EdgeInsets.only(top: 4.0),
child: Chip(
label: const Text('Default'),
labelStyle: const TextStyle(fontSize: 10),
padding: EdgeInsets.zero,
),
),
],
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.edit),
onPressed: () => _editMediaServer(server),
padding: const EdgeInsets.symmetric(vertical: 4),
child: Text(
'No media server configured',
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey,
fontSize: 12,
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: () => _removeMediaServer(server),
),
],
),
onTap: () => _setDefaultServer(server),
);
}),
// Add server button
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton.icon(
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: () => _addMediaServer(immichEnabled, defaultBlossomServer),
icon: const Icon(Icons.add),
label: const Text('Add Media Server'),
icon: const Icon(Icons.add, size: 16),
label: const Text('Add More', style: TextStyle(fontSize: 13)),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
minimumSize: const Size(0, 36),
),
),
],
),
);
},
),
],
],
),
),
],
),
// Error message
if (widget.controller.error != null)
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
color: Colors.red.shade100,
child: Row(
children: [
Icon(Icons.error, color: Colors.red.shade700),
const SizedBox(width: 8),
Expanded(
child: Text(
widget.controller.error!,
style: TextStyle(color: Colors.red.shade700),
),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: widget.controller.clearError,
color: Colors.red.shade700,
),
],
),
),
const SizedBox(height: 8),
// Relay Management Section (Expandable)
ExpansionTile(
title: const Text('Nostr Relays'),
subtitle: Text('${widget.controller.relays.length} relay(s) configured'),
initiallyExpanded: false,
children: [
Padding(
padding: const EdgeInsets.all(16),
// Relays Section
_buildSectionCard(
context: context,
title: 'Relays',
icon: Icons.cloud_outlined,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Test All and Toggle All buttons
Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: widget.controller.isCheckingHealth
? null
: widget.controller.checkRelayHealth,
icon: widget.controller.isCheckingHealth
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.network_check),
label: const Text('Test All'),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton.icon(
onPressed: widget.controller.relays.isEmpty
? null
: () async {
final hasEnabled = widget.controller.relays.any((r) => r.isEnabled);
if (hasEnabled) {
await widget.controller.turnAllOff();
} else {
await widget.controller.turnAllOn();
}
},
icon: const Icon(Icons.power_settings_new),
label: Text(
widget.controller.relays.isNotEmpty &&
widget.controller.relays.any((r) => r.isEnabled)
? 'Turn All Off'
: 'Turn All On',
),
),
),
],
),
const SizedBox(height: 16),
// Add relay input
Row(
children: [
Expanded(
child: TextField(
TextField(
controller: _urlController,
focusNode: _urlFocusNode,
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
labelText: 'Relay URL',
hintText: 'wss://relay.example.com',
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.link, size: 18),
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
isDense: true,
),
keyboardType: TextInputType.url,
),
),
const SizedBox(width: 8),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: () async {
final url = _urlController.text.trim();
String url = _urlController.text.trim();
// Remove wss:// prefix if user added it manually, we'll add it properly
if (url.startsWith('wss://')) {
url = url.substring(6);
}
if (url.isNotEmpty) {
final success = await widget.controller.addRelay(url);
final fullUrl = url.startsWith('wss://') ? url : 'wss://$url';
final success = await widget.controller.addRelay(fullUrl);
if (mounted) {
if (success) {
_urlController.clear();
@ -787,48 +665,49 @@ class _RelayManagementScreenState extends State<RelayManagementScreen> {
}
}
},
icon: const Icon(Icons.add),
label: const Text('Add'),
icon: const Icon(Icons.add, size: 16),
label: const Text('Add Relay', style: TextStyle(fontSize: 13)),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
minimumSize: const Size(0, 36),
),
],
),
const SizedBox(height: 16),
const SizedBox(height: 12),
// Relay list
SizedBox(
height: 300,
child: widget.controller.relays.isEmpty
? Center(
if (widget.controller.relays.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.cloud_off,
size: 48,
size: 36,
color: Colors.grey.shade400,
),
const SizedBox(height: 16),
const SizedBox(height: 8),
Text(
'No relays configured',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
style: theme.textTheme.bodyMedium?.copyWith(
color: Colors.grey,
fontSize: 13,
),
),
const SizedBox(height: 8),
const SizedBox(height: 4),
Text(
'Add a relay to get started',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey,
fontSize: 11,
),
),
],
),
)
: ListView.builder(
shrinkWrap: true,
itemCount: widget.controller.relays.length,
itemBuilder: (context, index) {
final relay = widget.controller.relays[index];
return _RelayListItem(
else
...widget.controller.relays.map((relay) {
return Padding(
padding: const EdgeInsets.only(bottom: 6),
child: _RelayListItem(
relay: relay,
onToggle: () async {
await widget.controller.toggleRelay(relay.url);
@ -842,15 +721,47 @@ class _RelayManagementScreenState extends State<RelayManagementScreen> {
),
);
},
),
);
},
}).toList(),
],
),
),
],
// Error message
if (widget.controller.error != null) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.red.shade50,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.red.shade200),
),
child: Row(
children: [
Icon(Icons.error_outline, size: 16, color: Colors.red.shade700),
const SizedBox(width: 8),
Expanded(
child: Text(
widget.controller.error!,
style: TextStyle(
color: Colors.red.shade700,
fontSize: 12,
),
),
),
IconButton(
icon: const Icon(Icons.close, size: 16),
onPressed: widget.controller.clearError,
color: Colors.red.shade700,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 24, minHeight: 24),
),
],
),
),
],
],
),
);
@ -858,6 +769,207 @@ class _RelayManagementScreenState extends State<RelayManagementScreen> {
),
);
}
Widget _buildSectionCard({
required BuildContext context,
required String title,
required IconData icon,
required Widget child,
}) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
return Card(
elevation: 0,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: BorderSide(
color: isDark ? Colors.grey.shade800 : Colors.grey.shade200,
width: 1,
),
),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: theme.primaryColor.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(6),
),
child: Icon(icon, color: theme.primaryColor, size: 16),
),
const SizedBox(width: 8),
Text(
title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
fontSize: 15,
),
),
],
),
const SizedBox(height: 12),
child,
],
),
),
);
}
Widget _buildSettingTile({
required BuildContext context,
required String title,
required String subtitle,
required bool value,
required ValueChanged<bool> onChanged,
required IconData icon,
}) {
final theme = Theme.of(context);
return Row(
children: [
Icon(icon, size: 16, color: theme.primaryColor),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w500,
fontSize: 14,
),
),
const SizedBox(height: 2),
Text(
subtitle,
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey,
fontSize: 11,
),
),
],
),
),
Transform.scale(
scale: 0.85,
child: Switch(
value: value,
onChanged: onChanged,
),
),
],
);
}
Widget _buildMediaServerTile({
required BuildContext context,
required MediaServerConfig server,
required bool isDefault,
required VoidCallback onEdit,
required VoidCallback onRemove,
}) {
final theme = Theme.of(context);
return Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: theme.cardColor,
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: isDefault ? theme.primaryColor.withValues(alpha: 0.3) : Colors.grey.shade300,
width: isDefault ? 1.5 : 1,
),
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(5),
decoration: BoxDecoration(
color: theme.primaryColor.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(6),
),
child: Icon(
Icons.storage,
color: theme.primaryColor,
size: 16,
),
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Flexible(
child: Text(
server.name ?? '${server.type.toUpperCase()} Server',
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
fontSize: 13,
),
overflow: TextOverflow.ellipsis,
),
),
if (isDefault) ...[
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: theme.primaryColor.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(3),
),
child: Text(
'Default',
style: TextStyle(
fontSize: 9,
fontWeight: FontWeight.w600,
color: theme.primaryColor,
),
),
),
],
],
),
const SizedBox(height: 2),
Text(
server.baseUrl,
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey,
fontSize: 11,
),
overflow: TextOverflow.ellipsis,
),
],
),
),
IconButton(
icon: const Icon(Icons.edit, size: 16),
onPressed: onEdit,
tooltip: 'Edit',
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 28, minHeight: 28),
),
IconButton(
icon: const Icon(Icons.delete_outline, size: 16),
onPressed: onRemove,
tooltip: 'Remove',
color: Colors.red,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 28, minHeight: 28),
),
],
),
);
}
}
/// Widget for displaying a single relay in the list.
@ -879,10 +991,21 @@ class _RelayListItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
final theme = Theme.of(context);
final isConnected = relay.isConnected && relay.isEnabled;
return Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: theme.cardColor,
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: isConnected
? Colors.green.withValues(alpha: 0.3)
: Colors.grey.shade300,
width: isConnected ? 1.5 : 1,
),
),
child: Row(
children: [
// Status indicator
@ -891,12 +1014,19 @@ class _RelayListItem extends StatelessWidget {
height: 10,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: relay.isConnected && relay.isEnabled
? Colors.green
: Colors.grey,
color: isConnected ? Colors.green : Colors.grey,
boxShadow: isConnected
? [
BoxShadow(
color: Colors.green.withValues(alpha: 0.5),
blurRadius: 3,
spreadRadius: 1,
),
]
: null,
),
),
const SizedBox(width: 8),
const SizedBox(width: 10),
// URL and status text
Expanded(
child: Column(
@ -905,69 +1035,59 @@ class _RelayListItem extends StatelessWidget {
children: [
Text(
relay.url,
style: const TextStyle(
fontSize: 13,
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w500,
fontSize: 13,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
const SizedBox(height: 2),
Row(
children: [
Icon(
isConnected ? Icons.check_circle : Icons.cancel,
size: 12,
color: isConnected ? Colors.green : Colors.grey,
),
const SizedBox(width: 3),
Text(
relay.isConnected && relay.isEnabled
? 'Connected'
: 'Disabled',
style: TextStyle(
isConnected ? 'Connected' : 'Disabled',
style: theme.textTheme.bodySmall?.copyWith(
color: isConnected ? Colors.green : Colors.grey,
fontWeight: FontWeight.w500,
fontSize: 11,
color: relay.isConnected && relay.isEnabled
? Colors.green
: Colors.grey,
),
),
],
),
],
),
),
const SizedBox(width: 8),
// Toggle switch
Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
relay.isEnabled ? 'ON' : 'OFF',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: relay.isEnabled
? Colors.green
: Colors.grey[600],
),
),
const SizedBox(width: 4),
Transform.scale(
scale: 0.8,
scale: 0.85,
child: Switch(
value: relay.isEnabled,
onChanged: (_) => onToggle(),
),
),
],
),
const SizedBox(width: 4),
// Remove button
IconButton(
icon: const Icon(Icons.delete, size: 18),
icon: const Icon(Icons.delete_outline, size: 16),
color: Colors.red,
tooltip: 'Remove',
onPressed: onRemove,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(
minWidth: 32,
minHeight: 32,
minWidth: 28,
minHeight: 28,
),
),
],
),
),
);
}
}

Loading…
Cancel
Save

Powered by TurnKey Linux.