ng-devui
Version:
DevUI components based on Angular
585 lines (574 loc) • 26.9 kB
JavaScript
import * as i0 from '@angular/core';
import { Directive, Input, EventEmitter, Inject, Output, HostListener, Pipe, HostBinding, 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) {
setTimeout(() => {
this.elementRef.nativeElement.focus();
});
}
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AutoFocusDirective, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Directive }); }
static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "18.2.13", type: AutoFocusDirective, selector: "[dAutoFocus]", inputs: { autoFocus: ["dAutoFocus", "autoFocus"] }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AutoFocusDirective, decorators: [{
type: Directive,
args: [{
selector: '[dAutoFocus]',
}]
}], ctorParameters: () => [{ 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();
}
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", 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 }); }
static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "18.2.13", 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: "18.2.13", ngImport: i0, type: ClipboardDirective, decorators: [{
type: Directive,
args: [{
selector: '[dClipboard]'
}]
}], ctorParameters: () => [{ 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);
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: DatePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.13", ngImport: i0, type: DatePipe, name: "dDatePipe" }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: DatePipe, decorators: [{
type: Pipe,
args: [{
name: 'dDatePipe'
}]
}] });
class SafeNullPipe {
transform(value, replace = '--') {
if (typeof value === 'undefined' || value === null || value === '') {
return replace;
}
return value;
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: SafeNullPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.13", ngImport: i0, type: SafeNullPipe, name: "dSafeNullPipe" }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: SafeNullPipe, decorators: [{
type: Pipe,
args: [{
name: 'dSafeNullPipe',
}]
}] });
class HelperUtils {
static { this._browserName = null; }
static { this._browserVersion = null; }
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 results = [
ua.match(/rv:([\d.]+)\) like gecko/) || ua.match(/msie ([\d\.]+)/),
ua.match(/edge\/([\d\.]+)/),
ua.match(/firefox\/([\d\.]+)/),
ua.match(/(?:opera|opr).([\d\.]+)/),
ua.match(/edg\/([\d\.]+)/),
ua.match(/chrome\/([\d\.]+)/),
ua.match(/version\/([\d\.]+).*safari/),
];
const index = results.findIndex((item) => item);
const infos = results[index];
const browserNames = ["IE" /* Browser.IE */, "ClassicEdge" /* Browser.ClassicEdge */, "Firefox" /* Browser.Firefox */, "Opera" /* Browser.Opera */, "Edge" /* Browser.Edge */, "Chrome" /* Browser.Chrome */, "Safari" /* Browser.Safari */];
this._browserName = browserNames[index] || "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?.iframename || 'download'}]`)) {
document.body.removeChild(document.querySelector(`iframe[name='${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.observe || option.reportProgress ? 'events' : 'response'),
params: requestOptionParams,
headers: {
'Content-Type': requestHeaderContentType,
},
withCredentials: option.withCredentials,
reportProgress: option.reportProgress,
responseType: (option.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?.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;
}
};
const subscriber = 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);
}
});
return subscriber;
}
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));
}
}
}
class SimulateATagDirective {
constructor() {
this.target = '_blank';
}
onClick() {
HelperUtils.jumpOuterUrl(this.href, this.target);
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: SimulateATagDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "18.2.13", type: SimulateATagDirective, selector: "[dSimulateATag]", inputs: { href: "href", target: "target" }, host: { listeners: { "click": "onClick()" } }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: SimulateATagDirective, decorators: [{
type: Directive,
args: [{
selector: '[dSimulateATag]',
}]
}], ctorParameters: () => [], 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();
}
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: IframeEventPropagateDirective, deps: [{ token: i0.ElementRef }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Directive }); }
static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "18.2.13", type: IframeEventPropagateDirective, selector: "[dIframeEventPropagate]", inputs: { event: "event" }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: IframeEventPropagateDirective, decorators: [{
type: Directive,
args: [{
selector: '[dIframeEventPropagate]',
}]
}], ctorParameters: () => [{ type: i0.ElementRef }, { type: undefined, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }], propDecorators: { event: [{
type: Input
}] } });
class ShapeIconHoverableDirective {
getStyle() {
return true;
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: ShapeIconHoverableDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "18.2.13", type: ShapeIconHoverableDirective, selector: "[dShapeIconHoverable]", host: { properties: { "class.devui-shape-icon": "this.getStyle" } }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: ShapeIconHoverableDirective, decorators: [{
type: Directive,
args: [{
selector: '[dShapeIconHoverable]'
}]
}], propDecorators: { getStyle: [{
type: HostBinding,
args: ['class.devui-shape-icon']
}] } });
class DCommonModule {
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: DCommonModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.13", ngImport: i0, type: DCommonModule, declarations: [SafeNullPipe,
AutoFocusDirective,
DatePipe,
SimulateATagDirective,
IframeEventPropagateDirective,
ClipboardDirective,
ShapeIconHoverableDirective], imports: [CommonModule,
ClipboardModule], exports: [SafeNullPipe,
AutoFocusDirective,
DatePipe,
SimulateATagDirective,
IframeEventPropagateDirective,
ClipboardDirective,
ShapeIconHoverableDirective] }); }
static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: DCommonModule, imports: [CommonModule,
ClipboardModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: DCommonModule, decorators: [{
type: NgModule,
args: [{
imports: [
CommonModule,
ClipboardModule
],
exports: [
SafeNullPipe,
AutoFocusDirective,
DatePipe,
SimulateATagDirective,
IframeEventPropagateDirective,
ClipboardDirective,
ShapeIconHoverableDirective,
],
declarations: [
SafeNullPipe,
AutoFocusDirective,
DatePipe,
SimulateATagDirective,
IframeEventPropagateDirective,
ClipboardDirective,
ShapeIconHoverableDirective
],
providers: [],
}]
}] });
/**
* Generated bundle index. Do not edit.
*/
export { AutoFocusDirective, ClipboardDirective, DCommonModule, DatePipe, HelperUtils, IframeEventPropagateDirective, SafeNullPipe, ShapeIconHoverableDirective, SimulateATagDirective };
//# sourceMappingURL=ng-devui-common.mjs.map