217 lines
7.2 KiB
Dart
217 lines
7.2 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'app_menu.dart';
|
|
import 'styles.dart';
|
|
import 'backend.dart';
|
|
import 'dart:async';
|
|
|
|
class Message {
|
|
final int? id;
|
|
final String sender;
|
|
final String text;
|
|
final bool isFromUser;
|
|
|
|
Message({required this.sender, required this.text, this.id}) : isFromUser = sender == "user";
|
|
|
|
Alignment get alignment => isFromUser ? Alignment.centerRight : Alignment.centerLeft;
|
|
EdgeInsets get padding => isFromUser ? EdgeInsets.zero : const EdgeInsets.only(left: 10);
|
|
}
|
|
|
|
class ChatScreen extends StatefulWidget {
|
|
final int chatId;
|
|
|
|
ChatScreen({required this.chatId});
|
|
|
|
static Future<List<Message>> getChatMessages(int chatId) async {
|
|
final response = await Backend.sendAction("get-chat-messages", {'chatId': chatId});
|
|
List<dynamic> messageObjects = response['messages'];
|
|
List<Message> messages = messageObjects.map((msg) => Message(sender: msg['sender'], text: msg['content'])).toList();
|
|
return messages;
|
|
}
|
|
|
|
@override
|
|
_ChatScreenState createState() => _ChatScreenState();
|
|
}
|
|
|
|
class _ChatScreenState extends State<ChatScreen> {
|
|
String? _title;
|
|
List<Message> _messages = [];
|
|
Offset? _longPressOffset;
|
|
StreamSubscription? _chatSubscription;
|
|
final TextEditingController _textController = TextEditingController();
|
|
final FocusNode _inputFocusNode = FocusNode();
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_loadInitialData();
|
|
_chatSubscription = Backend.chatMessages(widget.chatId).listen((data) {
|
|
final message = Message(sender: data['sender'], text: data['content']);
|
|
if (!message.isFromUser) {
|
|
addMessage(message);
|
|
}
|
|
});
|
|
BrowserContextMenu.disableContextMenu();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_chatSubscription?.cancel(); // Cancel the subscription
|
|
Backend.removeChatListener(widget.chatId);
|
|
BrowserContextMenu.enableContextMenu();
|
|
_textController.dispose();
|
|
_inputFocusNode.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
Future<void> _loadInitialData() async {
|
|
final chatInfo = (await Backend.getChat(widget.chatId))!;
|
|
final initialMessages = await ChatScreen.getChatMessages(widget.chatId);
|
|
setState(() {
|
|
_messages.addAll(initialMessages);
|
|
_title = chatInfo.name;
|
|
});
|
|
}
|
|
|
|
void addMessage(Message message) {
|
|
setState(() {
|
|
_messages.add(message);
|
|
});
|
|
}
|
|
|
|
void sendMessage(String content) {
|
|
if (content.trim().isEmpty) return; // Don't send empty messages
|
|
_textController.clear();
|
|
final newMessage = Message(sender: "user", text: content);
|
|
Backend.sendAction("send-chat-message", {'chatId': widget.chatId, 'content': content}).then((response) {
|
|
if (response['error'] != null) {
|
|
print("Error sending chat message: ${response['error']}");
|
|
}
|
|
});
|
|
addMessage(newMessage);
|
|
}
|
|
|
|
Color getMessageColor(BuildContext context) {
|
|
final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
|
|
final messageColor = Color.alphaBlend(Colors.white.withOpacity(0.1), backgroundColor);
|
|
return messageColor;
|
|
}
|
|
|
|
void _showMessageContextMenu(BuildContext context, Offset position) {
|
|
showMenu(
|
|
context: context,
|
|
position: RelativeRect.fromLTRB(position.dx, position.dy, position.dx + 1, position.dy + 1),
|
|
items: <PopupMenuEntry>[
|
|
PopupMenuItem(
|
|
child: Text('Pin'),
|
|
onTap: () {
|
|
// TODO: Implement Pin functionality
|
|
print('Pin clicked');
|
|
},
|
|
),
|
|
PopupMenuItem(
|
|
child: Text('Edit'),
|
|
onTap: () {
|
|
// TODO: Implement Edit functionality
|
|
print('Edit clicked');
|
|
},
|
|
),
|
|
PopupMenuItem(
|
|
child: Text('Delete'),
|
|
onTap: () {
|
|
// TODO: Implement Delete functionality
|
|
print('Delete clicked');
|
|
},
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final isWideScreen = MediaQuery.of(context).size.width > 600;
|
|
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: Text(_title ?? 'Chat Room ${widget.chatId}'),
|
|
actions: [
|
|
IconButton(icon: Icon(Icons.settings), onPressed: () {
|
|
Navigator.push(context, MaterialPageRoute(builder: (_) => AppMenu()));
|
|
}),
|
|
],
|
|
),
|
|
body: Column(
|
|
children: [
|
|
Expanded(
|
|
child: ListView.builder(
|
|
itemCount: _messages.length,
|
|
itemBuilder: (context, index) {
|
|
final message = _messages[index];
|
|
return GestureDetector(
|
|
onLongPressStart: (details) {
|
|
_longPressOffset = details.globalPosition;
|
|
},
|
|
onLongPress: () {
|
|
_showMessageContextMenu(context, _longPressOffset!);
|
|
_longPressOffset = null;
|
|
},
|
|
onSecondaryTapUp: (details) {
|
|
_showMessageContextMenu(context, details.globalPosition);
|
|
},
|
|
child: Padding(
|
|
padding: isWideScreen ? message.padding : EdgeInsets.zero,
|
|
child: Align(
|
|
alignment: isWideScreen ? Alignment.centerLeft : message.alignment,
|
|
child: Container(
|
|
margin: EdgeInsets.symmetric(vertical: 2, horizontal: 8),
|
|
padding: EdgeInsets.all(10),
|
|
decoration: BoxDecoration(
|
|
color: getMessageColor(context),
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
child: Text(message.text),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.all(8.0),
|
|
child: Row(
|
|
children: [
|
|
Expanded(
|
|
child: KeyboardListener(
|
|
focusNode: _inputFocusNode,
|
|
onKeyEvent: (event) {
|
|
// TODO: Probably doing this in the input focus node would be cleaner
|
|
if (HardwareKeyboard.instance.isControlPressed && HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.enter)) {
|
|
sendMessage(_textController.text);
|
|
//return KeyEventResult.handled;
|
|
}
|
|
//return KeyEventResult.ignored;
|
|
},
|
|
child: TextField(
|
|
controller: _textController,
|
|
maxLines: null, // Allows multiline input
|
|
keyboardType: TextInputType.multiline, // For better multiline support on mobile
|
|
decoration: inputDecoration().copyWith(hintText: 'Type a message...'), // Added a hint
|
|
),
|
|
),
|
|
),
|
|
SizedBox(width: 8),
|
|
ElevatedButton(
|
|
onPressed: () {
|
|
sendMessage(_textController.text);
|
|
},
|
|
child: Text('Send'),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
} |