text.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import URI from 'urijs';
  2. import log from '@converse/headless/log';
  3. import { _converse, api, converse } from '@converse/headless/core';
  4. import { containsDirectives, getDirectiveAndLength, getDirectiveTemplate, isQuoteDirective } from './styling.js';
  5. import { convertASCII2Emoji, getCodePointReferences, getEmojiMarkup, getShortnameReferences } from '@converse/headless/plugins/emoji/index.js';
  6. import { html } from 'lit-html';
  7. const u = converse.env.utils;
  8. const isString = (s) => typeof s === 'string';
  9. // We don't render more than two line-breaks, replace extra line-breaks with
  10. // the zero-width whitespace character
  11. const collapseLineBreaks = text => text.replace(/\n\n+/g, m => `\n${"\u200B".repeat(m.length-2)}\n`);
  12. const tpl_mention_with_nick = (o) => html`<span class="mention mention--self badge badge-info">${o.mention}</span>`;
  13. const tpl_mention = (o) => html`<span class="mention">${o.mention}</span>`;
  14. /**
  15. * @class RichText
  16. * A String subclass that is used to render rich text (i.e. text that contains
  17. * hyperlinks, images, mentions, styling etc.).
  18. *
  19. * The "rich" parts of the text is represented by lit-html TemplateResult
  20. * objects which are added via the {@link RichText.addTemplateResult}
  21. * method and saved as metadata.
  22. *
  23. * By default Converse adds TemplateResults to support emojis, hyperlinks,
  24. * images, map URIs and mentions.
  25. *
  26. * 3rd party plugins can listen for the `beforeMessageBodyTransformed`
  27. * and/or `afterMessageBodyTransformed` events and then call
  28. * `addTemplateResult` on the RichText instance in order to add their own
  29. * rich features.
  30. */
  31. export class RichText extends String {
  32. /**
  33. * Create a new {@link RichText} instance.
  34. * @param { String } text - The text to be annotated
  35. * @param { Integer } offset - The offset of this particular piece of text
  36. * from the start of the original message text. This is necessary because
  37. * RichText instances can be nested when templates call directives
  38. * which create new RichText instances (as happens with XEP-393 styling directives).
  39. * @param { Array } mentions - An array of mention references
  40. * @param { Object } options
  41. * @param { String } options.nick - The current user's nickname (only relevant if the message is in a XEP-0045 MUC)
  42. * @param { Boolean } options.render_styling - Whether XEP-0393 message styling should be applied to the message
  43. * @param { Boolean } options.show_images - Whether image URLs should be rendered as <img> tags.
  44. * @param { Boolean } options.show_me_message - Whether /me messages should be rendered differently
  45. * @param { Function } options.onImgClick - Callback for when an inline rendered image has been clicked
  46. * @param { Function } options.onImgLoad - Callback for when an inline rendered image has been loaded
  47. */
  48. constructor (text, offset=0, mentions=[], options={}) {
  49. super(text);
  50. this.mentions = mentions;
  51. this.nick = options?.nick;
  52. this.offset = offset;
  53. this.onImgClick = options?.onImgClick;
  54. this.onImgLoad = options?.onImgLoad;
  55. this.options = options;
  56. this.payload = [];
  57. this.references = [];
  58. this.render_styling = options?.render_styling;
  59. this.show_images = options?.show_images;
  60. }
  61. /**
  62. * Look for `http` URIs and return templates that render them as URL links
  63. * @param { String } text
  64. * @param { Integer } offset - The index of the passed in text relative to
  65. * the start of the message body text.
  66. */
  67. addHyperlinks (text, offset) {
  68. const objs = [];
  69. try {
  70. const parse_options = { 'start': /\b(?:([a-z][a-z0-9.+-]*:\/\/)|xmpp:|mailto:|www\.)/gi };
  71. URI.withinString(text, (url, start, end) => {
  72. objs.push({url, start, end})
  73. return url;
  74. } , parse_options);
  75. } catch (error) {
  76. log.debug(error);
  77. return;
  78. }
  79. objs.forEach(url_obj => {
  80. const url_text = text.slice(url_obj.start, url_obj.end);
  81. const filtered_url = u.filterQueryParamsFromURL(url_text);
  82. this.addTemplateResult(
  83. url_obj.start+offset,
  84. url_obj.end+offset,
  85. this.show_images && u.isImageURL(url_text) && u.isImageDomainAllowed(url_text) ?
  86. u.convertToImageTag(filtered_url, this.onImgLoad, this.onImgClick) :
  87. u.convertUrlToHyperlink(filtered_url),
  88. );
  89. });
  90. }
  91. /**
  92. * Look for `geo` URIs and return templates that render them as URL links
  93. * @param { String } text
  94. * @param { Integer } offset - The index of the passed in text relative to
  95. * the start of the message body text.
  96. */
  97. addMapURLs (text, offset) {
  98. const regex = /geo:([\-0-9.]+),([\-0-9.]+)(?:,([\-0-9.]+))?(?:\?(.*))?/g;
  99. const matches = text.matchAll(regex);
  100. for (const m of matches) {
  101. this.addTemplateResult(
  102. m.index+offset,
  103. m.index+m[0].length+offset,
  104. u.convertUrlToHyperlink(m[0].replace(regex, _converse.geouri_replacement))
  105. );
  106. }
  107. }
  108. /**
  109. * Look for emojis (shortnames or unicode) and add templates for rendering them.
  110. * @param { String } text
  111. * @param { Integer } offset - The index of the passed in text relative to
  112. * the start of the message body text.
  113. */
  114. addEmojis (text, offset) {
  115. const references = [...getShortnameReferences(text.toString()), ...getCodePointReferences(text.toString())];
  116. references.forEach(e => {
  117. this.addTemplateResult(
  118. e.begin+offset,
  119. e.end+offset,
  120. getEmojiMarkup(e, {'add_title_wrapper': true})
  121. );
  122. });
  123. }
  124. /**
  125. * Look for mentions included as XEP-0372 references and add templates for
  126. * rendering them.
  127. * @param { String } text
  128. * @param { Integer } local_offset - The index of the passed in text relative to
  129. * the start of this RichText instance (which is not necessarily the same as the
  130. * offset from the start of the original message stanza's body text).
  131. */
  132. addMentions (text, local_offset) {
  133. const full_offset = local_offset+this.offset;
  134. this.mentions?.forEach(ref => {
  135. const begin = Number(ref.begin)-full_offset;
  136. if (begin < 0 || begin >= full_offset+text.length) {
  137. return;
  138. }
  139. const end = Number(ref.end)-full_offset;
  140. const mention = text.slice(begin, end);
  141. if (mention === this.nick) {
  142. this.addTemplateResult(
  143. begin+local_offset,
  144. end+local_offset,
  145. tpl_mention_with_nick({mention})
  146. );
  147. } else {
  148. this.addTemplateResult(
  149. begin+local_offset,
  150. end+local_offset,
  151. tpl_mention({mention})
  152. );
  153. }
  154. });
  155. }
  156. /**
  157. * Look for XEP-0393 styling directives and add templates for rendering
  158. * them.
  159. */
  160. addStyling () {
  161. let i = 0;
  162. const references = [];
  163. if (containsDirectives(this)) {
  164. while (i < this.length) {
  165. const { d, length } = getDirectiveAndLength(this, i);
  166. if (d && length) {
  167. const is_quote = isQuoteDirective(d);
  168. const end = i+length;
  169. const slice_end = is_quote ? end : end-d.length;
  170. let slice_begin = d === '```' ? i+d.length+1 : i+d.length;
  171. if (is_quote && this[slice_begin] === ' ') {
  172. // Trim leading space inside codeblock
  173. slice_begin += 1;
  174. }
  175. const offset = slice_begin;
  176. const text = this.slice(slice_begin, slice_end);
  177. references.push({
  178. 'begin': i,
  179. 'template': getDirectiveTemplate(d, text, offset, this.mentions, this.options),
  180. end,
  181. });
  182. i = end;
  183. }
  184. i++;
  185. }
  186. }
  187. references.forEach(ref => this.addTemplateResult(ref.begin, ref.end, ref.template));
  188. }
  189. trimMeMessage () {
  190. if (this.offset === 0) {
  191. // Subtract `/me ` from 3rd person messages
  192. if (this.isMeCommand()) {
  193. this.payload[0] = this.payload[0].substring(4);
  194. }
  195. }
  196. }
  197. /**
  198. * Look for plaintext (i.e. non-templated) sections of this RichText
  199. * instance and add references via the passed in function.
  200. * @param { Function } func
  201. */
  202. addAnnotations (func) {
  203. const payload = this.marshall();
  204. let idx = 0; // The text index of the element in the payload
  205. for (const text of payload) {
  206. if (!text) {
  207. continue
  208. } else if (isString(text)) {
  209. func.call(this, text, idx);
  210. idx += text.length;
  211. } else {
  212. idx = text.end;
  213. }
  214. }
  215. }
  216. /**
  217. * Parse the text and add template references for rendering the "rich" parts.
  218. *
  219. * @param { RichText } text
  220. * @param { Boolean } show_images - Should URLs of images be rendered as `<img>` tags?
  221. * @param { Function } onImgLoad
  222. * @param { Function } onImgClick
  223. **/
  224. async addTemplates() {
  225. /**
  226. * Synchronous event which provides a hook for transforming a chat message's body text
  227. * before the default transformations have been applied.
  228. * @event _converse#beforeMessageBodyTransformed
  229. * @param { RichText } text - A {@link RichText } instance. You
  230. * can call {@link RichText#addTemplateResult } on it in order to
  231. * add TemplateResult objects meant to render rich parts of the message.
  232. * @example _converse.api.listen.on('beforeMessageBodyTransformed', (view, text) => { ... });
  233. */
  234. await api.trigger('beforeMessageBodyTransformed', this, {'Synchronous': true});
  235. this.render_styling && this.addStyling();
  236. this.addAnnotations(this.addMentions);
  237. this.addAnnotations(this.addHyperlinks);
  238. this.addAnnotations(this.addMapURLs);
  239. await api.emojis.initialize();
  240. this.addAnnotations(this.addEmojis);
  241. /**
  242. * Synchronous event which provides a hook for transforming a chat message's body text
  243. * after the default transformations have been applied.
  244. * @event _converse#afterMessageBodyTransformed
  245. * @param { RichText } text - A {@link RichText } instance. You
  246. * can call {@link RichText#addTemplateResult} on it in order to
  247. * add TemplateResult objects meant to render rich parts of the message.
  248. * @example _converse.api.listen.on('afterMessageBodyTransformed', (view, text) => { ... });
  249. */
  250. await api.trigger('afterMessageBodyTransformed', this, {'Synchronous': true});
  251. this.payload = this.marshall();
  252. this.options.show_me_message && this.trimMeMessage();
  253. this.payload = this.payload.map(item => isString(item) ? item : item.template);
  254. }
  255. /**
  256. * The "rich" markup parts of a chat message are represented by lit-html
  257. * TemplateResult objects.
  258. *
  259. * This method can be used to add new template results to this message's
  260. * text.
  261. *
  262. * @method RichText.addTemplateResult
  263. * @param { Number } begin - The starting index of the plain message text
  264. * which is being replaced with markup.
  265. * @param { Number } end - The ending index of the plain message text
  266. * which is being replaced with markup.
  267. * @param { Object } template - The lit-html TemplateResult instance
  268. */
  269. addTemplateResult (begin, end, template) {
  270. this.references.push({begin, end, template});
  271. }
  272. isMeCommand () {
  273. const text = this.toString();
  274. if (!text) {
  275. return false;
  276. }
  277. return text.startsWith('/me ');
  278. }
  279. /**
  280. * Take the annotations and return an array of text and TemplateResult
  281. * instances to be rendered to the DOM.
  282. * @method RichText#marshall
  283. */
  284. marshall () {
  285. let list = [this.toString()];
  286. this.references
  287. .sort((a, b) => b.begin - a.begin)
  288. .forEach(ref => {
  289. const text = list.shift();
  290. list = [
  291. text.slice(0, ref.begin),
  292. ref,
  293. text.slice(ref.end),
  294. ...list
  295. ];
  296. });
  297. return list.reduce((acc, i) => isString(i) ? [...acc, convertASCII2Emoji(collapseLineBreaks(i))] : [...acc, i], []);
  298. }
  299. }