minor changes

This commit is contained in:
divya abdar
2025-12-23 11:44:56 +05:30
parent e85ac4bf8c
commit d419e4ed60
11 changed files with 483 additions and 481 deletions

View File

@@ -1,18 +1,14 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'dart:io';
import 'package:file_selector/file_selector.dart';
import '../services/chat_service.dart';
import '../services/reverb_socket_service.dart';
import '../services/dio_client.dart';
import '../providers/chat_unread_provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:file_selector/file_selector.dart';
import 'chat_file_viewer.dart';
import '../widgets/chat_file_preview.dart';
import 'chat_file_viewer.dart';
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key});
@@ -24,6 +20,7 @@ class ChatScreen extends StatefulWidget {
class _ChatScreenState extends State<ChatScreen> {
final TextEditingController _messageCtrl = TextEditingController();
final ScrollController _scrollCtrl = ScrollController();
Map<String, dynamic>? uploadingMessage;
late ChatService _chatService;
@@ -33,22 +30,18 @@ class _ChatScreenState extends State<ChatScreen> {
List<Map<String, dynamic>> messages = [];
bool isLoading = true;
// ============================
// INIT STATE
// ============================
@override
void initState() {
super.initState();
_chatService = ChatService(DioClient.getInstance(context));
// 🔔 Mark chat as OPEN (important)
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<ChatUnreadProvider>().setChatOpen(true);
});
_initChat();
}
String _guessMimeType(String path) {
final lower = path.toLowerCase();
if (lower.endsWith('.jpg') || lower.endsWith('.png')) return 'image/*';
@@ -63,7 +56,6 @@ class _ChatScreenState extends State<ChatScreen> {
final file = File(picked.path);
// 1⃣ Show uploading UI
setState(() {
uploadingMessage = {
'local_file': file,
@@ -72,44 +64,26 @@ class _ChatScreenState extends State<ChatScreen> {
};
});
// 2⃣ Upload (NO adding message)
await _chatService.sendFile(
ticketId!,
file,
onProgress: (progress) {
if (!mounted) return;
setState(() {
uploadingMessage!['progress'] = progress;
});
setState(() => uploadingMessage!['progress'] = progress);
},
);
// 3⃣ Remove sending bubble ONLY
if (!mounted) return;
setState(() {
uploadingMessage = null;
});
// 🚫 DO NOT add message here
// WebSocket will handle it
setState(() => uploadingMessage = null);
}
// ============================
// INIT CHAT
// ============================
Future<void> _initChat() async {
// 1⃣ Start chat
final ticketRes = await _chatService.startChat();
ticketId = ticketRes['ticket']['id'];
// 2⃣ Load messages
final msgs = await _chatService.getMessages(ticketId!);
messages = List<Map<String, dynamic>>.from(msgs);
// 3⃣ Realtime socket
await _socket.connect(
context: context,
ticketId: ticketId!,
@@ -117,20 +91,12 @@ class _ChatScreenState extends State<ChatScreen> {
final incomingClientId = msg['client_id'];
setState(() {
// 🧹 Remove local temp message with same client_id
messages.removeWhere(
(m) => m['client_id'] != null &&
m['client_id'] == incomingClientId,
);
// ✅ Add confirmed socket message
messages.removeWhere((m) => m['client_id'] == incomingClientId);
messages.add(msg);
});
_scrollToBottom();
},
onAdminMessage: () {
if (!mounted) {
context.read<ChatUnreadProvider>().increment();
@@ -138,37 +104,30 @@ class _ChatScreenState extends State<ChatScreen> {
},
);
if (!mounted) return;
setState(() => isLoading = false);
_scrollToBottom();
}
// ============================
// SCROLL
// ============================
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollCtrl.hasClients) {
_scrollCtrl.jumpTo(_scrollCtrl.position.maxScrollExtent);
_scrollCtrl.animateTo(
_scrollCtrl.position.maxScrollExtent,
duration: const Duration(milliseconds: 250),
curve: Curves.easeOut,
);
}
});
}
// ============================
// SEND MESSAGE
// ============================
Future<void> _sendMessage() async {
final text = _messageCtrl.text.trim();
if (text.isEmpty || ticketId == null) return;
_messageCtrl.clear();
final clientId = DateTime.now().millisecondsSinceEpoch.toString();
// 1⃣ ADD LOCAL MESSAGE IMMEDIATELY
setState(() {
messages.add({
'client_id': clientId,
@@ -182,7 +141,6 @@ class _ChatScreenState extends State<ChatScreen> {
_scrollToBottom();
// 2⃣ SEND TO SERVER
await _chatService.sendMessage(
ticketId!,
message: text,
@@ -190,28 +148,68 @@ class _ChatScreenState extends State<ChatScreen> {
);
}
// ============================
// DISPOSE
// ============================
@override
void dispose() {
// 🔕 Mark chat CLOSED
context.read<ChatUnreadProvider>().setChatOpen(false);
_socket.disconnect();
_messageCtrl.dispose();
_scrollCtrl.dispose();
super.dispose();
}
// ============================
// UI
// ============================
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Support Chat")),
appBar: PreferredSize(
preferredSize: const Size.fromHeight(56),
child: AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF2196F3),
Color(0xFF1565C0),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 10,
offset: Offset(0, 3),
),
],
),
child: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: Padding(
padding: const EdgeInsets.only(left: 12),
child: CircleAvatar(
radius: 18,
backgroundColor: Colors.white,
child: Icon(
Icons.support_agent,
color: Colors.blue,
size: 20,
),
),
),
title: const Text(
"Support Chat",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 18,
),
),
centerTitle: false,
iconTheme: const IconThemeData(color: Colors.white),
),
),
),
body: isLoading
? const Center(child: CircularProgressIndicator())
: Column(
@@ -223,100 +221,54 @@ class _ChatScreenState extends State<ChatScreen> {
);
}
// Future<void> _openUrl(String url) async {
// final uri = Uri.parse(url);
//
// if (await canLaunchUrl(uri)) {
// await launchUrl(
// uri,
// mode: LaunchMode.externalApplication,
// );
// } else {
// debugPrint("❌ Cannot launch URL: $url");
// }
// }
Widget _buildMessageContent({
String? message,
String? filePath,
String? fileType,
required bool isUser,
}) {
final textColor = isUser ? Colors.white : Colors.black;
if (filePath == null) {
return Text(message ?? '', style: TextStyle(color: textColor));
}
final url = "${DioClient.baseUrl}/storage/$filePath";
return GestureDetector(
onTap: () {
ChatFileViewer.open(
context,
url: url,
fileType: fileType ?? '',
);
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(_iconForFile(fileType), color: textColor),
const SizedBox(width: 8),
Text(
_labelForFile(fileType),
style: TextStyle(color: textColor),
),
],
),
);
}
IconData _iconForFile(String? type) {
if (type == null) return Icons.insert_drive_file;
if (type.startsWith('image/')) return Icons.image;
if (type.startsWith('video/')) return Icons.play_circle_fill;
if (type == 'application/pdf') return Icons.picture_as_pdf;
return Icons.insert_drive_file;
}
String _labelForFile(String? type) {
if (type == null) return "File";
if (type.startsWith('image/')) return "Image";
if (type.startsWith('video/')) return "Video";
if (type == 'application/pdf') return "PDF";
return "Download file";
}
Widget _buildMessages() {
return ListView(
controller: _scrollCtrl,
padding: const EdgeInsets.all(12),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
children: [
// EXISTING MESSAGES
...messages.map((msg) {
final isUser = msg['sender_type'] == 'App\\Models\\User';
return Align(
alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
alignment:
isUser ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
constraints: const BoxConstraints(maxWidth: 280),
margin: const EdgeInsets.symmetric(vertical: 6),
padding: const EdgeInsets.all(10),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: isUser ? Colors.blue : Colors.grey.shade300,
borderRadius: BorderRadius.circular(12),
color: isUser ? null : Colors.white,
gradient: isUser
? LinearGradient(
colors: [
Colors.lightBlueAccent,
Colors.blue.shade700,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
)
: null,
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(16),
topRight: const Radius.circular(16),
bottomLeft:
isUser ? const Radius.circular(16) : Radius.zero,
bottomRight:
isUser ? Radius.zero : const Radius.circular(16),
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 6,
),
],
),
child: msg['file_path'] == null
? Text(
msg['message'] ?? '',
style: TextStyle(
color: isUser ? Colors.white : Colors.black,
color: isUser ? Colors.white : Colors.blue,
fontSize: 15,
),
)
: ChatFilePreview(
@@ -327,75 +279,49 @@ class _ChatScreenState extends State<ChatScreen> {
),
);
}),
// ⏳ UPLOADING MESSAGE
if (uploadingMessage != null)
Align(
alignment: Alignment.centerRight,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 6),
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(12),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ChatFilePreview(
filePath: uploadingMessage!['local_file'].path,
fileType: uploadingMessage!['file_type'],
isUser: true,
isLocal: true,
),
const SizedBox(height: 8),
LinearProgressIndicator(
value: uploadingMessage!['progress'],
backgroundColor: Colors.white24,
valueColor:
const AlwaysStoppedAnimation(Colors.white),
),
const SizedBox(height: 4),
const Text(
"Sending…",
style: TextStyle(
color: Colors.white,
fontSize: 12,
),
),
],
),
),
),
],
);
}
Widget _buildInput() {
return SafeArea(
child: Row(
children: [
IconButton(
icon: const Icon(Icons.attach_file),
onPressed: _pickAndSendFile,
),
Expanded(
child: TextField(
controller: _messageCtrl,
decoration: const InputDecoration(
hintText: "Type message",
border: InputBorder.none,
child: Padding(
padding: const EdgeInsets.all(8),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 6,
),
),
],
),
IconButton(
icon: const Icon(Icons.send),
onPressed: _sendMessage,
child: Row(
children: [
IconButton(
icon: const Icon(Icons.attach_file),
onPressed: _pickAndSendFile,
),
Expanded(
child: TextField(
controller: _messageCtrl,
decoration: const InputDecoration(
hintText: "Type a message…",
border: InputBorder.none,
),
),
),
IconButton(
icon: const Icon(Icons.send, color: Colors.blue),
onPressed: _sendMessage,
),
],
),
],
),
),
);
}
}