All files / src/form Compose.ts

80.16% Statements 679/847
86.99% Branches 107/123
75.86% Functions 22/29
80.16% Lines 679/847

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 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 84892x 102x 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 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 100x 100x 100x 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 26x 26x 92x 34x 34x 34x 11x 11x 11x 34x                                                                           34x   90x 22x 22x   22x 22x 17x 17x 11x 11x 22x 22x 90x 126x 126x 126x 126x 126x 126x 6x 6x 126x 27x 27x 27x 27x 27x 20x 7x 126x 28x 126x 126x 28x 28x 28x 28x 28x 8x 8x 28x 28x 28x 28x 28x 28x 28x 28x 28x 2x 2x 28x 28x   126x 126x 126x 99x 99x 40x 99x 99x 53x 99x 53x 53x 53x 99x 99x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x   46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 99x 53x 99x 99x 90x 27x 27x 27x 27x 27x 90x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 92x                                   92x 27x 92x 126x 126x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 126x 126x 126x 126x 28x 28x 28x 28x 126x 126x 28x 126x 99x 126x 92x 92x 54x 54x 54x 54x 54x 54x 54x 92x 55x 55x 55x 55x 55x 55x 55x 92x 11x 11x 11x 11x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 92x   92x 92x     92x 92x 69x 69x 69x 69x 69x 69x 69x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x                             31x 92x 103x 103x 103x 103x 36x 36x 56x 47x 47x 47x 47x 92x 92x 10x 10x                                 92x 4x 4x 4x 4x 4x           92x                                   92x 98x 92x                                                                                                       1x 1x 1x 1x         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 91x 91x 91x 91x 91x 91x 112x 112x 112x 92x 92x 92x 92x 92x 92x 92x 92x 91x 91x 91x 91x 91x 91x 91x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 100x 100x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x  
import { TemplateResult, html, css, PropertyValues, nothing } from 'lit';
import { FieldElement } from './FieldElement';
import { property } from 'lit/decorators.js';
import { Attachment, CustomEventType, Language, Shortcut } from '../interfaces';
import { Icon } from '../Icons';
import { DEFAULT_MEDIA_ENDPOINT } from '../utils';
import { Select } from './select/Select';
import { MessageEditor } from './MessageEditor';
import { ShortcutList } from '../list/ShortcutList';
import { setCaretOffset } from '../excellent/caret-utils';
 
export interface ComposeValue {
  text: string;
  attachments: { uuid: string }[];
  quick_replies: string[];
  optin: string;
  template: string;
  variables: string[];
}
 
export class Compose extends FieldElement {
  static get styles() {
    return css`
      ${super.styles}
      :host {
        border-top-right-radius: var(--curvature);
        border-top-left-radius: var(--curvature);
      }
 
      .container {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        position: relative;
        border-radius: var(--compose-curvature, var(--curvature-widget));
        background: var(--color-widget-bg);
        border: var(--compose-border, 1px solid var(--color-widget-border));
        transition: all ease-in-out var(--transition-speed);
        box-shadow: var(--compose-shadow, var(--widget-box-shadow));
        caret-color: var(--input-caret);
      }
 
      .container:focus-within {
        border-color: var(--color-focus);
        box-shadow: var(
          --widget-box-shadow-focused,
          0 0 0 3px rgba(0, 123, 255, 0.25)
        );
      }
 
      .editor-wrapper {
        --color-widget-border: none;
        --widget-box-shadow: none;
        --widget-box-shadow-focused: none;
        --temba-textinput-padding: 1em 1em;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
      }
 
      .editor-wrapper temba-message-editor {
        flex-grow: 1;
        --color-widget-border: transparent;
        --widget-box-shadow: none;
        --widget-box-shadow-focused: none;
        --color-focus: transparent;
      }
 
      .language {
        margin-bottom: 0.6em;
        display: block;
      }
 
      .send-error {
        color: rgba(250, 0, 0, 0.75);
        font-size: var(--help-text-size);
        padding: 0.5em;
      }
 
      .quick-replies {
        margin: 0.2em;
      }
 
      .optins {
        margin: 0.2em;
      }
 
      .templates {
        margin: 0.2em;
      }
 
      temba-accordion {
        margin-top: 0.5em;
      }
 
      .shortcut-overlay {
        position: fixed;
        margin-bottom: 4px;
        display: flex;
        flex-direction: row;
        align-items: stretch;
        --options-block-shadow: none;
        --curvature-widget: 0px;
        --color-options-bg: #fff;
        border: 1px solid var(--color-widget-border);
        border-radius: 6px;
        background: var(--color-widget-bg, #fff);
        box-shadow: var(--options-shadow);
        z-index: 1000003;
        overflow: hidden;
      }
 
      temba-shortcuts {
        flex-grow: 1;
      }
 
      .shortcut-icon {
        color: #888;
        background: rgba(0, 0, 0, 0.04);
        border-radius: 8px;
        transition:
          background-color 0.2s ease-in-out,
          color 0.2s ease-in-out;
      }
 
      .shortcut-icon:hover {
        color: var(--color-text-dark);
        background: rgba(0, 0, 0, 0.08);
      }
    `;
  }
 
