All files / packages/sds-components/src/sds/richText richText.js

81.25% Statements 65/80
54.83% Branches 17/31
96% Functions 24/25
80.51% Lines 62/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308            1x 1x 1x 1x 1x 1x   16x                                                                                                                     1x 1x 1x                   16x                 18x                 2x 2x                 8x 8x                                 1x     1x                             2x 2x 2x 2x 10x   10x   10x 10x 10x                           2x 2x                 10x     10x 10x 10x     10x 10x 10x   10x             2x 2x             2x 2x 16x 16x   8x   64x   20x                     6x 2x 6x 6x 6x                                   16x     16x 16x 16x               2x 2x 16x   2x       1x 1x       1x                                                            
import { LightningElement, api } from 'lwc';
import 'sds/privateThemeProvider';
 
export default class RichText extends LightningElement {
  static shadowSupportMode = 'native';
 
  _nodes = [];
  _styleMap = new Map();
  _copy = false;
  connected = false;
  _richTextElement;
  _richTextContainerElement;
 
  camelize = (s) => s.replace(/-./g, (x) => x[1].toUpperCase());
 
  CONFIGURABLE_TAGS = {
    h1: {
      props: [
        {
          cssProperty: 'font-size',
          stylingHook: '--sds-c-richtext-h1-font-size',
        },
      ],
    },
    h2: {
      props: [
        {
          cssProperty: 'font-size',
          stylingHook: '--sds-c-richtext-h2-font-size',
        },
      ],
    },
    h3: {
      props: [
        {
          cssProperty: 'font-size',
          stylingHook: '--sds-c-richtext-h3-font-size',
        },
      ],
    },
    h4: {
      props: [
        {
          cssProperty: 'font-size',
          stylingHook: '--sds-c-richtext-h4-font-size',
        },
      ],
    },
    ul: {
      props: [
        {
          cssProperty: 'padding',
          stylingHook: '--sds-c-richtext-list-spacing',
        },
      ],
    },
    ol: {
      props: [
        {
          cssProperty: 'padding',
          stylingHook: '--sds-c-richtext-list-spacing',
        },
      ],
    },
    p: {
      props: [
        {
          cssProperty: 'margin',
          stylingHook: '--sds-c-richtext-p-spacing',
        },
      ],
    },
    Eglobal: {
      props: [
        {
          cssProperty: 'font-size',
          stylingHook: '--sds-c-richtext-font-size',
        },
        {
          cssProperty: 'line-height',
          stylingHook: '--sds-c-richtext-font-lineheight',
        },
        {
          cssProperty: 'padding',
          stylingHook: '--sds-c-richtext-spacing',
        },
      ],
    },
  };
 
  connectedCallback() {
    if (!this.connected) {
      this._copy = !!this.template.host.querySelector('[slot~=copy-label]');
      this.connected = true;
    }
  }
 
  /**
   * Return the slotted nodes
   * @returns {Array} nodes
   * @private
   */
  get nodes() {
    return this._nodes;
  }
 
  /**
   * Return the style map
   * @returns {Map} style map
   * @private
   */
  get styleMap() {
    return this._styleMap;
  }
 
  /**
   * Return the Rich Text Element
   * @returns {Object} Rich Text Element
   * @private
   */
  get richText() {
    this._richTextElement = this._richTextElement || this.template.querySelector('[part~=rich-text]');
 
    return this._richTextElement;
  }
 
  /**
   * Return the Rich Text Container Element
   * @returns {Object} Rich Text Container Element
   * @private
   */
  get richTextContainer() {
    this._richTextContainerElement =
      this._richTextContainerElement || this.template.querySelector('[part~=rich-text-container]');
 
    return this._richTextContainerElement;
  }
 
  /**
   * Return the Copy Element status
   * @returns {Boolean} copy display status
   * @private
   */
  get copy() {
    return this._copy;
  }
 
  /**
   * Handle default slot change
   * @param {*} e
   */
  handleSlotChange(e) {
    const childNodes = e.target.assignedNodes({ flatten: true });
    this._nodes = [...childNodes];
  }
 
  /**
   * Copies the contents of the rich text elements to clipboard
   */
  handleCopy() {
    navigator.clipboard.writeText(this.copyRichText());
  }
 
