import * as i0 from '@angular/core';
import { Directive, Input, EventEmitter, Inject, Output, HostListener, Pipe, NgModule } from '@angular/core';
import * as i1 from '@angular/cdk/clipboard';
import { ClipboardModule } from '@angular/cdk/clipboard';
import { DOCUMENT, CommonModule } from '@angular/common';
import * as i2 from 'ng-devui/i18n';
import { I18nFormat } from 'ng-devui/i18n';
import * as i3 from 'ng-devui/overlay-container';
import { PopoverComponent } from 'ng-devui/popover';
import { HttpParams, HttpEventType } from '@angular/common/http';

class AutoFocusDirective {
    constructor(elementRef) {
        this.elementRef = elementRef;
    }
    ngAfterViewInit() {
        if (this.autoFocus) {
            this.elementRef.nativeElement.focus();
        }
    }
}
AutoFocusDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: AutoFocusDirective, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Directive });
AutoFocusDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "14.2.0", type: AutoFocusDirective, selector: "[dAutoFocus]", inputs: { autoFocus: ["dAutoFocus", "autoFocus"] }, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: AutoFocusDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[dAutoFocus]',
                }]
        }], ctorParameters: function () { return [{ type: i0.ElementRef }]; }, propDecorators: { autoFocus: [{
                type: Input,
                args: ['dAutoFocus']
            }] } });

class ClipboardDirective {
    constructor(elm, clipboard, i18n, overlayContainerRef, componentFactoryResolver, doc) {
        this.elm = elm;
        this.clipboard = clipboard;
        this.i18n = i18n;
        this.overlayContainerRef = overlayContainerRef;
        this.componentFactoryResolver = componentFactoryResolver;
        this.doc = doc;
        this.position = 'top';
        this.sticky = false;
        this.copyResultEvent = new EventEmitter();
        this.onDocumentClick = (event) => {
            event.stopPropagation();
            if (!this.elm.nativeElement.contains(event.target)) {
                this.destroy();
            }
        };
        this.document = this.doc;
    }
    ngOnInit() {
        this.setI18nText();
    }
    setI18nText() {
        this.i18nCommonText = this.i18n.getI18nText().common;
        this.i18nSubscription = this.i18n.langChange().subscribe((data) => {
            this.i18nCommonText = data.common;
        });
    }
    onClickEvent() {
        let isSucceeded = false;
        const isSupported = !!this.document.queryCommandSupported && !!this.document.queryCommandSupported('copy') && !!window;
        if (isSupported && this.content) {
            isSucceeded = this.clipboard.copy(this.content);
            if (isSucceeded) {
                this.tipContent = this.tipContent || this.i18nCommonText.copied;
                this.createPopover();
            }
            const result = { isSupported: isSupported, isSucceeded: isSucceeded, content: this.content };
            this.copyResultEvent.emit(result);
        }
    }
    createPopover() {
        if (this.popoverComponentRef) {
            this.popoverComponentRef.destroy();
        }
        this.popoverComponentRef = this.overlayContainerRef.createComponent(this.componentFactoryResolver.resolveComponentFactory(PopoverComponent));
        Object.assign(this.popoverComponentRef.instance, {
            content: this.tipContent,
            triggerElementRef: this.elm,
            position: this.position,
            popType: 'default',
            popMaxWidth: 200,
            appendToBody: true,
            zIndex: 1060
        });
        this.document.addEventListener('click', this.onDocumentClick);
        if (!this.sticky) {
            setTimeout(() => this.destroy(), 3000);
        }
    }
    destroy() {
        if (this.popoverComponentRef) {
            this.popoverComponentRef.destroy();
            this.popoverComponentRef = null;
        }
        this.document.removeEventListener('click', this.onDocumentClick);
    }
    ngOnDestroy() {
        if (this.i18nSubscription) {
            this.i18nSubscription.unsubscribe();
        }
    }
}
ClipboardDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: ClipboardDirective, deps: [{ token: i0.ElementRef }, { token: i1.Clipboard }, { token: i2.I18nService }, { token: i3.OverlayContainerRef }, { token: i0.ComponentFactoryResolver }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Directive });
ClipboardDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "14.2.0", type: ClipboardDirective, selector: "[dClipboard]", inputs: { devuiTargetElm: ["dClipboard", "devuiTargetElm"], container: "container", content: "content", position: "position", sticky: "sticky", tipContent: "tipContent" }, outputs: { copyResultEvent: "copyResultEvent" }, host: { listeners: { "click": "onClickEvent()" } }, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: ClipboardDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[dClipboard]'
                }]
        }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i1.Clipboard }, { type: i2.I18nService }, { type: i3.OverlayContainerRef }, { type: i0.ComponentFactoryResolver }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [DOCUMENT]
                }] }]; }, propDecorators: { devuiTargetElm: [{
                type: Input,
                args: ['dClipboard']
            }], container: [{
                type: Input
            }], content: [{
                type: Input
            }], position: [{
                type: Input
            }], sticky: [{
                type: Input
            }], tipContent: [{
                type: Input
            }], copyResultEvent: [{
                type: Output
            }], onClickEvent: [{
                type: HostListener,
                args: ['click']
            }] } });