  @property({ type: Number })
  index = 1;
 
  @property({ type: Number })
  maxAttachments = 3;
 
  @property({ type: Number })
  maxLength = 640;
 
  @property({ type: Number })
  maxQuickReplies = 10;
 
  @property({ type: Boolean })
  completion: boolean;
 
  @property({ type: Boolean })
  attachments: boolean;
 
  @property({ type: Boolean })
  quickReplies: boolean;
 
  @property({ type: Boolean })
  optIns: boolean;
 
  @property({ type: Boolean })
  templates: boolean;
 
  @property({ type: Boolean, attribute: 'template-session' })
  templateSession = false;
 
  @property({ type: String, attribute: 'template-warning' })
  templateWarning: string;
 
  @property({ type: Boolean })
  counter: boolean;
 
  @property({ type: Boolean })
  autogrow: boolean;
 
  @property({ type: Number, attribute: 'min-height' })
  minHeight = 150;
 
  @property({ type: Boolean })
  shortcuts: boolean;
 
  @property({ type: String })
  currentText = '';
 
  @property({ type: String })
  initialText = '';
 
  @property({ type: String })
  accept = ''; //e.g. ".xls,.xlsx"
 
  @property({ type: String, attribute: false })
  endpoint = DEFAULT_MEDIA_ENDPOINT;
 
  @property({ type: Boolean, attribute: false })
  uploading: boolean;
 
  @property({ type: Array })
  languages: Language[] = [];
 
  @property({ type: Array })
  currentAttachments: Attachment[] = [];
 
  @property({ type: Array })
  currentQuickReplies: { name: string; value: string }[] = [];
 
  @property({ type: Array })
  currentOptin: { name: string; uuid: string }[] = [];
 
  @property({ type: Array })
  variables: string[] = [];
 
  @property({ type: String })
  template: string;
 
  @property({ type: Object })
  currentTemplate: { name: string; uuid: string };
 
  // locale for the template
  @property({ type: String })
  locale: string;
 
  @property({ type: String })
  optinEndpoint = '/api/v2/optins.json';
 
  @property({ type: String })
  templateEndpoint = '/api/internal/templates.json';
 
  @property({ type: Boolean, attribute: false })
  empty = true;
 
  @property({ type: Boolean, attribute: 'widget_only' })
  widgetOnly: boolean;
 
  @property({ type: Array })
  errors: string[];
 
  @property({ type: Object })
  langValues: {
    [lang: string]: {
      text: string;
      attachments: Attachment[];
      quick_replies: string[];
      optin?: { name: string; uuid: string };
      template?: string;
      variables?: string[];
      locale?: string;
    };
  } = {};
 
  @property({ type: String })
  currentLanguage = 'und';
 
  @property({ type: Boolean })
  hasPendingText = false;
 
  @property({ type: Object })
  activeShortcut: Shortcut;
 
  @property({ type: Boolean, attribute: false })
  showShortcuts = false;
 
  private shortcutFilter: string = null;
  private shortcutViaIcon = false;
  private lastCaretPosition: number = 0;
 
  public constructor() {
    super();
  }
 
  private isBaseLanguage(): boolean {
    return (
      this.currentLanguage == 'und' ||
      this.currentLanguage == this.languages[0].iso
    );
  }
 
  private hasTranslation(iso: string): boolean {
    const entry = this.langValues?.[iso];
    if (!entry) return false;
    return !!(
      (entry.text && entry.text.trim().length > 0) ||
      (entry.attachments && entry.attachments.length > 0) ||
      (entry.quick_replies && entry.quick_replies.length > 0)
    );
  }
 
