-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathchatbox.dart
625 lines (490 loc) Β· 19.9 KB
/
chatbox.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
import 'dart:convert';
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:talkjs_flutter_inappwebview/talkjs_flutter_inappwebview.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import './session.dart';
import './conversation.dart';
import './chatoptions.dart';
import './user.dart';
import './message.dart';
import './predicate.dart';
import './webview_common.dart';
typedef SendMessageHandler = void Function(SendMessageEvent event);
typedef TranslationToggledHandler = void Function(TranslationToggledEvent event);
typedef LoadingStateHandler = void Function(LoadingState state);
typedef MessageActionHandler = void Function(MessageActionEvent event);
typedef NavigationHandler = UrlNavigationAction Function(UrlNavigationRequest navigationRequest);
class SendMessageEvent {
final ConversationData conversation;
final UserData me;
final SentMessage message;
SendMessageEvent.fromJson(Map<String, dynamic> json)
: conversation = ConversationData.fromJson(json['conversation']),
me = UserData.fromJson(json['me']),
message = SentMessage.fromJson(json['message']);
}
class TranslationToggledEvent {
final ConversationData conversation;
final bool isEnabled;
TranslationToggledEvent.fromJson(Map<String, dynamic> json)
: conversation = ConversationData.fromJson(json['conversation']),
isEnabled = json['isEnabled'];
}
enum LoadingState { loading, loaded }
class MessageActionEvent {
final String action;
final Message message;
MessageActionEvent.fromJson(Map<String, dynamic> json)
: action = json['action'],
message = Message.fromJson(json['message']);
}
class UrlNavigationRequest {
final String url;
UrlNavigationRequest(
this.url,
);
}
enum UrlNavigationAction { deny, allow }
/// A messaging UI for just a single conversation.
///
/// Create a Chatbox through [Session.createChatbox] and then call [mount] to show it.
/// There is no way for the user to switch between conversations
class ChatBox extends StatefulWidget {
final Session session;
final TextDirection? dir;
final MessageFieldOptions? messageField;
final bool? showChatHeader;
final TranslationToggle? showTranslationToggle;
final String? theme;
final TranslateConversations? translateConversations;
final List<String> highlightedWords = const <String>[];
final MessagePredicate messageFilter;
final Conversation? conversation;
final bool? asGuest;
final SendMessageHandler? onSendMessage;
final TranslationToggledHandler? onTranslationToggled;
final LoadingStateHandler? onLoadingStateChanged;
final Map<String, MessageActionHandler>? onCustomMessageAction;
final NavigationHandler? onUrlNavigation;
const ChatBox({
Key? key,
required this.session,
this.dir,
this.messageField,
this.showChatHeader,
this.showTranslationToggle,
this.theme,
this.translateConversations,
//this.highlightedWords = const <String>[], // Commented out due to bug #1953
this.messageFilter = const MessagePredicate(),
this.conversation,
this.asGuest,
this.onSendMessage,
this.onTranslationToggled,
this.onLoadingStateChanged,
this.onCustomMessageAction,
this.onUrlNavigation,
}) : super(key: key);
@override
State<ChatBox> createState() => ChatBoxState();
}
class ChatBoxState extends State<ChatBox> {
/// Used to control the underlying WebView
InAppWebViewController? _webViewController;
bool _webViewCreated = false;
/// List of JavaScript statements that haven't been executed.
final _pending = <String>[];
// A counter to ensure that IDs are unique
int _idCounter = 0;
/// A mapping of user ids to the variable name of the respective JavaScript
/// Talk.User object.
final _users = <String, String>{};
final _userObjs = <String, User>{};
/// A mapping of conversation ids to the variable name of the respective JavaScript
/// Talk.ConversationBuilder object.
final _conversations = <String, String>{};
final _conversationObjs = <String, Conversation>{};
/// Encapsulates the message entry field tied to the currently selected conversation.
// TODO: messageField still needs to be refactored
//late MessageField messageField;
/// Objects stored for comparing changes
ChatBoxOptions? _oldOptions;
List<String> _oldHighlightedWords = [];
MessagePredicate _oldMessageFilter = const MessagePredicate();
bool? _oldAsGuest;
Conversation? _oldConversation;
Set<String> _oldCustomActions = {};
@override
Widget build(BuildContext context) {
if (kDebugMode) {
print('π chatbox.build (_webViewCreated: $_webViewCreated)');
}
if (!_webViewCreated) {
// If it's the first time that the widget is built, then build everything
_webViewCreated = true;
if (Platform.isAndroid) {
InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
}
// Here a Timer is needed, as we can't change the widget's state while the widget
// is being constructed, and the callback may very possibly change the state
Timer.run(() => widget.onLoadingStateChanged?.call(LoadingState.loading));
execute('let chatBox;');
execute('''
function customMessageActionHandler(event) {
window.flutter_inappwebview.callHandler("JSCCustomMessageAction", JSON.stringify(event));
}
''');
createSession(execute: execute, session: widget.session, variableName: getUserVariableName(widget.session.me));
_createChatBox();
// messageFilter and highlightedWords are set as options for the chatbox
_createConversation();
execute('chatBox.mount(document.getElementById("talkjs-container")).then(() => window.flutter_inappwebview.callHandler("JSCLoadingState", "loaded"));');
} else {
// If it's not the first time that the widget is built,
// then check what needs to be rebuilt
// TODO: If something has changed in the Session we should do something
final chatBoxRecreated = _checkRecreateChatBox();
if (chatBoxRecreated) {
// messageFilter and highlightedWords are set as options for the chatbox
_createConversation();
} else {
_checkActionHandlers();
_checkMessageFilter();
_checkHighlightedWords();
_checkRecreateConversation();
}
// Mount the chatbox only if it's new (else the existing chatbox has already been mounted)
if (chatBoxRecreated) {
execute('chatBox.mount(document.getElementById("talkjs-container"));');
}
}
return InAppWebView(
initialSettings: InAppWebViewSettings(
useHybridComposition: true,
disableInputAccessoryView: true,
transparentBackground: true,
useShouldOverrideUrlLoading: true,
),
onWebViewCreated: _onWebViewCreated,
onLoadStop: _onLoadStop,
onConsoleMessage: (InAppWebViewController controller, ConsoleMessage message) {
print("chatbox [${message.messageLevel}] ${message.message}");
},
gestureRecognizers: {
// We need only the VerticalDragGestureRecognizer in order to be able to scroll through the messages
Factory(() => VerticalDragGestureRecognizer()),
},
onGeolocationPermissionsShowPrompt: (InAppWebViewController controller, String origin) async {
print("π chatbox onGeolocationPermissionsShowPrompt ($origin)");
final granted = await Permission.location.request().isGranted;
return GeolocationPermissionShowPromptResponse(origin: origin, allow: granted, retain: true);
},
onPermissionRequest: (InAppWebViewController controller, PermissionRequest permissionRequest) async {
print("π chatbox onPermissionRequest");
var granted = false;
if (permissionRequest.resources.indexOf(PermissionResourceType.MICROPHONE) >= 0) {
granted = await Permission.microphone.request().isGranted;
}
return PermissionResponse(resources: permissionRequest.resources, action: granted ? PermissionResponseAction.GRANT : PermissionResponseAction.DENY);
},
shouldOverrideUrlLoading: (InAppWebViewController controller, NavigationAction navigationAction) async {
if (navigationAction.navigationType == NavigationType.LINK_ACTIVATED) {
if (widget.onUrlNavigation != null) {
// The onUrlNavigation function has been defined, so let's see if we should open the browser or not
if (widget.onUrlNavigation!(UrlNavigationRequest(navigationAction.request.url!.rawValue)) == UrlNavigationAction.deny) {
return NavigationActionPolicy.CANCEL;
}
}
if (await launchUrl(navigationAction.request.url!)) {
// We launched the browser, so we don't navigate to the URL in the WebView
return NavigationActionPolicy.CANCEL;
} else {
// We couldn't launch the external browser, so as a fallback we're using the default action
return NavigationActionPolicy.ALLOW;
}
}
return NavigationActionPolicy.ALLOW;
},
);
}
void _createChatBox() {
_oldOptions = ChatBoxOptions(
dir: widget.dir,
messageField: widget.messageField,
showChatHeader: widget.showChatHeader,
showTranslationToggle: widget.showTranslationToggle,
theme: widget.theme,
translateConversations: widget.translateConversations,
);
_oldHighlightedWords = List<String>.of(widget.highlightedWords);
_oldMessageFilter = MessagePredicate.of(widget.messageFilter);
execute('chatBox = session.createChatbox(${_oldOptions!.getJsonString(this)});');
execute('chatBox.onSendMessage((event) => window.flutter_inappwebview.callHandler("JSCSendMessage", JSON.stringify(event)));');
execute('chatBox.onTranslationToggled((event) => window.flutter_inappwebview.callHandler("JSCTranslationToggled", JSON.stringify(event)));');
if (widget.onCustomMessageAction != null) {
_oldCustomActions = Set<String>.of(widget.onCustomMessageAction!.keys);
for (var action in _oldCustomActions) {
execute('chatBox.onCustomMessageAction("$action", customMessageActionHandler);');
}
} else {
_oldCustomActions = {};
}
}
bool _checkRecreateChatBox() {
final options = ChatBoxOptions(
dir: widget.dir,
messageField: widget.messageField,
showChatHeader: widget.showChatHeader,
showTranslationToggle: widget.showTranslationToggle,
theme: widget.theme,
translateConversations: widget.translateConversations,
);
if (options != _oldOptions) {
execute('chatBox.destroy();');
_createChatBox();
return true;
} else {
return false;
}
}
bool _checkActionHandlers() {
// If there are no handlers specified, then we don't need to create new handlers
if (widget.onCustomMessageAction == null) {
return false;
}
var customActions = Set<String>.of(widget.onCustomMessageAction!.keys);
if (!setEquals(customActions, _oldCustomActions)) {
var retval = false;
// Register only the new event handlers
//
// Possible memory leak: old event handlers are not getting unregistered
// This should not be a big problem in practice, as it is *very* rare that
// custom message handlers are being constantly changed
for (var action in customActions) {
if (!_oldCustomActions.contains(action)) {
_oldCustomActions.add(action);
execute('chatBox.onCustomMessageAction("$action", customMessageActionHandler);');
retval = true;
}
}
return retval;
} else {
return false;
}
}
void _createConversation() {
final result = <String, dynamic>{};
_oldAsGuest = widget.asGuest;
if (_oldAsGuest != null) {
result['asGuest'] = _oldAsGuest;
}
_oldConversation = widget.conversation;
if (_oldConversation != null) {
execute('chatBox.select(${getConversationVariableName(_oldConversation!)}, ${json.encode(result)});');
} else {
if (result.isNotEmpty) {
execute('chatBox.select(undefined, ${json.encode(result)});');
} else {
execute('chatBox.select(undefined);');
}
}
}
bool _checkRecreateConversation() {
if ((widget.asGuest != _oldAsGuest) || (widget.conversation != _oldConversation)) {
_createConversation();
return true;
}
return false;
}
void _setHighlightedWords() {
_oldHighlightedWords = List<String>.of(widget.highlightedWords);
execute('chatBox.setHighlightedWords(${json.encode(_oldHighlightedWords)});');
}
bool _checkHighlightedWords() {
if (!listEquals(widget.highlightedWords, _oldHighlightedWords)) {
_setHighlightedWords();
return true;
}
return false;
}
void _setMessageFilter() {
_oldMessageFilter = MessagePredicate.of(widget.messageFilter);
execute('chatBox.setMessageFilter(${json.encode(_oldMessageFilter)});');
}
bool _checkMessageFilter() {
if (widget.messageFilter != _oldMessageFilter) {
_setMessageFilter();
return true;
}
return false;
}
void _onWebViewCreated(InAppWebViewController controller) async {
if (kDebugMode) {
print('π chatbox._onWebViewCreated');
}
controller.addJavaScriptHandler(handlerName: 'JSCSendMessage', callback: _jscSendMessage);
controller.addJavaScriptHandler(handlerName: 'JSCTranslationToggled', callback: _jscTranslationToggled);
controller.addJavaScriptHandler(handlerName: 'JSCLoadingState', callback: _jscLoadingState);
controller.addJavaScriptHandler(handlerName: 'JSCCustomMessageAction', callback: _jscCustomMessageAction);
String htmlData = await rootBundle.loadString('packages/talkjs_flutter/assets/index.html');
controller.loadData(data: htmlData, baseUrl: WebUri("https://app.talkjs.com"));
}
void _onLoadStop(InAppWebViewController controller, WebUri? url) async {
if (kDebugMode) {
print('π chatbox._onLoadStop ($url)');
}
if (_webViewController == null) {
_webViewController = controller;
// Wait for TalkJS to be ready
final js = 'await Talk.ready;';
if (kDebugMode) {
print('π chatbox callAsyncJavaScript: $js');
}
await controller.callAsyncJavaScript(functionBody: js);
// Execute any pending instructions
for (var statement in _pending) {
if (kDebugMode) {
print('π chatbox._onLoadStop _pending: $statement');
}
controller.evaluateJavascript(source: statement);
}
}
}
void _jscSendMessage(List<dynamic> arguments) {
final message = arguments[0];
if (kDebugMode) {
print('π chatbox._jscSendMessage: $message');
}
widget.onSendMessage?.call(SendMessageEvent.fromJson(json.decode(message)));
}
void _jscTranslationToggled(List<dynamic> arguments) {
final message = arguments[0];
if (kDebugMode) {
print('π chatbox._jscTranslationToggled: $message');
}
widget.onTranslationToggled?.call(TranslationToggledEvent.fromJson(json.decode(message)));
}
void _jscLoadingState(List<dynamic> arguments) {
final message = arguments[0];
if (kDebugMode) {
print('π chatbox._jscLoadingState: $message');
}
widget.onLoadingStateChanged?.call(LoadingState.loaded);
}
void _jscCustomMessageAction(List<dynamic> arguments) {
final message = arguments[0];
if (kDebugMode) {
print('π chatbox._jscCustomMessageAction: $message');
}
Map<String, dynamic> jsonMessage = json.decode(message);
String action = jsonMessage['action'];
widget.onCustomMessageAction?[action]?.call(MessageActionEvent.fromJson(jsonMessage));
}
/// For internal use only. Implementation detail that may change anytime.
///
/// Return a string with a unique ID
String getUniqueId() {
final id = _idCounter;
_idCounter += 1;
return '_$id';
}
/// For internal use only. Implementation detail that may change anytime.
///
/// Returns the JavaScript variable name of the Talk.User object associated
/// with the given [User]
String getUserVariableName(User user) {
if (_users[user.id] == null) {
// Generate unique variable name
final variableName = 'user${getUniqueId()}';
_users[user.id] = variableName;
execute('let $variableName = new Talk.User(${user.getJsonString()});');
_userObjs[user.id] = User.of(user);
} else if (_userObjs[user.id] != user) {
final variableName = _users[user.id]!;
execute('$variableName = new Talk.User(${user.getJsonString()});');
_userObjs[user.id] = User.of(user);
}
return _users[user.id]!;
}
/// For internal use only. Implementation detail that may change anytime.
String getConversationVariableName(Conversation conversation) {
if (_conversations[conversation.id] == null) {
final variableName = 'conversation${getUniqueId()}';
_conversations[conversation.id] = variableName;
execute('let $variableName = session.getOrCreateConversation("${conversation.id}")');
_setConversationAttributes(variableName, conversation);
_setConversationParticipants(variableName, conversation);
_conversationObjs[conversation.id] = Conversation.of(conversation);
} else if (_conversationObjs[conversation.id] != conversation) {
final variableName = _conversations[conversation.id]!;
_setConversationAttributes(variableName, conversation);
if (!setEquals(conversation.participants, _conversationObjs[conversation.id]!.participants)) {
_setConversationParticipants(variableName, conversation);
}
_conversationObjs[conversation.id] = Conversation.of(conversation);
}
return _conversations[conversation.id]!;
}
void _setConversationAttributes(String variableName, Conversation conversation) {
final attributes = <String, dynamic>{};
if (conversation.custom != null) {
attributes['custom'] = conversation.custom;
}
if (conversation.welcomeMessages != null) {
attributes['welcomeMessages'] = conversation.welcomeMessages;
}
if (conversation.photoUrl != null) {
attributes['photoUrl'] = conversation.photoUrl;
}
if (conversation.subject != null) {
attributes['subject'] = conversation.subject;
}
if (attributes.isNotEmpty) {
execute('$variableName.setAttributes(${json.encode(attributes)});');
}
}
void _setConversationParticipants(String variableName, Conversation conversation) {
for (var participant in conversation.participants) {
final userVariableName = getUserVariableName(participant.user);
final result = <String, dynamic>{};
if (participant.access != null) {
result['access'] = participant.access!.getValue();
}
if (participant.notify != null) {
result['notify'] = participant.notify!.getValue();
}
execute('$variableName.setParticipant($userVariableName, ${json.encode(result)});');
}
}
/// For internal use only. Implementation detail that may change anytime.
///
/// Sets the options for ChatBoxOptions for the properties where there exists
/// both a declarative option and an imperative method
void setExtraOptions(Map<String, dynamic> result) {
result['highlightedWords'] = widget.highlightedWords;
result['messageFilter'] = widget.messageFilter;
}
/// For internal use only. Implementation detail that may change anytime.
///
/// Evaluates the JavaScript statement given.
void execute(String statement) {
final controller = _webViewController;
if (controller != null) {
if (kDebugMode) {
print('π chatbox.execute: $statement');
}
controller.evaluateJavascript(source: statement);
} else {
if (kDebugMode) {
print('π chatbox.execute: $statement');
}
this._pending.add(statement);
}
}
}