fix: fixed more widgets

This commit is contained in:
cogwheel0
2025-08-20 18:39:30 +05:30
parent 424aa7bffd
commit 9a5c5a573f
6 changed files with 1132 additions and 733 deletions

View File

@@ -1,12 +1,12 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import '../../../shared/theme/theme_extensions.dart';
import '../../../shared/widgets/markdown/streaming_markdown_widget.dart';
import 'enhanced_image_attachment.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'dart:io' show Platform;
import '../../../core/providers/app_providers.dart';
class ModernMessageBubble extends ConsumerStatefulWidget {
final dynamic message;
@@ -42,14 +42,6 @@ class _ModernMessageBubbleState extends ConsumerState<ModernMessageBubble>
bool _showActions = false;
late AnimationController _fadeController;
late AnimationController _slideController;
static const int _maxCachedImages = 24;
// Cache for image base64 data to prevent repeated API calls
final Map<String, String?> _imageCache = {};
// Cache for rendered image widgets to prevent rebuilding during streaming
final Map<String, Widget> _imageWidgetCache = {};
String? _lastAttachmentIds;
@override
void initState() {
@@ -66,202 +58,121 @@ class _ModernMessageBubbleState extends ConsumerState<ModernMessageBubble>
Widget _buildAttachmentImages() {
Widget _buildUserAttachmentImages() {
if (widget.message.attachmentIds == null ||
widget.message.attachmentIds!.isEmpty) {
return const SizedBox.shrink();
}
final currentAttachmentIds = widget.message.attachmentIds!.join('_');
final imageCount = widget.message.attachmentIds!.length;
// Clear cache if attachment IDs changed
if (_lastAttachmentIds != currentAttachmentIds) {
_imageWidgetCache.clear();
_lastAttachmentIds = currentAttachmentIds;
// iMessage-style image layout
if (imageCount == 1) {
// Single image - larger display
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.messageBubble),
child: EnhancedImageAttachment(
attachmentId: widget.message.attachmentIds![0],
isUserMessage: true,
constraints: const BoxConstraints(
maxWidth: 280,
maxHeight: 350,
),
),
),
],
);
} else if (imageCount == 2) {
// Two images side by side
return Row(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Row(
mainAxisSize: MainAxisSize.min,
children: widget.message.attachmentIds!.map((attachmentId) {
return Padding(
padding: EdgeInsets.only(
left: attachmentId == widget.message.attachmentIds!.first
? 0
: Spacing.xs,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.messageBubble),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isUserMessage: true,
constraints: const BoxConstraints(
maxWidth: 135,
maxHeight: 180,
),
),
),
);
}).toList(),
),
),
],
);
} else {
// Grid layout for 3+ images
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Flexible(
child: Container(
constraints: const BoxConstraints(maxWidth: 280),
child: Wrap(
alignment: WrapAlignment.end,
spacing: Spacing.xs,
runSpacing: Spacing.xs,
children: widget.message.attachmentIds!.map((attachmentId) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isUserMessage: true,
constraints: BoxConstraints(
maxWidth: imageCount == 3 ? 135 : 90,
maxHeight: imageCount == 3 ? 135 : 90,
),
),
);
}).toList(),
),
),
),
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: widget.message.attachmentIds!.map<Widget>((attachmentId) {
// Return cached widget if available
if (_imageWidgetCache.containsKey(attachmentId)) {
return _imageWidgetCache[attachmentId]!;
}
// Build widget and cache it
final imageWidget = _buildSingleImageWidget(attachmentId);
_imageWidgetCache[attachmentId] = imageWidget;
return imageWidget;
}).toList(),
);
}
Widget _buildSingleImageWidget(String attachmentId) {
return Consumer(
builder: (context, ref, child) {
final api = ref.read(apiServiceProvider);
if (api == null) return const SizedBox.shrink();
Widget _buildAssistantAttachmentImages() {
if (widget.message.attachmentIds == null ||
widget.message.attachmentIds!.isEmpty) {
return const SizedBox.shrink();
}
return FutureBuilder<String?>(
key: ValueKey('img_$attachmentId'),
future: _getCachedImageBase64(api, attachmentId),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Container(
height: 150,
width: 200,
margin: const EdgeInsets.only(bottom: Spacing.xs),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceBackground.withValues(
alpha: 0.5,
),
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
),
child: Center(
child: CircularProgressIndicator(
color: context.conduitTheme.buttonPrimary,
strokeWidth: 2,
),
),
);
}
if (snapshot.hasError ||
!snapshot.hasData ||
snapshot.data == null) {
return Container(
height: 100,
width: 150,
margin: const EdgeInsets.only(bottom: Spacing.xs),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceBackground.withValues(
alpha: 0.3,
),
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
border: Border.all(
color: context.conduitTheme.textSecondary.withValues(
alpha: 0.3,
),
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.broken_image_outlined,
color: context.conduitTheme.textSecondary,
size: 32,
),
const SizedBox(height: Spacing.xs),
Text(
'Image unavailable',
style: TextStyle(
color: context.conduitTheme.textSecondary,
fontSize: AppTypography.bodySmall,
),
),
],
),
);
}
final base64Data = snapshot.data!;
try {
// Handle data URLs (data:image/...;base64,...)
String actualBase64;
if (base64Data.startsWith('data:')) {
// Extract base64 part from data URL
final commaIndex = base64Data.indexOf(',');
if (commaIndex != -1) {
actualBase64 = base64Data.substring(commaIndex + 1);
} else {
throw Exception('Invalid data URL format');
}
} else {
// Direct base64 string
actualBase64 = base64Data;
}
final imageBytes = base64.decode(actualBase64);
return Container(
margin: const EdgeInsets.only(bottom: Spacing.xs),
constraints: const BoxConstraints(
maxWidth: 300,
maxHeight: 300,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
child: Image.memory(
imageBytes,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Container(
height: 100,
width: 150,
decoration: BoxDecoration(
color: context.conduitTheme.surfaceBackground
.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(
AppBorderRadius.sm,
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline,
color: context.conduitTheme.error,
size: 32,
),
const SizedBox(height: Spacing.xs),
Text(
'Failed to load image',
style: TextStyle(
color: context.conduitTheme.error,
fontSize: AppTypography.bodySmall,
),
),
],
),
);
},
),
),
);
} catch (e) {
return Container(
height: 100,
width: 150,
margin: const EdgeInsets.only(bottom: Spacing.xs),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceBackground.withValues(
alpha: 0.3,
),
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline,
color: context.conduitTheme.error,
size: 32,
),
const SizedBox(height: Spacing.xs),
Text(
'Invalid image format',
style: TextStyle(
color: context.conduitTheme.error,
fontSize: AppTypography.bodySmall,
),
),
],
),
);
}
},
// Assistant images - similar style but left-aligned
return Wrap(
spacing: Spacing.sm,
runSpacing: Spacing.sm,
children: widget.message.attachmentIds!.map<Widget>((attachmentId) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.messageBubble),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
constraints: const BoxConstraints(
maxWidth: 300,
maxHeight: 350,
),
),
);
},
}).toList(),
);
}
@@ -296,81 +207,84 @@ class _ModernMessageBubbleState extends ConsumerState<ModernMessageBubble>
}
Widget _buildUserMessage() {
return Container(
width: double.infinity,
margin: const EdgeInsets.only(
bottom: Spacing.messagePadding,
left: Spacing.xxxl,
right: Spacing.xs,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
final hasImages = widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty;
final hasText = widget.message.content.isNotEmpty;
return GestureDetector(
onLongPress: () => _toggleActions(),
behavior: HitTestBehavior.translucent,
child: Container(
width: double.infinity,
margin: const EdgeInsets.only(
bottom: Spacing.sm,
left: Spacing.xxxl,
right: Spacing.xs,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// Display images outside and above the text bubble (iMessage style)
if (hasImages) ...[
_buildUserAttachmentImages(),
if (hasText) const SizedBox(height: Spacing.xs),
],
// Display text bubble if there's text content
if (hasText)
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Flexible(
child: GestureDetector(
onLongPress: () => _toggleActions(),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.messagePadding,
vertical: Spacing.sm,
vertical: Spacing.xs,
),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
context.conduitTheme.chatBubbleUser.withValues(
alpha: 0.95,
),
context.conduitTheme.chatBubbleUser,
],
),
borderRadius: BorderRadius.circular(
AppBorderRadius.messageBubble,
),
border: Border.all(
color: context.conduitTheme.chatBubbleUserBorder,
width: BorderWidth.regular,
),
boxShadow: ConduitShadows.high,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Display images if any
if (widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty)
_buildAttachmentImages(),
// Display text content if any
if (widget.message.content.isNotEmpty) ...[
if (widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty)
const SizedBox(height: Spacing.sm),
_buildCustomText(
widget.message.content,
context.conduitTheme.chatBubbleUserText,
),
],
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
context.conduitTheme.chatBubbleUser.withValues(
alpha: 0.95,
),
context.conduitTheme.chatBubbleUser,
],
),
borderRadius: BorderRadius.circular(
AppBorderRadius.messageBubble,
),
border: Border.all(
color: context.conduitTheme.chatBubbleUserBorder,
width: BorderWidth.regular,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.08),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: _buildCustomText(
widget.message.content,
context.conduitTheme.chatBubbleUserText,
),
),
),
],
),
// Action buttons below the message bubble
if (_showActions) ...[
const SizedBox(height: Spacing.sm),
_buildUserActionButtons(),
],
// Action buttons below the message
if (_showActions) ...[
const SizedBox(height: Spacing.sm),
_buildUserActionButtons(),
],
),
)
],
),
),
)
.animate()
.fadeIn(duration: AnimationDuration.messageAppear)
.slideX(
@@ -382,103 +296,115 @@ class _ModernMessageBubbleState extends ConsumerState<ModernMessageBubble>
}
Widget _buildAssistantMessage() {
return Container(
width: double.infinity,
margin: const EdgeInsets.only(
bottom: Spacing.lg,
left: Spacing.xs,
right: Spacing.xxxl,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Simplified AI Name and Avatar
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Row(
children: [
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
context.conduitTheme.buttonPrimary.withValues(
alpha: 0.9,
),
context.conduitTheme.buttonPrimary,
],
),
borderRadius: BorderRadius.circular(
AppBorderRadius.small,
),
final hasImages = widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty;
final hasContent = widget.message.content.isNotEmpty &&
widget.message.content != '[TYPING_INDICATOR]';
final showTyping = (widget.message.content.isEmpty ||
widget.message.content == '[TYPING_INDICATOR]') &&
widget.isStreaming;
return GestureDetector(
onLongPress: () => _toggleActions(),
behavior: HitTestBehavior.translucent,
child: Container(
width: double.infinity,
margin: const EdgeInsets.only(
bottom: Spacing.md,
left: Spacing.xs,
right: Spacing.xxxl,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Simplified AI Name and Avatar
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
context.conduitTheme.buttonPrimary.withValues(
alpha: 0.9,
),
context.conduitTheme.buttonPrimary,
],
),
child: Icon(
Icons.auto_awesome,
color: context.conduitTheme.buttonPrimaryText,
size: 12,
borderRadius: BorderRadius.circular(
AppBorderRadius.small,
),
),
const SizedBox(width: Spacing.xs),
Text(
widget.modelName ?? 'Assistant',
style: TextStyle(
color: context.conduitTheme.textSecondary,
fontSize: AppTypography.bodySmall,
fontWeight: FontWeight.w500,
letterSpacing: 0.1,
),
child: Icon(
Icons.auto_awesome,
color: context.conduitTheme.buttonPrimaryText,
size: 12,
),
),
const SizedBox(width: Spacing.xs),
Text(
widget.modelName ?? 'Assistant',
style: TextStyle(
color: context.conduitTheme.textSecondary,
fontSize: AppTypography.bodySmall,
fontWeight: FontWeight.w500,
letterSpacing: 0.1,
),
),
],
),
),
// Display images outside the bubble if any
if (hasImages) ...[
_buildAssistantAttachmentImages(),
if (hasContent || showTyping) const SizedBox(height: Spacing.xs),
],
// Message Content Bubble
if (hasContent || showTyping)
Container(
padding: EdgeInsets.symmetric(
horizontal: Spacing.messagePadding,
vertical: Spacing.xs,
),
decoration: BoxDecoration(
color: context.conduitTheme.chatBubbleAssistant,
borderRadius: BorderRadius.circular(
AppBorderRadius.messageBubble,
),
border: Border.all(
color: context.conduitTheme.chatBubbleAssistantBorder,
width: BorderWidth.regular,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 3,
offset: const Offset(0, 1),
),
],
),
child: showTyping
? _buildTypingIndicator()
: _buildCustomText(
widget.message.content,
context.conduitTheme.chatBubbleAssistantText,
),
),
// Message Content
GestureDetector(
onLongPress: () => _toggleActions(),
child: Container(
padding: const EdgeInsets.all(Spacing.messagePadding),
decoration: BoxDecoration(
color: context.conduitTheme.chatBubbleAssistant,
borderRadius: BorderRadius.circular(
AppBorderRadius.messageBubble,
),
border: Border.all(
color: context.conduitTheme.chatBubbleAssistantBorder,
width: BorderWidth.regular,
),
boxShadow: ConduitShadows.low,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Check for typing indicator - show for empty content OR explicit typing indicator during streaming
if ((widget.message.content.isEmpty ||
widget.message.content == '[TYPING_INDICATOR]') &&
widget.isStreaming) ...[
_buildTypingIndicator(),
] else if (widget.message.content.isNotEmpty &&
widget.message.content != '[TYPING_INDICATOR]') ...[
_buildCustomText(
widget.message.content,
context.conduitTheme.chatBubbleAssistantText,
),
] else
// Fallback: show empty state for non-streaming empty messages
const SizedBox.shrink(),
],
),
),
),
// Action buttons below the message content
if (_showActions) ...[
const SizedBox(height: Spacing.sm),
_buildActionButtons(),
],
// Action buttons below the message content
if (_showActions) ...[
const SizedBox(height: Spacing.sm),
_buildActionButtons(),
],
),
)
],
),
),
)
.animate()
.fadeIn(duration: AnimationDuration.messageAppear)
.slideX(
@@ -491,216 +417,19 @@ class _ModernMessageBubbleState extends ConsumerState<ModernMessageBubble>
Future<String?> _getCachedImageBase64(dynamic api, String fileId) async {
// Check cache first to prevent repeated API calls
if (_imageCache.containsKey(fileId)) {
return _imageCache[fileId];
}
// If not in cache, get the image and cache it
final result = await _getImageBase64(api, fileId);
// Simple LRU-like eviction to bound memory
if (_imageCache.length >= _maxCachedImages) {
_imageCache.remove(_imageCache.keys.first);
}
_imageCache[fileId] = result;
return result;
}
Future<String?> _getImageBase64(dynamic api, String fileId) async {
try {
// Check if this is already a data URL (for images)
if (fileId.startsWith('data:')) {
return fileId;
}
// First, get file info to determine if it's an image
final fileInfo = await api.getFileInfo(fileId);
final fileName =
fileInfo['filename'] ??
fileInfo['meta']?['name'] ??
fileInfo['name'] ??
fileInfo['file_name'] ??
fileInfo['original_name'] ??
fileInfo['original_filename'] ??
'';
final ext = fileName.toLowerCase().split('.').last;
// Only process image files
if (!['jpg', 'jpeg', 'png', 'gif', 'webp'].contains(ext)) {
debugPrint('DEBUG: Skipping non-image file: $fileName');
return null;
}
// Get file content as base64 string
final fileContent = await api.getFileContent(fileId);
return fileContent;
} catch (e) {
debugPrint('DEBUG: Error getting image content for $fileId: $e');
return null;
}
}
Widget _buildCustomText(String text, [Color? textColor]) {
// Simple markdown-like parsing for efficiency
final lines = text.split('\n');
final widgets = <Widget>[];
for (int i = 0; i < lines.length; i++) {
final line = lines[i];
if (line.trim().isEmpty) {
if (i < lines.length - 1) {
widgets.add(const SizedBox(height: Spacing.sm));
}
continue;
}
// Parse basic markdown
Widget textWidget = _parseMarkdownLine(line, textColor);
if (i < lines.length - 1) {
widgets.add(textWidget);
widgets.add(const SizedBox(height: Spacing.xs));
} else {
widgets.add(textWidget);
}
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: widgets,
// Use the new markdown widget for rich text rendering
return StreamingMarkdownWidget(
staticContent: text,
isStreaming: widget.isStreaming,
);
}
Widget _parseMarkdownLine(String line, [Color? textColor]) {
// Handle code blocks
if (line.startsWith('```')) {
return Container(
margin: const EdgeInsets.symmetric(vertical: Spacing.xs),
padding: const EdgeInsets.all(Spacing.md),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceBackground.withValues(
alpha: Alpha.badgeBackground,
),
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
border: Border.all(
color: context.conduitTheme.textPrimary.withValues(
alpha: Alpha.subtle,
),
width: BorderWidth.regular,
),
),
child: Text(
line.substring(3),
style: AppTypography.chatCodeStyle.copyWith(
color: textColor ?? context.conduitTheme.textSecondary,
),
),
)
.animate()
.fadeIn(duration: AnimationDuration.microInteraction)
.slideX(
begin: 0.1,
end: 0,
duration: AnimationDuration.microInteraction,
);
}
// Handle headers
if (line.startsWith('#')) {
int level = 0;
while (level < line.length && line[level] == '#') {
level++;
}
final fontSize = AppTypography.headlineMedium - (level * 2);
return Text(
line.substring(level).trim(),
style: AppTypography.headlineMediumStyle.copyWith(
color: textColor ?? context.conduitTheme.textPrimary,
fontSize: fontSize.toDouble(),
),
)
.animate()
.fadeIn(duration: AnimationDuration.microInteraction)
.slideX(
begin: 0.1,
end: 0,
duration: AnimationDuration.microInteraction,
);
}
// Handle inline code
if (line.contains('`')) {
final parts = line.split('`');
final widgets = <Widget>[];
for (int i = 0; i < parts.length; i++) {
if (parts[i].isNotEmpty) {
if (i % 2 == 1) {
// Inline code
widgets.add(
Container(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.xs + Spacing.xxs,
vertical: Spacing.xxs,
),
decoration: BoxDecoration(
color: context.conduitTheme.textPrimary.withValues(
alpha: Alpha.badgeBackground,
),
borderRadius: BorderRadius.circular(AppBorderRadius.xs),
),
child: Text(
parts[i],
style: AppTypography.chatCodeStyle.copyWith(
color: textColor ?? context.conduitTheme.textSecondary,
),
),
),
);
} else {
// Regular text
widgets.add(
Text(
parts[i],
style: AppTypography.chatMessageStyle.copyWith(
color: textColor ?? context.conduitTheme.textPrimary,
),
),
);
}
}
}
return Wrap(
crossAxisAlignment: WrapCrossAlignment.start,
children: widgets,
)
.animate()
.fadeIn(duration: AnimationDuration.microInteraction)
.slideX(
begin: 0.1,
end: 0,
duration: AnimationDuration.microInteraction,
);
}
// Regular text
return Text(
line,
style: AppTypography.chatMessageStyle.copyWith(
color: textColor ?? context.conduitTheme.textPrimary,
letterSpacing: 0.1,
),
)
.animate()
.fadeIn(duration: AnimationDuration.microInteraction)
.slideX(
begin: 0.1,
end: 0,
duration: AnimationDuration.microInteraction,
);
}
Widget _buildTypingIndicator() {
return Consumer(