  private getSortedLanguages(): Language[] {
    if (this.languages.length === 0) return [];
    const [base, ...rest] = this.languages;
    const sorted = [...rest].sort((a, b) => {
      const aTranslated = this.hasTranslation(a.iso);
      const bTranslated = this.hasTranslation(b.iso);
      if (aTranslated !== bTranslated) {
        return aTranslated ? -1 : 1;
      }
      return 0;
    });
    return [base, ...sorted];
  }

  private renderLanguageOption = (option: Language): TemplateResult => {
    const isBase =
      this.languages.length > 0 && option.iso === this.languages[0].iso;

    const badgeBase =
      'display:inline-flex; align-items:center; border-radius:999px; font-size:10px; font-weight:700; line-height:1;';

    let badge: TemplateResult;
    if (isBase) {
      badge = html`<span
        style="${badgeBase} background:rgba(47, 63, 82, 0.12); color:#2f3f52; padding:3px 7px;"
        >Original</span
      >`;
    } else if (this.hasTranslation(option.iso)) {
      badge = html`<span
        style="${badgeBase} background:rgba(26, 127, 55, 0.15); color:#1a7f37; padding:3px 7px;"
        >Translated</span
      >`;
    } else {
      badge = html`<span
        style="${badgeBase} background:transparent; color:#8a94a1; border:1px solid #c2c8d0; padding:2px 6px;"
        >Missing</span
      >`;
    }

    return html`
      <div
        style="display:flex; align-items:center; justify-content:space-between; gap:8px; flex:1; padding:2px 8px;"
      >
        <span>${option.name}</span>
        ${badge}
      </div>
    `;
  };

  public willUpdate(changed: PropertyValues): void {
    super.willUpdate(changed);

    if (changed.has('languages') && this.languages.length > 0) {
      this.currentLanguage = this.languages[0].iso;
    }

    if (changed.has('value')) {
      this.langValues = this.getDeserializedValue() || {};
      this.variables = this.langValues[this.currentLanguage]?.variables || [];
      this.template = this.langValues[this.currentLanguage]?.template || null;
    }
 
    if (changed.has('currentLanguage') && this.langValues) {
      let langValue = {
        text: '',
        attachments: [],
        quick_replies: []
      };
 
      if (this.currentLanguage in this.langValues) {
        langValue = this.langValues[this.currentLanguage];
      }
 
      this.currentText = langValue.text || '';
      this.initialText = langValue.text || '';
      this.currentAttachments = langValue.attachments || [];
      this.currentQuickReplies = (langValue.quick_replies || []).map(
        (value) => {
          return { name: value, value };
        }
      );
      this.currentOptin = langValue['optin'] ? [langValue['optin']] : [];
    }
 
    if (
      this.langValues &&
      (changed.has('currentText') ||
        changed.has('currentAttachments') ||
        changed.has('currentQuickReplies') ||
        changed.has('currentOptin') ||
        changed.has('currentTemplate') ||
        changed.has('variables'))
    ) {
      this.checkIfEmpty();
 
      const trimmed = this.currentText ? this.currentText.trim() : '';
      if (
        trimmed ||
        (this.currentAttachments || []).length > 0 ||
        this.currentQuickReplies.length > 0 ||
        this.currentOptin.length > 0 ||
        this.variables.length > 0
      ) {
        this.langValues[this.currentLanguage] = {
          text: trimmed,
          attachments: this.currentAttachments,
          quick_replies: this.currentQuickReplies.map((option) => option.value),
          optin: this.currentOptin.length > 0 ? this.currentOptin[0] : null,
          template: this.currentTemplate ? this.currentTemplate.uuid : null,
          variables: this.variables,
          locale: this.locale
        };
      } else {
        delete this.langValues[this.currentLanguage];
      }
      this.setValue(this.langValues);
    }
  }
 
  connectedCallback() {
    super.connectedCallback();
    // Make the compose host focusable so clicks on it set activeElement
    if (!this.hasAttribute('tabindex')) {
      this.setAttribute('tabindex', '-1');
    }
    this.addEventListener('keydown', this.handleHostKeyDown as EventListener);
  }
 