class DatePipe {
    transform(date, pattern) {
        if (!date) {
            return;
        }
        return I18nFormat.formatDate(date, pattern);
    }
}
DatePipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: DatePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
DatePipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "14.2.0", ngImport: i0, type: DatePipe, name: "dDatePipe" });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: DatePipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'dDatePipe'
                }]
        }] });

;
class HelperUtils {
    static getBrowserName() {
        !this._browserName && this.getBrowserInfo();
        return this._browserName;
    }
    static getBrowserVersion() {
        !this._browserVersion && this.getBrowserInfo();
        return this._browserVersion;
    }
    static getBrowserInfo() {
        if (typeof navigator !== 'undefined') {
            const ua = navigator.userAgent.toLowerCase();
            const isIE = ua.match(/rv:([\d.]+)\) like gecko/) || ua.match(/msie ([\d\.]+)/);
            const isClassicEdge = ua.match(/edge\/([\d\.]+)/);
            const isFirefox = ua.match(/firefox\/([\d\.]+)/);
            const isOpera = ua.match(/(?:opera|opr).([\d\.]+)/);
            const isEdge = ua.match(/edg\/([\d\.]+)/);
            const isChrome = ua.match(/chrome\/([\d\.]+)/);
            const isSafari = ua.match(/version\/([\d\.]+).*safari/);
            const infos = isIE || isClassicEdge || isFirefox || isOpera || isEdge || isChrome || isSafari;
            this._browserName = isIE
                ? "IE" /* Browser.IE */
                : isClassicEdge
                    ? "ClassicEdge" /* Browser.ClassicEdge */
                    : isFirefox
                        ? "Firefox" /* Browser.Firefox */
                        : isOpera
                            ? "Opera" /* Browser.Opera */
                            : isEdge
                                ? "Edge" /* Browser.Edge */
                                : isChrome
                                    ? "Chrome" /* Browser.Chrome */
                                    : isSafari
                                        ? "Safari" /* Browser.Safari */
                                        : "Other" /* Browser.Other */;
            this._browserVersion = infos ? parseInt(infos[1], 10) : 0;
        }
    }
    static jumpOuterUrl(url, target = '_blank') {
        if (url !== undefined && typeof document !== 'undefined') {
            const tempLink = document.createElement('a');
            tempLink.style.display = 'none'; // for IE 11
            tempLink.target = target;
            tempLink.href = url;
            document.body.appendChild(tempLink); // for IE 11, IE11需要append到document.body里面的a链接才会生效
            const event = document.createEvent('MouseEvents');
            event.initEvent('click', false, true);
            tempLink.dispatchEvent(event);
            document.body.removeChild(tempLink); // for IE 11
        }
    }
    static downloadFile(url, option, onError) {
        if (typeof document === 'undefined') {
            return;
        }
        if (document.querySelector('iframe[name=' + (option && option.iframename || 'download') + ']')) {
            document.body.removeChild(document.querySelector('iframe[name=' + (option && option.iframename || 'download') + ']'));
        }
        const tempiframe = document.createElement('iframe');
        tempiframe.name = option && option.iframename || 'download';
        tempiframe.style.display = 'none';
        const tempform = document.createElement('form');
        tempform.action = url;
        tempform.method = option && option.method || 'post';
        tempform.target = option && option.iframename || 'download';
        tempform.enctype = option && option.enctype || 'application/x-www-form-urlencoded';
        tempform.style.display = 'none';
        if (option && option.params) {
            Object.keys(option.params).forEach(key => {
                const opt = document.createElement('input');
                opt.name = key;
                opt.value = option.params[key];
                tempform.appendChild(opt);
            });
        }
        const submit = document.createElement('input');
        submit.type = 'submit';
        tempform.appendChild(submit);
        tempiframe.appendChild(tempform);
        document.body.appendChild(tempiframe);
        // 下载错误处理。下载成功并不会响应，因为响应头中带有Content-Disposition（下载头）的url，无法监听iframe的load事件，load事件不会触发
        tempiframe.addEventListener('load', (event) => {
            try {
                const iframeDoc = tempiframe.contentDocument;
                if (onError !== undefined) {
                    let response;
                    try {
                        response = JSON.parse(iframeDoc.body && iframeDoc.body.textContent);
                    }
                    catch (e) {
                        response = iframeDoc.body && iframeDoc.body.textContent;
                    }
                    if (!response) {
                        response = 'Error';
                    }
                    onError(response);
                }
            }
            catch (e) {
                onError('Error');
            }
            document.body.removeChild(tempiframe);
        });
        tempform.submit();
    }
    static downloadFileByHttpClient(httpClient, url, option, onError, onSuccess, onProgress) {
        const requestMethod = option && option.method && option.method.toLowerCase() || 'post';
        const requestHeaderContentType = option.enctype || 'application/x-www-form-urlencoded';
        const requestParams = option.params ? new HttpParams({
            fromObject: option.params
        }) : null;
        const requestUrl = url;
        const requestOptionParams = requestMethod === 'get' ? requestParams : undefined;
        const requestBody = requestMethod === 'post' ? requestParams && requestParams.toString() : undefined;
        const responseOption = option.responseOption;
        /* eslint-disable-next-line prefer-object-spread */
        const requestOption = Object.assign({}, {
            body: requestBody,
            observe: (option.reportProgress ? 'events' : 'response'),
            params: requestOptionParams,
            headers: {
                'Content-Type': requestHeaderContentType
            },
            withCredentials: option.withCredentials,
            reportProgress: option.reportProgress,
            responseType: (option.reportProgress ? 'blob' : 'arraybuffer')
        }, {
            headers: option.header
        });
        const handleResponse = (resOption => {
            switch (resOption) {
                case 'response':
                    return (res) => res;
                case 'body':
                    return (res) => {
                        const arrayBuffer = res.body || res.error;
                        const body = HelperUtils.utf8ArrayToStr(arrayBuffer);
                        return body;
                    };
                case 'json':
                default:
                    return (res) => {
                        const arrayBuffer = res.body || res.error;
                        let response;
                        try {
                            const body = HelperUtils.utf8ArrayToStr(arrayBuffer);
                            try {
                                response = JSON.parse(body);
                            }
                            catch (e) {
                                const parser = new DOMParser();
                                const html = parser.parseFromString(body, 'text/html');
                                response = html.body.textContent;
                            }
                        }
                        catch (e) {
                            throw new Error('Parsing Error:' + e);
                        }
                        if (!response) {
                            response = 'Error';
                        }
                        return response;
                    };
            }
        })(responseOption);
        const downloadFileFromArrayBuffer = (data, filename, contentType) => {
            if (typeof document === 'undefined' || typeof window === 'undefined') {
                return;
            }
            if (window.navigator && window.navigator['msSaveOrOpenBlob']) { // IE11 support
                const blob = new Blob([data], { type: contentType });
                window.navigator['msSaveOrOpenBlob'](blob, filename);
            }
            else { // other browsers
                if ('download' in document.createElement('a')) {
                    const blob = new Blob([data], { type: contentType });
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = filename;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    URL.revokeObjectURL(link.href);
                }
                else {
                    // not support tag a download attribute use file download, filename won't support
                    const file = new File([data], filename, { type: contentType });
                    const exportUrl = URL.createObjectURL(file);
                    window.location.assign(exportUrl);
                    URL.revokeObjectURL(exportUrl);
                }
            }
        };
        const getFilenameFromDisposition = (disposition) => {
            const filenamePair = disposition.split(';').filter(str => /^filename=/.test(str.trim())).pop();
            if (filenamePair) {
                let str = filenamePair.trim();
                str = str.split('=')[1];
                str = str.replace(/['"]/g, '');
                return decodeURIComponent(str);
            }
            else {
                return null;
            }
        };
        httpClient.request(requestMethod, requestUrl, requestOption).subscribe((res) => {
            if (res.type === HttpEventType.DownloadProgress) {
                if (onProgress) {
                    onProgress(res);
                }
            }
            else if (res.type === HttpEventType.Response) {
                const httpResponse = res;
                const disposition = httpResponse.headers.get('content-disposition');
                const contentType = httpResponse.headers.get('content-type');
                if (/^attachment/i.test(disposition) || option.downloadWithoutDispositionHeader) {
                    const downloadFilename = option.filename || disposition && getFilenameFromDisposition(disposition) || url;
                    downloadFileFromArrayBuffer(httpResponse.body, downloadFilename, contentType);
                    if (onSuccess) {
                        onSuccess(httpResponse);
                    }
                }
                else {
                    if (onError) {
                        let response;
                        try {
                            response = handleResponse(httpResponse);
                        }
                        catch (e) {
                            response = httpResponse;
                        }
                        onError(response);
                    }
                }
            }
        }, err => {
            if (onError) {
                let response;
                try {
                    response = handleResponse(err);
                }
                catch (e) {
                    response = err;
                }
                onError(response);
            }
        });
    }
    static utf8ArrayToStr(arrayBuffer) {
        if (typeof TextDecoder !== 'undefined') {
            return new TextDecoder('utf-8').decode(arrayBuffer);
        }
        else {
            /**
             * fallback 方案，无TextDecoder场景使用直接解析，英文无问题，中文会存在乱码
             * ie 11 下支持中文需要使用MDN推荐的 fastestsmallesttextencoderdecoder以支持TextDecoder
             * npm install fastestsmallesttextencoderdecoder
             * polyfill.ts includes
             * ```
             * // polyfill for TextDecoder on IE 11
             * import 'fastestsmallesttextencoderdecoder';
             * ```
             */
            return String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
        }
    }
}
HelperUtils._browserName = null;
HelperUtils._browserVersion = null;
class SimulateATagDirective {
    constructor() {
        this.target = '_blank';
    }
    onClick() {
        HelperUtils.jumpOuterUrl(this.href, this.target);
    }
}
SimulateATagDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: SimulateATagDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
SimulateATagDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "14.2.0", type: SimulateATagDirective, selector: "[dSimulateATag]", inputs: { href: "href", target: "target" }, host: { listeners: { "click": "onClick()" } }, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: SimulateATagDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[dSimulateATag]'
                }]
        }], ctorParameters: function () { return []; }, propDecorators: { href: [{
                type: Input
            }], target: [{
                type: Input
            }], onClick: [{
                type: HostListener,
                args: ['click']
            }] } });