  /*E*
   * Returns html as string with rich text slotted elements populated with respective styles
   * @returns string
   */
  @api
  copyRichText() {
    this.populateStyleMap();
    const htmlElementsToExport = [`<div style=\"${this.createStyleStrWithStyleMap()}\">`]; // Start with a opening tag
    const configurableTags = Object.keys(this.CONFIGURABLE_TAGS);
    this.nodes.forEach((node) => {
      if (node instanceof HTMLElement) {
        if (configurableTags.includes(node.tagName.toLowerCase())) {
          let style = this.prepareStyleForTag(node.tagName);
          style += node.style.cssText;
          const clonedNode = node.cloneNode(true);
          clonedNode.style.cssText = style;
          htmlElementsToExport.push(`\t${clonedNode.outerHTML}`);
        } else {
          const clonedNode = node.cloneNode(true);
    I      htmlElementsToExport.push(`\t${clonedNode.outerHTML}`);
        }
      } else {
        const textContent = node.textContent.trim().length > 0 ? node.textContent.trim() : null;
        if (textContent) {
    I      const para = document.createElement('p');
          para.innerText = textContent;
          htmlElementsToExport.push(`\t${para.outerHTML}`);
        }
      }
    });
    htmlElementsToExport.push('</div>'); // End with a closing tag
    return htmlElementsToExport.join('\n').toString();
  }
 
  /**
   * Given a html tag name, creates inline styles
   * @param {*} tagName
   * @returns
   */
  prepareStyleForTag(tagName) {
    if (!tagName) {
      return;
    }
    tagName = tagName.toLowerCase();
    const configurableProps = this.CONFIGURABLE_TAGS[tagName];
    if (!configurableProps) {
      return;
    }
    let style = '';
    configurableProps.props.forEach((prop) => {
      style += `${prop.cssProperty}: var(${prop.stylingHook});`;
    });
    return style;
  }
 
  /**
   * Prepares stylesMap with necessary styling hooks and css properties
   */
  populateStyleMap() {
    this.populateStyleMapWithStylingHooks();
    this.populateStyleMapWithOtherStyles();
  }
 
  /**
   * Populates the styleMap with styling hooks
   */
  populateStyleMapWithStylingHooks() {
    const configurableTags = Object.keys(this.CONFIGURABLE_TAGS);
    configurableTags.forEach((tag) => {
      const props = this.CONFIGURABLE_TAGS[tag].props;
      ifI (tag === 'global') {
        // default css for whole container
        props.forEach((prop) =>
          this.styleMap.set(
            prop.cssProperty,
            this.getComputedStyleValOfProp(this.richTextContainer, prop.cssProperty),
          ),
        );
      } else {
        const configurableEle = this.nodes.find(
          (node) =>
            node instanceof HTMLElement &&
            configurableTags.includes(node.tagName.toLowerCase()) &&
            node.tagName.toLowerCase() === tag,
        );
        if (configurableEle) {
          props.forEach((prop) =>
            this.styleMap.set(
    I          prop.stylingHook,
              this.getComputedStyleValOfProp(configurableEle, prop.cssProperty),
            ),
          );
        }
      }
    });
  }
 
  /**
   * Populates the styleMap with css properties that are set directly (without using styling hooks)
   * to root tag or to any element via part attribute
   */
  populateStyleMapWithOtherStyles() {
    const globalStylingHooks = this.CONFIGURABLE_TAGS['global'].props.map((prop) => prop.stylingHook);
    [this.template.host, this.richText, this.richTextContainer].forEach((element) => {
      const elementStyles = element.style.cssText.trim();
      elementStyles.split(';').forEach((styleStr) => {
        if (styleStr.includes(':')) {
          const prop = styleStr.split(':')[0].trim();
          const value = styleStr.split(':')[1].trim();
          if (!globalStylingHooks.includes(prop)) {
            this.styleMap.set(prop, this.getComputedStyleValOfProp(element, prop) || value);
          }
        }
      });
    });
  }
 
  /**
   * Returns the css property value of a given element
   * @param {*} element
   * @param {*} cssProp
   * @returns
   */
  getComputedStyleValOfProp(element, cssProp) {
    if (!element || !cssProp) {
      return;
    }
    const computedStyles = getComputedStyle(element);
    const cssPropInCamelCase = this.camelize(cssProp);
    return computedStyles[cssPropInCamelCase];
  }
 
  /**
   * Creates inline style string with styleMap contents
   * @returns
   */
  createStyleStrWithStyleMap() {
    let style = '';
    this.styleMap.forEach((value, key) => {
      style += `${key}: ${value}; `;
    });
    return style.trim();
  }
}