  disconnectedCallback() {
    super.disconnectedCallback();
    this.removeEventListener(
      'keydown',
      this.handleHostKeyDown as EventListener
    );
  }
 
  private handleShortcutIconClick() {
    if (this.showShortcuts) {
      this.showShortcuts = false;
      return;
    }
 
    this.shortcutFilter = '';
    this.shortcutViaIcon = true;
    this.showShortcuts = true;
    this.updateComplete.then(() => {
      const shortcuts = this.shadowRoot.querySelector(
        'temba-shortcuts'
      ) as ShortcutList;
      if (shortcuts) {
        shortcuts.filter = '';
        shortcuts.showSearch = true;
        shortcuts.updateComplete.then(() => {
          shortcuts.focusSearch();
        });
      }
    });
  }
 
  private handleHostKeyDown = (evt: KeyboardEvent) => {
    if (evt.key === 'Escape' && this.showShortcuts) {
      evt.preventDefault();
      evt.stopPropagation();
      this.showShortcuts = false;
      return;
    }
 
    if (evt.key === 'Enter' && !evt.shiftKey) {
      if (this.showShortcuts) {
        return;
      }
      const editor = this.getMessageEditor();
      if (editor) {
        const richEdit = editor.getRichEditor();
        if (richEdit && richEdit.hasVisibleOptions()) {
          return;
        }
      }
      evt.preventDefault();
      evt.stopPropagation();
      this.triggerSend();
    }
  };
 
  public firstUpdated(changes: PropertyValues): void {
    super.firstUpdated(changes);
    this.setFocusOnEditor();
  }

  public updated(changes: Map<string, any>): void {
    super.updated(changes);

    if (changes.has('currentLanguage') && this.langValues) {
      this.setFocusOnEditor();

      const editor = this.getMessageEditor();
      if (editor) {
        const richEdit = editor.getRichEditor();
        if (richEdit) {
          const targetText = this.initialText;
          const targetLanguage = this.currentLanguage;
          richEdit.value = targetText;
          const editable = richEdit.inputElement;
          if (editable) {
            window.setTimeout(() => {
              if (this.currentLanguage === targetLanguage) {
                setCaretOffset(editable, targetText.length);
              }
            }, 0);
          }
        }
      }
    }
 
    if (
      (this.langValues &&
        (changes.has('currentText') ||
          changes.has('currentAttachments') ||
          changes.has('currentQuickReplies'))) ||
      changes.has('currentOptin') ||
      changes.has('currentTemplate') ||
      changes.has('variables')
    ) {
      this.fireCustomEvent(CustomEventType.ContentChanged, this.langValues);
    }
  }
 
  private handleLoading(event: CustomEvent) {
    this.uploading = event.detail.loading;
  }
 
  private handleAttachmentsChanged(event: CustomEvent) {
    if (event.detail && event.detail.attachments) {
      this.currentAttachments = event.detail.attachments;
    }
    this.requestUpdate();
  }
 
  private setFocusOnEditor(): void {
    const editor = this.getMessageEditor();
    if (editor) {
      window.setTimeout(() => {
        editor.focus();
      }, 0);
    }
  }
 
  public reset(): void {
    const editor = this.getMessageEditor();
    if (editor) {
      const richEdit = editor.getRichEditor();
      if (richEdit) {
        const textInput = richEdit.getTextInput();
        textInput.updateValue('');
        richEdit.fireEvent('change');
      }
      this.initialText = '';
      this.currentText = '';
      this.currentQuickReplies = [];
      this.currentAttachments = [];
      this.showShortcuts = false;
    }
  }
 
  private handleQuickReplyChange() {
    this.requestUpdate('currentQuickReplies');
  }
 
  private handleOptInChange(event: InputEvent) {
    this.currentOptin = (event.target as any).values;
    this.requestUpdate('currentOptin');
  }
 
