rich-text.js 16 KB

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