all files / block-manager/renderer/blocks/ code.js

94.12% Statements 240/255
82.41% Branches 89/108
94.74% Functions 36/38
94.49% Lines 240/254
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                       1390× 1390× 1390× 1390×   1390× 1390× 1390× 1390×   1390× 1390× 1390× 1390×   85× 85× 85× 85×     85× 85× 85× 85× 85× 85× 85×   85×       85×                 85×                 85×   85× 85× 37×   85×                   85× 85×           85× 85×         85× 77×       85× 85×   747× 40×   707× 707× 707× 692×   15× 15×   12×                                     14×   13× 13× 13×                 11× 11× 11× 11× 11×                                       13× 13×                                                       1390×        
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
define(["require", "exports", "../../../models/enums", "../../../common/utils/selection", "../../../common/utils/data", "../../../common/utils/block", "../../../common/utils/common", "../../../common/constant", "../../services/index", "@syncfusion/ej2-base", "../../../common/utils/transform"], function (require, exports, enums_1, selection_1, data_1, block_1, common_1, constant_1, index_1, ej2_base_1, transform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var CodeRenderer = (function () {
        function CodeRenderer(manager) {
            this.ctrlAPressed = false;
            this.INDENT_SIZE = 4;
            this.parent = manager;
            this.addEventListeners();
        }
        CodeRenderer.prototype.addEventListeners = function () {
            this.parent.observer.on(constant_1.events.keydown, this.handleKeyDownActions, this);
            this.parent.observer.on(constant_1.events.input, this.handleCodeBlockInput, this);
            this.parent.observer.on(constant_1.events.localeChanged, this.handleLocaleChange, this);
            this.parent.observer.on(constant_1.events.destroy, this.destroy, this);
        };
        CodeRenderer.prototype.removeEventListeners = function () {
            this.parent.observer.off(constant_1.events.keydown, this.handleKeyDownActions);
            this.parent.observer.off(constant_1.events.input, this.handleCodeBlockInput);
            this.parent.observer.off(constant_1.events.localeChanged, this.handleLocaleChange);
            this.parent.observer.off(constant_1.events.destroy, this.destroy);
        };
        CodeRenderer.prototype.renderCodeBlock = function (block) {
            var codeBlockSettings = block.properties;
            var _a = this.createCodeContainer(block), container = _a.container, preElement = _a.preElement, codeElement = _a.codeElement;
            var _b = this.createCodeToolbar(), toolbar = _b.toolbar, copyButton = _b.copyButton;
            var languageSelector = ej2_base_1.createElement('input', {
                className: 'e-code-block-languages'
            });
            toolbar.appendChild(languageSelector);
            this.initializeLanguageSelector(codeBlockSettings, preElement, codeElement, languageSelector);
            toolbar.appendChild(copyButton);
            container.appendChild(toolbar);
            container.appendChild(preElement);
            selection_1.setCursorPosition(codeElement.lastChild, 0);
            return container;
        };
        CodeRenderer.prototype.createCodeToolbar = function () {
            var toolbar = ej2_base_1.createElement('div', {
                className: 'e-code-block-toolbar',
                attrs: { contenteditable: 'false' }
            });
            var copyButton = ej2_base_1.createElement('button', {
                className: 'e-code-block-copy-button e-btn',
                innerHTML: '<span class="e-icons e-copy"></span>',
                attrs: {
                    title: this.parent.localeJson['codeCopyTooltip'],
                    type: 'button',
                    contenteditable: 'false'
                }
            });
            copyButton.addEventListener('click', function () {
                var codeElement = toolbar.closest('.e-code-block-container').querySelector('code');
                Eif (codeElement) {
                    var codeText = codeElement.textContent;
                    window.navigator.clipboard.writeText(codeText)
                        .then(function () {
                        var iconElement = copyButton.querySelector('.e-icons');
                        Eif (iconElement) {
                            var originalClass_1 = iconElement.className;
                            iconElement.className = 'e-icons e-check-tick';
                            setTimeout(function () {
                                iconElement.className = originalClass_1;
                            }, 2000);
                        }
                    })
                        .catch(function (err) {
                        console.error('Could not copy text: ', err);
                    });
                }
            });
            return { toolbar: toolbar, copyButton: copyButton };
        };
        CodeRenderer.prototype.initializeLanguageSelector = function (codeBlockSettings, preElement, codeElement, targetElement) {
            var languageDataSource = data_1.getLanguageItems();
            if (this.parent.codeBlockSettings.languages.length === 0) {
                this.parent.codeBlockSettings.languages = languageDataSource;
            }
            this.parent.observer.notify('renderDropdownList', {
                targetElement: targetElement,
                dataSource: this.parent.codeBlockSettings.languages,
                fields: { text: 'label', value: 'language' },
                value: this.parent.codeBlockSettings.defaultLanguage,
                change: function (e) {
                    var newLanguage = e.value;
                    Eif (codeElement && preElement) {
                        codeElement.className = "e-code-content e-block-content language-" + newLanguage;
                        preElement.setAttribute('data-language', newLanguage);
                        codeBlockSettings.language = newLanguage;
                    }
                }
            });
        };
        CodeRenderer.prototype.createCodeContainer = function (block) {
            var container = ej2_base_1.createElement('div', { className: 'e-code-block-container' });
            var preElement = ej2_base_1.createElement('pre', {
                className: 'e-code-block',
                attrs: {
                    'data-language': this.parent.codeBlockSettings.defaultLanguage
                }
            });
            var hasContent = block.content && block.content.length > 0;
            var codeElement = ej2_base_1.createElement('code', {
                id: hasContent ? block.content[0].id : '',
                className: "e-code-content e-block-content language-" + this.parent.codeBlockSettings.defaultLanguage,
                attrs: { contenteditable: 'true' }
            });
            if (hasContent && block.content[0].content) {
                codeElement.textContent = block.content[0].content;
            }
            else {
                codeElement.innerHTML = '<br>';
            }
            preElement.appendChild(codeElement);
            return { container: container, preElement: preElement, codeElement: codeElement };
        };
        CodeRenderer.prototype.handleKeyDownActions = function (e) {
            if (!this.parent.currentFocusedBlock) {
                return;
            }
            var codeElement = this.parent.currentFocusedBlock.querySelector('code');
            var block = block_1.getBlockModelById(this.parent.currentFocusedBlock.id, this.parent.getEditorBlocks());
            if (!codeElement || (block && block.blockType !== enums_1.BlockType.Code)) {
                return;
            }
            var normalizedKey = common_1.getNormalizedKey(e);
            if (normalizedKey === 'ctrl+a') {
                this.handleCtrlASelection(e, codeElement);
                return;
            }
            switch (e.key) {
                case 'Enter':
                    this.handleEnterKey(e, codeElement, block);
                    break;
                case 'Backspace':
                    this.handleDeletion(e, codeElement, block, false);
                    break;
                case 'Delete':
                    this.handleDeletion(e, codeElement, block, true);
                    break;
                case 'Tab':
                    this.handleTabKey(e, codeElement);
                    break;
            }
        };
        CodeRenderer.prototype.handleEnterKey = function (e, codeElement, block) {
            e.preventDefault();
            var action = this.determineEnterAction(codeElement);
            if (action.shouldExit) {
                this.exitCodeBlock(codeElement, block);
                return;
            }
            var afterTwoBr = this.isAfterTwoBrTags();
            this.insertTextAtCursor(!afterTwoBr, action.indentation);
        };
        CodeRenderer.prototype.determineEnterAction = function (codeElement) {
            var cursorPosition = this.getCursorPosition(codeElement);
            var indentation = this.getCurrentLineIndentation(codeElement, cursorPosition);
            var shouldExit = this.shouldExitCodeBlock(codeElement);
            return { shouldExit: shouldExit, indentation: indentation };
        };
        CodeRenderer.prototype.handleDeletion = function (e, codeElement, block, isDeleteKey) {
            var cursorPosition = this.getCursorPosition(codeElement);
            var textContent = codeElement.textContent;
            var range = selection_1.getSelectedRange();
            var shouldPreventDefault = isDeleteKey
                ? (cursorPosition >= textContent.length)
                : (cursorPosition === 0 || textContent.length === 0);
            if ((textContent.length === 1) || (range.toString() === textContent)) {
                e.preventDefault();
                codeElement.innerHTML = '<br>';
                selection_1.setCursorPosition(codeElement.firstChild, 0);
                this.updateBlockModel(codeElement, block);
            }
            if (shouldPreventDefault) {
                e.preventDefault();
                return;
            }
        };
        CodeRenderer.prototype.handleTabKey = function (e, codeElement) {
            e.preventDefault();
            if (e.shiftKey) {
                this.removeIndentation(codeElement);
            }
            else {
                this.addIndentation();
            }
        };
        CodeRenderer.prototype.handleCodeBlockInput = function (e) {
            if (!this.parent.currentFocusedBlock) {
                return;
            }
            var codeElement = this.parent.currentFocusedBlock.querySelector('code');
            var block = block_1.getBlockModelById(this.parent.currentFocusedBlock.id, this.parent.getEditorBlocks());
            if (!codeElement || block.blockType !== enums_1.BlockType.Code) {
                return;
            }
            var textContent = codeElement.textContent || '';
            if (!textContent.trim() && codeElement.innerHTML !== '<br>') {
                codeElement.innerHTML = '<br>';
            }
            this.updateBlockModel(codeElement, block);
        };
        CodeRenderer.prototype.handleCtrlASelection = function (e, codeElement) {
            var _this = this;
            if (!this.ctrlAPressed) {
                e.preventDefault();
                this.selectEntireCodeBlock(codeElement);
                this.ctrlAPressed = true;
                setTimeout(function () {
                    _this.ctrlAPressed = false;
                }, 500);
            }
            else {
                this.ctrlAPressed = false;
            }
        };
        CodeRenderer.prototype.getCursorPosition = function (element) {
            var range = this.parent.nodeSelection.getRange();
            var preCaretRange = range.cloneRange();
            preCaretRange.selectNodeContents(element);
            preCaretRange.setEnd(range.endContainer, range.endOffset);
            return preCaretRange.toString().length;
        };
        CodeRenderer.prototype.insertTextAtCursor = function (isDoubleBr, indentValue) {
            var selection = window.getSelection();
            Iif (!selection.rangeCount) {
                return;
            }
            var range = selection.getRangeAt(0);
            var brElement = ej2_base_1.createElement('br');
            range.insertNode(brElement);
            Eif (isDoubleBr) {
                var consecutiveBr = ej2_base_1.createElement('br');
                range.insertNode(consecutiveBr);
                range.setStartAfter(consecutiveBr);
                range.setEndAfter(consecutiveBr);
            }
            else {
                range.setStartAfter(brElement);
                range.setEndAfter(brElement);
            }
            if (indentValue) {
                range.insertNode(document.createTextNode(indentValue));
            }
            selection.removeAllRanges();
            selection.addRange(range);
        };
        CodeRenderer.prototype.getCurrentLineIndentation = function (element, cursorPosition) {
            var textContent = element.textContent;
            var lines = textContent.substring(0, cursorPosition).split('\n');
            var currentLine = lines[lines.length - 1];
            var indentMatch = currentLine.match(/^(\s*)/);
            return indentMatch ? indentMatch[1] : '';
        };
        CodeRenderer.prototype.isAfterTwoBrTags = function () {
            var selection = window.getSelection();
            Iif (!selection.rangeCount) {
                return false;
            }
            var range = selection.getRangeAt(0);
            var container = range.startContainer;
            var node = container;
            var brCount = 0;
            while (node && brCount < 2) {
                Iif (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'BR') {
                    brCount++;
                }
                else Eif (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '') {
                    break;
                }
                node = node.previousSibling;
            }
            return brCount >= 2;
        };
        CodeRenderer.prototype.shouldExitCodeBlock = function (element) {
            var children = element.childNodes;
            var brCount = 0;
            for (var i = children.length - 1; i >= 0; i--) {
                var node = children[i];
                if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'BR') {
                    brCount++;
                }
                else Eif (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '') {
                    break;
                }
            }
            return brCount >= 3;
        };
        CodeRenderer.prototype.exitCodeBlock = function (codeElement, block) {
            var _this = this;
            var blockElement = block_1.getParentBlock(codeElement);
            setTimeout(function () {
                var nextSibling = blockElement.nextElementSibling;
                if (nextSibling) {
                    _this.parent.setFocusAndUIForNewBlock(nextSibling);
                }
                else {
                    var newBlock = index_1.BlockFactory.createParagraphBlock();
                    _this.parent.blockCommand.addBlock({ block: newBlock, targetBlock: blockElement });
                }
            });
        };
        CodeRenderer.prototype.addIndentation = function () {
            var indent = ' '.repeat(this.INDENT_SIZE);
            var range = this.parent.nodeSelection.getRange();
            range.insertNode(document.createTextNode(indent));
            var endContainer = range.endContainer;
            selection_1.setCursorPosition(endContainer, endContainer.textContent.length);
        };
        CodeRenderer.prototype.removeIndentation = function (element) {
            var cursorPosition = this.getCursorPosition(element);
            var textContent = element.textContent;
            var beforeCursor = textContent.substring(0, cursorPosition);
            var lastNewlineIndex = beforeCursor.lastIndexOf('\n');
            var lineStart = lastNewlineIndex + 1;
            var currentLine = textContent.substring(lineStart, cursorPosition);
            var spacesToRemove = Math.min(this.INDENT_SIZE, currentLine.match(/^ */)[0].length);
            if (spacesToRemove > 0) {
                element.textContent = textContent.substring(0, lineStart) + textContent.substring(lineStart + spacesToRemove);
                selection_1.setCursorPosition(element, cursorPosition - spacesToRemove);
            }
        };
        CodeRenderer.prototype.selectEntireCodeBlock = function (element) {
            var range = document.createRange();
            range.selectNodeContents(element);
            var selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
        };
        CodeRenderer.prototype.updateBlockModel = function (codeElement, block) {
            var textContent = Array.from(codeElement.childNodes)
                .map(function (node) {
                if (node.nodeName === 'BR') {
                    return '\n';
                }
                Eif (node.nodeType === Node.TEXT_NODE) {
                    return node.textContent;
                }
                return '';
            })
                .join('')
                .replace(/\n$/, '');
            if (!block.content || block.content.length === 0) {
                this.parent.blockService.replaceBlock(block.id, __assign({}, common_1.decoupleReference(transform_1.sanitizeBlock(block)), { content: [index_1.BlockFactory.createTextContent({ content: textContent })] }));
            }
            else {
                block.content[0].content = textContent;
            }
            this.parent.stateManager.updateManagerBlocks();
        };
        CodeRenderer.prototype.handleLocaleChange = function () {
            var codeBlocks = this.parent.rootEditorElement.querySelectorAll('.e-code-block-container');
            for (var _i = 0, _a = Array.from(codeBlocks); _i < _a.length; _i++) {
                var codeBlock = _a[_i];
                var copyButton = codeBlock.querySelector('.e-code-block-copy-button');
                Eif (copyButton) {
                    copyButton.setAttribute('title', this.parent.localeJson['codeCopyTooltip']);
                }
            }
        };
        CodeRenderer.prototype.destroy = function () {
            this.removeEventListeners();
        };
        return CodeRenderer;
    }());
    exports.CodeRenderer = CodeRenderer;
});