All files / src/form TemplateEditor.ts

66.66% Statements 336/504
82.22% Branches 37/45
66.66% Functions 8/12
66.66% Lines 336/504

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 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 50592x 126x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 30x 30x 30x 30x 30x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 86x 86x 86x 86x 86x 86x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 37x 30x 30x 30x 30x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x     5x 4x 4x 92x 5x 5x 5x     5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 5x 1x         5x 5x 5x 5x 5x 5x 92x             92x                                       92x                                 92x               92x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 33x 33x 4x 4x 33x 12x 29x 4x 4x 4x 4x 4x 4x 4x 33x 33x 33x 5x 33x 9x 9x                                                                                                                                                                                                                                 4x 4x 4x 4x 4x 92x 6x 6x 6x 6x 4x 6x 6x 6x 6x 6x 9x 9x 9x 9x 6x 6x 4x 4x 4x 4x 4x 4x 92x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x  
import { property } from 'lit/decorators.js';
import { TemplateResult, html, css, LitElement, PropertyValues } from 'lit';
import { CustomEventType } from '../interfaces';
import { MediaPicker } from './MediaPicker';
import { getClasses } from '../utils';
import { FieldElement } from './FieldElement';
 
interface Component {
  name: string;
  type: string;
  content: string;
  variables: { [key: string]: number };
}
 
interface Translation {
  locale: string;
  status: string;
  channel: { uuid: string; name: string };
  components: Component[];
  variables: { type: string }[];
}
 
interface Template {
  created_on: string;
  modified_on: string;
  name: string;
  uuid: string;
  base_translation: Translation;
}
 
export class TemplateEditor extends FieldElement {
  static shadowRootOptions = {
    ...LitElement.shadowRootOptions,
    delegatesFocus: true
  };
 
  static get styles() {
    return css`
      .component {
        background: #fff;
        border: 1px solid var(--color-widget-border);
        border-radius: var(--curvature);
        padding: 1em;
        margin-top: 1em;
      }
 
      .content {
      }
 
      .picker {
        margin-bottom: 0.5em;
        display: block;
      }
      .param {
        display: flex;
        margin-bottom: 0.5em;
        align-items: center;
      }
      label {
        margin-right: 0.5em;
      }
 
      .content span {
        margin-right: 0.25em;
      }
 
      .error-message {
        padding-left: 0.5em;
        padding-bottom: 1em;
      }
 
      .variable {
        display: inline-block;
        margin: 0.25em 0em;
        margin-right: 0.25em;
      }
 
      .button-wrapper {
        background: #f9f9f9;
        border-radius: var(--curvature);
        padding: 0.5em;
        display: flex;
        flex-direction: column;
      }
 
      .button-header {
        font-weight: normal;
        margin-left: 0.25em;
        margin-bottom: -0.5em;
        font-size: 0.9em;
        color: #777;
      }
 
      .buttons {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        margin-bottom: 1em;
      }
 
      .button {
        background: #fff;
        padding: 0.3em 1em;
        border: 1px solid #e6e6e6;
        border-radius: var(--curvature);
        min-height: 23px;
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-right: 0.5em;
        margin-top: 0.5em;
        align-items: center;
      }
 
      .button .content {
        margin-bottom: 0;
      }
 
      .button .display {
        margin-right: 0.5em;
        background: #f9f9f9;
        padding: 0.25em 1em;
        border-radius: var(--curvature);
      }
 
      .variable {
        --temba-textinput-padding: 5px 5px;
        --temba-textinput-font-size: 0.9em;
        line-height: initial;
      }
 
      .template {
        background: #fff;
        border-radius: var(--curvature);
        border: 1px solid var(--color-widget-border);
        padding: 1em;
        line-height: 2.2em;
        max-height: 50vh;
        overflow-y: auto;
        overflow-x: hidden;
        padding-bottom: 0;
      }
 
      .label {
        font-size: 0.9em;
        color: #777;
        margin-left: 0.25em;
      }
    `;
  }
 
  @property({ type: String })
  url: string;
 
  // initial template uuid
  @property({ type: String })
  template: string;
 
  @property({ type: Object })
  selectedTemplate: Template;
 
  // initial variables, not reflected back
  @property({ type: Array })
  variables: string[];
 
  @property({ type: Array })
  currentVariables: string[];
 
  @property({ type: Object, attribute: false })
  translation: Translation;
 
  @property({ type: Boolean })
  translating: boolean;
 
  @property({ type: Boolean })
  session = false;
 
  @property({ type: String, attribute: 'template-warning' })
  templateWarning: string;
 