class IframeEventPropagateDirective {
    constructor(el, doc) {
        this.doc = doc;
        this.event = 'click';
        this.AddIframeContentDocumentClickListener = () => {
            const iframe = this.element.querySelector('iframe');
            if (iframe !== null) {
                if (iframe.contentDocument !== null) {
                    iframe.contentDocument.addEventListener(this.event, this.dispatchClickEvent);
                }
                else {
                    const loadHandler = () => {
                        iframe.contentDocument.addEventListener(this.event, this.dispatchClickEvent);
                        iframe.removeEventListener('load', loadHandler);
                    };
                    iframe.addEventListener('load', loadHandler);
                }
                this.element.removeEventListener('DOMSubtreeModified', this.AddIframeContentDocumentClickListener);
            }
        };
        this.dispatchClickEvent = ($event) => {
            const event = this.document.createEvent('MouseEvents');
            event.initEvent(this.event, true, true);
            event['originEvent'] = $event;
            this.element.dispatchEvent(event);
        };
        this.element = el.nativeElement;
        this.document = this.doc;
    }
    ngAfterViewInit() {
        this.element.addEventListener('DOMSubtreeModified', this.AddIframeContentDocumentClickListener);
        if (this.element.querySelector('iframe') !== null) {
            this.AddIframeContentDocumentClickListener();
        }
    }
}
IframeEventPropagateDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: IframeEventPropagateDirective, deps: [{ token: i0.ElementRef }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Directive });
IframeEventPropagateDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "14.2.0", type: IframeEventPropagateDirective, selector: "[dIframeEventPropagate]", inputs: { event: "event" }, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: IframeEventPropagateDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[dIframeEventPropagate]'
                }]
        }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [DOCUMENT]
                }] }]; }, propDecorators: { event: [{
                type: Input
            }] } });

