message-form.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import tpl_message_form from './templates/message-form.js';
  2. import { ElementView } from '@converse/skeletor/src/element.js';
  3. import { __ } from 'i18n';
  4. import { _converse, api, converse } from "@converse/headless/core.js";
  5. import { parseMessageForCommands } from './utils.js';
  6. import { prefixMentions } from '@converse/headless/utils/core.js';
  7. const { u } = converse.env;
  8. export default class MessageForm extends ElementView {
  9. async connectedCallback () {
  10. super.connectedCallback();
  11. this.model = _converse.chatboxes.get(this.getAttribute('jid'));
  12. await this.model.initialized;
  13. this.listenTo(this.model.messages, 'change:correcting', this.onMessageCorrecting);
  14. this.listenTo(this.model, 'change:composing_spoiler', () => this.render());
  15. this.handleEmojiSelection = ({ detail }) => this.insertIntoTextArea(
  16. detail.value,
  17. detail.autocompleting,
  18. false,
  19. detail.ac_position
  20. );
  21. document.addEventListener("emojiSelected", this.handleEmojiSelection);
  22. this.render();
  23. }
  24. disconnectedCallback () {
  25. super.disconnectedCallback();
  26. document.removeEventListener("emojiSelected", this.handleEmojiSelection);
  27. }
  28. toHTML () {
  29. return tpl_message_form(
  30. Object.assign(this.model.toJSON(), {
  31. 'onDrop': ev => this.onDrop(ev),
  32. 'hint_value': this.querySelector('.spoiler-hint')?.value,
  33. 'message_value': this.querySelector('.chat-textarea')?.value,
  34. 'onChange': ev => this.model.set({'draft': ev.target.value}),
  35. 'onKeyDown': ev => this.onKeyDown(ev),
  36. 'onKeyUp': ev => this.onKeyUp(ev),
  37. 'onPaste': ev => this.onPaste(ev),
  38. 'viewUnreadMessages': ev => this.viewUnreadMessages(ev)
  39. })
  40. );
  41. }
  42. /**
  43. * Insert a particular string value into the textarea of this chat box.
  44. * @param {string} value - The value to be inserted.
  45. * @param {(boolean|string)} [replace] - Whether an existing value
  46. * should be replaced. If set to `true`, the entire textarea will
  47. * be replaced with the new value. If set to a string, then only
  48. * that string will be replaced *if* a position is also specified.
  49. * @param {integer} [position] - The end index of the string to be
  50. * replaced with the new value.
  51. */
  52. insertIntoTextArea (value, replace = false, correcting = false, position) {
  53. const textarea = this.querySelector('.chat-textarea');
  54. if (correcting) {
  55. u.addClass('correcting', textarea);
  56. } else {
  57. u.removeClass('correcting', textarea);
  58. }
  59. if (replace) {
  60. if (position && typeof replace == 'string') {
  61. textarea.value = textarea.value.replace(new RegExp(replace, 'g'), (match, offset) =>
  62. offset == position - replace.length ? value + ' ' : match
  63. );
  64. } else {
  65. textarea.value = value;
  66. }
  67. } else {
  68. let existing = textarea.value;
  69. if (existing && existing[existing.length - 1] !== ' ') {
  70. existing = existing + ' ';
  71. }
  72. textarea.value = existing + value + ' ';
  73. }
  74. const ev = document.createEvent('HTMLEvents');
  75. ev.initEvent('change', false, true);
  76. textarea.dispatchEvent(ev);
  77. u.placeCaretAtEnd(textarea);
  78. }
  79. onMessageCorrecting (message) {
  80. if (message.get('correcting')) {
  81. this.insertIntoTextArea(prefixMentions(message), true, true);
  82. } else {
  83. const currently_correcting = this.model.messages.findWhere('correcting');
  84. if (currently_correcting && currently_correcting !== message) {
  85. this.insertIntoTextArea(prefixMentions(message), true, true);
  86. } else {
  87. this.insertIntoTextArea('', true, false);
  88. }
  89. }
  90. }
  91. onEscapePressed (ev) {
  92. const idx = this.model.messages.findLastIndex('correcting');
  93. const message = idx >= 0 ? this.model.messages.at(idx) : null;
  94. if (message) {
  95. ev.preventDefault();
  96. message.save('correcting', false);
  97. this.insertIntoTextArea('', true, false);
  98. }
  99. }
  100. onPaste (ev) {
  101. ev.stopPropagation();
  102. if (ev.clipboardData.files.length !== 0) {
  103. ev.preventDefault();
  104. // Workaround for quirk in at least Firefox 60.7 ESR:
  105. // It seems that pasted files disappear from the event payload after
  106. // the event has finished, which apparently happens during async
  107. // processing in sendFiles(). So we copy the array here.
  108. this.model.sendFiles(Array.from(ev.clipboardData.files));
  109. return;
  110. }
  111. this.model.set({'draft': ev.clipboardData.getData('text/plain')});
  112. }
  113. onKeyUp (ev) {
  114. this.model.set({'draft': ev.target.value});
  115. }
  116. onKeyDown (ev) {
  117. if (ev.ctrlKey) {
  118. // When ctrl is pressed, no chars are entered into the textarea.
  119. return;
  120. }
  121. if (!ev.shiftKey && !ev.altKey && !ev.metaKey) {
  122. if (ev.keyCode === converse.keycodes.TAB) {
  123. const value = u.getCurrentWord(ev.target, null, /(:.*?:)/g);
  124. if (value.startsWith(':')) {
  125. ev.preventDefault();
  126. ev.stopPropagation();
  127. this.model.trigger('emoji-picker-autocomplete', ev.target, value);
  128. }
  129. } else if (ev.keyCode === converse.keycodes.FORWARD_SLASH) {
  130. // Forward slash is used to run commands. Nothing to do here.
  131. return;
  132. } else if (ev.keyCode === converse.keycodes.ESCAPE) {
  133. return this.onEscapePressed(ev, this);
  134. } else if (ev.keyCode === converse.keycodes.ENTER) {
  135. return this.onFormSubmitted(ev);
  136. } else if (ev.keyCode === converse.keycodes.UP_ARROW && !ev.target.selectionEnd) {
  137. const textarea = this.querySelector('.chat-textarea');
  138. if (!textarea.value || u.hasClass('correcting', textarea)) {
  139. return this.model.editEarlierMessage();
  140. }
  141. } else if (
  142. ev.keyCode === converse.keycodes.DOWN_ARROW &&
  143. ev.target.selectionEnd === ev.target.value.length &&
  144. u.hasClass('correcting', this.querySelector('.chat-textarea'))
  145. ) {
  146. return this.model.editLaterMessage();
  147. }
  148. }
  149. if (
  150. [
  151. converse.keycodes.SHIFT,
  152. converse.keycodes.META,
  153. converse.keycodes.META_RIGHT,
  154. converse.keycodes.ESCAPE,
  155. converse.keycodes.ALT
  156. ].includes(ev.keyCode)
  157. ) {
  158. return;
  159. }
  160. if (this.model.get('chat_state') !== _converse.COMPOSING) {
  161. // Set chat state to composing if keyCode is not a forward-slash
  162. // (which would imply an internal command and not a message).
  163. this.model.setChatState(_converse.COMPOSING);
  164. }
  165. }
  166. async onFormSubmitted (ev) {
  167. ev?.preventDefault?.();
  168. const textarea = this.querySelector('.chat-textarea');
  169. const message_text = textarea.value.trim();
  170. if (
  171. (api.settings.get('message_limit') && message_text.length > api.settings.get('message_limit')) ||
  172. !message_text.replace(/\s/g, '').length
  173. ) {
  174. return;
  175. }
  176. if (!_converse.connection.authenticated) {
  177. const err_msg = __('Sorry, the connection has been lost, and your message could not be sent');
  178. api.alert('error', __('Error'), err_msg);
  179. api.connection.reconnect();
  180. return;
  181. }
  182. let spoiler_hint,
  183. hint_el = {};
  184. if (this.model.get('composing_spoiler')) {
  185. hint_el = this.querySelector('form.sendXMPPMessage input.spoiler-hint');
  186. spoiler_hint = hint_el.value;
  187. }
  188. u.addClass('disabled', textarea);
  189. textarea.setAttribute('disabled', 'disabled');
  190. this.querySelector('converse-emoji-dropdown')?.hideMenu();
  191. const is_command = await parseMessageForCommands(this.model, message_text);
  192. const message = is_command ? null : await this.model.sendMessage({'body': message_text, spoiler_hint});
  193. if (is_command || message) {
  194. hint_el.value = '';
  195. textarea.value = '';
  196. u.removeClass('correcting', textarea);
  197. textarea.style.height = 'auto';
  198. this.model.set({'draft': ''});
  199. }
  200. if (api.settings.get('view_mode') === 'overlayed') {
  201. // XXX: Chrome flexbug workaround. The .chat-content area
  202. // doesn't resize when the textarea is resized to its original size.
  203. const chatview = _converse.chatboxviews.get(this.getAttribute('jid'));
  204. const msgs_container = chatview.querySelector('.chat-content__messages');
  205. msgs_container.parentElement.style.display = 'none';
  206. }
  207. textarea.removeAttribute('disabled');
  208. u.removeClass('disabled', textarea);
  209. if (api.settings.get('view_mode') === 'overlayed') {
  210. // XXX: Chrome flexbug workaround.
  211. const chatview = _converse.chatboxviews.get(this.getAttribute('jid'));
  212. const msgs_container = chatview.querySelector('.chat-content__messages');
  213. msgs_container.parentElement.style.display = '';
  214. }
  215. // Suppress events, otherwise superfluous CSN gets set
  216. // immediately after the message, causing rate-limiting issues.
  217. this.model.setChatState(_converse.ACTIVE, { 'silent': true });
  218. textarea.focus();
  219. }
  220. }
  221. api.elements.define('converse-message-form', MessageForm);