fluffychat/lib/views/chat.dart

389 lines
15 KiB
Dart
Raw Normal View History

2020-01-05 12:27:03 +01:00
import 'dart:async';
2020-01-01 19:10:13 +01:00
import 'dart:io';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:file_picker/file_picker.dart';
import 'package:fluffychat/components/adaptive_page_layout.dart';
import 'package:fluffychat/components/chat_settings_popup_menu.dart';
import 'package:fluffychat/components/list_items/message.dart';
import 'package:fluffychat/components/matrix.dart';
2020-01-08 20:43:30 +01:00
import 'package:fluffychat/utils/room_name_calculator.dart';
2020-01-01 19:10:13 +01:00
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:toast/toast.dart';
import 'chat_list.dart';
class Chat extends StatefulWidget {
final String id;
const Chat(this.id, {Key key}) : super(key: key);
@override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
Room room;
Timeline timeline;
2020-01-08 14:19:15 +01:00
MatrixState matrix;
2020-01-05 12:27:03 +01:00
String seenByText = "";
2020-01-02 22:31:39 +01:00
final ScrollController _scrollController = ScrollController();
2020-01-01 19:10:13 +01:00
2020-01-05 12:27:03 +01:00
Timer typingCoolDown;
Timer typingTimeout;
bool currentlyTyping = false;
2020-01-01 19:10:13 +01:00
@override
void initState() {
_scrollController.addListener(() async {
if (_scrollController.position.pixels ==
2020-01-02 22:31:39 +01:00
_scrollController.position.maxScrollExtent &&
timeline.events.isNotEmpty &&
timeline.events[timeline.events.length - 1].type !=
EventTypes.RoomCreate) {
await timeline.requestHistory(historyCount: 100);
2020-01-01 19:10:13 +01:00
}
});
super.initState();
}
2020-01-05 12:27:03 +01:00
void updateView() {
String seenByText = "";
if (timeline.events.isNotEmpty) {
List lastReceipts = List.from(timeline.events.first.receipts);
lastReceipts.removeWhere((r) =>
r.user.id == room.client.userID ||
r.user.id == timeline.events.first.senderId);
if (lastReceipts.length == 1) {
seenByText = "Seen by ${lastReceipts.first.user.calcDisplayname()}";
} else if (lastReceipts.length == 2) {
seenByText =
"Seen by ${lastReceipts.first.user.calcDisplayname()} and ${lastReceipts[1].user.calcDisplayname()}";
} else if (lastReceipts.length > 2) {
seenByText =
"Seen by ${lastReceipts.first.user.calcDisplayname()} and ${lastReceipts.length - 1} others";
}
}
setState(() {
this.seenByText = seenByText;
2020-01-01 19:10:13 +01:00
});
2020-01-05 12:27:03 +01:00
}
Future<bool> getTimeline() async {
timeline ??= await room.getTimeline(onUpdate: updateView);
updateView();
2020-01-01 19:10:13 +01:00
return true;
}
@override
void dispose() {
timeline?.sub?.cancel();
2020-01-08 14:19:15 +01:00
matrix.activeRoomId = "";
2020-01-01 19:10:13 +01:00
super.dispose();
}
2020-01-17 10:41:28 +01:00
TextEditingController sendController = TextEditingController();
2020-01-01 19:10:13 +01:00
void send() {
if (sendController.text.isEmpty) return;
room.sendTextEvent(sendController.text);
sendController.text = "";
}
void sendFileAction(BuildContext context) async {
if (kIsWeb) {
return Toast.show("Not supported in web", context);
}
File file = await FilePicker.getFile();
if (file == null) return;
2020-01-08 14:19:15 +01:00
await matrix.tryRequestWithLoadingDialog(
2020-01-01 19:10:13 +01:00
room.sendFileEvent(
MatrixFile(bytes: await file.readAsBytes(), path: file.path),
),
);
}
void sendImageAction(BuildContext context) async {
if (kIsWeb) {
return Toast.show("Not supported in web", context);
}
File file = await ImagePicker.pickImage(
source: ImageSource.gallery,
imageQuality: 50,
maxWidth: 1600,
maxHeight: 1600);
if (file == null) return;
2020-01-08 14:19:15 +01:00
await matrix.tryRequestWithLoadingDialog(
2020-01-01 19:10:13 +01:00
room.sendImageEvent(
MatrixFile(bytes: await file.readAsBytes(), path: file.path),
),
);
}
void openCameraAction(BuildContext context) async {
if (kIsWeb) {
return Toast.show("Not supported in web", context);
}
File file = await ImagePicker.pickImage(
source: ImageSource.camera,
imageQuality: 50,
maxWidth: 1600,
maxHeight: 1600);
if (file == null) return;
2020-01-08 14:19:15 +01:00
await matrix.tryRequestWithLoadingDialog(
2020-01-01 19:10:13 +01:00
room.sendImageEvent(
MatrixFile(bytes: await file.readAsBytes(), path: file.path),
),
);
}
@override
Widget build(BuildContext context) {
2020-01-08 14:19:15 +01:00
matrix = Matrix.of(context);
Client client = matrix.client;
2020-01-01 19:10:13 +01:00
room ??= client.getRoomById(widget.id);
2020-01-05 12:27:03 +01:00
if (room == null) {
return Center(
child: Text("You are no longer participating in this chat"),
);
}
2020-01-08 14:19:15 +01:00
matrix.activeRoomId = widget.id;
2020-01-05 12:27:03 +01:00
if (room.membership == Membership.invite) {
2020-01-08 14:19:15 +01:00
matrix.tryRequestWithLoadingDialog(room.join());
2020-01-05 12:27:03 +01:00
}
2020-01-01 19:10:13 +01:00
2020-01-05 12:27:03 +01:00
String typingText = "";
List<User> typingUsers = room.typingUsers;
typingUsers.removeWhere((User u) => u.id == client.userID);
if (typingUsers.length == 1) {
2020-01-18 13:27:36 +01:00
typingText = "is typing...";
if (typingUsers.first.id != room.directChatMatrixID) {
typingText = typingUsers.first.calcDisplayname() + " " + typingText;
}
2020-01-05 12:27:03 +01:00
} else if (typingUsers.length == 2) {
typingText =
"${typingUsers.first.calcDisplayname()} and ${typingUsers[1].calcDisplayname()} are typing...";
} else if (typingUsers.length > 2) {
typingText =
"${typingUsers.first.calcDisplayname()} and ${typingUsers.length - 1} others are typing...";
}
2020-01-01 19:10:13 +01:00
return AdaptivePageLayout(
primaryPage: FocusPage.SECOND,
firstScaffold: ChatList(
activeChat: widget.id,
),
secondScaffold: Scaffold(
appBar: AppBar(
2020-01-05 12:27:03 +01:00
title: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
2020-01-08 20:43:30 +01:00
Text(RoomNameCalculator(room).name),
2020-01-05 12:27:03 +01:00
AnimatedContainer(
duration: Duration(milliseconds: 500),
height: typingText.isEmpty ? 0 : 20,
child: Row(
children: <Widget>[
typingText.isEmpty
? Container()
: Icon(Icons.edit,
color: Theme.of(context).primaryColor, size: 10),
SizedBox(width: 4),
Text(
typingText,
style: TextStyle(
color: Theme.of(context).primaryColor,
fontStyle: FontStyle.italic,
),
),
],
),
),
],
),
2020-01-01 19:10:13 +01:00
actions: <Widget>[ChatSettingsPopupMenu(room, !room.isDirectChat)],
),
body: SafeArea(
child: Column(
children: <Widget>[
Expanded(
child: FutureBuilder<bool>(
future: getTimeline(),
builder: (BuildContext context, snapshot) {
2020-01-02 22:31:39 +01:00
if (!snapshot.hasData) {
2020-01-01 19:10:13 +01:00
return Center(
child: CircularProgressIndicator(),
);
2020-01-02 22:31:39 +01:00
}
2020-01-05 12:27:03 +01:00
2020-01-01 19:10:13 +01:00
if (room.notificationCount != null &&
room.notificationCount > 0 &&
timeline != null &&
2020-01-02 22:31:39 +01:00
timeline.events.isNotEmpty) {
2020-01-01 19:10:13 +01:00
room.sendReadReceipt(timeline.events[0].eventId);
2020-01-02 22:31:39 +01:00
}
2020-01-01 19:10:13 +01:00
return ListView.builder(
reverse: true,
2020-01-05 12:27:03 +01:00
itemCount: timeline.events.length + 1,
2020-01-01 19:10:13 +01:00
controller: _scrollController,
2020-01-05 12:27:03 +01:00
itemBuilder: (BuildContext context, int i) => i == 0
? AnimatedContainer(
height: seenByText.isEmpty ? 0 : 36,
duration: seenByText.isEmpty
? Duration(milliseconds: 0)
: Duration(milliseconds: 500),
alignment: timeline.events.first.senderId ==
client.userID
? Alignment.centerRight
: Alignment.centerLeft,
child: Text(
seenByText,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Theme.of(context).primaryColor,
),
),
padding: EdgeInsets.all(8),
)
2020-01-17 10:39:46 +01:00
: Message(timeline.events[i - 1],
nextEvent:
i >= 2 ? timeline.events[i - 2] : null),
2020-01-01 19:10:13 +01:00
);
},
),
),
2020-01-05 12:27:03 +01:00
room.canSendDefaultMessages && room.membership == Membership.join
? Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 1,
blurRadius: 2,
offset: Offset(0, -1), // changes position of shadow
),
],
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
kIsWeb
? Container()
: PopupMenuButton<String>(
icon: Icon(Icons.add),
onSelected: (String choice) async {
if (choice == "file") {
sendFileAction(context);
} else if (choice == "image") {
sendImageAction(context);
}
if (choice == "camera") {
openCameraAction(context);
}
},
itemBuilder: (BuildContext context) =>
<PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: "file",
child: ListTile(
2020-01-17 10:47:30 +01:00
leading: CircleAvatar(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
child: Icon(Icons.attachment),
),
2020-01-05 12:27:03 +01:00
title: Text('Send file'),
contentPadding: EdgeInsets.all(0),
),
),
const PopupMenuItem<String>(
value: "image",
child: ListTile(
2020-01-17 10:47:30 +01:00
leading: CircleAvatar(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
child: Icon(Icons.image),
),
2020-01-05 12:27:03 +01:00
title: Text('Send image'),
contentPadding: EdgeInsets.all(0),
),
),
const PopupMenuItem<String>(
value: "camera",
child: ListTile(
2020-01-17 10:47:30 +01:00
leading: CircleAvatar(
backgroundColor: Colors.purple,
foregroundColor: Colors.white,
child: Icon(Icons.camera),
),
2020-01-05 12:27:03 +01:00
title: Text('Open camera'),
contentPadding: EdgeInsets.all(0),
),
),
],
2020-01-01 19:10:13 +01:00
),
2020-01-05 12:27:03 +01:00
SizedBox(width: 8),
Expanded(
child: Padding(
2020-01-17 10:47:30 +01:00
padding: const EdgeInsets.symmetric(vertical: 4.0),
2020-01-05 12:27:03 +01:00
child: TextField(
minLines: 1,
maxLines: kIsWeb ? 1 : 8,
2020-01-05 12:27:03 +01:00
keyboardType: kIsWeb
? TextInputType.text
: TextInputType.multiline,
onSubmitted: (t) => send(),
controller: sendController,
decoration: InputDecoration(
hintText: "Write a message...",
border: InputBorder.none,
2020-01-01 19:10:13 +01:00
),
2020-01-05 12:27:03 +01:00
onChanged: (String text) {
this.typingCoolDown?.cancel();
this.typingCoolDown =
Timer(Duration(seconds: 2), () {
this.typingCoolDown = null;
this.currentlyTyping = false;
room.sendTypingInfo(false);
});
this.typingTimeout ??=
Timer(Duration(seconds: 30), () {
this.typingTimeout = null;
this.currentlyTyping = false;
});
if (!this.currentlyTyping) {
this.currentlyTyping = true;
room.sendTypingInfo(true,
timeout:
Duration(seconds: 30).inMilliseconds);
}
},
),
)),
SizedBox(width: 8),
IconButton(
icon: Icon(Icons.send),
onPressed: () => send(),
2020-01-01 19:10:13 +01:00
),
2020-01-05 12:27:03 +01:00
],
2020-01-01 19:10:13 +01:00
),
2020-01-05 12:27:03 +01:00
)
: Container(),
2020-01-01 19:10:13 +01:00
],
),
),
),
);
}
}