You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

247 lines
6.5 KiB

import 'package:flutter/material.dart';
import 'dart:typed_data';
import '../../core/service_locator.dart';
import '../navigation/main_navigation_scaffold.dart';
/// Primary AppBar widget with user icon for all main screens.
class PrimaryAppBar extends StatefulWidget implements PreferredSizeWidget {
final String title;
const PrimaryAppBar({
super.key,
required this.title,
});
@override
State<PrimaryAppBar> createState() => _PrimaryAppBarState();
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
class _PrimaryAppBarState extends State<PrimaryAppBar> with WidgetsBindingObserver {
Uint8List? _avatarBytes;
bool _isLoadingAvatar = false;
String? _lastProfilePictureUrl; // Track URL to avoid reloading
String? _lastUserId; // Track user ID to detect user changes
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_loadAvatar();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
// Reload avatar when app resumes (in case user changed)
if (state == AppLifecycleState.resumed) {
_checkAndReloadAvatar();
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_checkAndReloadAvatar();
}
void _checkAndReloadAvatar() {
final sessionService = ServiceLocator.instance.sessionService;
if (sessionService == null) {
// Clear avatar if no session service
if (mounted) {
setState(() {
_avatarBytes = null;
_isLoadingAvatar = false;
_lastProfilePictureUrl = null;
_lastUserId = null;
});
}
return;
}
final currentUser = sessionService.currentUser;
final currentUserId = currentUser?.id;
final profilePictureUrl = currentUser?.nostrProfile?.picture;
// If user ID changed, clear cache and reload
if (currentUserId != _lastUserId) {
_lastUserId = currentUserId;
_lastProfilePictureUrl = null; // Clear to force reload
_avatarBytes = null; // Clear cached avatar
_loadAvatar();
return;
}
// If profile picture URL changed, reload
if (profilePictureUrl != _lastProfilePictureUrl) {
_lastProfilePictureUrl = profilePictureUrl;
_loadAvatar();
}
}
Future<void> _loadAvatar() async {
final sessionService = ServiceLocator.instance.sessionService;
if (sessionService == null || !sessionService.isLoggedIn) {
// Clear avatar when logged out
if (mounted) {
setState(() {
_avatarBytes = null;
_isLoadingAvatar = false;
_lastProfilePictureUrl = null;
_lastUserId = null;
});
}
return;
}
final currentUser = sessionService.currentUser;
if (currentUser == null) {
if (mounted) {
setState(() {
_avatarBytes = null;
_isLoadingAvatar = false;
_lastProfilePictureUrl = null;
_lastUserId = null;
});
}
return;
}
// Update last user ID
_lastUserId = currentUser.id;
final profilePictureUrl = currentUser.nostrProfile?.picture;
if (profilePictureUrl == null || profilePictureUrl.isEmpty) {
// Clear avatar if no profile picture
if (mounted) {
setState(() {
_avatarBytes = null;
_isLoadingAvatar = false;
_lastProfilePictureUrl = null;
});
}
return;
}
// Don't reload if it's the same URL
if (profilePictureUrl == _lastProfilePictureUrl && _avatarBytes != null) {
return;
}
_lastProfilePictureUrl = profilePictureUrl;
setState(() {
_isLoadingAvatar = true;
});
try {
// Extract asset ID from Immich URL using regex (same as SessionScreen)
final mediaService = ServiceLocator.instance.mediaService;
if (mediaService != null) {
// Try to extract asset ID from URL (format: .../api/assets/{id}/original or .../share/{shareId})
final assetIdMatch = RegExp(r'/api/assets/([^/]+)/').firstMatch(profilePictureUrl);
String? assetId;
if (assetIdMatch != null) {
assetId = assetIdMatch.group(1);
} else {
// For Blossom URLs, use the full URL
assetId = profilePictureUrl;
}
if (assetId != null) {
final bytes = await mediaService.fetchImageBytes(assetId, isThumbnail: true);
if (mounted) {
setState(() {
_avatarBytes = bytes;
_isLoadingAvatar = false;
});
}
return;
}
}
// Fallback: try to fetch as regular image (for non-Immich URLs or shared links)
// For now, we'll just set loading to false
if (mounted) {
setState(() {
_isLoadingAvatar = false;
});
}
} catch (e) {
// Log error for debugging
debugPrint('Failed to load avatar: $e');
if (mounted) {
setState(() {
_isLoadingAvatar = false;
_avatarBytes = null; // Clear on error
});
}
}
}
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(widget.title),
actions: [
// Only show user icon on Home screen (title == 'Home')
if (widget.title == 'Home')
IconButton(
icon: _buildUserIcon(),
tooltip: 'User',
onPressed: () {
// Navigate to User screen by finding the MainNavigationScaffold
final scaffold = context.findAncestorStateOfType<MainNavigationScaffoldState>();
scaffold?.navigateToUser();
},
),
],
);
}
Widget _buildUserIcon() {
if (_isLoadingAvatar) {
return const CircleAvatar(
radius: 12,
backgroundColor: Colors.transparent,
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
if (_avatarBytes != null) {
return CircleAvatar(
radius: 12,
backgroundImage: MemoryImage(_avatarBytes!),
onBackgroundImageError: (_, __) {
// Clear avatar on error
if (mounted) {
setState(() {
_avatarBytes = null;
});
}
},
);
}
return const CircleAvatar(
radius: 12,
child: Icon(Icons.person, size: 16),
);
}
}

Powered by TurnKey Linux.