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

332 lines
13 KiB
Dart

// ignore_for_file: library_private_types_in_public_api, deprecated_member_use
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/main.dart';
import 'package:didvan/models/ai/ai_chat_args.dart';
import 'package:didvan/models/ai/chats_model.dart';
import 'package:didvan/models/enums.dart';
import 'package:didvan/models/view/alert_data.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/widgets/didvan/icon_button.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/state_handlers/empty_state.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:provider/provider.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> {
TextEditingController message = TextEditingController();
@override
void initState() {
final state = context.read<AiChatState>();
state.chatId = widget.args.chatId;
if (state.chatId != null) {
state.getAllMessages(state.chatId!);
}
super.initState();
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
context.read<HistoryAiChatState>().getChats();
return true;
},
child: Scaffold(
appBar: AppBar(
shadowColor: Theme.of(context).colorScheme.border,
title: Row(
children: [
Padding(
padding: const EdgeInsets.all(12.0),
child: ClipOval(
child: CachedNetworkImage(
width: 32,
height: 32,
imageUrl: widget.args.bot.image.toString(),
),
),
),
Text('چت با ${widget.args.bot.name}'),
],
),
automaticallyImplyLeading: false,
actions: [
DidvanIconButton(
icon: DidvanIcons.angle_left_regular,
onPressed: () {
context.read<HistoryAiChatState>().getChats();
navigatorKey.currentState!.pop();
},
)
],
),
body: Consumer<AiChatState>(
builder: (BuildContext context, AiChatState state, Widget? child) {
return ValueListenableBuilder<bool>(
valueListenable: state.loading,
builder: (context, value, child) => value
? Center(
child: Image.asset(
Assets.loadingAnimation,
width: 60,
height: 60,
),
)
: state.messages.isEmpty
? Center(
child: EmptyState(
asset: Assets.emptyChat,
title: 'اولین پیام را بنویسید...',
),
)
: SingleChildScrollView(
reverse: true,
child: ListView.builder(
itemCount: state.messages.length,
controller: state.scrollController,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: const EdgeInsets.only(top: 12, bottom: 90),
itemBuilder: (context, index) {
final message = state.messages[index];
return messageBubble(
message, context, state, index);
},
),
),
);
},
),
bottomSheet: Container(
width: MediaQuery.sizeOf(context).width,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: Theme.of(context).colorScheme.cardBorder,
),
),
color: Theme.of(context).colorScheme.surface,
),
child: ValueListenableBuilder(
valueListenable: context.read<AiChatState>().onResponsing,
builder: (context, value, child) => Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
width: 12,
),
SizedBox(
width: 46,
height: 46,
child: Center(
child: value
? Center(
child: SpinKitThreeBounce(
size: 18,
color: Theme.of(context).colorScheme.primary,
),
)
: DidvanIconButton(
icon: DidvanIcons.send_solid,
onPressed: () async {
if (message.text.isEmpty) {
return;
}
final state = context.read<AiChatState>();
state.messages.add(Prompts(
text: message.text,
finished: true,
role: 'user',
createdAt: DateTime.now()
.subtract(const Duration(minutes: 210))
.toIso8601String(),
));
message.clear();
await state.postMessage(widget.args.bot);
},
size: 32,
color: Theme.of(context).colorScheme.focusedBorder,
),
),
),
const SizedBox(
width: 12,
),
Expanded(
flex: 15,
child: Form(
child: TextFormField(
textInputAction: TextInputAction.newline,
style: Theme.of(context).textTheme.bodyMedium,
maxLines: 6,
minLines: 1,
// keyboardType: TextInputType.text,
controller: message,
enabled: !value,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'بنویسید...',
hintStyle: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(
color:
Theme.of(context).colorScheme.disabledText),
),
onChanged: (value) {},
),
),
),
],
),
),
),
),
);
}
Padding messageBubble(
Prompts message, BuildContext context, AiChatState state, int index) {
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.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: state.messages[index].finished != null &&
!state.messages[index].finished!
? StreamBuilder<String>(
stream: state.messageOnstream,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const SizedBox();
}
return Markdown(
data: "${snapshot.data}...",
selectable: false,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
styleSheet: defaultMarkdownStyleSheet);
},
)
: Column(
children: [
Markdown(
data: state.messages[index].text.toString(),
selectable: true,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
styleSheet: defaultMarkdownStyleSheet,
),
if (!message.role.toString().contains('user'))
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () async {
await Clipboard.setData(ClipboardData(
text: state.messages[index].text
.toString()));
ActionSheetUtils.showAlert(AlertData(
message: "متن با موفقیت کپی شد",
aLertType: ALertType.success));
},
child: Icon(
DidvanIcons.copy_regular,
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,
),
],
),
],
),
);
}
}