All files / src/display ExpressionHighlight.ts

98.3% Statements 58/59
71.42% Branches 5/7
100% Functions 5/5
98.3% Lines 58/59

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 6092x 94x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 92x 92x 92x 92x 92x 92x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 92x 5x 5x 92x 92x 92x 92x 92x 92x 92x 92x 92x  
import { css, html, LitElement, TemplateResult } from 'lit';
import { property } from 'lit/decorators.js';
import { tokenize, Token } from '../excellent/tokenizer';
import {
  getTokenClass,
  tokenCss,
  EXPRESSION_TOKENS
} from '../excellent/token-styles';
import { sessionParser } from '../excellent/helpers';
 
export class ExpressionHighlight extends LitElement {
  static get styles() {
    return [
      tokenCss,
      css`
        :host {
          display: inline;
        }
      `
    ];
  }
 
  @property({ type: String })
  private text = '';
 
  private observer: MutationObserver;
 
  connectedCallback(): void {
    super.connectedCallback();
    this.text = this.textContent || '';
    this.observer = new MutationObserver(() => {
      this.text = this.textContent || '';
    });
    this.observer.observe(this, {
      childList: true,
      characterData: true,
      subtree: true
    });
  }
 
  disconnectedCallback(): void {
    super.disconnectedCallback();
    this.observer?.disconnect();
  }
 
  private renderTokens(): TemplateResult[] {
    const tokens = tokenize(this.text, sessionParser);
    return tokens.map((token: Token) => {
      const cls = getTokenClass(token);
      const isMono = EXPRESSION_TOKENS.has(token.type);
      const classes = isMono ? `${cls} tok-mono` : cls;
      return html`<span class="${classes}">${token.text}</span>`;
    });
  }
 
  public render(): TemplateResult {
    return html`${this.renderTokens()}`;
  }
}