all files / rich-text-editor/renderer/ ai-assistant.js

96.84% Statements 460/475
87.37% Branches 173/198
95.24% Functions 60/63
96.84% Lines 460/475
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   2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746×   2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746× 2746×   918× 918×     52× 52×   39× 39× 39× 39×     38× 38×   39× 39×   13×     14× 14× 14×       14×   14× 14×   14× 14× 13×       53× 53× 13×     13×     54× 54×   53× 53× 52× 36×     16×           56× 56× 56×   56× 56× 56×                 56× 56× 56× 56× 56×   56× 56×                   11×             11×                                                                                 56× 56×   18× 18× 18× 18×                 11×     11×         18×   18× 18× 18× 18× 18× 17× 17×   14×     11×         18× 18×               18× 18×     17×       11× 11× 11× 11× 11×     32×   56× 48×   11× 11× 11× 10×   11×       93× 93× 15×             15× 15× 15× 15× 15× 15× 15× 15× 15× 15× 15×       16×       16× 13×       613× 613×     62201×   2745× 2745× 2745× 2745× 2745× 2745× 2745× 2745× 2745× 2745× 2745× 2745× 2745× 2745×   1301×   12× 12× 12× 12× 12× 12×     5466× 2721×   2745× 2745× 56× 56× 55×   56× 56× 56× 56× 56× 56× 56×   2745× 2745× 2745×           22× 11× 11× 11× 11× 11×     11×                 57× 57× 56× 56× 56× 56×               56× 56×       57× 57×   57× 57× 57× 57× 57× 57×             57× 56× 56× 56×           57× 57× 57× 57× 57× 57×                             57× 57× 57× 57× 57×   56× 56× 56× 56× 56× 56× 56× 56× 56× 56×                 56× 56×   56× 55× 55×       56×       168× 168× 440× 440× 438× 438×   112× 112×   112× 112×   214× 214×   438×         168×   112× 112×   56× 56×   55× 55×     112×   112× 112×   56× 56×   56× 56×   112×   214× 214×   52× 52×   54× 54×   54× 54×   54× 54×   214×   69× 69×     69× 64× 64×     56×                                       69×   225× 286× 286×                             58× 58× 55× 55×       56×                 56×   40× 40× 40× 40× 40×   2746×                         24× 24×     24×           24×   14× 14×     14×           14×   110× 110× 109× 71×             2762×   2762×     57× 57× 57×        
define(["require", "exports", "../base/constant", "../base/classes", "@syncfusion/ej2-popups", "@syncfusion/ej2-interactive-chat", "@syncfusion/ej2-base", "../../selection/selection", "../base", "@syncfusion/ej2-splitbuttons", "../../editor-manager/plugin/ai-assitant-actions", "@syncfusion/ej2-markdown-converter"], function (require, exports, events, classes, ej2_popups_1, ej2_interactive_chat_1, ej2_base_1, selection_1, base_1, ej2_splitbuttons_1, ai_assitant_actions_1, ej2_markdown_converter_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var AIAssistant = (function () {
        function AIAssistant(parent, serviceLocator) {
            this.parent = parent;
            this.locator = serviceLocator;
            this.rendererFactory = this.locator.getService('rendererFactory');
            this.L10n = serviceLocator.getService('rteLocale');
            this.isDestroyed = false;
            this.lastResponse = '';
            this.isRendered = false;
            this.allPrompts = [];
            this.currentSelection = new selection_1.NodeSelection(this.parent.inputElement);
            this.handlePopupEscapeBoundFn = this.handlePopupEscape.bind(this);
            this.addEventListener();
        }
        AIAssistant.prototype.addEventListener = function () {
            this.parent.on(events.onAIAssistant, this.onToolbarClick, this);
            this.parent.on(events.menuItemselected, this.onMenuItemSelect, this);
            this.parent.on(events.menuBeforeOpen, this.beforeMenuOpen, this);
            this.parent.on(events.menuBeforeClose, this.beforeMenuClose, this);
            this.parent.on(events.editAreaClick, this.updateCurrentSelection, this);
            this.parent.on(events.destroy, this.destroy, this);
            this.parent.on(events.windowResize, this.refreshPosition, this);
            this.parent.on(events.scroll, this.refreshPosition, this);
            this.parent.on(events.keyDown, this.onKeyDown, this);
            this.parent.on(events.afterKeyDown, this.refreshPosition, this);
            this.parent.on(events.contentscroll, this.refreshPosition, this);
            this.parent.on(events.modelChanged, this.onPropertyChanged, this);
            this.parent.on(events.bindOnEnd, this.bindOnEnd, this);
            this.parent.on(events.bindCssClass, this.updateCssClass, this);
            this.parent.on(events.hidePopup, this.hideAIQueryPopup, this);
        };
        AIAssistant.prototype.onKeyDown = function (event) {
            var originalEvent = event.args;
            if (!ej2_base_1.isNullOrUndefined(originalEvent) && !ej2_base_1.isNullOrUndefined(originalEvent.action) && (originalEvent.action === 'ai-query')) {
                originalEvent.preventDefault();
                this.showAIQueryPopup(event.args);
                this.setEditAreaRangeAndFocus();
            }
        };
        AIAssistant.prototype.onToolbarClick = function (notifyArgs) {
            var command = notifyArgs.args.item.subCommand;
            switch (command) {
                case 'AIQuery':
                    this.currentAction = 'Toolbar';
                    this.currentSelection = notifyArgs.selection;
                    this.currentSelection.restore();
                    if (document.body.contains(this.element)) {
                        this.hideAIQueryPopup();
                    }
                    else {
                        this.showAIQueryPopup(notifyArgs.args.originalEvent);
                        this.setEditAreaRangeAndFocus();
                    }
                    this.updateAIQueryButtonActiveState();
                    break;
                case 'AICommands':
                    break;
            }
        };
        AIAssistant.prototype.onMenuItemSelect = function (args) {
            Eif (args.element.closest('.e-rte-aicommands-menu') && args.item.id !== 'aicommands' && !ej2_base_1.isNullOrUndefined(args.item.prompt)) {
                this.currentAction = 'Menu';
                Iif (this.parent.userAgentData.getBrowser() === 'Safari') {
                    this.currentSelection = this.parent.htmlEditorModule.saveSelection;
                }
                else {
                    this.updateCurrentSelection();
                }
                var isQuickToolbarOpen = this.parent.element.querySelectorAll('.e-rte-quick-popup.e-popup-open').length > 0;
                if (isQuickToolbarOpen) {
                    this.parent.quickToolbarModule.hideQuickToolbars();
                }
                var isNotFromToolbar = args.element.closest('#' + this.parent.getID() + '_QueryPopupCommandsMenu');
                if (ej2_base_1.isNullOrUndefined(isNotFromToolbar)) {
                    this.showAIQueryPopup(args.event, args.item.prompt);
                }
            }
        };
        AIAssistant.prototype.showAIQueryPopup = function (event, prompt) {
            this.showQueryPopup(event);
            if (!ej2_base_1.isNullOrUndefined(prompt)) {
                Iif (this.currentAction === 'Toolbar') {
                    this.currentSelection.restore();
                }
                this.assistView.executePrompt(prompt);
            }
        };
        AIAssistant.prototype.updateAIQueryButtonActiveState = function () {
            var toolbarItem = this.parent.getToolbarElement();
            if (ej2_base_1.isNullOrUndefined(toolbarItem)) {
                return;
            }
            var aiQueryButton = toolbarItem.querySelector('.e-magic-wand');
            if (!ej2_base_1.isNullOrUndefined(aiQueryButton) && !ej2_base_1.isNullOrUndefined(aiQueryButton.parentElement) && !ej2_base_1.isNullOrUndefined(aiQueryButton.parentElement.parentElement)) {
                if (document.body.contains(this.element)) {
                    aiQueryButton.parentElement.parentElement.classList.add('e-active');
                }
                else {
                    aiQueryButton.parentElement.parentElement.classList.remove('e-active');
                }
            }
            else {
                return;
            }
        };
        AIAssistant.prototype.render = function () {
            var popupRoot = this.parent.createElement('div', { id: this.parent.getID() + '_RTE_Smart_AI_Query_Popup', className: classes.CLS_RTE_ELEMENTS + ' e-rte-aiquery-popup e-popup-close ' + this.parent.getCssClass() });
            Eif (this.parent.aiAssistantSettings.popupMaxHeight !== 'auto') {
                popupRoot.style.maxHeight = ej2_base_1.formatUnit(this.parent.aiAssistantSettings.popupMaxHeight);
            }
            var contentWrapper = this.parent.createElement('div', { className: 'e-rte-ai-assit-content-container' });
            var assistViewRoot = this.parent.createElement('div', { id: this.parent.getID() + '_RTE_Smart_AI_Query_AssistView' });
            var queryPopup = new ej2_popups_1.Popup(null, {
                width: this.parent.userAgentData.isMobileDevice() ? '100%' : this.parent.aiAssistantSettings.popupWidth,
                position: this.parent.userAgentData.isMobileDevice() ? { X: 0, Y: 0 } : { X: 'right', Y: 'top' },
                enableRtl: this.parent.enableRtl,
                offsetX: -10,
                relateTo: this.parent.element,
                actionOnScroll: 'none',
                content: contentWrapper
            });
            contentWrapper.appendChild(assistViewRoot);
            this.renderAssistView(assistViewRoot);
            this.queryPopup = queryPopup;
            this.element = popupRoot;
            this.renderTooltip();
        };
        AIAssistant.prototype.renderAssistView = function (assistViewRoot) {
            var _this = this;
            this.assistView = new ej2_interactive_chat_1.AIAssistView({
                views: [
                    {
                        name: this.L10n.getConstant('aiAssistantName')
                    }
                ],
                promptRequest: this.onPromptRequest.bind(this),
                responseToolbarSettings: {
                    items: this.getToolbarItems(this.parent.aiAssistantSettings.responseToolbarSettings, 'Response'),
                    itemClicked: function (args) {
                        var eventArgs = {
                            requestType: 'Response',
                            originalEvent: args.event,
                            item: args.item,
                            dataIndex: args.dataIndex,
                            cancel: args.cancel
                        };
                        _this.onAssitantToolbarClick(eventArgs);
                    }
                },
                promptToolbarSettings: {
                    items: this.getToolbarItems(this.parent.aiAssistantSettings.promptToolbarSettings, 'Prompt'),
                    itemClicked: function (args) {
                        var eventArgs = {
                            requestType: 'Prompt',
                            originalEvent: args.event,
                            item: args.item,
                            dataIndex: args.dataIndex,
                            cancel: args.cancel
                        };
                        _this.onAssitantToolbarClick(eventArgs);
                    }
                },
                prompts: this.parsePromptResponses(this.parent.aiAssistantSettings.prompts),
                promptPlaceholder: this.parent.aiAssistantSettings.placeholder,
                promptSuggestions: this.parent.aiAssistantSettings.suggestions,
                bannerTemplate: this.parent.aiAssistantSettings.bannerTemplate,
                stopRespondingClick: this.handleStopResponse.bind(this),
                toolbarSettings: {
                    items: this.getToolbarItems(this.parent.aiAssistantSettings.headerToolbarSettings, 'Header'),
                    itemClicked: function (args) {
                        var eventArgs = {
                            requestType: 'Header',
                            originalEvent: args.event,
                            item: args.item,
                            dataIndex: args.dataIndex,
                            cancel: args.cancel
                        };
                        _this.onAssitantToolbarClick(eventArgs);
                    }
                },
                footerToolbarSettings: {
                    items: [
                        { iconCss: 'e-icons e-history', tooltip: this.L10n.getConstant('aiAssistantHistoryButton'), align: 'Right', disabled: true }
                    ],
                    itemClick: function (args) {
                        args.requestType = 'Footer';
                        _this.onAssitantToolbarClick(args);
                    }
                },
                showClearButton: true,
                enablePersistence: this.parent.enablePersistence,
                cssClass: this.parent.getCssClass()
            });
            this.assistView.appendTo(assistViewRoot);
            this.assistViewEditArea = this.assistView.element.querySelector('.e-assist-textarea');
        };
        AIAssistant.prototype.onAssitantToolbarClick = function (args) {
            var _this = this;
            this.parent.trigger('aiAssistantToolbarClick', args, function (toolbarClickArgs) {
                Eif (!toolbarClickArgs.cancel) {
                    switch (toolbarClickArgs.requestType) {
                        case 'Header': {
                            if (toolbarClickArgs.item.iconCss === 'e-icons e-close') {
                                _this.hideAIQueryPopup();
                                args.cancel = true;
                            }
                            if (toolbarClickArgs.item.iconCss === 'e-icons e-trash') {
                                _this.addEditorPromptCollection(_this.assistView.prompts);
                                _this.assistView.prompts = [];
                                _this.assistView.dataBind();
                                _this.updateHistoryButtonStatus();
                                args.cancel = true;
                            }
                            break;
                        }
                        case 'Prompt':
                            break;
                        case 'Footer':
                            if (toolbarClickArgs.item.iconCss === 'e-icons e-history') {
                                _this.handleHistoryButtonClick();
                            }
                            break;
                        case 'Response':
                            if (toolbarClickArgs.item.iconCss === 'e-icons e-check') {
                                var response = _this.assistView.prompts[args.dataIndex].response;
                                _this.hideAIQueryPopup();
                                _this.handleInsertContent(response);
                                args.cancel = true;
                            }
                            else if (toolbarClickArgs.item.iconCss === 'e-icons e-repeat') {
                                _this.assistView.executePrompt(_this.assistView.prompts[args.dataIndex].prompt);
                            }
                            break;
                    }
                }
            });
        };
        AIAssistant.prototype.onPromptRequest = function (args) {
            if (this.currentAction === 'Toolbar' || this.parent.userAgentData.getBrowser() === 'Safari') {
                this.currentSelection.restore();
            }
            this.blockNodes = this.parent.formatter.editorManager.domNode.blockNodes();
            this.queryPopup.element.classList.add('processing');
            var range = this.parent.getRange();
            var htmlString;
            if (this.assistView.prompts.length === 1) {
                this.isProcessWholeEditorContent = false;
                if (!this.parent.isRTEFocused) {
                    htmlString = this.parent.getHtml();
                    this.isProcessWholeEditorContent = true;
                }
                else if (range.collapsed && this.blockNodes.length > 0) {
                    htmlString = this.blockNodes[0].outerHTML;
                }
                else {
                    htmlString = this.parent.getSelectedHtml();
                }
            }
            else {
                var length_1 = this.assistView.prompts.length;
                htmlString = this.assistView.prompts[length_1 - 2].response;
            }
            var textContent = this.parent.createElement('div', { innerHTML: htmlString }).textContent;
            var promptEventArgs = {
                html: htmlString,
                text: textContent,
                cancel: args.cancel,
                responseToolbarItems: args.responseToolbarItems,
                prompt: args.prompt,
                promptSuggestions: args.promptSuggestions
            };
            this.parent.trigger('aiAssistantPromptRequest', promptEventArgs, function (eventArgs) {
                if (eventArgs.cancel) {
                    args.cancel = true;
                }
                else {
                    args.cancel = false;
                }
            });
        };
        AIAssistant.prototype.streamResponse = function (response, isFinalUpdate) {
            this.lastResponse = response;
            var htmlResponse = this.parseMarkdown(this.lastResponse);
            this.assistView.addPromptResponse(htmlResponse, isFinalUpdate);
            this.assistView.scrollToBottom();
            setTimeout(function () {
            }, this.parent.element.dataset.rteUnitTesting === 'true' ? 0 : 50);
        };
        AIAssistant.prototype.parseMarkdown = function (text) {
            return ej2_markdown_converter_1.MarkdownConverter.toHtml(text);
        };
        AIAssistant.prototype.parsePromptResponses = function (prompts) {
            if (!prompts || prompts.length === 0) {
                return prompts;
            }
            var parsedPrompts = [];
            for (var i = 0; i < prompts.length; i++) {
                var prompt_1 = prompts[i];
                var newPrompt = ej2_base_1.extend(null, prompt_1, null, true);
                if (newPrompt.response) {
                    newPrompt.response = this.parseMarkdown(newPrompt.response);
                }
                parsedPrompts.push(newPrompt);
            }
            return parsedPrompts;
        };
        AIAssistant.prototype.handleStopResponse = function (args) {
            this.parent.trigger('aiAssistantStopRespondingClick', args);
            this.lastResponse = '';
            this.queryPopup.element.classList.remove('processing');
        };
        AIAssistant.prototype.hideAIQueryPopup = function () {
            var _this = this;
            if (!ej2_base_1.isNullOrUndefined(this.queryPopup) && !ej2_base_1.isNullOrUndefined(this.queryPopup.element) && this.queryPopup.element.classList.contains('e-popup-open')) {
                var eventArgs = {
                    cancel: false,
                    popup: this.queryPopup,
                    element: this.queryPopup.element,
                    type: 'AIAssistant',
                    originalEvent: !ej2_base_1.isNullOrUndefined(event) ? event : undefined
                };
                this.triggerBeforePopupOpenCloseEvent('beforePopupClose', eventArgs, eventArgs, function () {
                    _this.historyDropDownButton.destroy();
                    _this.menu.destroy();
                    _this.menuDropDown.destroy();
                    _this.addEditorPromptCollection(_this.assistView.prompts);
                    _this.assistView.prompts = [];
                    _this.assistView.dataBind();
                    _this.toolTip.close();
                    _this.queryPopup.hide();
                    _this.element = ej2_base_1.detach(_this.element);
                    _this.updateAIQueryButtonActiveState();
                });
            }
        };
        AIAssistant.prototype.addEditorPromptCollection = function (prompts) {
            Iif (this.allPrompts.length > this.parent.aiAssistantSettings.maxPromptHistory) {
                var itemsToRemove = this.allPrompts.length - this.parent.aiAssistantSettings.maxPromptHistory;
                this.allPrompts.splice(0, itemsToRemove);
            }
            for (var i = 0; i < prompts.length; i++) {
                this.allPrompts.push(prompts[i]);
            }
        };
        AIAssistant.prototype.clearAIPromptHistory = function () {
            this.allPrompts = [];
        };
        AIAssistant.prototype.updateCurrentSelection = function () {
            Eif (!ej2_base_1.isNullOrUndefined(this.currentSelection)) {
                this.currentSelection = this.currentSelection.save(this.parent.getRange(), this.parent.inputElement.ownerDocument);
            }
        };
        AIAssistant.prototype.getModuleName = function () {
            return 'aiAssistant';
        };
        AIAssistant.prototype.removeEventListener = function () {
            this.parent.off(events.onAIAssistant, this.onToolbarClick);
            this.parent.off(events.menuItemselected, this.onMenuItemSelect);
            this.parent.off(events.menuBeforeOpen, this.beforeMenuOpen);
            this.parent.off(events.menuBeforeClose, this.beforeMenuClose);
            this.parent.off(events.editAreaClick, this.updateCurrentSelection);
            this.parent.off(events.destroy, this.destroy);
            this.parent.off(events.windowResize, this.refreshPosition);
            this.parent.off(events.scroll, this.refreshPosition);
            this.parent.off(events.contentscroll, this.refreshPosition);
            this.parent.off(events.afterKeyDown, this.refreshPosition);
            this.parent.off(events.modelChanged, this.onPropertyChanged);
            this.parent.off(events.bindOnEnd, this.bindOnEnd);
            this.parent.off(events.bindCssClass, this.updateCssClass);
            this.parent.off(events.hidePopup, this.hideAIQueryPopup);
        };
        AIAssistant.prototype.refreshPosition = function () {
            if (!this.dragged && this.queryPopup && !this.queryPopup.isDestroyed && this.queryPopup.element &&
                this.queryPopup.element.classList.contains('e-popup-open')) {
                this.queryPopup.setProperties({ offsetY: this.getQueryPopupOffsetY() });
                this.queryPopup.dataBind();
                this.queryPopup.refreshPosition();
                var footer = this.assistView.element.querySelector('.e-footer');
                this.historyDropDownButton.setProperties({ popupWidth: footer.getBoundingClientRect().width });
                this.historyDropDownButton.dataBind();
            }
        };
        AIAssistant.prototype.destroy = function () {
            if (this.isDestroyed) {
                return;
            }
            this.removeEventListener();
            if (this.isRendered) {
                this.draggable.destroy();
                if (!ej2_base_1.isNullOrUndefined(this.historyDropDownButton)) {
                    this.historyDropDownButton.destroy();
                }
                this.menu.destroy();
                this.menuDropDown.destroy();
                this.queryPopup.destroy();
                this.toolTip.destroy();
                this.assistView.destroy();
                document.removeEventListener('keydown', this.handlePopupEscapeBoundFn);
                ej2_base_1.detach(this.element);
            }
            this.allPrompts = [];
            this.isDestroyed = true;
            this.isRendered = false;
        };
        AIAssistant.prototype.getPromptHistory = function () {
            return this.allPrompts;
        };
        AIAssistant.prototype.executePrompt = function (prompt) {
            this.assistView.executePrompt(prompt);
        };
        AIAssistant.prototype.scrollToBottom = function () {
            this.assistView.scrollToBottom();
        };
        AIAssistant.prototype.addPromptResponse = function (outputResponse, isFinalUpdate) {
            if (isFinalUpdate) {
                var htmlResponse = this.parseMarkdown(this.lastResponse);
                this.assistView.addPromptResponse(htmlResponse, true);
                this.assistView.scrollToBottom();
                this.lastResponse = '';
                this.queryPopup.element.classList.remove('processing');
            }
            else {
                this.streamResponse(outputResponse, isFinalUpdate);
            }
        };
        AIAssistant.prototype.updateHistoryButtonStatus = function () {
            var items = this.getHistoryDropDownItem();
            this.historyDropDownButton.items = this.getHistoryDropDownItem();
            this.historyDropDownButton.disabled = items.length === 1 && items[0].text === 'No Prompts found' ? true : false;
            this.historyDropDownButton.dataBind();
            Iif (this.historyDropDownButton.disabled) {
                this.historyIconButton.classList.add('e-rte-icon-btn-disabled');
                this.enableDisableHistoryToolbarButton(true);
            }
            else {
                this.historyIconButton.classList.remove('e-rte-icon-btn-disabled');
                this.enableDisableHistoryToolbarButton(false);
            }
        };
        AIAssistant.prototype.showQueryPopup = function (event) {
            var _this = this;
            if (!this.isRendered) {
                this.render();
                document.body.appendChild(this.element);
                this.queryPopup.appendTo(this.element);
                this.draggable = new ej2_base_1.Draggable(this.queryPopup.element, {
                    clone: false,
                    isDragScroll: false,
                    handle: '.e-rte-aiquery-popup .e-view-header .e-toolbar-items .e-toolbar-item button',
                    dragStop: function () {
                        _this.dragged = true;
                    }
                });
                document.addEventListener('keydown', this.handlePopupEscapeBoundFn);
                this.isRendered = true;
            }
            else {
                document.body.appendChild(this.element);
            }
            Eif (this.parent.quickToolbarModule) {
                this.parent.quickToolbarModule.hideQuickToolbars();
            }
            this.renderMenuButton();
            this.dragged = false;
            Eif (!ej2_base_1.isNullOrUndefined(this.queryPopup) && this.queryPopup.element.classList.contains('e-popup-close')) {
                this.queryPopup.setProperties({ offsetY: this.getQueryPopupOffsetY() });
                this.queryPopup.dataBind();
                var eventArgs = {
                    cancel: false,
                    popup: this.queryPopup,
                    element: this.queryPopup.element,
                    type: 'AIAssistant',
                    originalEvent: !ej2_base_1.isNullOrUndefined(event) ? event : undefined
                };
                this.triggerBeforePopupOpenCloseEvent('beforePopupOpen', eventArgs, eventArgs, function () {
                    _this.queryPopup.show();
                    _this.queryPopup.refreshPosition();
                    _this.renderHistoryDropDownButton();
                });
            }
        };
        AIAssistant.prototype.handlePopupEscape = function (args) {
            if (args.key === 'Escape') {
                this.hideAIQueryPopup();
            }
        };
        AIAssistant.prototype.renderMenuButton = function () {
            var toolbar = this.assistView.element.querySelector('.e-view-header .e-toolbar');
            var menuName = 'aicommands';
            var rootElement = ej2_base_1.select('#' + this.parent.getID() + '_QueryPopupCommandsDropDown', toolbar);
            var ulElement = this.parent.createElement('ul', { id: this.parent.getID() + '_QueryPopupCommandsMenu' });
            rootElement.parentElement.appendChild(ulElement);
            var argument = {
                dropDownItems: {
                    content: 'AI Commands',
                    cssClass: classes.CLS_DROPDOWN_POPUP + ' ' + classes.CLS_DROPDOWN_ITEMS + ' ' + classes.CLS_AI_COMMANDS_TBAR_BTN + ' ' + classes.CLS_DROPDOWN_MENU,
                    target: ulElement
                },
                menuItems: {
                    items: this.parent.aiAssistantSettings.commands
                },
                name: menuName,
                containerType: 'Toolbar',
                toolbarElement: toolbar,
                dropDownRoot: rootElement,
                menuRoot: ulElement
            };
            var _a = this.rendererFactory.getRenderer(base_1.RenderType.Toolbar).renderMenu(argument), menu = _a.menu, dropDownButton = _a.dropDownButton;
            this.menu = menu;
            this.menuDropDown = dropDownButton;
            dropDownButton.iconCss = 'e-settings e-icons';
            dropDownButton.setProperties({ iconCss: 'e-settings e-icons', content: '' });
        };
        AIAssistant.prototype.renderHistoryDropDownButton = function () {
            var _this = this;
            var footer = this.assistView.element.querySelector('.e-footer');
            this.historyIconButton = footer.querySelector('.e-icons.e-history');
            var dropdownMenuRoot = this.parent.createElement('div', { id: this.assistView.element.id + '_DropDown_Menu' });
            dropdownMenuRoot.style.visibility = 'hidden';
            dropdownMenuRoot.style.padding = '0';
            dropdownMenuRoot.style.border = '0';
            footer.appendChild(dropdownMenuRoot);
            var items = this.getHistoryDropDownItem();
            var dropDownButton = new ej2_splitbuttons_1.DropDownButton({
                cssClass: 'e-caret-hide e-rte-ai-assist-history',
                disabled: items.length === 1 && items[0].text === 'No Prompts found.' ? true : false,
                popupWidth: footer.getBoundingClientRect().width,
                items: items,
                select: function (args) {
                    _this.assistView.prompt = args.item.text;
                }
            }, dropdownMenuRoot);
            Eif (this.parent.element.dataset.rteUnitTesting === 'true') {
                dropDownButton.animationSettings = { effect: 'None', duration: 0 };
            }
            if (items.length === 1 && items[0].text === 'No Prompts found.') {
                this.historyIconButton.classList.add('e-rte-icon-btn-disabled');
                this.enableDisableHistoryToolbarButton(true);
            }
            else {
                this.historyIconButton.classList.remove('e-rte-icon-btn-disabled');
                this.enableDisableHistoryToolbarButton(false);
            }
            this.historyDropDownButton = dropDownButton;
        };
        AIAssistant.prototype.handleHistoryButtonClick = function () {
            Eif (!this.historyIconButton.classList.contains('e-rte-icon-btn-disabled')) {
                this.historyDropDownButton.toggle();
            }
        };
        AIAssistant.prototype.getToolbarItems = function (items, type) {
            var finalITems = [];
            for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
                var item = items_1[_i];
                if (typeof item === 'string') {
                    var defaultItem = void 0;
                    switch (type) {
                        case 'Header':
                            defaultItem = this.getHeaderToolbarItem(item);
                            break;
                        case 'Prompt':
                            defaultItem = this.getPromptToolbarItem(item);
                            break;
                        case 'Response':
                            defaultItem = this.getReponseToolbarItem(item);
                            break;
                    }
                    finalITems.push(defaultItem);
                }
                else {
                    finalITems.push(item);
                }
            }
            return finalITems;
        };
        AIAssistant.prototype.getHeaderToolbarItem = function (item) {
            var value;
            switch (item) {
                case 'AIcommands':
                    value = { iconCss: 'e-icons e-ai-chat', align: 'Right', tooltip: this.L10n.getConstant('aicommands'), command: 'Header', subCommand: 'Close', template: "<button id=\"" + this.parent.getID() + "_QueryPopupCommandsDropDown\" tabindex=\"0\" data-tabindex=\"-1\"></button>" };
                    break;
                case 'Close':
                    value = { iconCss: 'e-icons e-close', align: 'Right', tooltip: this.L10n.getConstant('aiAssistantToolbarItemClose'), command: 'Header', subCommand: 'Close' };
                    break;
                case 'Clear':
                    value = { iconCss: 'e-icons e-trash', align: 'Right', tooltip: this.L10n.getConstant('aiAssistantToolbarItemClear'), command: 'Header', subCommand: 'Clear' };
                    break;
            }
            return value;
        };
        AIAssistant.prototype.getPromptToolbarItem = function (item) {
            var value;
            switch (item) {
                case 'Copy':
                    value = { iconCss: 'e-icons e-assist-copy', tooltip: this.L10n.getConstant('aiAssistantToolbarItemCopy'), command: 'Prompt', subCommand: 'Copy' };
                    break;
                case 'Edit':
                    value = { iconCss: 'e-icons e-assist-edit', tooltip: this.L10n.getConstant('aiAssistantToolbarItemEdit'), command: 'Prompt', subCommand: 'Edit' };
                    break;
            }
            return value;
        };
        AIAssistant.prototype.getReponseToolbarItem = function (item) {
            var value;
            switch (item) {
                case '|':
                    value = { type: 'Separator', command: 'Response', subCommand: 'Separator' };
                    break;
                case 'Copy':
                    value = { iconCss: 'e-icons e-assist-copy', tooltip: this.L10n.getConstant('aiAssistantToolbarItemCopy'), command: 'Response', subCommand: 'Copy' };
                    break;
                case 'Insert':
                    value = { iconCss: 'e-icons e-check', text: 'Insert', tooltip: this.L10n.getConstant('aiAssistantToolbarItemInsert'), command: 'Response', subCommand: 'Insert' };
                    break;
                case 'Regenerate':
                    value = { iconCss: 'e-icons e-repeat', tooltip: this.L10n.getConstant('aiAssistantToolbarItemRegenerate'), command: 'Response', subCommand: 'Regenerate' };
                    break;
            }
            return value;
        };
        AIAssistant.prototype.getQueryPopupOffsetY = function () {
            var offsetY = 0;
            Iif (this.parent.userAgentData.isMobileDevice()) {
                return offsetY;
            }
            if (this.parent.toolbarSettings.enableFloating && this.parent.toolbarSettings.position === 'Top' && !this.parent.inlineMode.enable) {
                var toolbarElemRect = this.parent.getToolbarElement().getBoundingClientRect();
                if (toolbarElemRect.top === 0) {
                    offsetY = window.pageYOffset - this.parent.element.offsetTop + toolbarElemRect.height + 11;
                }
                else {
                    offsetY = toolbarElemRect.height + 11;
                }
            }
            else {
                var inputElementRect = this.parent.iframeSettings.enable ?
                    this.parent.contentModule.getPanel().getBoundingClientRect() :
                    this.parent.inputElement.getBoundingClientRect();
                Iif (this.parent.toolbarSettings.position === 'Bottom' && !this.parent.inlineMode.enable) {
                    if (inputElementRect.top <= 0) {
                        offsetY = window.pageYOffset - this.parent.element.offsetTop + 11;
                    }
                    else {
                        offsetY = 10;
                    }
                }
                else {
                    if (!this.parent.inlineMode.enable) {
                        var toolbarElemRect = this.parent.getToolbarElement().getBoundingClientRect();
                        if (toolbarElemRect.top < 0) {
                            offsetY = window.pageYOffset - this.parent.element.offsetTop + 10;
                        }
                        else {
                            offsetY = toolbarElemRect.height + 11;
                        }
                    }
                }
            }
            return offsetY;
        };
        AIAssistant.prototype.onPropertyChanged = function (e) {
            for (var _i = 0, _a = Object.keys(e.newProp); _i < _a.length; _i++) {
                var prop = _a[_i];
                switch (prop) {
                    case 'aiAssistantSettings': {
                        switch (Object.keys(e.newProp.aiAssistantSettings)[0]) {
                            case 'popupMaxHeight':
                                this.queryPopup.element.style.maxHeight = ej2_base_1.formatUnit(this.parent.aiAssistantSettings.popupMaxHeight);
                                break;
                            case 'popupWidth':
                                this.queryPopup.width = e.newProp.aiAssistantSettings.popupWidth;
                                break;
                            case 'placeholder':
                                this.assistView.promptPlaceholder = e.newProp.aiAssistantSettings.placeholder;
                                this.assistView.dataBind();
                                break;
                            case 'prompts':
                                this.assistView.prompts = e.newProp.aiAssistantSettings.prompts;
                                this.assistView.dataBind();
                                break;
                            case 'suggestions':
                                this.assistView.promptSuggestions = e.newProp.aiAssistantSettings.suggestions;
                                this.assistView.dataBind();
                                break;
                            case 'bannerTemplate':
                                this.assistView.bannerTemplate = e.newProp.aiAssistantSettings.bannerTemplate;
                                this.assistView.dataBind();
                                break;
                        }
                        break;
                    }
                    case 'enablePersistence':
                        if (this.assistView) {
                            this.assistView.enablePersistence = e.newProp.enablePersistence;
                            this.assistView.dataBind();
                        }
                        break;
                }
            }
        };
        AIAssistant.prototype.getHistoryDropDownItem = function () {
            var finalItems = [];
            if (this.allPrompts.length === 0) {
                finalItems.push({ text: 'No Prompts found.' });
                return finalItems;
            }
            for (var i = 0; i < this.allPrompts.length; i++) {
                var currentPrompt = this.allPrompts[i];
                finalItems.push({ text: currentPrompt.prompt });
            }
            return finalItems;
        };
        AIAssistant.prototype.renderTooltip = function () {
            this.toolTip = new ej2_popups_1.Tooltip({
                target: '#' + this.parent.getID() + '_RTE_Smart_AI_Query_AssistView [title]',
                showTipPointer: true,
                openDelay: 400,
                opensOn: 'Hover',
                cssClass: this.parent.getCssClass(),
                windowCollision: true,
                position: 'BottomCenter'
            });
            this.toolTip.appendTo(this.assistView.element);
        };
        AIAssistant.prototype.setEditAreaRangeAndFocus = function () {
            var range = new Range();
            range.setStart(this.assistViewEditArea, 0);
            range.collapse(true);
            document.getSelection().removeAllRanges();
            document.getSelection().addRange(range);
        };
        AIAssistant.prototype.bindOnEnd = function () {
            this.parent.formatter.editorManager.aiAssistantActionObj = new ai_assitant_actions_1.AIAssistantActions(this.parent.formatter.editorManager);
        };
        AIAssistant.prototype.handleInsertContent = function (response) {
            this.currentSelection.restore();
            var actionBeginArgs = {
                requestType: 'AIAssistant',
                name: 'InsertResponseContent',
                item: {
                    command: 'AIAssistant',
                    subCommand: this.isProcessWholeEditorContent ? 'ReplaceEditorContent' : 'InsertResponseContent',
                    value: this.parent.htmlEditorModule.sanitizeHelper(response)
                }
            };
            this.parent.formatter.process(this.parent, actionBeginArgs, null, {
                selection: this.currentSelection
            });
        };
        AIAssistant.prototype.beforeMenuOpen = function (args) {
            var isAIAssitant = args.element.classList.contains('e-rte-aicommands-menu') || !ej2_base_1.isNullOrUndefined(args.element.closest('.e-rte-aicommands-menu'));
            Iif (!isAIAssitant) {
                return;
            }
            var eventArgs = {
                cancel: false,
                element: args.element,
                type: 'Menu',
                originalEvent: args.event
            };
            this.triggerBeforePopupOpenCloseEvent('beforePopupOpen', args, eventArgs);
        };
        AIAssistant.prototype.beforeMenuClose = function (args) {
            var isAIAssitant = args.element.classList.contains('e-rte-aicommands-menu') || !ej2_base_1.isNullOrUndefined(args.element.closest('.e-rte-aicommands-menu'));
            Iif (!isAIAssitant) {
                return;
            }
            var eventArgs = {
                cancel: false,
                element: args.element,
                type: 'Menu',
                originalEvent: args.event
            };
            this.triggerBeforePopupOpenCloseEvent('beforePopupClose', args, eventArgs);
        };
        AIAssistant.prototype.triggerBeforePopupOpenCloseEvent = function (eventName, originalArgs, eventArgs, callBack) {
            this.parent.trigger(eventName, eventArgs, function (updatedArgs) {
                if (!updatedArgs.cancel) {
                    if (!ej2_base_1.isNullOrUndefined(callBack)) {
                        callBack();
                    }
                }
                else {
                    originalArgs.cancel = true;
                }
            });
        };
        AIAssistant.prototype.updateCssClass = function () {
            if (this.assistView) {
                this.assistView.cssClass = this.parent.getCssClass();
            }
            if (this.element) {
                this.element.className = classes.CLS_RTE_ELEMENTS + ' e-rte-aiquery-popup e-popup-close ' + this.parent.getCssClass();
            }
        };
        AIAssistant.prototype.enableDisableHistoryToolbarButton = function (enable) {
            var footerToolbar = this.assistView.element.querySelector('.e-footer .e-toolbar');
            var toolbar = ej2_base_1.getComponent(footerToolbar, 'toolbar');
            toolbar.items[0].disabled = enable;
        };
        return AIAssistant;
    }());
    exports.AIAssistant = AIAssistant;
});