  pickersLoading: { [key: number]: boolean } = {};
 
  textInputAttachments: { [index: number]: boolean } = {};
 
  public willUpdate(changes: PropertyValues): void {
    super.willUpdate(changes);
    if (changes.has('template')) {
      this.textInputAttachments = {};
      this.currentVariables = this.variables || [];
 
      // check if our variables should be a textinput
      if (this.currentVariables.length > 0) {
        this.currentVariables.forEach((variable, index) => {
          const split = variable.split(':');
          if (split.length > 1) {
            // we have a generary content type
            if (split[0].indexOf('/') === -1) {
              this.textInputAttachments[index] = true;
            }
          }
        });
      }
    }
  }
 
  private handleTemplateChanged(event: CustomEvent) {
    const prev = this.selectedTemplate;
    this.selectedTemplate = (event.target as any).values[0] as Template;
    if (prev) {
      this.currentVariables = [];
      this.textInputAttachments = {};
    }
 
    if (this.selectedTemplate) {
      this.translation = this.selectedTemplate.base_translation;
      if (this.translation) {
        this.variables = new Array(
          (this.translation.variables || []).length
        ).fill('');
      } else {
        this.variables = [];
      }
    } else {
      this.translation = null;
      this.variables = [];
    }
 
    this.fireCustomEvent(CustomEventType.ContextChanged, {
      template: this.selectedTemplate,
      translation: this.translation,
      variables: this.currentVariables
    });
  }

  private handleAttachmentLoading(event: CustomEvent) {
    const media = event.target as MediaPicker;
    const index = parseInt(media.getAttribute('index'));
    this.pickersLoading[index] = event.detail.loading;
    this.requestUpdate();
  }
 
  private handleAttachmentsChanged(event: CustomEvent) {
    const media = event.target as MediaPicker;
    const index = parseInt(media.getAttribute('index'));

    if (media.attachments.length === 0) {
      this.currentVariables[index] = '';
    } else {
      const attachment = media.attachments[0];
      if (attachment.url && attachment.content_type) {
        this.currentVariables[index] =
          `${attachment.content_type}:${attachment.url}`;
      } else {
        this.currentVariables[index] = ``;
      }
    }
    this.fireContentChange();
    this.requestUpdate('currentVariables');
  }

  private handleVariableChanged(event: InputEvent) {
    const target = event.target as HTMLInputElement;
    const variableIndex = parseInt(target.getAttribute('index'));
    const prefix = target.getAttribute('prefix') || '';

    // add our prefix if we have a value
    let value = target.value;
    if (value) {
      value = prefix + value;
    }

    this.currentVariables[variableIndex] = value;
    this.fireContentChange();
  }

  private fireContentChange() {
    this.fireCustomEvent(CustomEventType.ContentChanged, {
      template: this.selectedTemplate,
      translation: this.translation,
      variables: this.currentVariables
    });
  }

