-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebchat_controller.js
262 lines (261 loc) · 12.7 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
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stimulus = require("@hotwired/stimulus");
var _dom = require("@floating-ui/dom");
var _actioncable = require("@rails/actioncable");
var _messages = _interopRequireDefault(require("../api/web_chat/messages"));
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.files = [];
this.consumer = (0, _actioncable.createConsumer)('ws://localhost:3000/cable');
_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);
});
});
var params = {
channel: "WebChatChannel",
id: this.idValue,
session: Hellotext.session
};
this.consumer.subscriptions.create(params, {
received(data) {
console.log("data received", data);
}
});
_get(_getPrototypeOf(_default.prototype), "connect", this).call(this);
}
}, {
key: "disconnect",
value: function disconnect() {
this.floatingUICleanup();
_get(_getPrototypeOf(_default.prototype), "disconnect", this).call(this);
}
}, {
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 (event.target.nodeType && this.element.contains(event.target) === false) {
this.openValue = false;
setTimeout(() => this.dispatch("aborted"), 400);
}
}
}, {
key: "openValueChanged",
value: function openValueChanged() {
if (this.disabledValue) return;
this.dispatch("toggle", {
detail: this.openValue
});
if (this.openValue) {
this.popoverTarget.showPopover();
this.popoverTarget.setAttribute("aria-expanded", "true");
this.dispatch("opened");
this.inputTarget.focus();
} else {
this.popoverTarget.hidePopover();
this.popoverTarget.removeAttribute("aria-expanded");
this.dispatch("hidden");
this.inputTarget.value = "";
}
}
}, {
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.session);
var response = yield this.messagesAPI.create(formData);
if (response.succeeded) {
var element = this.messageTemplateTarget.cloneNode(true);
element.style.display = 'flex';
element.innerText = this.inputTarget.value;
this.messagesContainerTarget.appendChild(element);
this.inputTarget.value = "";
this.files = [];
this.attachmentContainerTarget.innerHTML = "";
this.attachmentContainerTarget.classList.add("hidden");
this.inputTarget.focus();
}
console.log(response);
});
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));
this.errorMessageContainerTarget.classList.remove('hidden');
return;
}
this.errorMessageContainerTarget.classList.add('hidden');
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 = element.querySelector('img');
thumbnail.src = URL.createObjectURL(file);
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.classList.add("hidden");
}
}
}, {
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,
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
}
};
_default.targets = ['trigger', 'popover', 'input', 'attachmentInput', 'attachmentButton', 'errorMessageContainer', 'attachmentTemplate', 'attachmentContainer', 'attachment', 'messageTemplate', 'messagesContainer'];