  private handleEditorChange(evt: Event) {
    const richEdit = (evt.target as MessageEditor).getRichEditor();
    if (!richEdit) return;
 
    this.currentText = richEdit.value || '';
    this.hasPendingText = this.currentText.length > 0;
 
    // Track caret for shortcut icon click
    this.lastCaretPosition = richEdit.getCaretPosition();
 
    // Detect / at beginning of line for shortcuts
    if (this.shortcuts) {
      const text = this.currentText;
      const cursor = richEdit.getCaretPosition();
      const lineStart = text.lastIndexOf('\n', cursor - 1) + 1;
      const line = text.substring(lineStart, cursor);
 
      if (line.startsWith('/')) {
        if (!this.showShortcuts) {
          this.shortcutViaIcon = false;
        }
        this.shortcutFilter = line.substring(1);
        this.showShortcuts = true;
        this.updateComplete.then(() => {
          const shortcuts = this.shadowRoot.querySelector(
            'temba-shortcuts'
          ) as ShortcutList;
          if (shortcuts) {
            shortcuts.showSearch = false;
            shortcuts.filter = this.shortcutFilter;
          }
        });
      } else {
        this.showShortcuts = false;
      }
    }
  }
 
  public checkIfEmpty() {
    const chatboxEmpty = this.currentText.trim().length === 0;
    const attachmentsEmpty = this.currentAttachments.length === 0;
    if (this.attachments) {
      this.empty = chatboxEmpty && attachmentsEmpty;
    } else {
      this.empty = chatboxEmpty;
    }
  }

  private handleKeyDown(evt: KeyboardEvent) {
    if (evt.key === 'Backspace' && this.shortcuts && this.showShortcuts) {
      // Check if we're deleting the / trigger
      const editor = this.getMessageEditor();
      if (editor) {
        const richEdit = editor.getRichEditor();
        if (richEdit) {
          const text = richEdit.getText();
          const cursor = richEdit.getCaretPosition();
          const lineStart = text.lastIndexOf('\n', cursor - 1) + 1;
          const line = text.substring(lineStart, cursor);
          if (line === '/') {
            this.showShortcuts = false;
          }
        }
      }
    }
  }
 
  public triggerSend() {
    this.checkIfEmpty();
    if (!this.empty) {
      this.fireCustomEvent(CustomEventType.Submitted, {
        langValues: this.langValues
      });
    }
  }

  private handleLanguageChange(evt: Event) {
    const select = evt.target as Select<any>;
    this.currentLanguage = select.values[0].iso;
  }

  private getShortcutOverlayStyle(): string {
    const container = this.shadowRoot?.querySelector('.container');
    if (!container) return '';
    const rect = container.getBoundingClientRect();
    const margin = 16;
    const bottom = window.innerHeight - rect.top;
    const maxHeight = rect.top - margin;
    return `left: ${rect.left}px; bottom: ${bottom}px; width: ${rect.width}px; max-height: ${maxHeight}px;`;
  }
 
  private getMessageEditor(): MessageEditor {
    return this.shadowRoot.querySelector(
      'temba-message-editor'
    ) as MessageEditor;
  }

  public handleShortcutSelection(event: CustomEvent) {
    this.activeShortcut = event.detail.selected;
    const editor = this.getMessageEditor();
    if (!editor) return;

    const richEdit = editor.getRichEditor();
    if (!richEdit) return;

    const text = richEdit.getText();
    const cursor = richEdit.getCaretPosition() || this.lastCaretPosition;

    // Find current line
    const lineStart = text.lastIndexOf('\n', cursor - 1) + 1;
    let lineEnd = text.indexOf('\n', lineStart);
    if (lineEnd === -1) lineEnd = text.length;
    const line = text.substring(lineStart, lineEnd);

    // Build the new text with shortcut replacing the /command line
    let newText: string;
    let newCursor: number;
    if (line.startsWith('/')) {
      const before = text.substring(0, lineStart);
      const after = text.substring(lineEnd);
      newText = before + this.activeShortcut.text + after;
      newCursor = lineStart + this.activeShortcut.text.length;
    } else {
      newText =
        text.substring(0, cursor) +
        this.activeShortcut.text +
        text.substring(cursor);
      newCursor = cursor + this.activeShortcut.text.length;
    }

    // Update the rendered content and fire change so the char counter
    // and form value pick up the new text
    const textInput = richEdit.getTextInput();
    textInput.updateValue(newText);
    richEdit.fireEvent('change');

    // Restore focus and place cursor at end of inserted text
    const editableDiv = richEdit.inputElement;
    if (editableDiv) {
      editableDiv.focus();
      setCaretOffset(editableDiv, newCursor);
    }

    this.showShortcuts = false;
  }

  private handleTemplateChanged(evt: CustomEvent) {
    this.currentTemplate = evt.detail.template;
    this.locale = evt.detail.translation?.locale;
    this.requestUpdate();
  }