  private renderVariables(component: Component) {
    // create a regex match based on the variable names
    const variableRegex = new RegExp(
      `{{(${Object.keys(component.variables || []).join('|')})}}`,
      'g'
    );

    let variables = null;

    let parts = [];
    if (component.content && component.content.trim().length > 0) {
      parts = component.content?.split(variableRegex) || [];
    }
    const currVariables = this.currentVariables || [];
    if (parts.length > 0) {
      variables = parts.map((part, index) => {
        if (index % 2 === 0) {
          return html`<span class="text">${part}</span>`;
        }
        const variableIndex = component.variables[part];
 
        return html`<temba-completion
          class="variable"
          type="text"
          ?session=${this.session}
          value=${variableIndex < currVariables.length
            ? currVariables[variableIndex]
            : null}
          @keyup=${this.handleVariableChanged}
          name="${component.name}"
          index="${variableIndex}"
          placeholder="{{${part}}}"
        ></temba-completion>`;
      });
    } else {
      variables = Object.values(component.variables).map((variableIndex) => {
        const variableSpec = this.translation.variables[variableIndex];
        if (
          variableSpec.type === 'image' ||
          variableSpec.type === 'document' ||
          variableSpec.type === 'audio' ||
          variableSpec.type === 'video'
        ) {
          let attachments = [];
          if (this.currentVariables[variableIndex]) {
            const parts = this.currentVariables[variableIndex].split(':');
            const content_type = parts[0];
            const url = parts.slice(1).join(':');
            attachments = [{ url, content_type }];
          }

          const loading = this.pickersLoading[variableIndex];

          const prefix = variableSpec.type + ':';
          let value =
            variableIndex < currVariables.length
              ? currVariables[variableIndex]
              : null;

          if (value && value.startsWith(prefix)) {
            value = value.slice(prefix.length);
          }

          return html`
            ${this.textInputAttachments[variableIndex]
              ? html` <div class="label">
                    ${variableSpec.type.charAt(0).toUpperCase() +
                    variableSpec.type.slice(1)}
                    URL
                  </div>
                  <div
                    style="display:flex;align-items:center;margin-bottom:1em;"
                  >
                    <temba-completion
                      style="flex-grow:1; margin-right:1em;"
                      ?session=${this.session}
                      prefix="${prefix}"
                      index=${variableIndex}
                      value=${value}
                      @keyup=${this.handleVariableChanged}
                    ></temba-completion>
                    <temba-icon
                      name="close"
                      clickable
                      @click=${() => {
                        this.textInputAttachments[variableIndex] = false;
                        this.currentVariables[variableIndex] = '';
                        this.requestUpdate();
                      }}
                    >
                    </temba-icon>
                    <div></div>
                  </div>`
              : html`
                  <div
                    class=${getClasses({ loading })}
                    style="
              display: flex; 
              align-items: center; 
              border-radius: var(--curvature);
              margin-bottom: 0.5em;
              ${attachments.length === 0 && !loading
                      ? `background-color:rgba(0,0,0,.04);`
                      : ``}"
                  >
                    <temba-media-picker
                      accept="${variableSpec.type === 'document'
                        ? 'application/pdf'
                        : variableSpec.type + '/*'}"
                      max="1"
                      index=${variableIndex}
                      icon="attachment_${variableSpec.type}"
                      attachments=${JSON.stringify(attachments)}
                      @temba-loading=${this.handleAttachmentLoading.bind(this)}
                      @change=${this.handleAttachmentsChanged.bind(this)}
                    ></temba-media-picker>
                    <div style="flex-grow:1">
                      ${attachments.length == 0 && !loading
                        ? html`Attach ${variableSpec.type} to continue`
                        : ''}
                    </div>
                    <temba-icon
                      clickable
                      name="edit"
                      @click=${() => {
                        this.currentVariables[variableIndex] = '';
                        this.textInputAttachments[variableIndex] = true;
                        this.requestUpdate();
                      }}
                      style="margin-right:1em"
                    ></temba-icon>
                  </div>
                `}
          `;
        }
      });
    }

    return html`<div class="content">${variables}</div> `;
  }

  public renderComponents(components: Component[]): TemplateResult {
    const nonButtons = components
      .filter((comp) => !comp.type.startsWith('button/'))
      .map(
        (component) =>
          html`<div class="${component['name']}">
            ${this.renderVariables(component)}
          </div>`
      );
    const buttonComponents = components.filter((comp) =>
      comp.type.startsWith('button/')
    );
    const buttons =
      buttonComponents.length > 0 ? this.renderButtons(buttonComponents) : null;
    return html`<div class="main">${nonButtons}</div>
      <div class="buttons">
        ${buttons}
        <div></div>
      </div>`;
  }
 
  public renderButtons(components): TemplateResult {
    const buttons = components.map((component) => {
      if (component.display) {
        return html`
          <div class="button">
            <div class="display">${component.display}</div>
            ${this.renderVariables(component)}
          </div>
        `;
      } else {
        return html`
          <div class="button">${this.renderVariables(component)}</div>
        `;
      }
    });
    return html`<div class="button-wrapper">
      <div class="button-header">Template Buttons</div>
      <div class="buttons">${buttons}</div>
    </div>`;
  }
 
  public renderWidget(): TemplateResult {
    let content = null;
    if (this.translation) {
      content = this.renderComponents(this.translation.components);
    } else if (this.selectedTemplate) {
      content = html`<div class="error-message">
        This template currently has no approved translations.
      </div>`;
    }
 
    return html`
      <div>
        <temba-select
          searchable
          ?clearable=${!this.translating}
          ?disabled=${this.translating}
          valuekey="uuid"
          class="picker"
          value="${this.template}"
          endpoint="${this.url}"
          shouldExclude=${(template) => template.status !== 'approved'}
          placeholder="Select a template"
          @temba-content-changed=${this.swallowEvent}
          @change=${this.handleTemplateChanged}
        >
        </temba-select>
        ${this.templateWarning && this.selectedTemplate
          ? html`<temba-alert
              level="warning"
              style="margin-bottom: 0.5em; display: block;"
              >${this.templateWarning}</temba-alert
            >`
          : null}
        ${content ? html` <div class="template">${content}</div>` : null}
      </div>
    `;
  }
}