rich-text.js 14 KB

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