  private handleTemplateVariablesChanged(evt: CustomEvent) {
    this.variables = [...evt.detail.variables];
  }

  public render(): TemplateResult {
    return this.renderField();
  }

  protected renderWidget(): TemplateResult {
    const showOptins = this.optIns && this.isBaseLanguage();
    const showTemplates = this.templates && this.isBaseLanguage();
    const hasAccordionSections =
      this.quickReplies || showOptins || showTemplates;

    return html`
      <div>
        ${this.languages.length > 1
          ? html`<temba-select
              @change=${this.handleLanguageChange}
              class="language"
              name="language"
              .staticOptions=${this.getSortedLanguages()}
              .renderOption=${this.renderLanguageOption}
              valueKey="iso"
            >
            </temba-select>`
          : null}
        <div class="container">
          <div class="editor-wrapper">
            <temba-message-editor
              .value=${this.initialText}
              .attachments=${this.currentAttachments}
              attachment-format="object"
              accept=${this.accept}
              max-attachments=${this.maxAttachments}
              endpoint=${this.endpoint}
              placeholder="Write something here"
              gsm
              textarea
              minHeight=${this.minHeight}
              ?autogrow=${this.autogrow}
              ?disableCompletion=${!this.completion}
              counter=${this.counter ? 'true' : nothing}
              @change=${this.handleEditorChange}
              @keydown=${this.handleKeyDown}
              @temba-content-changed=${this.handleAttachmentsChanged}
              @loading=${this.handleLoading}
            >
              ${this.shortcuts
                ? html`<temba-icon
                    slot="icons"
                    class="shortcut-icon"
                    name=${Icon.shortcut}
                    size="1"
                    @click=${this.handleShortcutIconClick}
                  ></temba-icon>`
                : null}
            </temba-message-editor>
          </div>
 
          ${this.shortcuts && this.showShortcuts
            ? html`<div
                class="shortcut-overlay"
                style=${this.getShortcutOverlayStyle()}
                @mousedown=${(e: MouseEvent) => e.preventDefault()}
              >
                <temba-shortcuts
                  @temba-selection=${this.handleShortcutSelection}
                ></temba-shortcuts>
              </div>`
            : null}
        </div>
        ${hasAccordionSections
          ? html`<temba-accordion>
              ${this.quickReplies
                ? html`<temba-accordion-section
                    label="Quick Replies"
                    .count=${this.currentQuickReplies.length}
                  >
                    <temba-select
                      @change=${this.handleQuickReplyChange}
                      .values=${this.currentQuickReplies}
                      maxItems=${this.maxQuickReplies}
                      maxItemsText="You can only add ${this
                        .maxQuickReplies} Quick Replies"
                      class="quick-replies"
                      tags
                      multi
                      searchable
                      expressions
                      placeholder="Add Quick Reply"
                    ></temba-select>
                  </temba-accordion-section>`
                : null}
              ${showTemplates
                ? html`<temba-accordion-section
                    label="WhatsApp Template"
                    ?checked=${!!this.currentTemplate}
                    ?hasError=${this.errors &&
                    !!this.errors.find((error) => error.includes('template'))}
                  >
                    <temba-template-editor
                      class="templates"
                      ?session=${this.templateSession}
                      @temba-context-changed=${this.handleTemplateChanged}
                      @temba-content-changed=${this
                        .handleTemplateVariablesChanged}
                      template=${this.template}
                      variables=${JSON.stringify(this.variables)}
                      url=${this.templateEndpoint}
                      lang=${this.currentLanguage}
                      template-warning=${this.templateWarning || nothing}
                    >
                    </temba-template-editor>
                  </temba-accordion-section>`
                : null}
              ${showOptins
                ? html`<temba-accordion-section
                    label="Facebook Opt-in"
                    ?checked=${this.currentOptin.length > 0}
                  >
                    <temba-select
                      @change=${this.handleOptInChange}
                      .values=${this.currentOptin}
                      endpoint="${this.optinEndpoint}"
                      valueKey="uuid"
                      class="optins"
                      searchable
                      clearable
                      placeholder="Select an opt-in to use for Facebook (optional)"
                    ></temba-select>
                  </temba-accordion-section>`
                : null}
            </temba-accordion>`
          : null}
      </div>
    `;
  }
}