소스 검색

Rename RichText to Texture

JC Brand 6 달 전
부모
커밋
30e6d844f3

+ 3 - 3
src/plugins/muc-views/modals/templates/muc-details.js

@@ -11,7 +11,7 @@ const subject = (model) => {
     const i18n_topic = __('Topic');
     const i18n_topic_author = __('Topic author');
     return html`
-        <p class="room-info"><strong>${i18n_topic}</strong>: <converse-rich-text text=${subject.text} render_styling></converse-rich-text></p>
+        <p class="room-info"><strong>${i18n_topic}</strong>: <converse-texture text=${subject.text} render_styling></converse-texture></p>
         <p class="room-info"><strong>${i18n_topic_author}</strong>: ${subject && subject.author}</p>
     `;
 }
@@ -66,9 +66,9 @@ export default (model) => {
                 height="72" width="72"></converse-avatar>
 
             <p class="room-info"><strong>${i18n_name}</strong>: ${model.get('name')}</p>
-            <p class="room-info"><strong>${i18n_address}</strong>: <converse-rich-text text="xmpp:${model.get('jid')}?join"></converse-rich-text></p>
+            <p class="room-info"><strong>${i18n_address}</strong>: <converse-texture text="xmpp:${model.get('jid')}?join"></converse-texture></p>
             <br/>
-            <p class="room-info"><strong>${i18n_desc}</strong>: <converse-rich-text text="${config.description}" render_styling></converse-rich-text></p>
+            <p class="room-info"><strong>${i18n_desc}</strong>: <converse-texture text="${config.description}" render_styling></converse-texture></p>
             ${ (model.get('subject')) ? subject(model) : '' }
             <p class="room-info"><strong>${i18n_online_users}</strong>: ${num_occupants}</p>
             <p class="room-info"><strong>${i18n_features}</strong>:

+ 3 - 3
src/plugins/muc-views/templates/mep-message.js

@@ -15,13 +15,13 @@ export default (el) => {
                 <div class="chat-msg__body chat-msg__body--${el.model.get('type')} ${el.model.get('is_delayed') ? 'chat-msg__body--delayed' : '' }">
                     <div class="chat-info__message">
                         ${ el.isRetracted() ? el.renderRetraction() : html`
-                            <converse-rich-text
+                            <converse-texture
                                 .mentions=${el.model.get('references')}
                                 render_styling
                                 text=${el.model.getMessageText()}>
-                            </converse-rich-text>
+                            </converse-texture>
                             ${ el.model.get('reason') ?
-                                html`<q class="reason"><converse-rich-text text=${el.model.get('reason')}></converse-rich-text></q>` : `` }
+                                html`<q class="reason"><converse-texture text=${el.model.get('reason')}></converse-texture></q>` : `` }
                         `}
                     </div>
                     <converse-message-actions

+ 5 - 5
src/plugins/muc-views/templates/muc-head.js

@@ -1,10 +1,10 @@
-import 'shared/components/dropdown.js';
-import 'shared/components/rich-text.js';
+import { html } from "lit";
+import { until } from 'lit/directives/until.js';
 import { __ } from 'i18n';
 import { _converse, api } from "@converse/headless";
 import { getStandaloneButtons, getDropdownButtons } from 'shared/chat/utils.js';
-import { html } from "lit";
-import { until } from 'lit/directives/until.js';
+import 'shared/components/dropdown.js';
+import 'shared/texture/component.js';
 
 /** @param {import('../heading').default} el} */
 export default (el) => {
@@ -52,7 +52,7 @@ export default (el) => {
             </div>
         </div>
         ${ show_subject ? html`<p class="chat-head__desc" title="${i18n_hide_topic}">
-            <converse-rich-text text=${subject} render_styling></converse-rich-text>
+            <converse-texture text=${subject} render_styling></converse-texture>
           </p>` : '' }
     `;
 }

+ 6 - 6
src/plugins/muc-views/tests/mep.js

@@ -37,7 +37,7 @@ describe("A XEP-0316 MEP notification", function () {
 
         _converse.api.connection.get()._dataRecv(mock.createRequest(message));
         await u.waitUntil(() => view.querySelectorAll('.chat-info').length === 1);
-        expect(view.querySelector('.chat-info__message converse-rich-text').textContent.trim()).toBe(msg);
+        expect(view.querySelector('.chat-info__message converse-texture').textContent.trim()).toBe(msg);
         expect(view.querySelector('.reason').textContent.trim()).toBe(reason);
 
         // Check that duplicates aren't created
@@ -76,7 +76,7 @@ describe("A XEP-0316 MEP notification", function () {
 
         _converse.api.connection.get()._dataRecv(mock.createRequest(message));
         await u.waitUntil(() => view.querySelectorAll('.chat-info').length === 2);
-        expect(view.querySelector('converse-chat-message:last-child .chat-info__message converse-rich-text').textContent.trim()).toBe(msg);
+        expect(view.querySelector('converse-chat-message:last-child .chat-info__message converse-texture').textContent.trim()).toBe(msg);
         expect(view.querySelector('converse-chat-message:last-child .reason').textContent.trim()).toBe(reason);
 
         // Check that duplicates aren't created
@@ -129,7 +129,7 @@ describe("A XEP-0316 MEP notification", function () {
 
         const view = await u.waitUntil(() => _converse.chatboxviews.get(muc_jid));
         await u.waitUntil(() => view.querySelectorAll('.chat-info').length === 1, 1000);
-        expect(view.querySelector('.chat-info__message converse-rich-text').textContent.trim()).toBe(msg);
+        expect(view.querySelector('.chat-info__message converse-texture').textContent.trim()).toBe(msg);
         expect(view.querySelector('.reason').textContent.trim()).toBe(reason);
     }));
 
@@ -165,8 +165,8 @@ describe("A XEP-0316 MEP notification", function () {
 
         const view = await u.waitUntil(() => _converse.chatboxviews.get(muc_jid));
         await u.waitUntil(() => view.querySelectorAll('.chat-info').length === 1, 1000);
-        expect(view.querySelector('.chat-info__message converse-rich-text').textContent.trim()).toBe(msg);
-        expect(view.querySelector('.reason converse-rich-text').innerHTML.replace(/<!-.*?->/g, '').trim()).toBe(
+        expect(view.querySelector('.chat-info__message converse-texture').textContent.trim()).toBe(msg);
+        expect(view.querySelector('.reason converse-texture').innerHTML.replace(/<!-.*?->/g, '').trim()).toBe(
             'Check out <a target="_blank" rel="noopener" href="https://conversejs.org/">https://conversejs.org</a>');
     }));
 
@@ -205,7 +205,7 @@ describe("A XEP-0316 MEP notification", function () {
         ));
 
         await u.waitUntil(() => view.querySelectorAll('.chat-info').length === 1);
-        expect(view.querySelector('.chat-info__message converse-rich-text').textContent.trim()).toBe(msg);
+        expect(view.querySelector('.chat-info__message converse-texture').textContent.trim()).toBe(msg);
         expect(view.querySelector('.reason').textContent.trim()).toBe(reason);
         expect(view.querySelectorAll('converse-message-actions converse-dropdown .chat-msg__action').length).toBeGreaterThanOrEqual(1);
         const action = view.querySelector('converse-message-actions converse-dropdown .chat-msg__action');

+ 5 - 5
src/plugins/muc-views/tests/muc-avatar.js

@@ -119,11 +119,11 @@ describe('Groupchats', () => {
                     expect(els[0].textContent).toBe('Name: A Dark Cave');
 
                     expect(els[1].querySelector('strong').textContent).toBe('XMPP address');
-                    expect(els[1].querySelector('converse-rich-text').textContent.trim()).toBe(
+                    expect(els[1].querySelector('converse-texture').textContent.trim()).toBe(
                         'xmpp:coven@chat.shakespeare.lit?join'
                     );
                     expect(els[2].querySelector('strong').textContent).toBe('Description');
-                    expect(els[2].querySelector('converse-rich-text').textContent).toBe('This is the description');
+                    expect(els[2].querySelector('converse-texture').textContent).toBe('This is the description');
 
                     expect(els[3].textContent).toBe('Online users: 1');
                     const features_list = modal.querySelector('.features-list');
@@ -154,14 +154,14 @@ describe('Groupchats', () => {
                     expect(els[0].textContent).toBe('Name: A Dark Cave');
 
                     expect(els[1].querySelector('strong').textContent).toBe('XMPP address');
-                    expect(els[1].querySelector('converse-rich-text').textContent.trim()).toBe(
+                    expect(els[1].querySelector('converse-texture').textContent.trim()).toBe(
                         'xmpp:coven@chat.shakespeare.lit?join'
                     );
                     expect(els[2].querySelector('strong').textContent).toBe('Description');
-                    expect(els[2].querySelector('converse-rich-text').textContent).toBe('This is the description');
+                    expect(els[2].querySelector('converse-texture').textContent).toBe('This is the description');
                     expect(els[3].querySelector('strong').textContent).toBe('Topic');
                     await u.waitUntil(
-                        () => els[3].querySelector('converse-rich-text').textContent === 'Hatching dark plots'
+                        () => els[3].querySelector('converse-texture').textContent === 'Hatching dark plots'
                     );
 
                     expect(els[4].textContent).toBe('Topic author: someone');

+ 3 - 3
src/shared/chat/message-body.js

@@ -1,8 +1,8 @@
+import { api } from "@converse/headless";
 import 'shared/registry.js';
 import 'shared/modals/image.js';
-import renderRichText from 'shared/directives/rich-text.js';
 import { CustomElement } from 'shared/components/element.js';
-import { api } from "@converse/headless";
+import renderTexture from 'shared/texture/directive.js';
 
 import './styles/message-body.scss';
 
@@ -65,7 +65,7 @@ export default class MessageBody extends CustomElement {
             options.embed_videos = false;
             options.show_images = false;
         }
-        return renderRichText(this.text, offset, options, callback);
+        return renderTexture(this.text, offset, options, callback);
     }
 }
 

+ 2 - 2
src/shared/chat/templates/info-message.js

@@ -14,11 +14,11 @@ export default (el) => {
             data-value="${el.data_value}">
 
             <div class="chat-info__message">
-                <converse-rich-text
+                <converse-texture
                     .mentions=${el.model.get('references')}
                     render_styling
                     text=${el.model.getMessageText()}>
-                </converse-rich-text>
+                </converse-texture>
             </div>
             ${ el.model.get('reason') ? html`<q class="reason">${el.model.get('reason')}</q>` : `` }
             ${ el.model.get('error_text') ? html`<q class="reason">${el.model.get('error_text')}</q>` : `` }

+ 1 - 1
src/shared/chat/templates/unfurl.js

@@ -36,7 +36,7 @@ export default o => {
                       ${o.title ? tplUrlWrapper(o, o => html`<h5 class="card-title">${o.title}</h5>`) : ''}
                       ${o.description
                           ? html`<p class="card-text">
-                                <converse-rich-text text=${o.description}></converse-rich-text>
+                                <converse-texture text=${o.description}></converse-texture>
                             </p>`
                           : ''}
                       ${o.url

+ 0 - 87
src/shared/components/rich-text.js

@@ -1,87 +0,0 @@
-import renderRichText from 'shared/directives/rich-text.js';
-import { CustomElement } from 'shared/components/element.js';
-import { api } from "@converse/headless";
-
-import './styles/rich-text.scss';
-
-/**
- * The RichText custom element allows you to parse transform text into rich DOM elements.
- * @example <converse-rich-text text="*_hello_ world!*"></converse-rich-text>
- */
-export default class RichText extends CustomElement {
-
-    static get properties () {
-        /**
-         * @typedef { Object } RichTextComponentProperties
-         * @property { Boolean } embed_audio
-         *  Whether URLs that point to audio files should render as audio players.
-         * @property { Boolean } embed_videos
-         *  Whether URLs that point to video files should render as video players.
-         * @property { Array } mentions - An array of objects representing chat mentions
-         * @property { String } nick - The current user's nickname, relevant for mentions
-         * @property { Number } offset - The text offset, in case this is a nested RichText element.
-         * @property { Function } onImgClick
-         * @property { Function } onImgLoad
-         * @property { Boolean } render_styling
-         *  Whether XEP-0393 message styling hints should be rendered
-         * @property { Boolean } show_images
-         *  Whether URLs that point to image files should render as images
-         * @property { Boolean } hide_media_urls
-         *  If media URLs are rendered as media, then this option determines
-         *  whether the original URL is also still shown or not.
-         *  Only relevant in conjunction with `show_images`, `embed_audio` and `embed_videos`.
-         * @property { Boolean } show_me_message
-         *  Whether text that starts with /me should be rendered in the 3rd person.
-         * @property { String } text - The text that will get transformed.
-         */
-        return {
-            embed_audio: { type: Boolean },
-            embed_videos: { type: Boolean },
-            mentions: { type: Array },
-            nick: { type: String },
-            offset: { type: Number },
-            onImgClick: { type: Function },
-            onImgLoad: { type: Function },
-            render_styling: { type: Boolean },
-            show_images: { type: Boolean },
-            hide_media_urls: { type: Boolean },
-            show_me_message: { type: Boolean },
-            text: { type: String },
-        }
-    }
-
-    constructor () {
-        super();
-        this.nick = null;
-        this.onImgClick = null;
-        this.onImgLoad = null;
-        this.text = null;
-        this.embed_audio = false;
-        this.embed_videos = false;
-        this.hide_media_urls = false;
-        this.mentions = [];
-        this.offset = 0;
-        this.render_styling = false;
-        this.show_image_urls = true;
-        this.show_images = false;
-        this.show_me_message = false;
-    }
-
-    render () {
-        const options = {
-            embed_audio: this.embed_audio,
-            embed_videos: this.embed_videos,
-            hide_media_urls: this.hide_media_urls,
-            mentions: this.mentions,
-            nick: this.nick,
-            onImgClick: this.onImgClick,
-            onImgLoad: this.onImgLoad,
-            render_styling: this.render_styling,
-            show_images: this.show_images,
-            show_me_message: this.show_me_message,
-        }
-        return renderRichText(this.text, this.offset, options);
-    }
-}
-
-api.elements.define('converse-rich-text', RichText);

+ 0 - 43
src/shared/directives/rich-text.js

@@ -1,43 +0,0 @@
-import { log } from '@converse/headless';
-import { Directive, directive } from 'lit/directive.js';
-import { RichText } from 'shared/rich-text.js';
-import { html } from "lit";
-import { until } from 'lit/directives/until.js';
-
-
-class RichTextRenderer {
-
-    constructor (text, offset, options={}) {
-        this.offset = offset;
-        this.options = options;
-        this.text = text;
-    }
-
-    async transform () {
-        const text = new RichText(this.text, this.offset, this.options);
-        try {
-            await text.addTemplates();
-        } catch (e) {
-            log.error(e);
-        }
-        return text.payload;
-    }
-
-    render () {
-        return html`${until(this.transform(), html`${this.text}`)}`;
-    }
-}
-
-
-class RichTextDirective extends Directive {
-    render (text, offset, options, callback) { // eslint-disable-line class-methods-use-this
-        const renderer = new RichTextRenderer(text, offset, options);
-        const result = renderer.render();
-        callback?.();
-        return result;
-    }
-}
-
-
-const renderRichText = directive(RichTextDirective);
-export default renderRichText;

+ 0 - 27
src/shared/directives/styling.js

@@ -1,27 +0,0 @@
-import { log } from '@converse/headless';
-import { Directive, directive } from 'lit/directive.js';
-import { RichText } from '../rich-text.js';
-import { html } from 'lit';
-import { until } from 'lit/directives/until.js';
-
-async function transform (t) {
-    try {
-        await t.addTemplates();
-    } catch (e) {
-        log.error(e);
-    }
-    return t.payload;
-}
-
-class StylingDirective extends Directive {
-    render (txt, offset, options) {
-        const t = new RichText(
-            txt,
-            offset,
-            Object.assign(options, { 'show_images': false, 'embed_videos': false, 'embed_audio': false })
-        );
-        return html`${until(transform(t), html`${t}`)}`;
-    }
-}
-
-export const renderStylingDirectiveBody = directive(StylingDirective);

+ 3 - 0
src/shared/texture/README.md

@@ -0,0 +1,3 @@
+# Texture
+
+Converse's library for showing rich, multi-media messages based on text

+ 70 - 0
src/shared/texture/component.js

@@ -0,0 +1,70 @@
+import { LitElement } from 'lit';
+import renderTexture from './directive.js';
+
+import './texture.scss';
+
+/**
+ * The Texture custom element allows you to parse transform text into rich DOM elements.
+ * @example <converse-texture text="*_hello_ world!*"></converse-texture>
+ */
+export default class Texture extends LitElement {
+    static get properties() {
+        return {
+            embed_audio: { type: Boolean }, // Whether URLs to audio files should render as audio players.
+            embed_videos: { type: Boolean }, //  Whether URLs to video files should render as video players.
+            mentions: { type: Array }, // An array of objects representing chat mentions
+            nick: { type: String }, // The current user's nickname, relevant for mentions
+            offset: { type: Number }, // The text offset, in case this is a nested Texture element.
+            onImgClick: { type: Function },
+            onImgLoad: { type: Function },
+            render_styling: { type: Boolean }, //  Whether XEP-0393 message styling hints should be rendered
+            show_images: { type: Boolean }, //  Whether URLs to image files should render as images
+            // If media URLs are rendered as media, then this option determines
+            // whether the original URL is also still shown or not.
+            // Only relevant in conjunction with `show_images`, `embed_audio` and `embed_videos`.
+            hide_media_urls: { type: Boolean },
+            show_me_message: { type: Boolean }, // Whether text that starts with /me is rendered in the 3rd person.
+            text: { type: String }, // The text that will get transformed.
+        };
+    }
+
+    createRenderRoot () {
+        // Render without the shadow DOM
+        return this;
+    }
+
+    constructor() {
+        super();
+        this.nick = null;
+        this.onImgClick = null;
+        this.onImgLoad = null;
+        this.text = null;
+        this.embed_audio = false;
+        this.embed_videos = false;
+        this.hide_media_urls = false;
+        this.mentions = [];
+        this.offset = 0;
+        this.render_styling = false;
+        this.show_image_urls = true;
+        this.show_images = false;
+        this.show_me_message = false;
+    }
+
+    render() {
+        const options = {
+            embed_audio: this.embed_audio,
+            embed_videos: this.embed_videos,
+            hide_media_urls: this.hide_media_urls,
+            mentions: this.mentions,
+            nick: this.nick,
+            onImgClick: this.onImgClick,
+            onImgLoad: this.onImgLoad,
+            render_styling: this.render_styling,
+            show_images: this.show_images,
+            show_me_message: this.show_me_message,
+        };
+        return renderTexture(this.text, this.offset, options);
+    }
+}
+
+customElements.define('converse-texture', Texture);

+ 11 - 0
src/shared/texture/constants.js

@@ -0,0 +1,11 @@
+export const bracketing_directives = ['*', '_', '~', '`'];
+export const styling_directives = [...bracketing_directives, '```', '>'];
+export const styling_map = {
+    '*': { 'name': 'strong', 'type': 'span' },
+    '_': { 'name': 'emphasis', 'type': 'span' },
+    '~': { 'name': 'strike', 'type': 'span' },
+    '`': { 'name': 'preformatted', 'type': 'span' },
+    '```': { 'name': 'preformatted_block', 'type': 'block' },
+    '>': { 'name': 'quote', 'type': 'block' },
+};
+export const dont_escape = ['_', '>', '`', '~'];

+ 48 - 0
src/shared/texture/directive.js

@@ -0,0 +1,48 @@
+import { html } from 'lit';
+import { until } from 'lit/directives/until.js';
+import { Directive, directive } from 'lit/directive.js';
+import { Texture } from './texture.js';
+
+class TextureRenderer {
+    /**
+     * @param {string} text
+     * @param {number} offset
+     */
+    constructor(text, offset, options = {}) {
+        this.offset = offset;
+        this.options = options;
+        this.text = text;
+    }
+
+    async transform() {
+        const text = new Texture(this.text, this.offset, this.options);
+        try {
+            await text.addTemplates();
+        } catch (e) {
+            console.error(e);
+        }
+        return text.payload;
+    }
+
+    render() {
+        return html`${until(this.transform(), html`${this.text}`)}`;
+    }
+}
+
+class TextureDirective extends Directive {
+    /**
+     * @param {string} text
+     * @param {number} offset
+     * @param {object} options
+     * @param {Function} [callback]
+     */
+    render(text, offset, options, callback) {
+        const renderer = new TextureRenderer(text, offset, options);
+        const result = renderer.render();
+        callback?.();
+        return result;
+    }
+}
+
+const renderTexture = directive(TextureDirective);
+export default renderTexture;

+ 135 - 248
src/shared/rich-text.js → src/shared/texture/texture.js

@@ -1,18 +1,24 @@
-/**
- * @typedef {module:headless-shared-parsers.MediaURLMetadata} MediaURLMetadata
- * @typedef {module:headless-shared-parsers.MediaURLMetadata} MediaURLData
- */
 import { html } from 'lit';
 import { until } from 'lit/directives/until.js';
 import { Directive, directive } from 'lit/directive.js';
-import { api, log, u } from '@converse/headless';
+import { api, u } from '@converse/headless';
 import tplAudio from 'templates/audio.js';
 import tplGif from 'templates/gif.js';
 import tplImage from 'templates/image.js';
 import tplVideo from 'templates/video.js';
-import { getEmojiMarkup } from './chat/utils.js';
-import { getHyperlinkTemplate } from '../utils/html.js';
+import { getEmojiMarkup } from '../chat/utils.js';
+import { getHyperlinkTemplate } from '../../utils/html.js';
 import { shouldRenderMediaFromURL } from 'utils/url.js';
+import {
+    collapseLineBreaks,
+    containsDirectives,
+    getDirectiveAndLength,
+    isQuoteDirective,
+    isString,
+    tplMention,
+    tplMentionWithNick,
+} from './utils.js';
+import { styling_map } from './constants.js';
 
 const {
     convertASCII2Emoji,
@@ -27,14 +33,13 @@ const {
     isVideoURL,
 } = u;
 
-
 /**
- * @class RichText
+ * @class Texture
  * A String subclass that is used to render rich text (i.e. text that contains
  * hyperlinks, images, mentions, styling etc.).
  *
  * The "rich" parts of the text is represented by lit TemplateResult
- * objects which are added via the {@link RichText.addTemplateResult}
+ * objects which are added via the {@link Texture.addTemplateResult}
  * method and saved as metadata.
  *
  * By default Converse adds TemplateResults to support emojis, hyperlinks,
@@ -42,17 +47,17 @@ const {
  *
  * 3rd party plugins can listen for the `beforeMessageBodyTransformed`
  * and/or `afterMessageBodyTransformed` events and then call
- * `addTemplateResult` on the RichText instance in order to add their own
+ * `addTemplateResult` on the Texture instance in order to add their own
  * rich features.
  */
-export class RichText extends String {
+export class Texture extends String {
     /**
-     * Create a new {@link RichText} instance.
+     * Create a new {@link Texture} instance.
      * @param {string} text - The text to be annotated
      * @param {number} offset - The offset of this particular piece of text
      *  from the start of the original message text. This is necessary because
-     *  RichText instances can be nested when templates call directives
-     *  which create new RichText instances (as happens with XEP-393 styling directives).
+     *  Texture instances can be nested when templates call directives
+     *  which create new Texture instances (as happens with XEP-393 styling directives).
      * @param {Object} [options]
      * @param {string} [options.nick] - The current user's nickname (only relevant if the message is in a XEP-0045 MUC)
      * @param {boolean} [options.render_styling] - Whether XEP-0393 message styling should be applied to the message
@@ -76,8 +81,10 @@ export class RichText extends String {
      * @param {Function} [options.onImgClick] - Callback for when an inline rendered image has been clicked
      * @param {Function} [options.onImgLoad] - Callback for when an inline rendered image has been loaded
      * @param {boolean} [options.hide_media_urls] - Callback for when an inline rendered image has been loaded
+     *
+     * @typedef {module:headless-shared-parsers.MediaURLMetadata} MediaURLMetadata
      */
-    constructor (text, offset = 0, options = {}) {
+    constructor(text, offset = 0, options = {}) {
         super(text);
         this.embed_audio = options?.embed_audio;
         this.embed_videos = options?.embed_videos;
@@ -95,7 +102,11 @@ export class RichText extends String {
         this.hide_media_urls = options?.hide_media_urls;
     }
 
-    shouldRenderMedia (url_text, type) {
+    /**
+     * @param {string} url - The URL to be checked
+     * @param {'audio'|'image'|'video'} type - The type of media
+     */
+    shouldRenderMedia(url, type) {
         let override;
         if (type === 'image') {
             override = this.show_images;
@@ -107,53 +118,57 @@ export class RichText extends String {
         if (typeof override === 'boolean') {
             return override;
         }
-        return shouldRenderMediaFromURL(url_text, type);
+        return shouldRenderMediaFromURL(url, type);
     }
 
     /**
      * Look for `http` URIs and return templates that render them as URL links
      * @param {string} text
      * @param {number} local_offset - The index of the passed in text relative to
-     *  the start of this RichText instance (which is not necessarily the same as the
+     *  the start of this Texture instance (which is not necessarily the same as the
      *  offset from the start of the original message stanza's body text).
+     *
+     * @typedef {module:headless-shared-parsers.MediaURLData} MediaURLData
      */
-    addHyperlinks (text, local_offset) {
+    addHyperlinks(text, local_offset) {
         const full_offset = local_offset + this.offset;
         const urls_meta = this.media_urls || getMediaURLsMetadata(text, local_offset).media_urls || [];
-        const media_urls = /** @type {MediaURLData[]} */(getMediaURLs(urls_meta, text, full_offset));
-
-        media_urls.filter(o => !o.is_encrypted).forEach(url_obj => {
-            const url_text = url_obj.url;
-            const filtered_url = filterQueryParamsFromURL(url_text);
-            let template;
-            if (isGIFURL(url_text) && this.shouldRenderMedia(url_text, 'image')) {
-                template = tplGif(filtered_url, this.hide_media_urls);
-            } else if (isImageURL(url_text) && this.shouldRenderMedia(url_text, 'image')) {
-                template = tplImage({
-                    'src': filtered_url,
-                    // XXX: bit of an abuse of `hide_media_urls`, might want a dedicated option here
-                    'href': this.hide_media_urls ? null : filtered_url,
-                    'onClick': this.onImgClick,
-                    'onLoad': this.onImgLoad
-                });
-            } else if (isVideoURL(url_text) && this.shouldRenderMedia(url_text, 'video')) {
-                template = tplVideo(filtered_url, this.hide_media_urls);
-            } else if (isAudioURL(url_text) && this.shouldRenderMedia(url_text, 'audio')) {
-                template = tplAudio(filtered_url, this.hide_media_urls);
-            } else {
-                template = getHyperlinkTemplate(filtered_url);
-            }
-            this.addTemplateResult(url_obj.start + local_offset, url_obj.end + local_offset, template);
-        });
+        const media_urls = /** @type {MediaURLData[]} */ (getMediaURLs(urls_meta, text, full_offset));
+
+        media_urls
+            .filter((o) => !o.is_encrypted)
+            .forEach((url_obj) => {
+                const url_text = url_obj.url;
+                const filtered_url = filterQueryParamsFromURL(url_text);
+                let template;
+                if (isGIFURL(url_text) && this.shouldRenderMedia(url_text, 'image')) {
+                    template = tplGif(filtered_url, this.hide_media_urls);
+                } else if (isImageURL(url_text) && this.shouldRenderMedia(url_text, 'image')) {
+                    template = tplImage({
+                        'src': filtered_url,
+                        // XXX: bit of an abuse of `hide_media_urls`, might want a dedicated option here
+                        'href': this.hide_media_urls ? null : filtered_url,
+                        'onClick': this.onImgClick,
+                        'onLoad': this.onImgLoad,
+                    });
+                } else if (isVideoURL(url_text) && this.shouldRenderMedia(url_text, 'video')) {
+                    template = tplVideo(filtered_url, this.hide_media_urls);
+                } else if (isAudioURL(url_text) && this.shouldRenderMedia(url_text, 'audio')) {
+                    template = tplAudio(filtered_url, this.hide_media_urls);
+                } else {
+                    template = getHyperlinkTemplate(filtered_url);
+                }
+                this.addTemplateResult(url_obj.start + local_offset, url_obj.end + local_offset, template);
+            });
     }
 
     /**
      * Look for `geo` URIs and return templates that render them as URL links
-     * @param { String } text
-     * @param { number } offset - The index of the passed in text relative to
+     * @param {String} text
+     * @param {number} offset - The index of the passed in text relative to
      *  the start of the message body text.
      */
-    addMapURLs (text, offset) {
+    addMapURLs(text, offset) {
         const regex = /geo:([\-0-9.]+),([\-0-9.]+)(?:,([\-0-9.]+))?(?:\?(.*))?/g;
         const matches = text.matchAll(regex);
         for (const m of matches) {
@@ -171,28 +186,24 @@ export class RichText extends String {
      * @param {number} offset - The index of the passed in text relative to
      *  the start of the message body text.
      */
-    addEmojis (text, offset) {
+    addEmojis(text, offset) {
         const references = [...getShortnameReferences(text.toString()), ...getCodePointReferences(text.toString())];
-        references.forEach(e => {
-            this.addTemplateResult(
-                e.begin + offset,
-                e.end + offset,
-                getEmojiMarkup(e, { add_title_wrapper: true })
-            );
+        references.forEach((e) => {
+            this.addTemplateResult(e.begin + offset, e.end + offset, getEmojiMarkup(e, { add_title_wrapper: true }));
         });
     }
 
     /**
      * Look for mentions included as XEP-0372 references and add templates for
      * rendering them.
-     * @param { String } text
-     * @param { number } local_offset - The index of the passed in text relative to
-     *  the start of this RichText instance (which is not necessarily the same as the
+     * @param {String} text
+     * @param {number} local_offset - The index of the passed in text relative to
+     *  the start of this Texture instance (which is not necessarily the same as the
      *  offset from the start of the original message stanza's body text).
      */
-    addMentions (text, local_offset) {
+    addMentions(text, local_offset) {
         const full_offset = local_offset + this.offset;
-        this.mentions?.forEach(ref => {
+        this.mentions?.forEach((ref) => {
             const begin = Number(ref.begin) - full_offset;
             if (begin < 0 || begin >= full_offset + text.length) {
                 return;
@@ -203,10 +214,10 @@ export class RichText extends String {
                 this.addTemplateResult(
                     begin + local_offset,
                     end + local_offset,
-                    tplMentionWithNick({...ref, mention })
+                    tplMentionWithNick({ ...ref, mention })
                 );
             } else {
-                this.addTemplateResult(begin + local_offset, end + local_offset, tplMention({...ref, mention }));
+                this.addTemplateResult(begin + local_offset, end + local_offset, tplMention({ ...ref, mention }));
             }
         });
     }
@@ -214,18 +225,19 @@ export class RichText extends String {
     /**
      * Look for XEP-0393 styling directives and add templates for rendering them.
      */
-    addStyling () {
+    addStyling() {
         if (!containsDirectives(this)) {
             return;
         }
 
         const references = [];
-        const mention_ranges = this.mentions.map(m =>
+        const mention_ranges = this.mentions.map((m) =>
             Array.from({ 'length': Number(m.end) }, (_, i) => Number(m.begin) + i)
         );
         let i = 0;
         while (i < this.length) {
-            if (mention_ranges.filter(r => r.includes(i)).length) { // eslint-disable-line no-loop-func
+            if (mention_ranges.filter((r) => r.includes(i)).length) {
+                // eslint-disable-line no-loop-func
                 // Don't treat potential directives if they fall within a
                 // declared XEP-0372 reference
                 i++;
@@ -244,18 +256,18 @@ export class RichText extends String {
                 const offset = slice_begin;
                 const text = this.slice(slice_begin, slice_end);
                 references.push({
-                    'begin': i,
-                    'template': getDirectiveTemplate(d, text, offset, this.options),
-                    end
+                    begin: i,
+                    template: getDirectiveTemplate(d, text, offset, this.options),
+                    end,
                 });
                 i = end;
             }
             i++;
         }
-        references.forEach(ref => this.addTemplateResult(ref.begin, ref.end, ref.template));
+        references.forEach((ref) => this.addTemplateResult(ref.begin, ref.end, ref.template));
     }
 
-    trimMeMessage () {
+    trimMeMessage() {
         if (this.offset === 0) {
             // Subtract `/me ` from 3rd person messages
             if (this.isMeCommand()) {
@@ -265,11 +277,11 @@ export class RichText extends String {
     }
 
     /**
-     * Look for plaintext (i.e. non-templated) sections of this RichText
+     * Look for plaintext (i.e. non-templated) sections of this Texture
      * instance and add references via the passed in function.
      * @param { Function } func
      */
-    addAnnotations (func) {
+    addAnnotations(func) {
         const payload = this.marshall();
         let idx = 0; // The text index of the element in the payload
         for (const text of payload) {
@@ -287,13 +299,13 @@ export class RichText extends String {
     /**
      * Parse the text and add template references for rendering the "rich" parts.
      **/
-    async addTemplates () {
+    async addTemplates() {
         /**
          * Synchronous event which provides a hook for transforming a chat message's body text
          * before the default transformations have been applied.
          * @event _converse#beforeMessageBodyTransformed
-         * @param { RichText } text - A {@link RichText } instance. You
-         *  can call {@link RichText#addTemplateResult } on it in order to
+         * @param { Texture } text - A {@link Texture } instance. You
+         *  can call {@link Texture#addTemplateResult } on it in order to
          *  add TemplateResult objects meant to render rich parts of the message.
          * @example _converse.api.listen.on('beforeMessageBodyTransformed', (view, text) => { ... });
          */
@@ -311,8 +323,8 @@ export class RichText extends String {
          * Synchronous event which provides a hook for transforming a chat message's body text
          * after the default transformations have been applied.
          * @event _converse#afterMessageBodyTransformed
-         * @param { RichText } text - A {@link RichText } instance. You
-         *  can call {@link RichText#addTemplateResult} on it in order to
+         * @param { Texture } text - A {@link Texture } instance. You
+         *  can call {@link Texture#addTemplateResult} on it in order to
          *  add TemplateResult objects meant to render rich parts of the message.
          * @example _converse.api.listen.on('afterMessageBodyTransformed', (view, text) => { ... });
          */
@@ -320,7 +332,7 @@ export class RichText extends String {
 
         this.payload = this.marshall();
         this.options.show_me_message && this.trimMeMessage();
-        this.payload = this.payload.map(item => (isString(item) ? item : item.template));
+        this.payload = this.payload.map((item) => (isString(item) ? item : item.template));
     }
 
     /**
@@ -330,18 +342,18 @@ export class RichText extends String {
      * This method can be used to add new template results to this message's
      * text.
      *
-     * @method RichText.addTemplateResult
-     * @param { Number } begin - The starting index of the plain message text
+     * @method Texture.addTemplateResult
+     * @param {Number} begin - The starting index of the plain message text
      * which is being replaced with markup.
-     * @param { Number } end - The ending index of the plain message text
+     * @param {Number} end - The ending index of the plain message text
      * which is being replaced with markup.
-     * @param { Object } template - The lit TemplateResult instance
+     * @param {Object} template - The lit TemplateResult instance
      */
-    addTemplateResult (begin, end, template) {
+    addTemplateResult(begin, end, template) {
         this.references.push({ begin, end, template });
     }
 
-    isMeCommand () {
+    isMeCommand() {
         const text = this.toString();
         if (!text) {
             return false;
@@ -352,13 +364,13 @@ export class RichText extends String {
     /**
      * Take the annotations and return an array of text and TemplateResult
      * instances to be rendered to the DOM.
-     * @method RichText#marshall
+     * @method Texture#marshall
      */
-    marshall () {
+    marshall() {
         let list = [this.toString()];
         this.references
             .sort((a, b) => b.begin - a.begin)
-            .forEach(ref => {
+            .forEach((ref) => {
                 const text = list.shift();
                 list = [text.slice(0, ref.begin), ref, text.slice(ref.end), ...list];
             });
@@ -369,194 +381,69 @@ export class RichText extends String {
     }
 }
 
-const isString = (s) => typeof s === 'string';
-
-// We don't render more than two line-breaks, replace extra line-breaks with
-// the zero-width whitespace character
-// This takes into account other characters that may have been removed by
-// being replaced with a zero-width space, such as '> ' in the case of
-// multi-line quotes.
-const collapseLineBreaks = (text) => text.replace(/\n(\u200B*\n)+/g, m => `\n${'\u200B'.repeat(m.length - 2)}\n`);
-
-const tplMentionWithNick = (o) =>
-    html`<span class="mention mention--self badge badge-info" data-uri="${o.uri}">${o.mention}</span>`;
-
-const tplMention = (o) => html`<span class="mention" data-uri="${o.uri}">${o.mention}</span>`;
-
-async function transform (t) {
-    try {
-        await t.addTemplates();
-    } catch (e) {
-        log.error(e);
+// Kept here to avoid circular dependencies
+class StylingDirective extends Directive {
+    /**
+     * @param {Texture} t
+     */
+    static async transform(t) {
+        try {
+            await t.addTemplates();
+        } catch (e) {
+            console.error(e);
+        }
+        return t.payload;
     }
-    return t.payload;
-}
 
-class StylingDirective extends Directive {
-    render (txt, offset, options) {
-        const t = new RichText(
+    /**
+     * @param {string} txt
+     * @param {number} offset
+     * @param {object} options
+     */
+    render(txt, offset, options) {
+        const t = new Texture(
             txt,
             offset,
             Object.assign(options, { 'show_images': false, 'embed_videos': false, 'embed_audio': false })
         );
-        return html`${until(transform(t), html`${t}`)}`;
+        return html`${until(StylingDirective.transform(t), html`${t}`)}`;
     }
 }
 
-const renderStylingDirectiveBody = directive(StylingDirective);
-const bracketing_directives = ['*', '_', '~', '`'];
-const styling_directives = [...bracketing_directives, '```', '>'];
-const styling_map = {
-    '*': {'name': 'strong', 'type': 'span'},
-    '_': {'name': 'emphasis', 'type': 'span'},
-    '~': {'name': 'strike', 'type': 'span'},
-    '`': {'name': 'preformatted', 'type': 'span'},
-    '```': {'name': 'preformatted_block', 'type': 'block'},
-    '>': {'name': 'quote', 'type': 'block'}
-};
-
-const dont_escape = ['_', '>', '`', '~'];
+const renderStyling = directive(StylingDirective);
 
 // prettier-ignore
 /* eslint-disable max-len */
 const styling_templates = {
     // m is the chatbox model
     // i is the offset of this directive relative to the start of the original message
-    'emphasis': (txt, i, options) => html`<span class="styling-directive">_</span><i>${renderStylingDirectiveBody(txt, i, options)}</i><span class="styling-directive">_</span>`,
-    'preformatted': txt => html`<span class="styling-directive">\`</span><code>${txt}</code><span class="styling-directive">\`</span>`,
-    'preformatted_block': txt => html`<div class="styling-directive">\`\`\`</div><pre><code class="block">${txt}</code></pre><div class="styling-directive">\`\`\`</div>`,
-    'quote': (txt, i, options) => html`<blockquote>${renderStylingDirectiveBody(txt, i, options)}</blockquote>`,
-    'strike': (txt, i, options) => html`<span class="styling-directive">~</span><del>${renderStylingDirectiveBody(txt, i, options)}</del><span class="styling-directive">~</span>`,
-    'strong': (txt, i, options) => html`<span class="styling-directive">*</span><b>${renderStylingDirectiveBody(txt, i, options)}</b><span class="styling-directive">*</span>`,
+    emphasis: (txt, i, options) => html`<span class="styling-directive">_</span><i>${renderStyling(txt, i, options)}</i><span class="styling-directive">_</span>`,
+    preformatted: (txt) => html`<span class="styling-directive">\`</span><code>${txt}</code><span class="styling-directive">\`</span>`,
+    preformatted_block: (txt) => html`<div class="styling-directive">\`\`\`</div><pre><code class="block">${txt}</code></pre><div class="styling-directive">\`\`\`</div>`,
+    quote: (txt, i, options) => html`<blockquote>${renderStyling(txt, i, options)}</blockquote>`,
+    strike: (txt, i, options) => html`<span class="styling-directive">~</span><del>${renderStyling(txt, i, options)}</del><span class="styling-directive">~</span>`,
+    strong: (txt, i, options) => html`<span class="styling-directive">*</span><b>${renderStyling(txt, i, options)}</b><span class="styling-directive">*</span>`,
 };
 
 /**
- * Checks whether a given character "d" at index "i" of "text" is a valid opening or closing directive.
- * @param { String } d - The potential directive
- * @param { String } text - The text in which  the directive appears
- * @param { Number } i - The directive index
- * @param { Boolean } opening - Check for a valid opening or closing directive
+ * @param {string} d
+ * @param {string} text
+ * @param {number} offset
+ * @param {object} options
  */
-function isValidDirective (d, text, i, opening) {
-    // Ignore directives that are parts of words
-    // More info on the Regexes used here: https://javascript.info/regexp-unicode#unicode-properties-p
-    if (opening) {
-        const regex = RegExp(dont_escape.includes(d) ? `^(\\p{L}|\\p{N})${d}` : `^(\\p{L}|\\p{N})\\${d}`, 'u');
-        if (i > 1 && regex.test(text.slice(i-1))) {
-            return false;
-        }
-        const is_quote = isQuoteDirective(d);
-        if (is_quote && i > 0 && text[i-1] !== '\n') {
-            // Quote directives must be on newlines
-            return false;
-        } else if (bracketing_directives.includes(d) && (text[i+1] === d)) {
-            // Don't consider empty bracketing directives as valid (e.g. **, `` etc.)
-            return false;
-        }
-    } else {
-        const regex = RegExp(dont_escape.includes(d) ? `^${d}(\\p{L}|\\p{N})` : `^\\${d}(\\p{L}|\\p{N})`, 'u');
-        if (i < text.length-1 && regex.test(text.slice(i))) {
-            return false;
-        }
-        if (bracketing_directives.includes(d) && (text[i-1] === d)) {
-            // Don't consider empty directives as valid (e.g. **, `` etc.)
-            return false;
-        }
-    }
-    return true;
-}
-
-/**
- * Given a specific index "i" of "text", return the directive it matches or null otherwise.
- * @param { String } text - The text in which  the directive appears
- * @param { Number } i - The directive index
- * @param { Boolean } opening - Whether we're looking for an opening or closing directive
- */
-function getDirective (text, i, opening=true) {
-    let d;
-
-    if (
-        (/(^```[\s,\u200B]*\n)|(^```[\s,\u200B]*$)/).test(text.slice(i)) &&
-        (i === 0 || text[i-1] === '>' || (/\n\u200B{0,2}$/).test(text.slice(0, i)))
-    ) {
-        d = text.slice(i, i+3);
-    } else if (styling_directives.includes(text.slice(i, i+1))) {
-        d = text.slice(i, i+1);
-        if (!isValidDirective(d, text, i, opening)) return null;
-    } else {
-        return null;
-    }
-    return d;
-}
-
-/**
- * Given a directive "d", which occurs in "text" at index "i", check that it
- * has a valid closing directive and return the length from start to end of the
- * directive.
- * @param { String } d -The directive
- * @param { Number } i - The directive index
- * @param { String } text -The text in which the directive appears
- */
-function getDirectiveLength (d, text, i) {
-    if (!d) return 0;
-
-    const begin = i;
-    i += d.length;
-    if (isQuoteDirective(d)) {
-        i += text.slice(i).split(/\n\u200B*[^>\u200B]/).shift().length;
-        return i-begin;
-    } else if (styling_map[d].type === 'span') {
-        const line = text.slice(i).split('\n').shift();
-        let j = 0;
-        let idx = line.indexOf(d);
-        while (idx !== -1) {
-            if (getDirective(text, i+idx, false) === d) {
-                return idx+2*d.length;
-            }
-            idx = line.indexOf(d, j++);
-        }
-        return 0;
-    } else {
-        // block directives
-        const substring = text.slice(i+1);
-        let j = 0;
-        let idx = substring.indexOf(d);
-        while (idx !== -1) {
-            if (getDirective(text, i+1+idx, false) === d) {
-                return idx+1+2*d.length;
-            }
-            idx = substring.indexOf(d, j++);
-        }
-        return 0;
-    }
-}
-
-function getDirectiveAndLength (text, i) {
-    const d = getDirective(text, i);
-    const length = d ? getDirectiveLength(d, text, i) : 0;
-    return length > 0 ? { d, length } : {};
-}
-
-const isQuoteDirective = (d) => ['>', '&gt;'].includes(d);
-
-function getDirectiveTemplate (d, text, offset, options) {
+export function getDirectiveTemplate(d, text, offset, options) {
     const template = styling_templates[styling_map[d].name];
     if (isQuoteDirective(d)) {
         const newtext = text
             // Don't show the directive itself
             // This big [] corresponds to \s without newlines, to avoid issues when the > is the last character of the line
-            .replace(/\n\u200B*>[ \f\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]?/g, m => `\n${'\u200B'.repeat(m.length - 1)}`)
+            .replace(
+                /\n\u200B*>[ \f\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]?/g,
+                (m) => `\n${'\u200B'.repeat(m.length - 1)}`
+            )
             .replace(/\n$/, ''); // Trim line-break at the end
         return template(newtext, offset, options);
     } else {
         return template(text, offset, options);
     }
 }
-
-function containsDirectives (text) {
-    for (let i=0; i<styling_directives.length; i++) {
-        if (text.includes(styling_directives[i])) {
-            return true;
-        }
-    }
-}

+ 0 - 0
src/shared/components/styles/rich-text.scss → src/shared/texture/texture.scss


+ 165 - 0
src/shared/texture/utils.js

@@ -0,0 +1,165 @@
+import { html } from 'lit';
+import { bracketing_directives, dont_escape, styling_directives, styling_map } from './constants';
+
+/**
+ * @param {any} s
+ * @returns {boolean} - Returns true if the input is a string, otherwise false.
+ */
+export function isString(s) {
+    return typeof s === 'string';
+}
+
+/**
+ * We don't render more than two line-breaks, replace extra line-breaks with
+ * the zero-width whitespace character
+ * This takes into account other characters that may have been removed by
+ * being replaced with a zero-width space, such as '> ' in the case of
+ * multi-line quotes.
+ * @param {string} text
+ */
+export function collapseLineBreaks(text) {
+    return text.replace(/\n(\u200B*\n)+/g, (m) => `\n${'\u200B'.repeat(m.length - 2)}\n`);
+}
+
+export const tplMentionWithNick = (o) =>
+    html`<span class="mention mention--self badge badge-info" data-uri="${o.uri}">${o.mention}</span>`;
+
+export function tplMention(o) {
+    return html`<span class="mention" data-uri="${o.uri}">${o.mention}</span>`;
+}
+
+/**
+ * Checks whether a given character "d" at index "i" of "text" is a valid opening or closing directive.
+ * @param {String} d - The potential directive
+ * @param {import('./texture').Texture} text - The text in which  the directive appears
+ * @param {Number} i - The directive index
+ * @param {Boolean} opening - Check for a valid opening or closing directive
+ * @returns {boolean}
+ */
+function isValidDirective(d, text, i, opening) {
+    // Ignore directives that are parts of words
+    // More info on the Regexes used here: https://javascript.info/regexp-unicode#unicode-properties-p
+    if (opening) {
+        const regex = RegExp(dont_escape.includes(d) ? `^(\\p{L}|\\p{N})${d}` : `^(\\p{L}|\\p{N})\\${d}`, 'u');
+        if (i > 1 && regex.test(text.slice(i - 1))) {
+            return false;
+        }
+        const is_quote = isQuoteDirective(d);
+        if (is_quote && i > 0 && text[i - 1] !== '\n') {
+            // Quote directives must be on newlines
+            return false;
+        } else if (bracketing_directives.includes(d) && text[i + 1] === d) {
+            // Don't consider empty bracketing directives as valid (e.g. **, `` etc.)
+            return false;
+        }
+    } else {
+        const regex = RegExp(dont_escape.includes(d) ? `^${d}(\\p{L}|\\p{N})` : `^\\${d}(\\p{L}|\\p{N})`, 'u');
+        if (i < text.length - 1 && regex.test(text.slice(i))) {
+            return false;
+        }
+        if (bracketing_directives.includes(d) && text[i - 1] === d) {
+            // Don't consider empty directives as valid (e.g. **, `` etc.)
+            return false;
+        }
+    }
+    return true;
+}
+
+/**
+ * Given a specific index "i" of "text", return the directive it matches or null otherwise.
+ * @param {import('./texture').Texture} text - The text in which  the directive appears
+ * @param {Number} i - The directive index
+ * @param {Boolean} opening - Whether we're looking for an opening or closing directive
+ * @returns {string|null}
+ */
+function getDirective(text, i, opening = true) {
+    let d;
+
+    if (
+        /(^```[\s,\u200B]*\n)|(^```[\s,\u200B]*$)/.test(text.slice(i)) &&
+        (i === 0 || text[i - 1] === '>' || /\n\u200B{0,2}$/.test(text.slice(0, i)))
+    ) {
+        d = text.slice(i, i + 3);
+    } else if (styling_directives.includes(text.slice(i, i + 1))) {
+        d = text.slice(i, i + 1);
+        if (!isValidDirective(d, text, i, opening)) return null;
+    } else {
+        return null;
+    }
+    return d;
+}
+
+/**
+ * @param {import('./texture').Texture} text
+ * @param {number} i
+ */
+export function getDirectiveAndLength(text, i) {
+    const d = getDirective(text, i);
+    const length = d ? getDirectiveLength(d, text, i) : 0;
+    return length > 0 ? { d, length } : {};
+}
+
+/**
+ * Given a directive "d", which occurs in "text" at index "i", check that it
+ * has a valid closing directive and return the length from start to end of the
+ * directive.
+ * @param {String} d -The directive
+ * @param {Number} i - The directive index
+ * @param {import('./texture').Texture} text -The text in which the directive appears
+ */
+function getDirectiveLength(d, text, i) {
+    if (!d) return 0;
+
+    const begin = i;
+    i += d.length;
+    if (isQuoteDirective(d)) {
+        i += text
+            .slice(i)
+            .split(/\n\u200B*[^>\u200B]/)
+            .shift().length;
+        return i - begin;
+    } else if (styling_map[d].type === 'span') {
+        const line = text.slice(i).split('\n').shift();
+        let j = 0;
+        let idx = line.indexOf(d);
+        while (idx !== -1) {
+            if (getDirective(text, i + idx, false) === d) {
+                return idx + 2 * d.length;
+            }
+            idx = line.indexOf(d, j++);
+        }
+        return 0;
+    } else {
+        // block directives
+        const substring = text.slice(i + 1);
+        let j = 0;
+        let idx = substring.indexOf(d);
+        while (idx !== -1) {
+            if (getDirective(text, i + 1 + idx, false) === d) {
+                return idx + 1 + 2 * d.length;
+            }
+            idx = substring.indexOf(d, j++);
+        }
+        return 0;
+    }
+}
+
+/**
+ * @param {string} d
+ */
+export function isQuoteDirective(d) {
+    return ['>', '&gt;'].includes(d);
+}
+
+/**
+ * @param {import('./texture').Texture} text
+ * @returns {boolean}
+ */
+export function containsDirectives(text) {
+    for (let i = 0; i < styling_directives.length; i++) {
+        if (text.includes(styling_directives[i])) {
+            return true;
+        }
+    }
+    return false;
+}

+ 1 - 1
src/types/shared/chat/message-body.d.ts

@@ -21,7 +21,7 @@ export default class MessageBody extends CustomElement {
     onImgLoad(): void;
     render(): import("lit/directive").DirectiveResult<{
         new (_partInfo: import("lit/directive").PartInfo): {
-            render(text: any, offset: any, options: any, callback: any): import("lit").TemplateResult<1>;
+            render(text: string, offset: number, options: object, callback?: Function): import("lit").TemplateResult<1>;
             readonly _$isConnected: boolean;
             update(_part: import("lit").Part, props: Array<unknown>): unknown;
         };

+ 0 - 7
src/types/shared/directives/rich-text.d.ts

@@ -1,7 +0,0 @@
-export default renderRichText;
-declare const renderRichText: (text?: any, offset?: any, options?: any, callback?: any) => import("lit/directive.js").DirectiveResult<typeof RichTextDirective>;
-declare class RichTextDirective extends Directive {
-    render(text: any, offset: any, options: any, callback: any): import("lit").TemplateResult<1>;
-}
-import { Directive } from 'lit/directive.js';
-//# sourceMappingURL=rich-text.d.ts.map

+ 9 - 8
src/types/shared/components/rich-text.d.ts → src/types/shared/texture/component.d.ts

@@ -1,8 +1,8 @@
 /**
- * The RichText custom element allows you to parse transform text into rich DOM elements.
- * @example <converse-rich-text text="*_hello_ world!*"></converse-rich-text>
+ * The Texture custom element allows you to parse transform text into rich DOM elements.
+ * @example <converse-texture text="*_hello_ world!*"></converse-texture>
  */
-export default class RichText extends CustomElement {
+export default class Texture extends LitElement {
     static get properties(): {
         embed_audio: {
             type: BooleanConstructor;
@@ -41,6 +41,7 @@ export default class RichText extends CustomElement {
             type: StringConstructor;
         };
     };
+    createRenderRoot(): this;
     nick: any;
     onImgClick: any;
     onImgLoad: any;
@@ -54,13 +55,13 @@ export default class RichText extends CustomElement {
     show_image_urls: boolean;
     show_images: boolean;
     show_me_message: boolean;
-    render(): import("lit/directive").DirectiveResult<{
-        new (_partInfo: import("lit/directive").PartInfo): {
-            render(text: any, offset: any, options: any, callback: any): import("lit").TemplateResult<1>;
+    render(): import("lit/directive.js").DirectiveResult<{
+        new (_partInfo: import("lit/directive.js").PartInfo): {
+            render(text: string, offset: number, options: object, callback?: Function): import("lit").TemplateResult<1>;
             readonly _$isConnected: boolean;
             update(_part: import("lit").Part, props: Array<unknown>): unknown;
         };
     }>;
 }
-import { CustomElement } from 'shared/components/element.js';
-//# sourceMappingURL=rich-text.d.ts.map
+import { LitElement } from 'lit';
+//# sourceMappingURL=component.d.ts.map

+ 30 - 0
src/types/shared/texture/constants.d.ts

@@ -0,0 +1,30 @@
+export const bracketing_directives: string[];
+export const styling_directives: string[];
+export const styling_map: {
+    '*': {
+        name: string;
+        type: string;
+    };
+    _: {
+        name: string;
+        type: string;
+    };
+    '~': {
+        name: string;
+        type: string;
+    };
+    '`': {
+        name: string;
+        type: string;
+    };
+    '```': {
+        name: string;
+        type: string;
+    };
+    '>': {
+        name: string;
+        type: string;
+    };
+};
+export const dont_escape: string[];
+//# sourceMappingURL=constants.d.ts.map

+ 13 - 0
src/types/shared/texture/directive.d.ts

@@ -0,0 +1,13 @@
+export default renderTexture;
+declare const renderTexture: (text: string, offset: number, options: any, callback?: Function) => import("lit/directive.js").DirectiveResult<typeof TextureDirective>;
+declare class TextureDirective extends Directive {
+    /**
+     * @param {string} text
+     * @param {number} offset
+     * @param {object} options
+     * @param {Function} [callback]
+     */
+    render(text: string, offset: number, options: object, callback?: Function): import("lit").TemplateResult<1>;
+}
+import { Directive } from 'lit/directive.js';
+//# sourceMappingURL=directive.d.ts.map

+ 38 - 25
src/types/shared/rich-text.d.ts → src/types/shared/texture/texture.d.ts

@@ -1,10 +1,17 @@
 /**
- * @class RichText
+ * @param {string} d
+ * @param {string} text
+ * @param {number} offset
+ * @param {object} options
+ */
+export function getDirectiveTemplate(d: string, text: string, offset: number, options: object): any;
+/**
+ * @class Texture
  * A String subclass that is used to render rich text (i.e. text that contains
  * hyperlinks, images, mentions, styling etc.).
  *
  * The "rich" parts of the text is represented by lit TemplateResult
- * objects which are added via the {@link RichText.addTemplateResult}
+ * objects which are added via the {@link Texture.addTemplateResult}
  * method and saved as metadata.
  *
  * By default Converse adds TemplateResults to support emojis, hyperlinks,
@@ -12,17 +19,17 @@
  *
  * 3rd party plugins can listen for the `beforeMessageBodyTransformed`
  * and/or `afterMessageBodyTransformed` events and then call
- * `addTemplateResult` on the RichText instance in order to add their own
+ * `addTemplateResult` on the Texture instance in order to add their own
  * rich features.
  */
-export class RichText extends String {
+export class Texture extends String {
     /**
-     * Create a new {@link RichText} instance.
+     * Create a new {@link Texture} instance.
      * @param {string} text - The text to be annotated
      * @param {number} offset - The offset of this particular piece of text
      *  from the start of the original message text. This is necessary because
-     *  RichText instances can be nested when templates call directives
-     *  which create new RichText instances (as happens with XEP-393 styling directives).
+     *  Texture instances can be nested when templates call directives
+     *  which create new Texture instances (as happens with XEP-393 styling directives).
      * @param {Object} [options]
      * @param {string} [options.nick] - The current user's nickname (only relevant if the message is in a XEP-0045 MUC)
      * @param {boolean} [options.render_styling] - Whether XEP-0393 message styling should be applied to the message
@@ -46,6 +53,8 @@ export class RichText extends String {
      * @param {Function} [options.onImgClick] - Callback for when an inline rendered image has been clicked
      * @param {Function} [options.onImgLoad] - Callback for when an inline rendered image has been loaded
      * @param {boolean} [options.hide_media_urls] - Callback for when an inline rendered image has been loaded
+     *
+     * @typedef {module:headless-shared-parsers.MediaURLMetadata} MediaURLMetadata
      */
     constructor(text: string, offset?: number, options?: {
         nick?: string;
@@ -53,7 +62,7 @@ export class RichText extends String {
         embed_audio?: boolean;
         embed_videos?: boolean;
         mentions?: any[];
-        media_urls?: MediaURLMetadata[];
+        media_urls?: any[];
         show_images?: boolean;
         show_me_message?: boolean;
         onImgClick?: Function;
@@ -74,7 +83,7 @@ export class RichText extends String {
         embed_audio?: boolean;
         embed_videos?: boolean;
         mentions?: any[];
-        media_urls?: MediaURLMetadata[];
+        media_urls?: any[];
         show_images?: boolean;
         show_me_message?: boolean;
         onImgClick?: Function;
@@ -86,19 +95,25 @@ export class RichText extends String {
     render_styling: boolean;
     show_images: boolean;
     hide_media_urls: boolean;
-    shouldRenderMedia(url_text: any, type: any): any;
+    /**
+     * @param {string} url - The URL to be checked
+     * @param {'audio'|'image'|'video'} type - The type of media
+     */
+    shouldRenderMedia(url: string, type: "audio" | "image" | "video"): any;
     /**
      * Look for `http` URIs and return templates that render them as URL links
      * @param {string} text
      * @param {number} local_offset - The index of the passed in text relative to
-     *  the start of this RichText instance (which is not necessarily the same as the
+     *  the start of this Texture instance (which is not necessarily the same as the
      *  offset from the start of the original message stanza's body text).
+     *
+     * @typedef {module:headless-shared-parsers.MediaURLData} MediaURLData
      */
     addHyperlinks(text: string, local_offset: number): void;
     /**
      * Look for `geo` URIs and return templates that render them as URL links
-     * @param { String } text
-     * @param { number } offset - The index of the passed in text relative to
+     * @param {String} text
+     * @param {number} offset - The index of the passed in text relative to
      *  the start of the message body text.
      */
     addMapURLs(text: string, offset: number): void;
@@ -112,9 +127,9 @@ export class RichText extends String {
     /**
      * Look for mentions included as XEP-0372 references and add templates for
      * rendering them.
-     * @param { String } text
-     * @param { number } local_offset - The index of the passed in text relative to
-     *  the start of this RichText instance (which is not necessarily the same as the
+     * @param {String} text
+     * @param {number} local_offset - The index of the passed in text relative to
+     *  the start of this Texture instance (which is not necessarily the same as the
      *  offset from the start of the original message stanza's body text).
      */
     addMentions(text: string, local_offset: number): void;
@@ -124,7 +139,7 @@ export class RichText extends String {
     addStyling(): void;
     trimMeMessage(): void;
     /**
-     * Look for plaintext (i.e. non-templated) sections of this RichText
+     * Look for plaintext (i.e. non-templated) sections of this Texture
      * instance and add references via the passed in function.
      * @param { Function } func
      */
@@ -140,22 +155,20 @@ export class RichText extends String {
      * This method can be used to add new template results to this message's
      * text.
      *
-     * @method RichText.addTemplateResult
-     * @param { Number } begin - The starting index of the plain message text
+     * @method Texture.addTemplateResult
+     * @param {Number} begin - The starting index of the plain message text
      * which is being replaced with markup.
-     * @param { Number } end - The ending index of the plain message text
+     * @param {Number} end - The ending index of the plain message text
      * which is being replaced with markup.
-     * @param { Object } template - The lit TemplateResult instance
+     * @param {Object} template - The lit TemplateResult instance
      */
     addTemplateResult(begin: number, end: number, template: any): void;
     isMeCommand(): boolean;
     /**
      * Take the annotations and return an array of text and TemplateResult
      * instances to be rendered to the DOM.
-     * @method RichText#marshall
+     * @method Texture#marshall
      */
     marshall(): any[];
 }
-export type MediaURLMetadata = any;
-export type MediaURLData = any;
-//# sourceMappingURL=rich-text.d.ts.map
+//# sourceMappingURL=texture.d.ts.map

+ 37 - 0
src/types/shared/texture/utils.d.ts

@@ -0,0 +1,37 @@
+/**
+ * @param {any} s
+ * @returns {boolean} - Returns true if the input is a string, otherwise false.
+ */
+export function isString(s: any): boolean;
+/**
+ * We don't render more than two line-breaks, replace extra line-breaks with
+ * the zero-width whitespace character
+ * This takes into account other characters that may have been removed by
+ * being replaced with a zero-width space, such as '> ' in the case of
+ * multi-line quotes.
+ * @param {string} text
+ */
+export function collapseLineBreaks(text: string): string;
+export function tplMention(o: any): import("lit").TemplateResult<1>;
+/**
+ * @param {import('./texture').Texture} text
+ * @param {number} i
+ */
+export function getDirectiveAndLength(text: import("./texture").Texture, i: number): {
+    d: string;
+    length: number;
+} | {
+    d?: undefined;
+    length?: undefined;
+};
+/**
+ * @param {string} d
+ */
+export function isQuoteDirective(d: string): boolean;
+/**
+ * @param {import('./texture').Texture} text
+ * @returns {boolean}
+ */
+export function containsDirectives(text: import("./texture").Texture): boolean;
+export function tplMentionWithNick(o: any): import("lit").TemplateResult<1>;
+//# sourceMappingURL=utils.d.ts.map