(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('ngx-quill'), require('@angular/forms'), require('uuid'), require('rxjs'), require('quill-mention'), require('@sd-angular/core/common'), require('@angular/common'), require('@sd-angular/core/translate'), require('@sd-angular/core/button'), require('@sd-angular/core/textarea'), require('@sd-angular/core/api')) :
    typeof define === 'function' && define.amd ? define('@sd-angular/core/editor', ['exports', '@angular/core', 'ngx-quill', '@angular/forms', 'uuid', 'rxjs', 'quill-mention', '@sd-angular/core/common', '@angular/common', '@sd-angular/core/translate', '@sd-angular/core/button', '@sd-angular/core/textarea', '@sd-angular/core/api'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global['sd-angular'] = global['sd-angular'] || {}, global['sd-angular'].core = global['sd-angular'].core || {}, global['sd-angular'].core.editor = {}), global.ng.core, global['ngx-quill'], global.ng.forms, global.uuid, global.rxjs, null, global['sd-angular'].core.common, global.ng.common, global['sd-angular'].core.translate, global['sd-angular'].core.button, global['sd-angular'].core.textarea, global['sd-angular'].core.api));
}(this, (function (exports, core, ngxQuill, forms, uuid, rxjs, quillMention, common, common$1, translate, button, textarea, api) { 'use strict';

    var EDITOR_CONFIG = new core.InjectionToken('editor.configuration');

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise */
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b)
                if (Object.prototype.hasOwnProperty.call(b, p))
                    d[p] = b[p]; };
        return extendStatics(d, b);
    };
    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    var __assign = function () {
        __assign = Object.assign || function __assign(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);
    };
    function __rest(s, e) {
        var t = {};
        for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
                t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }
    function __decorate(decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    }
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try {
                step(generator.next(value));
            }
            catch (e) {
                reject(e);
            } }
            function rejected(value) { try {
                step(generator["throw"](value));
            }
            catch (e) {
                reject(e);
            } }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }
    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function () { if (t[0] & 1)
                throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f)
                throw new TypeError("Generator is already executing.");
            while (_)
                try {
                    if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
                        return t;
                    if (y = 0, t)
                        op = [op[0] & 2, t.value];
                    switch (op[0]) {
                        case 0:
                        case 1:
                            t = op;
                            break;
                        case 4:
                            _.label++;
                            return { value: op[1], done: false };
                        case 5:
                            _.label++;
                            y = op[1];
                            op = [0];
                            continue;
                        case 7:
                            op = _.ops.pop();
                            _.trys.pop();
                            continue;
                        default:
                            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                                _ = 0;
                                continue;
                            }
                            if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
                                _.label = op[1];
                                break;
                            }
                            if (op[0] === 6 && _.label < t[1]) {
                                _.label = t[1];
                                t = op;
                                break;
                            }
                            if (t && _.label < t[2]) {
                                _.label = t[2];
                                _.ops.push(op);
                                break;
                            }
                            if (t[2])
                                _.ops.pop();
                            _.trys.pop();
                            continue;
                    }
                    op = body.call(thisArg, _);
                }
                catch (e) {
                    op = [6, e];
                    y = 0;
                }
                finally {
                    f = t = 0;
                }
            if (op[0] & 5)
                throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
        }
    }
    var __createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                __createBinding(o, m, p);
    }
    function __values(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m)
            return m.call(o);
        if (o && typeof o.length === "number")
            return {
                next: function () {
                    if (o && i >= o.length)
                        o = void 0;
                    return { value: o && o[i++], done: !o };
                }
            };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m)
            return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
                ar.push(r.value);
        }
        catch (error) {
            e = { error: error };
        }
        finally {
            try {
                if (r && !r.done && (m = i["return"]))
                    m.call(i);
            }
            finally {
                if (e)
                    throw e.error;
            }
        }
        return ar;
    }
    /** @deprecated */
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    /** @deprecated */
    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++)
            s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }
    function __spreadArray(to, from, pack) {
        if (pack || arguments.length === 2)
            for (var i = 0, l = from.length, ar; i < l; i++) {
                if (ar || !(i in from)) {
                    if (!ar)
                        ar = Array.prototype.slice.call(from, 0, i);
                    ar[i] = from[i];
                }
            }
        return to.concat(ar || Array.prototype.slice.call(from));
    }
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
        function verb(n) { if (g[n])
            i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
        function resume(n, v) { try {
            step(g[n](v));
        }
        catch (e) {
            settle(q[0][3], e);
        } }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) { if (f(v), q.shift(), q.length)
            resume(q[0][0], q[0][1]); }
    }
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
    }
    function __asyncValues(o) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
    }
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    }
    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }
    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }
    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m")
            throw new TypeError("Private method is not writable");
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }

    var Constants = {
        ARE_YOU_WANT_TO_DELETE: 'Are you sure you want to delete?',
        ACTIVE: 'active',
        IN_ACTIVE: 'inactive',
        APPROVE: 'approve',
        UN_APPROVE: 'unapprove',
        ACCEPT_SIZE_IMAGE: 'Logo only accept image with size <= 2MB',
        ACCEPT_TYPE_IMAGE: 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon',
        PAGE_TYPE_NEW: 'new',
        PAGE_TYPE_EDIT: 'edit',
        SAVE: 'saveOb',
        SAVE_AND_CONTINUE: 'saveAndContOb',
        IMAGE_SIZE: 2048000,
        SUCCESS: 'Success',
        IMPORT_SUCCESSFULLY: 'Import successfully!',
        ERROR: 'Error',
        FAILED: 'fail',
        FILE: 'file',
        NONE: 'none',
        NOT_EXIST_ID_OR_LINK: 'This ID/Link is not existing',
        FEATURE_IS_PENDING: 'This feature is pending',
        NOT_SUPPORT_FILE_IMAGE: 'File upload is not supported.',
        NOT_SUPPORT_FILE_IMPORT: 'File import is not supported.',
        NETWORK_ERROR: 'Network Error',
        SORT_BY: [
            {
                value: 0,
                name: 'Created Date'
            },
            {
                value: 1,
                name: 'Title'
            }
        ],
        DESC: [
            {
                value: true,
                name: 'Descending'
            },
            {
                value: false,
                name: 'Ascending'
            }
        ],
        FORM_ERRORS: {
            Id: '',
            textSearch: '',
            ImportLogId: '',
            SortBy: '',
            Reverse: '',
        },
        VALIDATION_MESSAGES: {}
    };
    var PROMOTION_PERMISSIONS = ['ListPromotion', 'AddNewPromotion', 'EditPromotion',
        'ActiveOrInactivePromotion', 'RemovePromotion', 'ImportPromotion', 'ExportPromotion'];
    var ValidateMessageConstants = {
        TITLE_REQUIRED: 'Title is required',
        TITLE_MAXLENGTH: 'Title is not more than 55 characters',
        TITLE_PATTERN: 'Title is required',
        CREATED_AT_REQUIRED: 'Created At is required',
        SHOW_ON_HOME_REQUIRED: 'Show On Home is required',
        DISPLAY_NUMBER_REQUIRED: 'Display Number is required',
        CONTENT_TYPE_REQUIRED: 'Content Type is required',
        DISCOUNT_PERCENT_REQUIRED: 'Discount percent is required',
        DISCOUNT_PERCENT_MAX: 'Max discount percent is 100, cannot input greater',
        DISCOUNT_PERCENT_MIN: 'Min discount percent is 0, cannot input lower'
    };
    var PROMOTION_FORM = {
        FORM_ERRORS: {
            title: '',
            createdAt: '',
            displayNumber: '',
            showOnHome: '',
            discountPercent: '',
            isActive: '',
            ctaLabelName: '',
            ctaDeepLink: '',
            tags: ''
        },
        VALIDATION_MESSAGES: {
            title: {
                required: ValidateMessageConstants.TITLE_REQUIRED,
                maxlength: ValidateMessageConstants.TITLE_MAXLENGTH,
                pattern: ValidateMessageConstants.TITLE_PATTERN
            },
            createdAt: {
                required: ValidateMessageConstants.CREATED_AT_REQUIRED
            },
            showOnHome: {
                required: ValidateMessageConstants.SHOW_ON_HOME_REQUIRED
            },
            displayNumber: {
                required: ValidateMessageConstants.DISPLAY_NUMBER_REQUIRED
            },
            discountPercent: {
                required: ValidateMessageConstants.DISCOUNT_PERCENT_REQUIRED,
                max: ValidateMessageConstants.DISCOUNT_PERCENT_MAX,
                min: ValidateMessageConstants.DISCOUNT_PERCENT_MIN
            },
            tags: {
                required: ValidateMessageConstants.CONTENT_TYPE_REQUIRED
            }
        }
    };

    var _name, _subscription, _model, _form, _updateValidator, _quill, _initUploadImage;
    var SdEditor = /** @class */ (function () {
        function SdEditor(ngZone, ref, configuration) {
            var _this = this;
            this.ngZone = ngZone;
            this.ref = ref;
            this.configuration = configuration;
            _name.set(this, "N" + uuid.v4());
            this.id = "I" + uuid.v4();
            _subscription.set(this, new rxjs.Subscription());
            _model.set(this, void 0);
            this.required = false;
            this.modelChange = new core.EventEmitter();
            this.placeholder = '';
            this.styles = { height: '250px' };
            this.formControl = new forms.FormControl();
            this.domain = '';
            _form.set(this, void 0);
            this.enableHTMLButton = false;
            this.showHtmlEditor = false;
            this.quillConfig = {
                // toolbar: '.toolbar',
                toolbar: {
                    container: [
                        ['bold', 'italic', 'underline', 'strike'],
                        ['blockquote', 'code-block'],
                        [{ 'header': 1 }, { 'header': 2 }],
                        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                        [{ 'script': 'sub' }, { 'script': 'super' }],
                        [{ 'indent': '-1' }, { 'indent': '+1' }],
                        [{ 'direction': 'rtl' }],
                        [{ 'size': ['small', false, 'large', 'huge'] }],
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'font': [] }],
                        [{ 'align': [] }],
                        ['clean'],
                        ['link', 'image', 'video'] // link and image, video
                    ]
                },
                mention: {
                    allowedChars: /^[A-Za-z0-9\sÅÄÖåäö._-]*$/,
                    mentionDenotationChars: ['@', '#'],
                    source: function (searchTerm, renderList, mentionChar) {
                        if ((_this.mentionValues && mentionChar === '@') || (_this.hashTagValues && mentionChar === '#')) {
                            var values = void 0;
                            if (mentionChar === '@') {
                                values = _this.mentionValues;
                            }
                            else if (mentionChar === '#') {
                                values = _this.hashTagValues;
                            }
                            else {
                                values = [];
                            }
                            if (searchTerm.length === 0) {
                                renderList(values, searchTerm);
                            }
                            else {
                                var matches = [];
                                // tslint:disable-next-line:prefer-for-of
                                for (var i = 0; i < values.length; i++) {
                                    // tslint:disable-next-line:no-bitwise
                                    if (~values[i].value.toLowerCase().indexOf(searchTerm.toLowerCase())) {
                                        matches.push(values[i]);
                                    }
                                }
                                renderList(matches, searchTerm);
                            }
                        }
                    },
                },
                keyboard: {
                    bindings: {
                        enter: {
                            key: 13,
                            handler: function (range, context) {
                                return true;
                            }
                        }
                    }
                }
            };
            this.sdChange = new core.EventEmitter();
            this.timerLoadQuillToolbar = null;
            _updateValidator.set(this, function () {
                _this.formControl.clearValidators();
                _this.formControl.clearAsyncValidators();
                var validators = [];
                if (_this.required) {
                    validators.push(forms.Validators.required);
                }
                if (_this.minlength > 0) {
                    validators.push(forms.Validators.minLength(_this.minlength));
                }
                if (_this.maxlength > 0) {
                    validators.push(forms.Validators.maxLength(_this.maxlength));
                }
                _this.formControl.setValidators(validators);
                _this.formControl.updateValueAndValidity();
                _this.ref.markForCheck();
            });
            _quill.set(this, void 0);
            this.editorInit = function (quill) {
                __classPrivateFieldSet(_this, _quill, quill);
                _this.quillEvent = quill;
                // const txtArea = document.createElement('textarea');
                // txtArea.style.cssText =
                //   'width: 100%;margin: 0px;background: rgb(29, 29, 29);' +
                //   'box-sizing: border-box;color: rgb(204, 204, 204);' +
                //   'font-size: 15px;outline: none;padding: 20px;' +
                //   'line-height: 24px;font-family: Consolas, Menlo, Monaco, &quot;Courier New&quot;, monospace;' +
                //   'position: absolute;top: 0;bottom: 0;border: none;display:none';
                // const htmlEditor = quill.addContainer('ql-custom');
                // htmlEditor.appendChild(txtArea);
                // const myEditor = quill.container;
                // quill.on('text-change', (delta, oldDelta, source) => {
                //   const html = myEditor.children[0].innerHTML;
                //   txtArea.value = html;
                //   // if (quill.getLength() > this.maxlength) {
                //   //   quill.deleteText(this.maxlength, quill.getLength());
                //   // }
                //   // this.formControl.setValue(html);
                // });
                var self = _this;
                __classPrivateFieldGet(_this, _initUploadImage).call(_this, quill);
                // this.ngZone.runOutsideAngular(() => {
                //   quill.getModule('toolbar').addHandler('image', function () {
                //     let fileInput = this.container.querySelector('input.ql-image[type=file]');
                //     if (fileInput == null) {
                //       fileInput = document.createElement('input');
                //       fileInput.setAttribute('type', Constants.FILE);
                //       fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
                //       fileInput.classList.add('ql-image');
                //       fileInput.addEventListener('change', () => {
                //         const files = fileInput.files;
                //         const range = this.quill.getSelection(true);
                //         if (!files || !files.length) {
                //           return;
                //         }
                //         const formData = new FormData();
                //         formData.append(Constants.FILE, files[0]);
                //         this.quill.enable(false);
                //         self.#uploadImage(formData, quill, range, fileInput);
                //       });
                //       this.container.appendChild(fileInput);
                //     }
                //     fileInput.click();
                //   });
                // });
                _this.ref.markForCheck();
            };
            _initUploadImage.set(this, function (quill) {
                var self = _this;
                _this.ngZone.runOutsideAngular(function () {
                    quill.getModule('toolbar').addHandler('image', function () {
                        var _this = this;
                        var fileInput = this.container.querySelector('input.ql-image[type=file]');
                        if (fileInput == null) {
                            fileInput = document.createElement('input');
                            fileInput.setAttribute('type', Constants.FILE);
                            fileInput.setAttribute('accept', '.jpg,.jpeg,.png');
                            fileInput.classList.add('ql-image');
                            fileInput.addEventListener('change', function () {
                                var _a;
                                var files = fileInput.files;
                                var range = _this.quill.getSelection(true);
                                if (!files || !files.length) {
                                    return;
                                }
                                var fileName = files[0].name;
                                var idxDot = fileName.lastIndexOf('.') + 1;
                                var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
                                if (extFile === 'jpg' || extFile === 'jpeg' || extFile === 'png') {
                                    // TO DO
                                }
                                else {
                                    alert('Vui lòng chọn file đúng định dạng cho phép');
                                    return;
                                }
                                var formData = new FormData();
                                formData.append(Constants.FILE, files[0]);
                                _this.quill.enable(false);
                                // self.#uploadImage(formData, quill, range, fileInput);
                                (_a = self.configuration) === null || _a === void 0 ? void 0 : _a.uploadImage(formData, self.args).then(function (url) {
                                    self.ngZone.runOutsideAngular(function () {
                                        quill.enable(true);
                                        // quill.editor.insertEmbed(range.index, 'image', resp?.data?.imageUrl || resp?.data?.publish_url || resp?.url || '');
                                        quill.getModule('clipboard').dangerouslyPasteHTML(range.index, '<a target="_blank" href="' + (url || '')
                                            + '"><img src="' + (url || '') + '" alt="c-image-editor-quill"></a>', 'user');
                                        // quill.insertText();
                                        var content = quill.getContents();
                                        quill.setContents(content);
                                        quill.setSelection(range.index + 1, 'user');
                                        fileInput.value = '';
                                    });
                                });
                            });
                            this.container.appendChild(fileInput);
                        }
                        fileInput.click();
                    });
                });
            });
            this.onModelChange = function (val) {
                _this.formControl.setValue(val);
                _this.modelHTML = val;
                _this.ref.markForCheck();
            };
            this.onClickShowHtmlEditor = function () {
                _this.showHtmlEditor = !_this.showHtmlEditor;
                _this.ref.markForCheck();
            };
        }
        Object.defineProperty(SdEditor.prototype, "model", {
            set: function (val) {
                __classPrivateFieldSet(this, _model, val);
                this.modelHTML = val;
                this.formControl.setValue(__classPrivateFieldGet(this, _model), {
                    emitEvent: false
                });
                this.ref.detectChanges();
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdEditor.prototype, "disabled", {
            set: function (val) {
                val = (val === '') || val;
                if (val) {
                    this.formControl.disable();
                }
                else {
                    this.formControl.enable();
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdEditor.prototype, "pRequired", {
            set: function (val) {
                this.required = (val === '') || val;
                __classPrivateFieldGet(this, _updateValidator).call(this);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdEditor.prototype, "_minlength", {
            set: function (val) {
                this.minlength = +val;
                __classPrivateFieldGet(this, _updateValidator).call(this);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdEditor.prototype, "_maxlength", {
            set: function (val) {
                this.maxlength = +val;
                __classPrivateFieldGet(this, _updateValidator).call(this);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdEditor.prototype, "form", {
            set: function (val) {
                if (val) {
                    if (val instanceof forms.NgForm) {
                        __classPrivateFieldSet(this, _form, val.form);
                    }
                    else {
                        __classPrivateFieldSet(this, _form, val);
                    }
                }
            },
            enumerable: false,
            configurable: true
        });
        SdEditor.prototype.ngOnInit = function () {
            var e_1, _c;
            var _this = this;
            var _a, _b;
            (_a = __classPrivateFieldGet(this, _form)) === null || _a === void 0 ? void 0 : _a.addControl(__classPrivateFieldGet(this, _name), this.formControl);
            if (this.toolbar) {
                this.quillConfig.toolbar.container = this.toolbar;
            }
            var _loop_1 = function (action) {
                if (this_1.quillConfig.toolbar.container.toString().includes(action.key)) {
                    var qlKey_1 = "button.ql-" + action.key;
                    var interval_1 = setInterval(function () {
                        if (document.querySelector(qlKey_1)) {
                            clearInterval(interval_1);
                            document.querySelector(qlKey_1).innerHTML = action.icon;
                            var customAction = document.querySelector(qlKey_1);
                            if (customAction.getAttribute('listener') !== '1') {
                                customAction.setAttribute('listener', '1');
                                if (action.tooltip) {
                                    customAction.setAttribute('title', action.tooltip);
                                }
                                customAction.addEventListener('click', function (e) {
                                    var cursorPosition = localStorage.getItem('quillRange');
                                    var element = e.currentTarget; // Lấy element của action được click
                                    var toolbar = element.closest('.ql-formats').closest('.ql-toolbar'); // Lấy toolbar element
                                    var id = toolbar.closest('quill-editor').id; // Lấy id của editor để phục vụ loading
                                    var loadingId = "#box-" + id; // id của editor;
                                    action.click(e, {
                                        qlKey: qlKey_1,
                                        element: element,
                                        loadingId: loadingId,
                                        cursorPosition: JSON.parse(cursorPosition),
                                        quill: __classPrivateFieldGet(_this, _quill),
                                        args: _this.args
                                    });
                                });
                            }
                        }
                    }, 1000);
                }
            };
            var this_1 = this;
            try {
                for (var _d = __values((((_b = this.configuration) === null || _b === void 0 ? void 0 : _b.actions) || [])), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var action = _e.value;
                    _loop_1(action);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_e && !_e.done && (_c = _d.return)) _c.call(_d);
                }
                finally { if (e_1) throw e_1.error; }
            }
            // if (this.quillConfig.toolbar.container.toString().includes('customFile')) {
            //   this.timerLoadQuillToolbar = setInterval(() => {
            //     if (document.querySelector('button.ql-customFile')) {
            //       clearInterval(this.timerLoadQuillToolbar);
            //       document.querySelector('button.ql-customFile').innerHTML = this.customButtonFileSVG;
            //       const customButton = document.querySelector('button.ql-customFile');
            //       if (customButton.getAttribute('listener') !== '1') {
            //         customButton.setAttribute('listener', '1');
            //         customButton.addEventListener('click', this.customFileHandler);
            //       }
            //     }
            //   }, 1000);
            // }
            this.ref.markForCheck();
        };
        // customFileHandler = (e) => {
        //   const customButton = e.currentTarget;
        //   const quillToolbar = customButton.closest('.ql-formats').closest('.ql-toolbar');
        //   const quillBox = quillToolbar.closest('.ql-formats')
        //   let fileInput: HTMLInputElement = quillToolbar.querySelector('input.ql-customFile[type=file]');
        //   if (fileInput == null) {
        //     fileInput = document.createElement('input');
        //     fileInput.setAttribute('type', Constants.FILE);
        //     fileInput.setAttribute('accept', '*');
        //     fileInput.classList.add('ql-customFile');
        //     fileInput.addEventListener('change', () => {
        //       const files = fileInput.files;
        //       if (!files || !files.length) {
        //         return;
        //       }
        //       const formData = new FormData();
        //       formData.append(Constants.FILE, files[0]);
        //       let range = localStorage.getItem('quillRange');
        //       if (range) {
        //         range = JSON.parse(range);
        //       }
        //       this.quillEvent.enable(false);
        //       this.#uploadFile(formData, this.quillEvent, range, fileInput, quillToolbar.closest('quill-editor').id);
        //     });
        //     quillToolbar.appendChild(fileInput);
        //   }
        //   fileInput.click();
        // }
        SdEditor.prototype.ngAfterViewInit = function () {
            var _this = this;
            __classPrivateFieldGet(this, _subscription).add(this.formControl.valueChanges.subscribe(function (val) {
                _this.modelChange.emit(val);
                _this.sdChange.emit(val);
            }));
        };
        SdEditor.prototype.ngOnDestroy = function () {
            var _a;
            (_a = __classPrivateFieldGet(this, _form)) === null || _a === void 0 ? void 0 : _a.removeControl(__classPrivateFieldGet(this, _name));
            __classPrivateFieldGet(this, _subscription).unsubscribe();
        };
        // #uploadImage = (formData, quill, range, fileInput) => {
        //   if (!this.urlUploadImage) {
        //     this.urlUploadImage = '/partner/v2/merchandise/file/uploaduserfile';
        //   }
        //   // this.domain = 'https://api-commerce-qc.vinid.dev';
        //   this.sdApiService.post(this.urlUploadImage, formData).then((resp: any) => {
        //     this.ngZone.runOutsideAngular(() => {
        //       quill.enable(true);
        //       // quill.editor.insertEmbed(range.index, 'image', resp?.data?.imageUrl || resp?.data?.publish_url || resp?.url || '');
        //       quill.getModule('clipboard').dangerouslyPasteHTML(range.index, '<a target="_blank" href="' + (resp?.data?.imageUrl || resp?.data?.publish_url || resp?.url || '')
        //         + '"><img src="' + (resp?.data?.imageUrl || resp?.data?.publish_url || resp?.url || '') + '" alt="c-image-editor-quill"></a>', 'user');
        //       // quill.insertText();
        //       const content = quill.getContents();
        //       quill.setContents(content);
        //       quill.setSelection(range.index + 1, 'user');
        //       fileInput.value = '';
        //     });
        //   });
        //   this.ref.markForCheck();
        // }
        // #uploadFile = (formData, quill, range, fileInput, loadingID) => {
        //   if (!this.urlUploadFile) {
        //     this.urlUploadFile = '/partner/v2/merchandise/file/uploaduserfile';
        //   }
        //   // this.domain = 'https://api-commerce-qc.vinid.dev';
        //   this.loadingService.start('#box-' + loadingID);
        //   this.sdApiService.post(this.urlUploadFile, formData).then((resp: any) => {
        //     this.ngZone.runOutsideAngular(() => {
        //       quill.enable(true);
        //       // quill.editor.insertEmbed(range.index, 'image', resp?.data?.imageUrl || resp?.data?.publish_url || resp?.url || '');
        //       quill.getModule('clipboard').dangerouslyPasteHTML(range.index, '<a target="_blank" href="' + (resp?.data?.imageUrl || resp?.data?.publish_url || resp?.url || '')
        //         + '">' + (resp?.data?.imageUrl || resp?.data?.publish_url || resp?.url || '') + '</a>', 'user');
        //       // quill.insertText();
        //       const content = quill.getContents();
        //       quill.setContents(content);
        //       quill.setSelection(range.index + 1, 'user');
        //       fileInput.value = '';
        //     });
        //     this.loadingService.stop('#box-' + loadingID);
        //   }).catch((er) => {
        //     this.loadingService.stop('#box-' + loadingID);
        //   });
        //   this.ref.markForCheck();
        // }
        SdEditor.prototype.onSelectionChanged = function (e) {
            // localStorage.setItem('quillRange', e.range ? JSON.stringify(e.range) : (e.oldRange ? JSON.stringify(e.oldRange) : null));
            localStorage.setItem('quillRange', e.editor.getSelection() ? JSON.stringify(e.editor.getSelection()) : null);
        };
        SdEditor.prototype.onContentChanged = function (e) {
            localStorage.setItem('quillRange', JSON.stringify({
                index: (e.editor.getLength() ? e.editor.getLength() - 1 : 0),
                length: 0
            }));
        };
        return SdEditor;
    }());
    _name = new WeakMap(), _subscription = new WeakMap(), _model = new WeakMap(), _form = new WeakMap(), _updateValidator = new WeakMap(), _quill = new WeakMap(), _initUploadImage = new WeakMap();
    SdEditor.decorators = [
        { type: core.Component, args: [{
                    selector: 'sd-editor',
                    template: "<div id=\"box-{{id}}\">\r\n  <label *ngIf=\"label && !sdLabelDef?.templateRef\" class=\"d-block T14M\">{{label}} <span class=\"text-danger mb-2\"\r\n                                                                                        *ngIf=\"required\">*</span></label>\r\n  <ng-container *ngIf=\"sdLabelDef?.templateRef\" matSuffix>\r\n    <ng-container *ngTemplateOutlet=\"sdLabelDef.templateRef\">\r\n    </ng-container>\r\n  </ng-container>\r\n  <ng-container *ngIf=\"!formControl.disabled && !showHtmlEditor\">\r\n    <quill-editor #editor [styles]=\"styles\" (onEditorCreated)=\"editorInit($event)\" [ngModel]=\"formControl.value\"\r\n                  (onSelectionChanged)=\"onSelectionChanged($event)\"\r\n                  (onContentChanged)=\"onContentChanged($event)\"\r\n                  (ngModelChange)=\"onModelChange($event)\" [id]=\"id\" [modules]=\"quillConfig\" [placeholder]=\"placeholder\"\r\n                  [maxLength]=\"maxlength\">\r\n    </quill-editor>\r\n    <span class=\"d-block text-danger mt-5\" *ngIf=\"formControl.errors?.required\">\r\n    {{'This field is required' | sdTranslate}}\r\n  </span>\r\n    <span class=\"d-block text-danger mt-5\" *ngIf=\"formControl.errors?.minlength\">\r\n    {{'Max length' | sdTranslate}} <strong>{{minlength}}</strong>\r\n  </span>\r\n    <span class=\"d-block text-danger mt-5\" *ngIf=\"formControl.errors?.maxlength\">\r\n    {{'Max length' | sdTranslate}} <strong>{{maxlength}}</strong>\r\n  </span>\r\n  </ng-container>\r\n  <ng-container *ngIf=\"formControl.disabled\">\r\n    <div [innerHtml]=\"formControl.value\"></div>\r\n  </ng-container>\r\n  <ng-container *ngIf=\"enableHTMLButton\">\r\n    <sd-textarea [(model)]=\"modelHTML\" *ngIf=\"showHtmlEditor\" rows=\"20\"\r\n                 (modelChange)=\"onModelChange($event)\"></sd-textarea>\r\n    <sd-button\r\n      title=\"{{showHtmlEditor?'\u1EA8n':'Hi\u1EC7n'}} m\u00E3 HTML\"\r\n      class=\"mr-8\"\r\n      fontSet=\"material-icons-outlined\"\r\n      (action)=\"onClickShowHtmlEditor()\"\r\n      type=\"light\"\r\n    ></sd-button>\r\n  </ng-container>\r\n</div>\r\n",
                    changeDetection: core.ChangeDetectionStrategy.OnPush,
                    styles: ["::ng-deep .c-image-editor-quill-box{background:#000;display:inline-block;position:relative}::ng-deep .c-image-editor-quill-box:hover:after{background:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAA7EAAAOxAGVKw4bAAACoklEQVRIia2WzUtVURTF1748RCQkHIhEiIiINJAGDqMcRYRNQgqiSCKoUUVE/0FIQ2lYJtGgQUhUUA36IIIggkD6HgU6iJz0IZpmrl+Dd67c7nv6hNqTe+5dZ++19zr7bG6oZEAmqU/SQUk7JHVLqgCzEfFK0i1JjyNisezb0Gx3AJeBOWAZ+AJM2X4JfALm0/cXwCCw8eBAJ/Caqj0Dhmy35UGAJmA7MAb8tD0PjNjeUPAO229tL9k+b7vSYP8A8DHtH24UPAPGU+bnbGcFTLb32z4DtJb8epOEM8DW9Qj6gXnbT9MBFzEBj2wDdJV9bR8DVmxfWI9g1PYysKcOJttPEkF3HbwFeG/7czm53DJJgxExCzyvh0eEIiLf+5dFxIKkhxHRoWpr11hF1T6fzrLsR8pqWNLR1D2ZpH5AETEOLKQ901mWnUjrtymBbknv6hE0AauXBuiRNFR4z5c783VEfChUsZi+N69VwWxEtNuuZFn2OyKuSLqTss8iYlzSgKR9ETGdSIsJbUkVzNYjEHDD9hzQW8Zsrx6y7Z46vgLup9u9uV78TNKkpBZJR8pgyqxmXbB+VefVw4j4tlYFm9KI+A70lTABN9Ic6iphFeAusGS7psX/Mtt7bS8BU0BnHZLiYefBLybpbgLrjpZ8XJwClm3PAAdsN62RzDbbt1NwbL+3fRI4BNT4rAqbbuIIMBoRbZLeSHqQ+vwXsDUidkkaBJoj4h6wPSJy6QxcjYjT6QKuKVeP7Uu2v1JrK2k2DSWZzuZAGicrtq81lCxV1JTG8gHbh23vBtpLe46noDlB/rwOtDQk2UASLanLaiq1PWH730lst9q+lVdQlAsY+2cCqSpnTlKUC/j6XwgSSSswWWqIif9GIK3KNUH1r+QasOkPpU8FJ4KtSqcAAAAASUVORK5CYII=\") 50% no-repeat;background-size:16px;bottom:0;content:\"\";left:0;position:absolute;top:0;width:100%}::ng-deep .c-image-editor-quill-box:hover img{opacity:.4}::ng-deep .ql-toolbar input.ql-customFile[type=file]{display:none}"]
                },] }
    ];
    SdEditor.ctorParameters = function () { return [
        { type: core.NgZone },
        { type: core.ChangeDetectorRef },
        { type: undefined, decorators: [{ type: core.Inject, args: [EDITOR_CONFIG,] }, { type: core.Optional }] }
    ]; };
    SdEditor.propDecorators = {
        editor: [{ type: core.ViewChild, args: ['editor',] }],
        label: [{ type: core.Input }],
        model: [{ type: core.Input }],
        disabled: [{ type: core.Input }],
        pRequired: [{ type: core.Input }],
        _minlength: [{ type: core.Input, args: ['minlength',] }],
        _maxlength: [{ type: core.Input, args: ['maxlength',] }],
        modelChange: [{ type: core.Output }],
        placeholder: [{ type: core.Input }],
        styles: [{ type: core.Input }],
        args: [{ type: core.Input }],
        domain: [{ type: core.Input }],
        form: [{ type: core.Input }],
        toolbar: [{ type: core.Input }],
        enableHTMLButton: [{ type: core.Input }],
        mentionValues: [{ type: core.Input }],
        hashTagValues: [{ type: core.Input }],
        sdLabelDef: [{ type: core.ContentChild, args: [common.SdLabelDefDirective,] }],
        sdChange: [{ type: core.Output }]
    };

    var SdEditorModule = /** @class */ (function () {
        function SdEditorModule() {
        }
        return SdEditorModule;
    }());
    SdEditorModule.decorators = [
        { type: core.NgModule, args: [{
                    declarations: [SdEditor],
                    imports: [
                        common$1.CommonModule,
                        forms.FormsModule,
                        forms.ReactiveFormsModule,
                        ngxQuill.QuillModule.forRoot(),
                        translate.SdTranslateModule,
                        button.SdButtonModule,
                        textarea.SdTextareaModule,
                        api.SdApiModule
                    ],
                    exports: [SdEditor],
                    providers: [],
                },] }
    ];

    /*
     * Public API Surface of superdev-angular-core
     */

    /**
     * Generated bundle index. Do not edit.
     */

    exports.Constants = Constants;
    exports.EDITOR_CONFIG = EDITOR_CONFIG;
    exports.PROMOTION_FORM = PROMOTION_FORM;
    exports.PROMOTION_PERMISSIONS = PROMOTION_PERMISSIONS;
    exports.SdEditor = SdEditor;
    exports.SdEditorModule = SdEditorModule;
    exports.ValidateMessageConstants = ValidateMessageConstants;

    Object.defineProperty(exports, '__esModule', { value: true });

})));
//# sourceMappingURL=sd-angular-core-editor.umd.js.map