class DCommonModule {
}
DCommonModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: DCommonModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
DCommonModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "14.2.0", ngImport: i0, type: DCommonModule, declarations: [AutoFocusDirective,
        DatePipe,
        SimulateATagDirective,
        IframeEventPropagateDirective,
        ClipboardDirective], imports: [CommonModule,
        ClipboardModule], exports: [AutoFocusDirective,
        DatePipe,
        SimulateATagDirective,
        IframeEventPropagateDirective,
        ClipboardDirective] });
DCommonModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: DCommonModule, imports: [CommonModule,
        ClipboardModule] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.0", ngImport: i0, type: DCommonModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        CommonModule,
                        ClipboardModule
                    ],
                    exports: [
                        AutoFocusDirective,
                        DatePipe,
                        SimulateATagDirective,
                        IframeEventPropagateDirective,
                        ClipboardDirective
                    ],
                    declarations: [
                        AutoFocusDirective,
                        DatePipe,
                        SimulateATagDirective,
                        IframeEventPropagateDirective,
                        ClipboardDirective
                    ],
                    providers: [],
                }]
        }] });

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

export { AutoFocusDirective, ClipboardDirective, DCommonModule, DatePipe, HelperUtils, IframeEventPropagateDirective, SimulateATagDirective };
//# sourceMappingURL=ng-devui-common.mjs.map
