-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebchat_controller.js
368 lines (367 loc) · 17.1 KB
/
webchat_controller.js
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
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stimulus = require("@hotwired/stimulus");
var _dom = require("@floating-ui/dom");
var _messages = _interopRequireDefault(require("../api/web_chat/messages"));
var _web_chat_channel = _interopRequireDefault(require("../channels/web_chat_channel"));
var _hellotext = _interopRequireDefault(require("../hellotext"));
var _web_chat = require("../core/configuration/web_chat");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var _default = /*#__PURE__*/function (_Controller) {
_inherits(_default, _Controller);
var _super = _createSuper(_default);
function _default() {
_classCallCheck(this, _default);
return _super.apply(this, arguments);
}
_createClass(_default, [{
key: "initialize",
value: function initialize() {
this.messagesAPI = new _messages.default(this.idValue);
this.webChatChannel = new _web_chat_channel.default(this.idValue, _hellotext.default.session);
this.files = [];
this.onMessageReceived = this.onMessageReceived.bind(this);
this.onConversationAssignment = this.onConversationAssignment.bind(this);
this.onScroll = this.onScroll.bind(this);
_get(_getPrototypeOf(_default.prototype), "initialize", this).call(this);
}
}, {
key: "connect",
value: function connect() {
this.floatingUICleanup = (0, _dom.autoUpdate)(this.triggerTarget, this.popoverTarget, () => {
(0, _dom.computePosition)(this.triggerTarget, this.popoverTarget, {
placement: this.placementValue,
middleware: this.middlewares
}).then(_ref => {
var {
x,
y
} = _ref;
var newStyle = {
left: "".concat(x, "px"),
top: "".concat(y, "px")
};
Object.assign(this.popoverTarget.style, newStyle);
});
});
this.webChatChannel.onMessage(this.onMessageReceived);
this.webChatChannel.onConversationAssignment(this.onConversationAssignment);
this.messagesContainerTarget.addEventListener('scroll', this.onScroll);
_hellotext.default.eventEmitter.dispatch('webchat:mounted');
_get(_getPrototypeOf(_default.prototype), "connect", this).call(this);
}
}, {
key: "disconnect",
value: function disconnect() {
this.messagesContainerTarget.removeEventListener('scroll', this.onScroll);
this.floatingUICleanup();
_get(_getPrototypeOf(_default.prototype), "disconnect", this).call(this);
}
}, {
key: "onScroll",
value: function () {
var _onScroll = _asyncToGenerator(function* () {
if (this.messagesContainerTarget.scrollTop > 300 || !this.nextPageValue || this.fetchingNextPage) return;
this.fetchingNextPage = true;
var response = yield this.messagesAPI.index({
page: this.nextPageValue,
session: _hellotext.default.session
});
var {
next: nextPage,
messages
} = yield response.json();
this.nextPageValue = nextPage;
this.oldScrollHeight = this.messagesContainerTarget.scrollHeight;
messages.forEach(message => {
var {
body,
attachments
} = message;
var div = document.createElement('div');
div.innerHTML = body;
var element = this.messageTemplateTarget.cloneNode(true);
element.removeAttribute('[data-hellotext--webchat-target]');
element.style.removeProperty('display');
element.querySelector('[data-body]').innerHTML = div.innerHTML;
if (message.state === 'received') {
element.classList.add('received');
} else {
element.classList.remove('received');
}
if (attachments) {
attachments.forEach(attachmentUrl => {
var image = this.attachmentImageTarget.cloneNode(true);
image.removeAttribute('data-hellotext--webchat-target');
image.src = attachmentUrl;
image.style.display = 'block';
element.querySelector('[data-attachment-container]').appendChild(image);
});
}
element.setAttribute('data-body', body);
this.messagesContainerTarget.prepend(element);
});
this.messagesContainerTarget.scroll({
top: this.messagesContainerTarget.scrollHeight - this.oldScrollHeight,
behavior: 'instant'
});
this.fetchingNextPage = false;
});
function onScroll() {
return _onScroll.apply(this, arguments);
}
return onScroll;
}()
}, {
key: "show",
value: function show() {
this.openValue = true;
}
}, {
key: "hide",
value: function hide() {
this.openValue = false;
}
}, {
key: "toggle",
value: function toggle() {
this.openValue = !this.openValue;
}
}, {
key: "onClickOutside",
value: function onClickOutside(event) {
if (_web_chat.WebChat.behaviour === _web_chat.behaviors.POPOVER && this.openValue && event.target.nodeType && this.element.contains(event.target) === false) {
this.openValue = false;
}
}
}, {
key: "openValueChanged",
value: function openValueChanged() {
if (this.disabledValue) return;
if (this.openValue) {
this.popoverTarget.showPopover();
this.popoverTarget.setAttribute("aria-expanded", "true");
this.inputTarget.focus();
if (!this.scrolled) {
this.messagesContainerTarget.scroll({
top: this.messagesContainerTarget.scrollHeight,
behavior: 'instant'
});
this.scrolled = true;
}
_hellotext.default.eventEmitter.dispatch('webchat:opened');
} else {
this.popoverTarget.hidePopover();
this.popoverTarget.removeAttribute("aria-expanded");
this.dispatch("hidden");
this.inputTarget.value = "";
_hellotext.default.eventEmitter.dispatch('webchat:closed');
}
}
}, {
key: "onMessageReceived",
value: function onMessageReceived(message) {
var {
body,
attachments
} = message;
var div = document.createElement('div');
div.innerHTML = body;
var element = this.messageTemplateTarget.cloneNode(true);
element.style.display = 'flex';
element.querySelector('[data-body]').innerHTML = div.innerHTML;
if (attachments) {
attachments.forEach(attachmentUrl => {
var image = this.attachmentImageTarget.cloneNode(true);
image.src = attachmentUrl;
image.style.display = 'block';
element.querySelector('[data-attachment-container]').appendChild(image);
});
}
this.messagesContainerTarget.appendChild(element);
}
}, {
key: "onConversationAssignment",
value: function onConversationAssignment(conversation) {
var {
to: user
} = conversation;
this.titleTarget.innerText = user.name;
if (user.online) {
this.onlineStatusTarget.style.display = 'flex';
} else {
this.onlineStatusTarget.style.display = 'none';
}
}
}, {
key: "sendMessage",
value: function () {
var _sendMessage = _asyncToGenerator(function* () {
var formData = new FormData();
formData.append('message[body]', this.inputTarget.value);
this.files.forEach(file => {
formData.append('message[attachments][]', file);
});
formData.append('session', _hellotext.default.session);
var response = yield this.messagesAPI.create(formData);
if (response.succeeded) {
var element = this.messageTemplateTarget.cloneNode(true);
element.classList.add('received');
element.style.removeProperty('display');
element.setAttribute('data-hellotext--webchat-target', 'message');
element.querySelector('[data-body]').innerText = this.inputTarget.value;
var attachments = this.attachmentContainerTarget.querySelectorAll('img');
if (attachments.length > 0) {
attachments.forEach(attachment => {
element.querySelector('[data-attachment-container]').appendChild(attachment);
});
}
this.messagesContainerTarget.appendChild(element);
this.inputTarget.value = "";
this.files = [];
this.attachmentContainerTarget.innerHTML = "";
this.attachmentContainerTarget.classList.add("hidden");
this.inputTarget.focus();
}
});
function sendMessage() {
return _sendMessage.apply(this, arguments);
}
return sendMessage;
}()
}, {
key: "openAttachment",
value: function openAttachment() {
this.attachmentInputTarget.click();
}
}, {
key: "onFileInputChange",
value: function onFileInputChange() {
this.errorMessageContainerTarget.classList.add('hidden');
this.files = Array.from(this.attachmentInputTarget.files);
var fileMaxSizeTooMuch = this.files.find(file => {
var type = file.type.split("/")[0];
if (['image', 'video', 'audio'].includes(type)) {
return this.mediaValue[type].max_size < file.size;
} else {
return this.mediaValue.document.max_size < file.size;
}
});
if (fileMaxSizeTooMuch) {
var type = fileMaxSizeTooMuch.type.split("/")[0];
var mediaType = ['image', 'audio', 'video'].includes(type) ? type : 'document';
this.errorMessageContainerTarget.innerText = this.fileSizeErrorMessageValue.replace('%{limit}', this.byteToMegabyte(this.mediaValue[mediaType].max_size));
return;
}
this.errorMessageContainerTarget.innerText = "";
this.files.forEach(file => this.createAttachmentElement(file));
this.inputTarget.focus();
}
}, {
key: "createAttachmentElement",
value: function createAttachmentElement(file) {
var element = this.attachmentElement();
this.attachmentContainerTarget.classList.remove('hidden');
element.setAttribute('data-name', file.name);
if (file.type.startsWith("image/")) {
var thumbnail = this.attachmentImageTarget.cloneNode(true);
thumbnail.src = URL.createObjectURL(file);
thumbnail.style.display = 'block';
element.appendChild(thumbnail);
this.attachmentContainerTarget.appendChild(element);
this.attachmentContainerTarget.style.display = 'flex';
} else {
element.querySelector("main").classList.add(...this.widthClasses, "h-20", "rounded-md", "bg-gray-200", "p-1");
element.querySelector("p[data-attachment-name]").innerText = file.name;
}
}
}, {
key: "removeAttachment",
value: function removeAttachment(_ref2) {
var {
currentTarget
} = _ref2;
var attachment = currentTarget.closest("[data-hellotext--webchat-target='attachment']");
this.files = this.files.filter(file => file.name !== attachment.dataset.name);
attachment.remove();
this.inputTarget.focus();
}
}, {
key: "attachmentTargetDisconnected",
value: function attachmentTargetDisconnected() {
if (this.attachmentTargets.length === 0) {
this.attachmentContainerTarget.innerHTML = "";
this.attachmentContainerTarget.style.display = 'none';
}
}
}, {
key: "attachmentElement",
value: function attachmentElement() {
var element = this.attachmentTemplateTarget.cloneNode(true);
element.removeAttribute("hidden");
element.style.display = 'flex';
element.setAttribute("data-hellotext--webchat-target", "attachment");
return element;
}
}, {
key: "byteToMegabyte",
value: function byteToMegabyte(bytes) {
return Math.ceil(bytes / 1024 / 1024);
}
}, {
key: "middlewares",
get: function get() {
return [(0, _dom.offset)(5), (0, _dom.shift)({
padding: 24
}), (0, _dom.flip)()];
}
}]);
return _default;
}(_stimulus.Controller);
exports.default = _default;
_default.values = {
id: String,
conversationId: String,
media: Object,
fileSizeErrorMessage: String,
placement: {
type: String,
default: "bottom-end"
},
open: {
type: Boolean,
default: false
},
autoPlacement: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
nextPage: {
type: Number,
default: undefined
}
};
_default.targets = ['trigger', 'popover', 'input', 'attachmentInput', 'attachmentButton', 'errorMessageContainer', 'attachmentTemplate', 'attachmentContainer', 'attachment', 'messageTemplate', 'messagesContainer', 'title', 'onlineStatus', 'attachmentImage'];