didvan-app/lib/views/ai/ai_chat_page.dart

614 lines
30 KiB
Dart

// ignore_for_file: library_private_types_in_public_api, deprecated_member_use, depend_on_referenced_packages
import 'package:cached_network_image/cached_network_image.dart';
import 'package:didvan/config/design_config.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/constants/assets.dart';
import 'package:didvan/models/ai/ai_chat_args.dart';
import 'package:didvan/models/ai/chats_model.dart';
import 'package:didvan/models/ai/files_model.dart';
import 'package:didvan/models/enums.dart';
import 'package:didvan/models/view/action_sheet_data.dart';
import 'package:didvan/models/view/alert_data.dart';
import 'package:didvan/services/storage/storage.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/utils/date_time.dart';
import 'package:didvan/views/ai/ai_chat_state.dart';
import 'package:didvan/views/ai/history_ai_chat_state.dart';
import 'package:didvan/views/ai/widgets/ai_message_bar.dart';
import 'package:didvan/views/ai/widgets/voice_message_view.dart';
import 'package:didvan/views/widgets/didvan/icon_button.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:mime/mime.dart';
import 'package:persian_number_utility/persian_number_utility.dart';
import 'package:provider/provider.dart';
import 'package:voice_message_package/voice_message_package.dart';
class AiChatPage extends StatefulWidget {
final AiChatArgs args;
const AiChatPage({Key? key, required this.args}) : super(key: key);
@override
_AiChatPageState createState() => _AiChatPageState();
}
class _AiChatPageState extends State<AiChatPage> {
FocusNode focusNode = FocusNode();
@override
void initState() {
final state = context.read<AiChatState>();
if (widget.args.chat != null) {
state.chatId = widget.args.chat!.id!;
state.chat = widget.args.chat;
}
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (state.chatId != null) {
state.getAllMessages(state.chatId!).then((value) => Future.delayed(
const Duration(
milliseconds: 100,
),
() => focusNode.requestFocus(),
));
} else {
Future.delayed(
const Duration(
milliseconds: 100,
),
() => focusNode.requestFocus(),
);
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
context.read<HistoryAiChatState>().getChats();
return true;
},
child: Consumer<AiChatState>(
builder: (context, state, child) => Scaffold(
appBar: AppBar(
shadowColor: Theme.of(context).colorScheme.border,
title: Text(widget.args.bot.name.toString()),
leading: Row(
children: [
DidvanIconButton(
icon: DidvanIcons.angle_right_solid,
onPressed: () {
Navigator.of(context).pop();
context.read<HistoryAiChatState>().getChats();
},
),
],
),
actions: [
if (state.chatId != null)
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: InkWell(
onTap: () {
final TextEditingController placeholder =
TextEditingController(
text: state.chat?.placeholder);
ActionSheetUtils.openDialog(
data: ActionSheetData(
hasConfirmButtonClose: false,
onConfirmed: () async {
final state = context.read<AiChatState>();
await state
.changePlaceHolder(placeholder.text);
ActionSheetUtils.pop();
},
content: ValueListenableBuilder<bool>(
valueListenable: state.changingPlaceHolder,
builder: (context, value, child) => Column(
children: [
Stack(
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
DidvanText(
'شخصی‌سازی دستورات',
style: Theme.of(context)
.textTheme
.titleMedium,
),
],
),
Positioned(
right: 0,
top: 0,
bottom: 0,
child: Center(
child: InkWell(
onTap: () {
ActionSheetUtils.pop();
},
child: const Icon(
DidvanIcons.close_solid,
size: 24,
),
),
)),
],
),
const SizedBox(
height: 12,
),
const DidvanText(
'دوست دارید هوشان، چه چیزهایی را درباره شما بداند تا بتواند پاسخ‌های بهتری ارائه دهد؟ \nدستورات و اطلاعات ارائه شما، بر روی تمامی پیام‌هایی که از این به بعد ارسال می‌کنید، اعمال خواهد شد.'),
const SizedBox(
height: 12,
),
value
? Center(
child: Image.asset(
Assets.loadingAnimation,
width: 60,
height: 60,
),
)
: TextField(
controller: placeholder,
style: (Theme.of(context)
.textTheme
.bodyMedium)!
.copyWith(
fontFamily: DesignConfig
.fontFamily
.padRight(3)),
decoration: InputDecoration(
filled: true,
fillColor: Theme.of(context)
.colorScheme
.secondCTA,
contentPadding:
const EdgeInsets.fromLTRB(
10, 10, 10, 0),
border: const OutlineInputBorder(
borderRadius: DesignConfig
.lowBorderRadius),
errorStyle: const TextStyle(
height: 0.01),
),
)
],
),
)));
},
child: const Icon(Icons.shopping_bag_outlined)),
)
],
centerTitle: true,
automaticallyImplyLeading: false,
),
body: state.loading
? Center(
child: Image.asset(
Assets.loadingAnimation,
width: 60,
height: 60,
),
)
: state.messages.isEmpty
? Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(
height: 12,
),
Center(
child: Icon(
DidvanIcons.ai_solid,
size: MediaQuery.sizeOf(context).width / 5,
),
),
const DidvanText('هوشان'),
const SizedBox(
height: 24,
),
Container(
width: MediaQuery.sizeOf(context).height / 5,
height: MediaQuery.sizeOf(context).height / 5,
decoration: BoxDecoration(
borderRadius: DesignConfig.highBorderRadius,
color: Theme.of(context).colorScheme.focused),
padding: const EdgeInsets.all(12),
child: CachedNetworkImage(
imageUrl: widget.args.bot.image.toString(),
),
),
const SizedBox(
height: 24,
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 20.0),
child: Text(
"به هوشان, هوش مصنوعی دیدوان خوش آمدید. \nبرای شروع گفتگو پیام مورد نظر خود را در کادر زیر بنویسید.\n دریافت پاسخ از: ${widget.args.bot.name}",
textAlign: TextAlign.center,
),
)
],
)
: SingleChildScrollView(
reverse: true,
controller: state.scrollController,
child: ListView.builder(
itemCount: state.messages.length,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: const EdgeInsets.only(bottom: 120),
itemBuilder: (context, mIndex) {
final prompts = state.messages[mIndex].prompts;
final time = state.messages[mIndex].dateTime;
return Column(
children: [
timeLabel(context, time),
ListView.builder(
itemCount: prompts.length,
shrinkWrap: true,
physics:
const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
final message = prompts[index];
return messageBubble(message, context,
state, index, mIndex);
},
),
],
);
}),
),
bottomSheet: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(
top: 8, bottom: 24.0, left: 12, right: 12),
child: AiMessageBar(
bot: widget.args.bot,
focusNode: focusNode,
),
),
],
)),
),
);
}
Center timeLabel(BuildContext context, String time) {
return Center(
child: Container(
margin: const EdgeInsets.symmetric(vertical: 12),
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.splash,
borderRadius: DesignConfig.lowBorderRadius,
),
child: DidvanText(
DateTime.parse(time).toPersianDateStr(),
style: Theme.of(context).textTheme.labelSmall,
color: DesignConfig.isDark
? Theme.of(context).colorScheme.white
: Theme.of(context).colorScheme.black,
),
),
);
}
Padding messageBubble(Prompts message, BuildContext context,
AiChatState state, int index, int mIndex) {
FilesModel? file =
message.file == null ? null : FilesModel(message.file.toString());
MarkdownStyleSheet defaultMarkdownStyleSheet = MarkdownStyleSheet(
code: TextStyle(
backgroundColor: Theme.of(context).colorScheme.black,
color: Theme.of(context).colorScheme.white,
),
codeblockPadding: const EdgeInsets.all(8),
codeblockDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: Theme.of(context).colorScheme.black));
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: message.role.toString().contains('user')
? CrossAxisAlignment.start
: CrossAxisAlignment.end,
children: [
Row(
mainAxisAlignment: message.role.toString().contains('user')
? MainAxisAlignment.start
: MainAxisAlignment.end,
children: [
Container(
padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
decoration: BoxDecoration(
borderRadius: DesignConfig.mediumBorderRadius.copyWith(
bottomLeft: !message.role.toString().contains('user')
? Radius.zero
: null,
bottomRight: message.role.toString().contains('user')
? Radius.zero
: null,
),
color: message.error != null && message.error!
? Theme.of(context).colorScheme.error.withOpacity(0.4)
: (message.role.toString().contains('user')
? Theme.of(context).colorScheme.surface
: Theme.of(context).colorScheme.focused)
.withOpacity(0.9),
border: Border.all(
color: Theme.of(context).colorScheme.border,
width: 0.5,
),
),
child: Container(
constraints: BoxConstraints(
maxWidth: MediaQuery.sizeOf(context).width / 1.5),
child: message.finished != null && !message.finished!
? Column(
children: [
ValueListenableBuilder<Stream<String>>(
valueListenable: state.messageOnstream,
builder: (context, value, child) {
return StreamBuilder<String>(
stream: value,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const SizedBox();
}
return Markdown(
data: "${snapshot.data}...",
selectable: false,
shrinkWrap: true,
physics:
const NeverScrollableScrollPhysics(),
styleSheet:
defaultMarkdownStyleSheet);
},
);
}),
SpinKitThreeBounce(
color: Theme.of(context).colorScheme.primary,
size: 18,
)
],
)
: Column(
children: [
if (message.role.toString().contains('user') &&
file != null)
lookupMimeType(file.path)?.startsWith('audio/') ??
false
? Directionality(
textDirection: TextDirection.ltr,
child: FutureBuilder(
future: StorageService.getValue(
key: 'token'),
builder: (context, snapshot) {
return MyVoiceMessageView(
size: 32,
controller: VoiceController(
audioSrc: file.path
.startsWith('/uploads')
? 'https://api.didvan.app${file.path}?accessToken=${snapshot.data}'
: file.path,
onComplete: () {
/// do something on complete
},
onPause: () {
/// do something on pause
},
onPlaying: () {
/// do something on playing
},
onError: (err) {
/// do somethin on error
},
isFile: !file.path
.startsWith('/uploads'),
maxDuration:
const Duration(seconds: 10),
),
innerPadding: 0,
cornerRadius: 20,
circlesColor: Theme.of(context)
.colorScheme
.primary,
activeSliderColor:
Theme.of(context)
.colorScheme
.primary,
);
}),
)
: Container(
decoration: BoxDecoration(
borderRadius:
DesignConfig.mediumBorderRadius,
color: Theme.of(context)
.colorScheme
.border,
),
constraints:
const BoxConstraints(minWidth: 200),
padding: const EdgeInsets.fromLTRB(
12, 8, 12, 8),
margin: const EdgeInsets.symmetric(
horizontal: 12),
child: Row(
children: [
const Icon(Icons.file_copy),
const SizedBox(
width: 12,
),
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
SizedBox(
width: 200,
child: DidvanText((message
.fileName
.toString())),
),
if (state.file != null)
FutureBuilder(
future: state.file!.main
.length(),
builder:
(context, snapshot) {
if (!snapshot.hasData) {
return const SizedBox();
}
return DidvanText(
'File Size ${(snapshot.data! / 1000).round()} KB',
fontSize: 12,
);
})
],
),
)
],
),
),
if (message.text != null)
Markdown(
data: message.text.toString(),
selectable: true,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
styleSheet: defaultMarkdownStyleSheet,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
if (message.role.toString().contains('user') &&
index ==
state.messages[mIndex].prompts.length -
2)
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () async {
state.isEdite = true;
state.message.text =
message.text.toString();
state.update();
},
child: Icon(
Icons.edit_outlined,
size: 18,
color: Theme.of(context)
.colorScheme
.focusedBorder,
),
),
),
if (message.error != null && message.error!)
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () async {
state.messages.last.prompts
.remove(message);
state.messages.last.prompts.add(
message.copyWith(error: false));
state.update();
await state
.postMessage(widget.args.bot);
},
child: Icon(
DidvanIcons.refresh_solid,
size: 18,
color: Theme.of(context)
.colorScheme
.focusedBorder,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () async {
await Clipboard.setData(ClipboardData(
text: state.messages[mIndex]
.prompts[index].text
.toString()));
ActionSheetUtils.showAlert(AlertData(
message: "متن با موفقیت کپی شد",
aLertType: ALertType.success));
},
child: Icon(
DidvanIcons.copy_regular,
size: 18,
color: Theme.of(context)
.colorScheme
.focusedBorder,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () async {
if (message.id != null) {
state.deleteMessage(
message.id!, mIndex, index);
} else {
state.messages[mIndex].prompts
.removeAt(index);
}
},
child: Icon(
DidvanIcons.trash_solid,
size: 18,
color: Theme.of(context)
.colorScheme
.focusedBorder,
),
),
),
],
)
],
),
),
)
],
),
const SizedBox(height: 4),
Row(
mainAxisSize: MainAxisSize.min,
children: [
DidvanText(
DateTimeUtils.timeWithAmPm(message.createdAt.toString()),
// DateTimeUtils.timeWithAmPm(message.createdAt),
style: Theme.of(context).textTheme.labelSmall,
color: Theme.of(context).colorScheme.caption,
),
],
),
],
),
);
}
}