diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 00000000..c4a623cd --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,145 @@ +module.exports = { + rules: { + "no-useless-constructor": "off", + "no-useless-concat":"off", + "max-params": "off", + "@typescript-eslint/no-useless-constructor": "off", + "@typescript-eslint/no-parameter-properties": "off", + "@typescript-eslint/no-require-imports": "off", + "@typescript-eslint/no-var-requires": "off", + "@angular-eslint/component-class-suffix": ["error", { suffixes: ["Component", "Directive"] }], + "@angular-eslint/component-selector": [ + "error", + { + "type": "element", + "prefix": "d", + "style": "kebab-case" + } + ], + "@angular-eslint/directive-class-suffix":["error", { suffixes: ["Component", "Directive"] }], + "@angular-eslint/directive-selector": [ + "error", + { + "type": ["attribute","element"], + "prefix": "d", + "style": "camelCase" + } + ], + "@angular-eslint/no-host-metadata-property": "error", + "@angular-eslint/no-input-rename": "off", + "@angular-eslint/no-inputs-metadata-property": "error", + "@angular-eslint/no-output-on-prefix": "error", + "@angular-eslint/no-output-rename": "error", + "@angular-eslint/no-outputs-metadata-property": "error", + "@angular-eslint/use-lifecycle-interface": "error", + "@angular-eslint/use-pipe-transform-interface": "error", + "complexity": [ + 'error', + { + max: 40, + }, + ], + + "curly": "error", + "eol-last": "error", + "eqeqeq": [ + "error", + "smart" + ], + "max-len": [ + "error", + { + "code": 140 + } + ], + "no-console": [ + "error", + { + "allow": [ + "log", + "warn", + "dir", + "timeLog", + "assert", + "clear", + "count", + "countReset", + "group", + "groupEnd", + "table", + "dirxml", + "error", + "groupCollapsed", + "Console", + "profile", + "profileEnd", + "timeStamp", + "context" + ] + } + ], + + "no-multiple-empty-lines": "error", + "no-shadow": "off", // 使用@typescript-eslint/no-shadow,规避使用enum类型报错 + "no-trailing-spaces": "error", + "no-unused-labels": "error", + "no-use-before-define": "error", + "no-var": "error", + "prefer-const": "error", + "semi": "error", + "space-in-parens": [ + "error", + "never" + ], + "spaced-comment": [ + "error", + "always" + ], + "@typescript-eslint/dot-notation": "off", + "@typescript-eslint/indent": [ + "error", + 2, + { + "FunctionDeclaration": { + "parameters": "first" + }, + "FunctionExpression": { + "parameters": "first" + } + } + ], + "@typescript-eslint/member-delimiter-style": [ + "error", + { + "multiline": { + "delimiter": "semi", + "requireLast": true + }, + "singleline": { + "delimiter": "semi", + "requireLast": false + } + } + ], + "@typescript-eslint/no-misused-new": "error", + "@typescript-eslint/no-non-null-assertion": "error", + "@typescript-eslint/prefer-function-type": "error", + "@typescript-eslint/semi": [ + "error", + "always" + ], + "@typescript-eslint/type-annotation-spacing": "error", + "@typescript-eslint/unified-signatures": "error", + "@typescript-eslint/no-shadow":"error", + "@angular-eslint/no-output-on-prefix":"off", + "@angular-eslint/use-pipe-transform-interface":"off", + + "prefer-promise-reject-errors": "off", + 'max-nested-callbacks': ['error', 6], + "@typescript-eslint/no-this-alias":"off", + "accessor-pairs": "off", + "max-depth": "off", + "@typescript-eslint/member-ordering": "off", + "array-callback-return":"off" + } +}; diff --git a/.gitignore b/.gitignore index 2feffe82..8b3fdd89 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,5 @@ testem.log Thumbs.db desktop.ini debug.log - # package-lock package-lock.json diff --git a/angular.json b/angular.json index a700d025..73187739 100755 --- a/angular.json +++ b/angular.json @@ -36,7 +36,8 @@ ], "styles": [ "node_modules/highlight.js/styles/an-old-hope.css", - "src/styles.scss" + "src/styles.scss", + "devui/style/layout/devui-layout.scss" ], "scripts": [] }, @@ -118,14 +119,11 @@ } }, "lint": { - "builder": "@angular-devkit/build-angular:tslint", + "builder": "@angular-eslint/builder:lint", "options": { - "tsConfig": [ - "src/tsconfig.app.json", - "src/tsconfig.spec.json" - ], - "exclude": [ - "**/node_modules/**" + "fix": true, + "lintFilePatterns": [ + "src/**/*.ts" ] } } @@ -147,15 +145,6 @@ "devServerTarget": "devui:serve:production" } } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": "e2e/tsconfig.e2e.json", - "exclude": [ - "**/node_modules/**" - ] - } } } }, @@ -194,14 +183,11 @@ } }, "lint": { - "builder": "@angular-devkit/build-angular:tslint", + "builder": "@angular-eslint/builder:lint", "options": { - "tsConfig": [ - "devui/tsconfig.lib.json", - "devui/tsconfig.spec.json" - ], - "exclude": [ - "**/node_modules/**" + "fix": true, + "lintFilePatterns": [ + "devui/**/*.ts" ] } } diff --git a/devui/accordion/accordion-base-component.class.ts b/devui/accordion/accordion-base-component.class.ts index 54bdcd87..f75ef32e 100644 --- a/devui/accordion/accordion-base-component.class.ts +++ b/devui/accordion/accordion-base-component.class.ts @@ -2,7 +2,6 @@ import { Directive, HostBinding, Input } from '@angular/core'; import { AccordionBase, AccordionOptions } from './accordion.type'; @Directive() -// tslint:disable-next-line: directive-class-suffix export abstract class AccordionBaseComponent { @Input() item: any | T; @Input() deepth = 0; diff --git a/devui/accordion/accordion-base-item-component.class.ts b/devui/accordion/accordion-base-item-component.class.ts index c0e25b77..f078dac2 100644 --- a/devui/accordion/accordion-base-item-component.class.ts +++ b/devui/accordion/accordion-base-item-component.class.ts @@ -3,7 +3,6 @@ import { AccordionBaseComponent } from './accordion-base-component.class'; import { AccordionBaseItem, AccordionOptions } from './accordion.type'; @Directive() -// tslint:disable-next-line: directive-class-suffix export abstract class AccordionBaseItemComponent extends AccordionBaseComponent { get itemTemplate() { return this.accordion.itemTemplate; diff --git a/devui/accordion/accordion-base-link-component.class.ts b/devui/accordion/accordion-base-link-component.class.ts index f1a1ddac..9d40c152 100644 --- a/devui/accordion/accordion-base-link-component.class.ts +++ b/devui/accordion/accordion-base-link-component.class.ts @@ -3,7 +3,6 @@ import { AccordionBaseItemComponent } from './accordion-base-item-component.clas import { AccordionLinkableItem, AccordionOptions } from './accordion.type'; @Directive() -// tslint:disable-next-line: directive-class-suffix export abstract class AccordionBaseLinkComponent extends AccordionBaseItemComponent { get link() { return this.item && this.item[this.accordion.linkKey]; diff --git a/devui/accordion/accordion-list.component.ts b/devui/accordion/accordion-list.component.ts index 33ea8180..8494e5a3 100644 --- a/devui/accordion/accordion-list.component.ts +++ b/devui/accordion/accordion-list.component.ts @@ -99,17 +99,17 @@ export class AccordionListComponent implements OnInit, OnDestroy { get routerLinkActived(): boolean { return (!!this.accordionItemRouterlinkQueryList && this.accordionItemRouterlinkQueryList.some(airlc => this.isLinkRouterActive(airlc)) - ) || ( - !!this.accordionMenuQueryList + ) || ( + !!this.accordionMenuQueryList && this.accordionMenuQueryList.some(amc => this.isMenuRouterActive(amc)) - ); + ); } get hasActiveChildren(): boolean { return (!!this.accordionMenuQueryList && this.accordionMenuQueryList.some(amc => this.isMenuDataActive(amc))) || (!!this.data && !!this.data.length && this.data.some(item => this.isItemData(item) && this.isItemDataActive(item)) - ); + ); } menuToggleItemFn = (item: any , event?: any) => { this.accordion.menuToggleFn({ @@ -118,12 +118,12 @@ export class AccordionListComponent implements OnInit, OnDestroy { parent: this.parent.parent, event: event }); - } + }; itemClickItemFn = (item: any, event?: any) => { this.accordion.itemClickFn({ item: item, parent: this.parent, event: event }); - } + }; } diff --git a/devui/accordion/accordion.component.ts b/devui/accordion/accordion.component.ts index fd9e2a93..f0404a2f 100755 --- a/devui/accordion/accordion.component.ts +++ b/devui/accordion/accordion.component.ts @@ -53,7 +53,7 @@ export class AccordionComponent implements AccordionOptions, OnChanges, OnInit, ngOnChanges(changes: SimpleChanges) { if (changes['data']) { - this.initActiveItem(); + this.initActiveItem(); } if (changes['autoOpenActiveMenu']) { if (this.autoOpenActiveMenu && changes['autoOpenActiveMenu'].previousValue === false) { @@ -99,7 +99,7 @@ export class AccordionComponent implements AccordionOptions, OnChanges, OnInit, private cleanOpenData() { this.flatten(this.data, this.childrenKey, true, false).forEach( - item => item[this.openKey] = undefined + item => {item[this.openKey] = undefined;} ); } // 默认激活 @@ -120,19 +120,19 @@ export class AccordionComponent implements AccordionOptions, OnChanges, OnInit, const prevActiveItem = this.activeItem; this.activeItemFn(itemEvent.item); this.itemClick.emit({...itemEvent, prevActiveItem: prevActiveItem}); - } + }; linkItemClickFn = (itemEvent: AccordionItemClickEvent) => { const prevActiveItem = this.activeItem; this.activeItem = itemEvent.item; this.itemClick.emit({...itemEvent, prevActiveItem: prevActiveItem}); - } + }; // 打开或关闭可折叠菜单 public menuToggleFn = (menuEvent: AccordionMenuToggleEvent) => { this.openMenuFn(menuEvent.item, menuEvent.open); this.menuToggle.emit(menuEvent); - } + }; // 激活子菜单项并去掉其他子菜单的激活 activeItemFn(item) { diff --git a/devui/accordion/accordion.type.ts b/devui/accordion/accordion.type.ts index 10d525fc..e1b59128 100755 --- a/devui/accordion/accordion.type.ts +++ b/devui/accordion/accordion.type.ts @@ -23,7 +23,7 @@ interface IAccordionLinkable { } export interface AccordionBaseItem extends AccordionBase, - IAccordionActiveable { + IAccordionActiveable { } export interface AccordionBaseMenu extends AccordionBase, @@ -37,9 +37,9 @@ export interface AccordionLinkableItem } export interface AccordionMenuItem extends AccordionBase, - IAccordionActiveable, - IAccordionFoldable, - IAccordionLinkable { + IAccordionActiveable, + IAccordionFoldable, + IAccordionLinkable { } export type AccordionMenuType = Array; diff --git a/devui/accordion/demo/accordion-demo.component.ts b/devui/accordion/demo/accordion-demo.component.ts index a044571b..8a1b6c57 100755 --- a/devui/accordion/demo/accordion-demo.component.ts +++ b/devui/accordion/demo/accordion-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox/devui-source-data'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'd-accordion-demo', diff --git a/devui/accordion/demo/accordion-demo.moudule.ts b/devui/accordion/demo/accordion-demo.moudule.ts index 2df6c8eb..1ee1812f 100755 --- a/devui/accordion/demo/accordion-demo.moudule.ts +++ b/devui/accordion/demo/accordion-demo.moudule.ts @@ -51,6 +51,6 @@ import { TemplateComponent } from './template/template.component'; ChangeKeyComponent, ], providers: [], - + }) export class AccordionDemoModule {} diff --git a/devui/accordion/demo/multi-level/multi-level.component.ts b/devui/accordion/demo/multi-level/multi-level.component.ts index 56e801bf..53a0871a 100644 --- a/devui/accordion/demo/multi-level/multi-level.component.ts +++ b/devui/accordion/demo/multi-level/multi-level.component.ts @@ -20,29 +20,29 @@ export class MultiLevelComponent { title: 'Content 3 (as a parent menu, has children)', children: [{ - title: 'Child Content 1 (has children)', - children: [ - {title: 'Child Content 1'}, - {title: 'Child Content 2', active: true}, - {title: 'Child Content 3'}, - ] - }, { - title: 'Child Content 2 (has children', - children: [ - {title: 'Child Content 1'}, - { - title: 'Child Content 2 (has children', - children: [ - {title: 'Child Content 1'}, - {title: 'Child Content 2'}, - {title: 'Child Content 3'}, - ] - }, - {title: 'Child Content 3'}, - ] - }, - {title: 'Child Content 2'}, - {title: 'Child Content 3'}, + title: 'Child Content 1 (has children)', + children: [ + {title: 'Child Content 1'}, + {title: 'Child Content 2', active: true}, + {title: 'Child Content 3'}, + ] + }, { + title: 'Child Content 2 (has children', + children: [ + {title: 'Child Content 1'}, + { + title: 'Child Content 2 (has children', + children: [ + {title: 'Child Content 1'}, + {title: 'Child Content 2'}, + {title: 'Child Content 3'}, + ] + }, + {title: 'Child Content 3'}, + ] + }, + {title: 'Child Content 2'}, + {title: 'Child Content 3'}, ] }, { title: 'Content 4 (as a parent menu, has no child)', diff --git a/devui/alert/demo/alert-demo.component.html b/devui/alert/demo/alert-demo.component.html index 765e3805..0f54c603 100755 --- a/devui/alert/demo/alert-demo.component.html +++ b/devui/alert/demo/alert-demo.component.html @@ -26,7 +26,7 @@ {{ 'components.alert.withoutIconDemo.description' | translate }} - + diff --git a/devui/alert/demo/alert-demo.component.ts b/devui/alert/demo/alert-demo.component.ts index a416c00a..5b9441e4 100755 --- a/devui/alert/demo/alert-demo.component.ts +++ b/devui/alert/demo/alert-demo.component.ts @@ -1,10 +1,10 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ - selector: 'd-alert-demo', - templateUrl: './alert-demo.component.html' + selector: 'd-alert-demo', + templateUrl: './alert-demo.component.html' }) export class AlertDemoComponent implements OnInit, OnDestroy { basicSource: Array = [ diff --git a/devui/alert/demo/alert-demo.module.ts b/devui/alert/demo/alert-demo.module.ts index 7c37fd59..186dba2e 100755 --- a/devui/alert/demo/alert-demo.module.ts +++ b/devui/alert/demo/alert-demo.module.ts @@ -38,7 +38,7 @@ import { WithoutIconComponent } from './withoutIcon/withoutIcon.component'; CloseComponent, WithoutIconComponent ], - + }) export class AlertDemoModule { } diff --git a/devui/alert/demo/withoutIcon/withoutIcon.component.ts b/devui/alert/demo/withoutIcon/withoutIcon.component.ts index 010b7a2f..df7a692e 100644 --- a/devui/alert/demo/withoutIcon/withoutIcon.component.ts +++ b/devui/alert/demo/withoutIcon/withoutIcon.component.ts @@ -1,7 +1,7 @@ import { Component, OnInit } from '@angular/core'; @Component({ - selector: 'd-alert-withoutIcon', + selector: 'd-alert-without-icon', templateUrl: './withoutIcon.component.html', styleUrls: ['./withoutIcon.component.css'] }) diff --git a/devui/anchor/anchor-box-hash.directive.ts b/devui/anchor/anchor-box-hash.directive.ts index eeeabec8..97d6a528 100644 --- a/devui/anchor/anchor-box-hash.directive.ts +++ b/devui/anchor/anchor-box-hash.directive.ts @@ -47,7 +47,7 @@ export class AnchorBoxHashSupportDirective implements OnInit, AfterViewInit, OnD if (targetAnchor.activeChangeBy === 'initial') { return; } this.router.navigate([], { fragment: targetAnchor.anchor, replaceUrl: true }); this.manual = true; - } + }; navigateToAnchor = (event: NavigationEnd) => { if (this.manual) { @@ -57,7 +57,7 @@ export class AnchorBoxHashSupportDirective implements OnInit, AfterViewInit, OnD if (this.scrollToAnchorByHashOnlyInit) { return; } const frag = this.router.parseUrl(event.url).fragment; this.scrollToFragment(frag); - } + }; scrollToFragment = (frag: string) => { if (!frag) { return; } @@ -67,5 +67,5 @@ export class AnchorBoxHashSupportDirective implements OnInit, AfterViewInit, OnD tempAnchor.anchorBlock = this.box.anchorMap[frag]; tempAnchor.scrollToAnchor('fragment'); } - } + }; } diff --git a/devui/anchor/anchor-box.directive.ts b/devui/anchor/anchor-box.directive.ts index 1998897c..51fdfc39 100755 --- a/devui/anchor/anchor-box.directive.ts +++ b/devui/anchor/anchor-box.directive.ts @@ -13,8 +13,8 @@ export class AnchorBoxDirective implements IAnchorBox, OnDestroy { public activeChange = this.activeChangeSubject.asObservable(); sub: Subscription; @Input() view: { - top?: number, - bottom?: number + top?: number; + bottom?: number; }; @Input() defaultAnchor: string; @Input() scrollTarget: HTMLElement; @@ -33,12 +33,12 @@ export class AnchorBoxDirective implements IAnchorBox, OnDestroy { this.anchorMap = {}; this._anchorList = list; this._anchorList.toArray().forEach(targetAnchor => { - this.anchorMap[targetAnchor.anchor] = targetAnchor; - targetAnchor.boxElement = this; - this.sub.add( - targetAnchor.activeChangeSubject.pipe(filter(bool => !!bool)).subscribe(() => { - this.activeChangeSubject.next(targetAnchor); - })); + this.anchorMap[targetAnchor.anchor] = targetAnchor; + targetAnchor.boxElement = this; + this.sub.add( + targetAnchor.activeChangeSubject.pipe(filter(bool => !!bool)).subscribe(() => { + this.activeChangeSubject.next(targetAnchor); + })); }); this.refreshAnchorMap.next(); } @@ -51,12 +51,12 @@ export class AnchorBoxDirective implements IAnchorBox, OnDestroy { this.anchorMap[anchorName].isActive = true; if (deactivateOtherAnchor) { Object.keys(this.anchorMap) - .filter(name => name !== anchorName) - .map(name => this.anchorMap[name]) - .forEach(anchor => { - anchor.activeChangeBy = forceActiveSource; - anchor.isActive = false; - }); + .filter(name => name !== anchorName) + .map(name => this.anchorMap[name]) + .forEach(anchor => { + anchor.activeChangeBy = forceActiveSource; + anchor.isActive = false; + }); } } ngOnDestroy() { diff --git a/devui/anchor/anchor-link.directive.ts b/devui/anchor/anchor-link.directive.ts index 9353744a..0e4a1337 100755 --- a/devui/anchor/anchor-link.directive.ts +++ b/devui/anchor/anchor-link.directive.ts @@ -62,7 +62,7 @@ export class AnchorLinkDirective implements OnInit, OnDestroy { } else { this.bindingAnchorTimer = setTimeout(this.bindAnchorAfterBoxReady, 500); } - } + }; @HostListener('click') scrollToAnchor(activeChangeBy?: AnchorActiveChangeSource) { diff --git a/devui/anchor/anchor.directive.ts b/devui/anchor/anchor.directive.ts index e65785b9..9404d8bd 100755 --- a/devui/anchor/anchor.directive.ts +++ b/devui/anchor/anchor.directive.ts @@ -97,7 +97,7 @@ export class AnchorDirective implements AfterViewInit, OnDestroy { this.scrollTimer = null; }, this.THROTTLE_DELAY); } - } + }; checkActiveStatus = (activeChangeBy?: AnchorActiveChangeSource) => { if (this.boxElement.isScrollingToTarget) { @@ -116,7 +116,7 @@ export class AnchorDirective implements AfterViewInit, OnDestroy { // 默认处理 this.activeChangeBy = activeChangeBy || 'scroll'; this.isActive = bottom > this.REACH_TOP_VISION_OFFSET && top < this.REACH_TOP_VISION_OFFSET; - } + }; updateScrollListenTarget() { if (this.scrollListenTarget) { diff --git a/devui/anchor/anchor.module.ts b/devui/anchor/anchor.module.ts index f5226a6a..325451e7 100755 --- a/devui/anchor/anchor.module.ts +++ b/devui/anchor/anchor.module.ts @@ -9,22 +9,22 @@ import { AnchorLinkDirective } from './anchor-link.directive'; import { AnchorDirective } from './anchor.directive'; @NgModule({ - imports: [ - CommonModule, - RouterModule - ], - declarations: [ - AnchorLinkDirective, - AnchorBoxDirective, - AnchorDirective, - AnchorBoxHashSupportDirective - ], - exports: [ - AnchorLinkDirective, - AnchorBoxDirective, - AnchorDirective, - AnchorBoxHashSupportDirective - ], + imports: [ + CommonModule, + RouterModule + ], + declarations: [ + AnchorLinkDirective, + AnchorBoxDirective, + AnchorDirective, + AnchorBoxHashSupportDirective + ], + exports: [ + AnchorLinkDirective, + AnchorBoxDirective, + AnchorDirective, + AnchorBoxHashSupportDirective + ], }) export class AnchorModule {} diff --git a/devui/anchor/anchor.type.ts b/devui/anchor/anchor.type.ts index 70e4ff29..bb108a4a 100755 --- a/devui/anchor/anchor.type.ts +++ b/devui/anchor/anchor.type.ts @@ -4,8 +4,8 @@ export interface IAnchorBox { defaultAnchor: string; forceActiveAnchor: Function; view: { - top?: number, - bottom?: number + top?: number; + bottom?: number; }; } export type AnchorActiveChangeSource = 'anchor-link' | 'scroll' | 'click-inside' | 'initial' | 'fragment'; diff --git a/devui/anchor/demo/anchor-demo.component.ts b/devui/anchor/demo/anchor-demo.component.ts index b9fad743..a1b89f0b 100755 --- a/devui/anchor/demo/anchor-demo.component.ts +++ b/devui/anchor/demo/anchor-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/anchor/demo/anchor-demo.module.ts b/devui/anchor/demo/anchor-demo.module.ts index 594cc6a2..f3398723 100755 --- a/devui/anchor/demo/anchor-demo.module.ts +++ b/devui/anchor/demo/anchor-demo.module.ts @@ -44,6 +44,6 @@ import { ScrollTargetComponent } from './scroll-target/scroll-target.component'; ], exports: [AnchorDemoComponent], declarations: [AnchorDemoComponent, BasicComponent, AsyncComponent, HashComponent, ScrollTargetComponent], - + }) export class AnchorDemoModule {} diff --git a/devui/animations/demo/animation-icon/animation-icon.component.ts b/devui/animations/demo/animation-icon/animation-icon.component.ts index 6d343f74..e76fc3a4 100644 --- a/devui/animations/demo/animation-icon/animation-icon.component.ts +++ b/devui/animations/demo/animation-icon/animation-icon.component.ts @@ -24,7 +24,7 @@ export class AnimationIconComponent { this.startDiffusion = true; setTimeout(() => { - this.startDiffusion = false; - }, 400); + this.startDiffusion = false; + }, 400); } } diff --git a/devui/animations/demo/animations-demo.component.ts b/devui/animations/demo/animations-demo.component.ts index c1a76328..643f50dc 100644 --- a/devui/animations/demo/animations-demo.component.ts +++ b/devui/animations/demo/animations-demo.component.ts @@ -1,10 +1,10 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ - selector: 'lib-animations-demo', + selector: 'd-animations-demo', templateUrl: './animations-demo.component.html' }) export class AnimationsDemoComponent implements OnInit, OnDestroy { diff --git a/devui/auto-complete/auto-complete.directive.ts b/devui/auto-complete/auto-complete.directive.ts index 691246c3..83fa7ea5 100755 --- a/devui/auto-complete/auto-complete.directive.ts +++ b/devui/auto-complete/auto-complete.directive.ts @@ -91,7 +91,7 @@ export class AutoCompleteDirective implements OnInit, OnDestroy, OnChanges, Cont @Output() selectValue = new EventEmitter(); @Output() transInputFocusEmit = new EventEmitter(); // input状态传给父组件函数 @Output() changeDropDownStatus = new EventEmitter(); - KEYBOARD_EVENT_NOT_REFRESH = ['escape', 'enter', 'arrowup', 'arrowdown', /*ie 10 edge */ 'esc', 'up', 'down']; + KEYBOARD_EVENT_NOT_REFRESH = ['escape', 'enter', 'arrowup', 'arrowdown', /* ie 10 edge */ 'esc', 'up', 'down']; popupRef: ComponentRef; private destroy$ = new Subject(); @@ -179,14 +179,14 @@ export class AutoCompleteDirective implements OnInit, OnDestroy, OnChanges, Cont this.popupRef.instance.overlayPositions = this.appendToBodyDirections && this.appendToBodyDirections.length > 0 ? this.appendToBodyDirections - .map((position) => { - if (typeof position === 'string') { - return AppendToBodyDirectionsConfig[position]; - } else { - return position; - } - }) - .filter((position) => position !== undefined) + .map((position) => { + if (typeof position === 'string') { + return AppendToBodyDirectionsConfig[position]; + } else { + return position; + } + }) + .filter((position) => position !== undefined) : undefined; } } diff --git a/devui/auto-complete/auto-complete.module.ts b/devui/auto-complete/auto-complete.module.ts index 52d0ac9a..1d0fff3a 100755 --- a/devui/auto-complete/auto-complete.module.ts +++ b/devui/auto-complete/auto-complete.module.ts @@ -14,6 +14,6 @@ import { AutoCompleteDirective } from './auto-complete.directive'; exports: [AutoCompleteDirective, AutoCompletePopupComponent], declarations: [AutoCompleteDirective, AutoCompletePopupComponent], providers: [AutoCompleteConfig], - + }) export class AutoCompleteModule { } diff --git a/devui/auto-complete/demo/array/auto-complete-demo-array.component.ts b/devui/auto-complete/demo/array/auto-complete-demo-array.component.ts index aae4d485..368df50b 100755 --- a/devui/auto-complete/demo/array/auto-complete-demo-array.component.ts +++ b/devui/auto-complete/demo/array/auto-complete-demo-array.component.ts @@ -15,7 +15,6 @@ export class AutoDemoArrayComponent { } selectValue(value) { - // tslint:disable-next-line:no-console - console.info(value); + console.log(value); } } diff --git a/devui/auto-complete/demo/auto-complete-demo.component.ts b/devui/auto-complete/demo/auto-complete-demo.component.ts index 4addd148..2dccd0e6 100755 --- a/devui/auto-complete/demo/auto-complete-demo.component.ts +++ b/devui/auto-complete/demo/auto-complete-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/avatar/avatar.spec.ts b/devui/avatar/avatar.spec.ts index 8dbbcacd..dfd62a63 100644 --- a/devui/avatar/avatar.spec.ts +++ b/devui/avatar/avatar.spec.ts @@ -17,7 +17,7 @@ class TestAvatarComponent { template: ` `, }) class TestCustomAvatarComponent { - @ViewChild('comp') comp: AvatarComponent; + @ViewChild('comp') comp: AvatarComponent; } describe('avatar basic', () => { diff --git a/devui/avatar/demo/avatar-demo.component.ts b/devui/avatar/demo/avatar-demo.component.ts index 2707b647..1ec9bdab 100644 --- a/devui/avatar/demo/avatar-demo.component.ts +++ b/devui/avatar/demo/avatar-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/avatar/demo/basic/basic.component.ts b/devui/avatar/demo/basic/basic.component.ts index c6eeaa4b..b424cfed 100644 --- a/devui/avatar/demo/basic/basic.component.ts +++ b/devui/avatar/demo/basic/basic.component.ts @@ -1,10 +1,10 @@ import { Component, OnInit } from '@angular/core'; @Component({ - selector: 'd-basic', - styleUrls: ['./basic.component.css'], - templateUrl: './basic.component.html' + selector: 'd-basic', + styleUrls: ['./basic.component.css'], + templateUrl: './basic.component.html' }) export class BasicComponent implements OnInit { - ngOnInit() { } + ngOnInit() { } } diff --git a/devui/avatar/demo/config/config.component.ts b/devui/avatar/demo/config/config.component.ts index 83bb9649..8d558bd9 100644 --- a/devui/avatar/demo/config/config.component.ts +++ b/devui/avatar/demo/config/config.component.ts @@ -2,10 +2,10 @@ import { Component } from '@angular/core'; import { environment } from 'src/environments/environment'; @Component({ - selector: 'd-config', - styleUrls: ['./config.component.css'], - templateUrl: './config.component.html' + selector: 'd-config', + styleUrls: ['./config.component.css'], + templateUrl: './config.component.html' }) export class ConfigComponent { - imgSrc = environment.deployPrefix + 'assets/logo.svg'; + imgSrc = environment.deployPrefix + 'assets/logo.svg'; } diff --git a/devui/avatar/demo/special/special.component.ts b/devui/avatar/demo/special/special.component.ts index 0b3525fd..52b9e1be 100644 --- a/devui/avatar/demo/special/special.component.ts +++ b/devui/avatar/demo/special/special.component.ts @@ -1,10 +1,10 @@ import { Component, OnInit } from '@angular/core'; @Component({ - selector: 'd-special', - styleUrls: ['./special.component.css'], - templateUrl: './special.component.html' + selector: 'd-special', + styleUrls: ['./special.component.css'], + templateUrl: './special.component.html' }) export class SpecialComponent implements OnInit { - ngOnInit() { } + ngOnInit() { } } diff --git a/devui/back-top/back-top.component.ts b/devui/back-top/back-top.component.ts index 49d34bd5..3b07698c 100644 --- a/devui/back-top/back-top.component.ts +++ b/devui/back-top/back-top.component.ts @@ -49,11 +49,11 @@ export class BackTopComponent implements OnInit, OnChanges, OnDestroy { addScrollEvent() { this.subs.add( fromEvent(this.getScrollTarget(), 'scroll') - .pipe(debounceTime(this.SCROLL_REFRESH_INTERVAL)) - .subscribe(() => { - this.showButton(); - this.cdr.detectChanges(); - }) + .pipe(debounceTime(this.SCROLL_REFRESH_INTERVAL)) + .subscribe(() => { + this.showButton(); + this.cdr.detectChanges(); + }) ); } @@ -68,7 +68,7 @@ export class BackTopComponent implements OnInit, OnChanges, OnDestroy { showButton() { this.currScrollTop = this.target === window ? - (window.pageYOffset || this.document.documentElement.scrollTop || this.document.body.scrollTop) : this.scrollTarget.scrollTop; + (window.pageYOffset || this.document.documentElement.scrollTop || this.document.body.scrollTop) : this.scrollTarget.scrollTop; if (this.isVisible !== (this.currScrollTop >= this.visibleHeight)) { this.isVisible = !this.isVisible; } diff --git a/devui/back-top/back-top.spec.ts b/devui/back-top/back-top.spec.ts index 1952944f..02f30716 100644 --- a/devui/back-top/back-top.spec.ts +++ b/devui/back-top/back-top.spec.ts @@ -84,10 +84,10 @@ class TestCustomBackTopComponent { describe('back-top', () => { let fixture: ComponentFixture; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [BackTopModule], - declarations: [TestBackTopComponent, TestTargetBackTopComponent, TestCustomBackTopComponent] - }); + TestBed.configureTestingModule({ + imports: [BackTopModule], + declarations: [TestBackTopComponent, TestTargetBackTopComponent, TestCustomBackTopComponent] + }); }); const triggerScroll = (target) => { diff --git a/devui/back-top/demo/back-top-demo.component.ts b/devui/back-top/demo/back-top-demo.component.ts index fe5759e2..6801e247 100644 --- a/devui/back-top/demo/back-top-demo.component.ts +++ b/devui/back-top/demo/back-top-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/badge/badge.spec.ts b/devui/badge/badge.spec.ts index f386312d..78f9021c 100644 --- a/devui/badge/badge.spec.ts +++ b/devui/badge/badge.spec.ts @@ -4,150 +4,150 @@ import { By } from '@angular/platform-browser'; import { BadgeModule } from 'ng-devui/badge/badge.module'; import { BadgeComponent } from './badge.component'; @Component({ - template: ` + template: `
未读消息
` }) class HasContentBadgeComponent { - count = 8; - status = 'danger'; - badgePos = 'top-right'; - showDot = false; - maxCount = 99; + count = 8; + status = 'danger'; + badgePos = 'top-right'; + showDot = false; + maxCount = 99; } @Component({ - template: ` + template: ` ` }) class NoContentBadgeComponent { - count = 6; - status = 'danger'; - showDot = false; + count = 6; + status = 'danger'; + showDot = false; } describe('badge', () => { - let fixture: ComponentFixture; + let fixture: ComponentFixture; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [BadgeModule], + declarations: [HasContentBadgeComponent, NoContentBadgeComponent], + }); + }); + + describe('has content badge', () => { + let debugEl: DebugElement; + let component: HasContentBadgeComponent; + let spanElement: HTMLElement; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [BadgeModule], - declarations: [HasContentBadgeComponent, NoContentBadgeComponent], - }); + fixture = TestBed.createComponent(HasContentBadgeComponent); + debugEl = fixture.debugElement; + component = fixture.componentInstance; + spanElement = debugEl.query(By.directive(BadgeComponent)).nativeElement; + + fixture.detectChanges(); + }); + + it('should create correctly', () => { + expect(component).toBeTruthy(); + }); + + it('should have create status container', () => { + expect(spanElement).toBeTruthy(); + }); + + describe('content badge', () => { + it('Badge should has content type', () => { + expect(spanElement.querySelector('.devui-badge-content')).toBeTruthy(); + }); + + it('Badge should has danger type', () => { + expect(spanElement.querySelector('.devui-badge-content-danger')).toBeTruthy(); + }); + + it('Badge should has warning type', () => { + component.status = 'warning'; + fixture.detectChanges(); + expect(spanElement.querySelector('.devui-badge-content-warning')).toBeTruthy(); + }); + + it('Badge should has waiting type', () => { + component.status = 'waiting'; + fixture.detectChanges(); + expect(spanElement.querySelector('.devui-badge-content-waiting')).toBeTruthy(); + }); + + it('Badge should has success type', () => { + component.status = 'success'; + fixture.detectChanges(); + expect(spanElement.querySelector('.devui-badge-content-success')).toBeTruthy(); + }); + + it('Badge should has info type', () => { + component.status = 'info'; + fixture.detectChanges(); + expect(spanElement.querySelector('.devui-badge-content-info')).toBeTruthy(); + }); + }); + + describe('max count', () => { + it('Badge should has max count', () => { + component.count = 12; + component.maxCount = 9; + fixture.detectChanges(); + expect(spanElement.querySelector('.devui-badge-content-count').textContent).toBe('9+'); + }); + }); + + describe('content dot badge', () => { + it('Badge should has content dot type', () => { + component.showDot = true; + fixture.detectChanges(); + expect(spanElement.querySelector('.devui-badge-content-dot')).toBeTruthy(); + }); + }); + }); + + describe('no content badge', () => { + let debugEl: DebugElement; + let component: NoContentBadgeComponent; + let spanElement: HTMLElement; + + beforeEach(() => { + fixture = TestBed.createComponent(NoContentBadgeComponent); + debugEl = fixture.debugElement; + component = fixture.componentInstance; + spanElement = debugEl.query(By.directive(BadgeComponent)).nativeElement; + + fixture.detectChanges(); + }); + + it('should create correctly', () => { + expect(component).toBeTruthy(); + }); + + it('should have create status container', () => { + expect(spanElement).toBeTruthy(); }); - describe('has content badge', () => { - let debugEl: DebugElement; - let component: HasContentBadgeComponent; - let spanElement: HTMLElement; - - beforeEach(() => { - fixture = TestBed.createComponent(HasContentBadgeComponent); - debugEl = fixture.debugElement; - component = fixture.componentInstance; - spanElement = debugEl.query(By.directive(BadgeComponent)).nativeElement; - - fixture.detectChanges(); - }); - - it('should create correctly', () => { - expect(component).toBeTruthy(); - }); - - it('should have create status container', () => { - expect(spanElement).toBeTruthy(); - }); - - describe('content badge', () => { - it('Badge should has content type', () => { - expect(spanElement.querySelector('.devui-badge-content')).toBeTruthy(); - }); - - it('Badge should has danger type', () => { - expect(spanElement.querySelector('.devui-badge-content-danger')).toBeTruthy(); - }); - - it('Badge should has warning type', () => { - component.status = 'warning'; - fixture.detectChanges(); - expect(spanElement.querySelector('.devui-badge-content-warning')).toBeTruthy(); - }); - - it('Badge should has waiting type', () => { - component.status = 'waiting'; - fixture.detectChanges(); - expect(spanElement.querySelector('.devui-badge-content-waiting')).toBeTruthy(); - }); - - it('Badge should has success type', () => { - component.status = 'success'; - fixture.detectChanges(); - expect(spanElement.querySelector('.devui-badge-content-success')).toBeTruthy(); - }); - - it('Badge should has info type', () => { - component.status = 'info'; - fixture.detectChanges(); - expect(spanElement.querySelector('.devui-badge-content-info')).toBeTruthy(); - }); - }); - - describe('max count', () => { - it('Badge should has max count', () => { - component.count = 12; - component.maxCount = 9; - fixture.detectChanges(); - expect(spanElement.querySelector('.devui-badge-content-count').textContent).toBe('9+'); - }); - }); - - describe('content dot badge', () => { - it('Badge should has content dot type', () => { - component.showDot = true; - fixture.detectChanges(); - expect(spanElement.querySelector('.devui-badge-content-dot')).toBeTruthy(); - }); - }); + describe('count badge', () => { + it('Badge should has count type', () => { + expect(spanElement.querySelector('.devui-badge-count')).toBeTruthy(); + }); }); - describe('no content badge', () => { - let debugEl: DebugElement; - let component: NoContentBadgeComponent; - let spanElement: HTMLElement; - - beforeEach(() => { - fixture = TestBed.createComponent(NoContentBadgeComponent); - debugEl = fixture.debugElement; - component = fixture.componentInstance; - spanElement = debugEl.query(By.directive(BadgeComponent)).nativeElement; - - fixture.detectChanges(); - }); - - it('should create correctly', () => { - expect(component).toBeTruthy(); - }); - - it('should have create status container', () => { - expect(spanElement).toBeTruthy(); - }); - - describe('count badge', () => { - it('Badge should has count type', () => { - expect(spanElement.querySelector('.devui-badge-count')).toBeTruthy(); - }); - }); - - describe('status badge', () => { - it('Badge should has status type', () => { - component.showDot = true; - fixture.detectChanges(); - expect(spanElement.querySelector('.devui-badge-status')).toBeTruthy(); - }); - }); + describe('status badge', () => { + it('Badge should has status type', () => { + component.showDot = true; + fixture.detectChanges(); + expect(spanElement.querySelector('.devui-badge-status')).toBeTruthy(); + }); }); + }); }); diff --git a/devui/badge/demo/badge-demo.component.ts b/devui/badge/demo/badge-demo.component.ts index d8df9c72..71559ae1 100644 --- a/devui/badge/demo/badge-demo.component.ts +++ b/devui/badge/demo/badge-demo.component.ts @@ -1,10 +1,10 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ - selector: 'app-badge-demo', + selector: 'd-badge-demo', templateUrl: './badge-demo.component.html', }) export class BadgeDemoComponent implements OnInit, OnDestroy { diff --git a/devui/breadcrumb/breadcrumb-item/breadcrumb-item.component.ts b/devui/breadcrumb/breadcrumb-item/breadcrumb-item.component.ts index 6a10e3d9..4e22a1f5 100644 --- a/devui/breadcrumb/breadcrumb-item/breadcrumb-item.component.ts +++ b/devui/breadcrumb/breadcrumb-item/breadcrumb-item.component.ts @@ -5,38 +5,38 @@ import { BreadCrumbService } from '../breadcrumb.service'; import { MenuConfig } from '../breadcrumb.type'; @Component({ - changeDetection: ChangeDetectionStrategy.OnPush, - selector: 'd-breadcrumb-item', - exportAs: 'dBreadcrumbItem', - templateUrl: './breadcrumb-item.component.html', - styleUrls: ['./breadcrumb-item.component.scss'], - preserveWhitespaces: false, + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'd-breadcrumb-item', + exportAs: 'dBreadcrumbItem', + templateUrl: './breadcrumb-item.component.html', + styleUrls: ['./breadcrumb-item.component.scss'], + preserveWhitespaces: false, }) export class BreadCrumbItemComponent implements OnInit { - @Input() showMenu = false; - @Input() customMenuTemplate: TemplateRef; - @Input() menuList: Array; - @Input() isSearch = false; - @Output() toggleEvent = new EventEmitter(); + @Input() showMenu = false; + @Input() customMenuTemplate: TemplateRef; + @Input() menuList: Array; + @Input() isSearch = false; + @Output() toggleEvent = new EventEmitter(); - menuListDisplay: Array; - isOpen: boolean; + menuListDisplay: Array; + isOpen: boolean; - constructor(public breadCrumbComponent: BreadCrumbComponent, private breadCrumbService: BreadCrumbService) { } - ngOnInit(): void { - this.menuListDisplay = this.menuList; - } - onToggle($event) { - this.isOpen = $event; - this.toggleEvent.emit($event); - } - searchEvent($event) { - if (this.menuList) { - this.menuListDisplay = this.menuList.filter(item => item.name.toLowerCase().includes($event.toLowerCase())); - } - } - navigateTo($event, item) { - this.breadCrumbService.navigateTo($event, item); + constructor(public breadCrumbComponent: BreadCrumbComponent, private breadCrumbService: BreadCrumbService) { } + ngOnInit(): void { + this.menuListDisplay = this.menuList; + } + onToggle($event) { + this.isOpen = $event; + this.toggleEvent.emit($event); + } + searchEvent($event) { + if (this.menuList) { + this.menuListDisplay = this.menuList.filter(item => item.name.toLowerCase().includes($event.toLowerCase())); } + } + navigateTo($event, item) { + this.breadCrumbService.navigateTo($event, item); + } } diff --git a/devui/breadcrumb/breadcrumb.component.ts b/devui/breadcrumb/breadcrumb.component.ts index a701f7f4..c74aaa4a 100644 --- a/devui/breadcrumb/breadcrumb.component.ts +++ b/devui/breadcrumb/breadcrumb.component.ts @@ -1,23 +1,23 @@ import { - Component, - Input, - TemplateRef, + Component, + Input, + TemplateRef, } from '@angular/core'; import { BreadCrumbService } from './breadcrumb.service'; import { SourceConfig } from './breadcrumb.type'; @Component({ - selector: 'd-breadcrumb', - exportAs: 'dBreadcrumb', - templateUrl: './breadcrumb.component.html', - styleUrls: ['./breadcrumb.component.scss'], - preserveWhitespaces: false, + selector: 'd-breadcrumb', + exportAs: 'dBreadcrumb', + templateUrl: './breadcrumb.component.html', + styleUrls: ['./breadcrumb.component.scss'], + preserveWhitespaces: false, }) export class BreadCrumbComponent { - @Input() separatorIcon: TemplateRef; - @Input() source: Array = []; - constructor(private breadCrumbService: BreadCrumbService) { } - navigateTo($event, item) { - this.breadCrumbService.navigateTo($event, item); - } + @Input() separatorIcon: TemplateRef; + @Input() source: Array = []; + constructor(private breadCrumbService: BreadCrumbService) { } + navigateTo($event, item) { + this.breadCrumbService.navigateTo($event, item); + } } diff --git a/devui/breadcrumb/breadcrumb.module.ts b/devui/breadcrumb/breadcrumb.module.ts index 53da691e..aeb3857d 100644 --- a/devui/breadcrumb/breadcrumb.module.ts +++ b/devui/breadcrumb/breadcrumb.module.ts @@ -8,10 +8,10 @@ import { BreadCrumbComponent } from './breadcrumb.component'; import { BreadCrumbService } from './breadcrumb.service'; @NgModule({ - imports: [CommonModule, RouterModule , DropDownModule, SearchModule], - exports: [BreadCrumbComponent, BreadCrumbItemComponent], - declarations: [BreadCrumbComponent, BreadCrumbItemComponent], - providers: [BreadCrumbService], + imports: [CommonModule, RouterModule , DropDownModule, SearchModule], + exports: [BreadCrumbComponent, BreadCrumbItemComponent], + declarations: [BreadCrumbComponent, BreadCrumbItemComponent], + providers: [BreadCrumbService], }) export class BreadcrumbModule { } diff --git a/devui/breadcrumb/breadcrumb.service.ts b/devui/breadcrumb/breadcrumb.service.ts index b262b355..6bbf485d 100644 --- a/devui/breadcrumb/breadcrumb.service.ts +++ b/devui/breadcrumb/breadcrumb.service.ts @@ -3,18 +3,18 @@ import { Router } from '@angular/router'; @Injectable() export class BreadCrumbService { - constructor(private router: Router) { } - // 与原生routerLink表现形式一致,navigateByUrl()可直接传入字符串类型的链接,并将链接解析为routerLink的urlTree的形式 - navigateTo($event, item) { - // 兼容a标签与不同键的交互形式 - if ($event.button !== 0 || $event.ctrlKey || $event.metaKey || $event.shiftKey) { - return; - } - if (typeof item.target === 'string' && item.target !== '_self') { - return; - } - $event.preventDefault(); - this.router.navigateByUrl(item.link); + constructor(private router: Router) { } + // 与原生routerLink表现形式一致,navigateByUrl()可直接传入字符串类型的链接,并将链接解析为routerLink的urlTree的形式 + navigateTo($event, item) { + // 兼容a标签与不同键的交互形式 + if ($event.button !== 0 || $event.ctrlKey || $event.metaKey || $event.shiftKey) { + return; } + if (typeof item.target === 'string' && item.target !== '_self') { + return; + } + $event.preventDefault(); + this.router.navigateByUrl(item.link); + } } diff --git a/devui/breadcrumb/breadcrumb.spec.ts b/devui/breadcrumb/breadcrumb.spec.ts index 236562df..a296d5d5 100644 --- a/devui/breadcrumb/breadcrumb.spec.ts +++ b/devui/breadcrumb/breadcrumb.spec.ts @@ -9,7 +9,7 @@ import { BreadCrumbItemComponent } from './breadcrumb-item/breadcrumb-item.compo import { BreadCrumbComponent } from './breadcrumb.component'; import { BreadcrumbModule } from './breadcrumb.module'; @Component({ - template: ` + template: ` DevUI @@ -21,83 +21,83 @@ import { BreadcrumbModule } from './breadcrumb.module'; `, }) class TestBreadCrumbComponent { - @ViewChild('breadcrumb') breadcrumb: BreadCrumbComponent; - @ViewChild('breadcrumbItem') breadcrumbItem: BreadCrumbItemComponent; - source = [{ title: 'DevUI', showMenu: false, link: '/components/zh-cn/get-start' }, + @ViewChild('breadcrumb') breadcrumb: BreadCrumbComponent; + @ViewChild('breadcrumbItem') breadcrumbItem: BreadCrumbItemComponent; + source = [{ title: 'DevUI', showMenu: false, link: '/components/zh-cn/get-start' }, { - title: '面包屑', showMenu: true, link: '/components/zh-cn/breadcrumb/demo', noNavigation: true, isSearch: true, - menuList: [ - { name: '锚点', link: 'http://devui.huawei.com/components/anchor/demo', target: '_blank' }, - { name: '按钮', link: '/', linkType: 'routerLink' } // 测试是否进入navigateTo方法处理routerLink的情况 - ] + title: '面包屑', showMenu: true, link: '/components/zh-cn/breadcrumb/demo', noNavigation: true, isSearch: true, + menuList: [ + { name: '锚点', link: 'http://devui.huawei.com/components/anchor/demo', target: '_blank' }, + { name: '按钮', link: '/', linkType: 'routerLink' } // 测试是否进入navigateTo方法处理routerLink的情况 + ] }]; } describe('breadcrumb basic', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [BreadcrumbModule, RouterTestingModule.withRoutes([]), NoopAnimationsModule], + declarations: [TestBreadCrumbComponent], + }).compileComponents(); + }); + + describe('breadcrumb display', () => { + let fixture: ComponentFixture; + let component: TestBreadCrumbComponent; + let debugEl: DebugElement; + let domHelper: DomHelper; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [BreadcrumbModule, RouterTestingModule.withRoutes([]), NoopAnimationsModule], - declarations: [TestBreadCrumbComponent], - }).compileComponents(); + fixture = TestBed.createComponent(TestBreadCrumbComponent); + component = fixture.componentInstance; + debugEl = fixture.debugElement; + domHelper = new DomHelper(fixture); + fixture.detectChanges(); }); - describe('breadcrumb display', () => { - let fixture: ComponentFixture; - let component: TestBreadCrumbComponent; - let debugEl: DebugElement; - let domHelper: DomHelper; - beforeEach(() => { - fixture = TestBed.createComponent(TestBreadCrumbComponent); - component = fixture.componentInstance; - debugEl = fixture.debugElement; - domHelper = new DomHelper(fixture); - fixture.detectChanges(); + describe('should breadcrumb work correctly', () => { + it('should breadcrumb display correctly', () => { + const classes = [ + '.devui-breadcrumb-item', + '.devui-breadcrumb-separator', + ]; + expect(domHelper.judgeStyleClasses(classes)).toBeTruthy(); + }); + it('should jump to link correctly', fakeAsync(() => { + const toggleEl: HTMLElement = debugEl.query(By.css('.devui-breadcrumb-item-with-menu')).nativeElement; + toggleEl.dispatchEvent(new Event('mouseenter')); + tick(300); + fixture.detectChanges(); + expect(document.querySelector('.cdk-overlay-container .devui-dropdown-menu')).toBeTruthy(); + const targetEl = debugEl.query(By.css('.cdk-overlay-pane .devui-dropdown-menu ul > li:nth-child(2) > a')).nativeElement; + targetEl.click(); + tick(300); + fixture.detectChanges(); + })); + it('should show search result correctly', fakeAsync(() => { + const toggleEl: HTMLElement = debugEl.query(By.css('.devui-breadcrumb-item-with-menu')).nativeElement; + toggleEl.dispatchEvent(new Event('mouseenter')); + tick(300); + fixture.detectChanges(); + const inputEl = debugEl.query(By.css('.cdk-overlay-pane > div > div > div > d-search > div > input')).nativeElement; + inputEl.dispatchEvent(new Event('focus')); + inputEl.value = '按钮'; + inputEl.dispatchEvent(new Event('input')); + tick(500); + fixture.detectChanges(); + expect(inputEl.value).toBe('按钮'); + const enterEvent = createKeyBoardEvent('keydown', { + key: 'Enter', + code: 'Enter' }); - - describe('should breadcrumb work correctly', () => { - it('should breadcrumb display correctly', () => { - const classes = [ - '.devui-breadcrumb-item', - '.devui-breadcrumb-separator', - ]; - expect(domHelper.judgeStyleClasses(classes)).toBeTruthy(); - }); - it('should jump to link correctly', fakeAsync(() => { - const toggleEl: HTMLElement = debugEl.query(By.css('.devui-breadcrumb-item-with-menu')).nativeElement; - toggleEl.dispatchEvent(new Event('mouseenter')); - tick(300); - fixture.detectChanges(); - expect(document.querySelector('.cdk-overlay-container .devui-dropdown-menu')).toBeTruthy(); - const targetEl = debugEl.query(By.css('.cdk-overlay-pane .devui-dropdown-menu ul > li:nth-child(2) > a')).nativeElement; - targetEl.click(); - tick(300); - fixture.detectChanges(); - })); - it('should show search result correctly', fakeAsync(() => { - const toggleEl: HTMLElement = debugEl.query(By.css('.devui-breadcrumb-item-with-menu')).nativeElement; - toggleEl.dispatchEvent(new Event('mouseenter')); - tick(300); - fixture.detectChanges(); - const inputEl = debugEl.query(By.css('.cdk-overlay-pane > div > div > div > d-search > div > input')).nativeElement; - inputEl.dispatchEvent(new Event('focus')); - inputEl.value = '按钮'; - inputEl.dispatchEvent(new Event('input')); - tick(500); - fixture.detectChanges(); - expect(inputEl.value).toBe('按钮'); - const enterEvent = createKeyBoardEvent('keydown', { - key: 'Enter', - code: 'Enter' - }); - inputEl.dispatchEvent(enterEvent); - tick(300); - fixture.detectChanges(); - const resultEl = debugEl.queryAll(By.css('.cdk-overlay-container .devui-dropdown-menu > ul > li')); - resultEl.forEach(ele => { - expect(ele.nativeElement.querySelector('a').textContent).toContain('按钮'); - }); - })); + inputEl.dispatchEvent(enterEvent); + tick(300); + fixture.detectChanges(); + const resultEl = debugEl.queryAll(By.css('.cdk-overlay-container .devui-dropdown-menu > ul > li')); + resultEl.forEach(ele => { + expect(ele.nativeElement.querySelector('a').textContent).toContain('按钮'); }); + })); }); + }); }); diff --git a/devui/breadcrumb/breadcrumb.type.ts b/devui/breadcrumb/breadcrumb.type.ts index 56a6a45c..2045a6f9 100644 --- a/devui/breadcrumb/breadcrumb.type.ts +++ b/devui/breadcrumb/breadcrumb.type.ts @@ -1,19 +1,19 @@ import { TemplateRef } from '@angular/core'; export interface MenuConfig { - name: string; - link: string; - linkType?: 'hrefLink' | 'routerLink'; - target?: string; + name: string; + link: string; + linkType?: 'hrefLink' | 'routerLink'; + target?: string; } export interface SourceConfig { - title: string; - link?: string; - showMenu?: boolean; - isSearch?: boolean; - target?: string; - menuList?: Array; - customMenuTemplate?: TemplateRef; - noNavigation?: boolean; - linkType?: 'hrefLink' | 'routerLink'; + title: string; + link?: string; + showMenu?: boolean; + isSearch?: boolean; + target?: string; + menuList?: Array; + customMenuTemplate?: TemplateRef; + noNavigation?: boolean; + linkType?: 'hrefLink' | 'routerLink'; } diff --git a/devui/breadcrumb/demo/breadcrumb-demo.component.ts b/devui/breadcrumb/demo/breadcrumb-demo.component.ts index e5e630f7..a518b468 100644 --- a/devui/breadcrumb/demo/breadcrumb-demo.component.ts +++ b/devui/breadcrumb/demo/breadcrumb-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/breadcrumb/demo/menu/menu.component.ts b/devui/breadcrumb/demo/menu/menu.component.ts index 1173f959..1eaea936 100644 --- a/devui/breadcrumb/demo/menu/menu.component.ts +++ b/devui/breadcrumb/demo/menu/menu.component.ts @@ -6,13 +6,13 @@ import { Component, OnInit } from '@angular/core'; export class MenuComponent implements OnInit { breadData = [{ label: 'DevUI', showMenu: false, link: '/components/zh-cn/get-start' }, - { - label: 'Breadcrumb', showMenu: true, isSearch: true, - menuList: [ - { name: 'Anchor', link: '/components/zh-cn/anchor/demo' }, - { name: 'Button', link: '/components/zh-cn/button/demo' } - ] - }]; + { + label: 'Breadcrumb', showMenu: true, isSearch: true, + menuList: [ + { name: 'Anchor', link: '/components/zh-cn/anchor/demo' }, + { name: 'Button', link: '/components/zh-cn/button/demo' } + ] + }]; constructor() { } ngOnInit(): void { diff --git a/devui/breadcrumb/demo/source-config/source-config.component.ts b/devui/breadcrumb/demo/source-config/source-config.component.ts index 0c6e15d5..8052ecbb 100644 --- a/devui/breadcrumb/demo/source-config/source-config.component.ts +++ b/devui/breadcrumb/demo/source-config/source-config.component.ts @@ -6,13 +6,13 @@ import { SourceConfig } from 'ng-devui/breadcrumb'; }) export class SourceConfigComponent { source: SourceConfig[] = [{ title: 'DevUI', showMenu: false, link: '/components/zh-cn/get-start' }, - { - title: 'Breadcrumb', showMenu: true, link: 'components/zh-cn/breadcrumb/demo', noNavigation: true, - menuList: [ - { name: 'Anchor', link: '/components/zh-cn/anchor/demo', target: '_blank' }, - { name: 'Button', link: '/components/zh-cn/button/demo#button-primary', linkType: 'routerLink' } - ] - }]; + { + title: 'Breadcrumb', showMenu: true, link: 'components/zh-cn/breadcrumb/demo', noNavigation: true, + menuList: [ + { name: 'Anchor', link: '/components/zh-cn/anchor/demo', target: '_blank' }, + { name: 'Button', link: '/components/zh-cn/button/demo#button-primary', linkType: 'routerLink' } + ] + }]; constructor() { } } diff --git a/devui/button/button-group.spec.ts b/devui/button/button-group.spec.ts index 594ee1ec..8219078c 100644 --- a/devui/button/button-group.spec.ts +++ b/devui/button/button-group.spec.ts @@ -21,10 +21,10 @@ describe('button-group', () => { let buttonGroupElement: HTMLElement; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ButtonModule], - declarations: [TestButtonGroupComponent] - }); + TestBed.configureTestingModule({ + imports: [ButtonModule], + declarations: [TestButtonGroupComponent] + }); }); beforeEach(() => { diff --git a/devui/button/demo/button-demo.component.ts b/devui/button/demo/button-demo.component.ts index 61fcdfab..65559374 100755 --- a/devui/button/demo/button-demo.component.ts +++ b/devui/button/demo/button-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'd-demo-button', diff --git a/devui/button/demo/button-demo.module.ts b/devui/button/demo/button-demo.module.ts index 4989d410..64943546 100755 --- a/devui/button/demo/button-demo.module.ts +++ b/devui/button/demo/button-demo.module.ts @@ -56,7 +56,7 @@ import { TextComponent } from './text/text.component'; SizeComponent, GroupsComponent, ], - + }) export class ButtonDemoModule { } diff --git a/devui/button/demo/loading/loading.component.ts b/devui/button/demo/loading/loading.component.ts index 06a10fc3..a581e40a 100755 --- a/devui/button/demo/loading/loading.component.ts +++ b/devui/button/demo/loading/loading.component.ts @@ -14,8 +14,8 @@ export class LoadingComponent implements OnInit { toggleLoading() { this.showLoading = true; setTimeout(() => { - this.showLoading = false; - }, 1000); + this.showLoading = false; + }, 1000); } } diff --git a/devui/card/card.spec.ts b/devui/card/card.spec.ts index d93cde2a..58d462ec 100644 --- a/devui/card/card.spec.ts +++ b/devui/card/card.spec.ts @@ -32,10 +32,10 @@ describe('card', () => { let cardElement: HTMLElement; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [CardModule, AvatarModule], - declarations: [TestCardComponent] - }); + TestBed.configureTestingModule({ + imports: [CardModule, AvatarModule], + declarations: [TestCardComponent] + }); }); beforeEach(() => { diff --git a/devui/card/demo/card-demo.component.ts b/devui/card/demo/card-demo.component.ts index da0daedb..3531ad1e 100644 --- a/devui/card/demo/card-demo.component.ts +++ b/devui/card/demo/card-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/carousel/carousel-item.component.spec.ts b/devui/carousel/carousel-item.component.spec.ts index 4f7ecf4f..d122c4dd 100644 --- a/devui/carousel/carousel-item.component.spec.ts +++ b/devui/carousel/carousel-item.component.spec.ts @@ -10,7 +10,7 @@ describe('CarouselItemComponent', () => { TestBed.configureTestingModule({ declarations: [ CarouselItemComponent ] }) - .compileComponents(); + .compileComponents(); })); beforeEach(() => { diff --git a/devui/carousel/carousel.component.spec.ts b/devui/carousel/carousel.component.spec.ts index b054dd28..99f6c131 100644 --- a/devui/carousel/carousel.component.spec.ts +++ b/devui/carousel/carousel.component.spec.ts @@ -43,7 +43,7 @@ describe('CarouselComponent', () => { imports: [CarouselModule], declarations: [ TestCarouselComponent ], }) - .compileComponents(); + .compileComponents(); })); beforeEach(() => { diff --git a/devui/cascader/cascader.component.ts b/devui/cascader/cascader.component.ts index 13c4f27a..ecafbc1a 100644 --- a/devui/cascader/cascader.component.ts +++ b/devui/cascader/cascader.component.ts @@ -148,7 +148,9 @@ export class CascaderComponent implements OnInit, OnDestroy, OnChanges, ControlV this.writeValue([...this.cascaderSrv.multipleValue, option.valueList]); this.onChange(this.cascaderSrv.multipleValue); this.mainDropdown.updateCdkConnectedOverlayOrigin(); - this.innerInput?.nativeElement.focus(); + if (this.innerInput) { + this.innerInput.nativeElement.focus(); + } } else { this.writeValue(option.valueList); this.onChange(option.valueList); @@ -213,8 +215,8 @@ export class CascaderComponent implements OnInit, OnDestroy, OnChanges, ControlV this.mainDropdown.isOpen = true; } - if (this.multiple) { - this.innerInput?.nativeElement.focus(); + if (this.multiple && this.innerInput) { + this.innerInput.nativeElement.focus(); } this.cascaderSrv.searchResultList = []; this.cascaderSrv.searchByString(value); @@ -347,7 +349,9 @@ export class CascaderComponent implements OnInit, OnDestroy, OnChanges, ControlV if (isOpen && this.multiple) { this.cascaderSrv.clearTargetActive(this.cascaderSrv.options.find(t => t.active)); this.cascaderSrv.columnList.splice(1); - this.innerInput?.nativeElement.focus(); + if (this.innerInput) { + this.innerInput.nativeElement.focus(); + } } if (!isOpen && this.allowSearch) { @@ -377,7 +381,7 @@ export class CascaderComponent implements OnInit, OnDestroy, OnChanges, ControlV const width = this.dropdownComp.overlay.overlayRef?.overlayElement.clientWidth; const offsetX = this.dropdownComp.overlay.overlayRef?.overlayElement.offsetLeft; const offsetRight = window.innerWidth - width - offsetX - 20; - this.subMenuDirections.map(t => t.offsetX = offsetRight < 0 ? offsetRight : 0); + this.subMenuDirections.map(t => {t.offsetX = offsetRight < 0 ? offsetRight : 0;}); this.dropdownComp.reposition(); }, 0); } diff --git a/devui/cascader/cascader.service.ts b/devui/cascader/cascader.service.ts index bcffc138..93fd4049 100644 --- a/devui/cascader/cascader.service.ts +++ b/devui/cascader/cascader.service.ts @@ -50,16 +50,16 @@ export class CascaderService implements OnDestroy { readonly openDrawer = new Subject(); readonly updateShowText = new Subject(); readonly updateTagList = new Subject<{ - isAdd: boolean, - option: CascaderItem, - isEmit: boolean // 是否触发onchanges,对外发出值 + isAdd: boolean; + option: CascaderItem; + isEmit: boolean; // 是否触发onchanges,对外发出值 }>(); initOptions(options: CascaderItem[]): void { this.columnList = []; this.options = cloneDeep(options); // 标记根节点 - this.options.forEach(t => t['isRoot'] = true); + this.options.forEach(t => {t['isRoot'] = true;}); this.columnList.push(this.options); } diff --git a/devui/cascader/cascader.spec.ts b/devui/cascader/cascader.spec.ts index 2a1501dd..bbd67723 100644 --- a/devui/cascader/cascader.spec.ts +++ b/devui/cascader/cascader.spec.ts @@ -295,7 +295,7 @@ class LazyLoadComponent { } else { return of(this.children3); } - } + }; } describe('cascader', () => { diff --git a/devui/cascader/demo/cascader-demo.component.ts b/devui/cascader/demo/cascader-demo.component.ts index 5761ff56..8c26c46b 100644 --- a/devui/cascader/demo/cascader-demo.component.ts +++ b/devui/cascader/demo/cascader-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/cascader/demo/lazyload-cascader/lazyload-cascader.component.ts b/devui/cascader/demo/lazyload-cascader/lazyload-cascader.component.ts index beecb2bd..d4751a54 100644 --- a/devui/cascader/demo/lazyload-cascader/lazyload-cascader.component.ts +++ b/devui/cascader/demo/lazyload-cascader/lazyload-cascader.component.ts @@ -105,5 +105,5 @@ export class LazyloadCascaderComponent { }, 1000); }); } - } + }; } diff --git a/devui/category-search/category-search.component.ts b/devui/category-search/category-search.component.ts index 09073bfb..42bdb42a 100644 --- a/devui/category-search/category-search.component.ts +++ b/devui/category-search/category-search.component.ts @@ -89,7 +89,6 @@ export class CategorySearchComponent implements OnInit, OnChanges, OnDestroy, Af scrollToTailFlag = true; // 是否在更新标签内容后滚动至输入框的开关 DROPDOWN_ANIMATION_TIMEOUT = 200; // 下拉动画延迟 document: Document; - get showFilterNameClear() { return typeof this.filterName === 'string' && this.filterName.length > 0; } @@ -180,7 +179,7 @@ export class CategorySearchComponent implements OnInit, OnChanges, OnDestroy, Af this.searchKeyCache = this.searchKey; } this.searchKey = ''; - setTimeout(() => (this.enterSearch = false), 300); + setTimeout(() => {this.enterSearch = false;}, 300); return result; } @@ -224,7 +223,7 @@ export class CategorySearchComponent implements OnInit, OnChanges, OnDestroy, Af setValue(data) { if (data && Array.isArray(data) && data.length) { - data.forEach((item) => (item = this.initCategoryItem(item))); + data.forEach((item) => {item = this.initCategoryItem(item);}); } } @@ -630,23 +629,25 @@ export class CategorySearchComponent implements OnInit, OnChanges, OnDestroy, Af handleAccordingType(type, options) { switch (type) { - case 'treeSelect': - options = cloneDeep(options); - break; - case 'textInput': - setTimeout(() => { - const inputDom: HTMLElement = this.document.querySelector('.devui-category-search-type-text-input'); - inputDom?.focus(); - }, this.DROPDOWN_ANIMATION_TIMEOUT); - break; - default: + case 'treeSelect': + options = cloneDeep(options); + break; + case 'textInput': + setTimeout(() => { + const inputDom: HTMLElement = this.document.querySelector('.devui-category-search-type-text-input'); + if (inputDom) { + inputDom.focus(); + } + }, this.DROPDOWN_ANIMATION_TIMEOUT); + break; + default: } } // label 合并名称和颜色字段赋给tag,待[tag]支持传入对象后可移除 mergeToLabel(obj) { if (obj && obj.options && Array.isArray(obj.options)) { - obj.options.map((item) => (item.$label = `${item[obj.filterKey || 'label']}_${item[obj.colorKey || 'color']}`)); + obj.options.map((item) => {item.$label = `${item[obj.filterKey || 'label']}_${item[obj.colorKey || 'color']}`;}); } return obj; } diff --git a/devui/category-search/category-search.type.ts b/devui/category-search/category-search.type.ts index fe867ed6..236568fe 100644 --- a/devui/category-search/category-search.type.ts +++ b/devui/category-search/category-search.type.ts @@ -1,6 +1,16 @@ import { TemplateRef } from '@angular/core'; export type CategorySearchTagType = 'radio' | 'checkbox' | 'dateRange' | 'label' | 'textInput' | 'numberRange' | 'treeSelect' | 'keyword'; + +export interface ITagOption { + /** + * 选项,label和color默认都会取对应的 filterKey 和 colorKey,如未设置取默认值 + */ + label?: string; // 通用默认属性,用于设置分类名称 + color?: string; // label 专用,用于设置标签颜色 + [propName: string]: any; +} + /** * 候选tag数据配置项 */ @@ -49,15 +59,6 @@ export interface ICategorySearchTagItem { [propName: string]: any; } -export interface ITagOption { - /** - * 选项,label和color默认都会取对应的 filterKey 和 colorKey,如未设置取默认值 - */ - label?: string; // 通用默认属性,用于设置分类名称 - color?: string; // label 专用,用于设置标签颜色 - [propName: string]: any; -} - export interface SelectedTagsEvent { selectedTags: Array; currentChangeTag: ICategorySearchTagItem; diff --git a/devui/category-search/demo/basic/basic.component.ts b/devui/category-search/demo/basic/basic.component.ts index 71d16a1e..6c55a978 100644 --- a/devui/category-search/demo/basic/basic.component.ts +++ b/devui/category-search/demo/basic/basic.component.ts @@ -74,5 +74,5 @@ export class BasicComponent { console.log('selected and clicked tag:', tag); console.log('unassigned tag:', currentSelectTag); } - } + }; } diff --git a/devui/checkbox/checkbox-group.component.ts b/devui/checkbox/checkbox-group.component.ts index 134a24de..7e7543ff 100755 --- a/devui/checkbox/checkbox-group.component.ts +++ b/devui/checkbox/checkbox-group.component.ts @@ -48,7 +48,7 @@ export class CheckBoxGroupComponent implements OnChanges, ControlValueAccessor { private onTouch = () => null; constructor( private devConfigService: DevConfigService - ) { + ) { } ngOnChanges(changes: SimpleChanges) { if (changes['options']) { diff --git a/devui/checkbox/checkbox.component.ts b/devui/checkbox/checkbox.component.ts index 694d7534..49e0b6d0 100755 --- a/devui/checkbox/checkbox.component.ts +++ b/devui/checkbox/checkbox.component.ts @@ -51,7 +51,7 @@ export class CheckBoxComponent implements ControlValueAccessor, OnChanges { constructor( private changeDetectorRef: ChangeDetectorRef, private devConfigService: DevConfigService - ) { + ) { this.id = CheckBoxComponent.ID_SEED++; } diff --git a/devui/checkbox/demo/checkbox-demo.component.ts b/devui/checkbox/demo/checkbox-demo.component.ts index 7d845710..d8c74cb2 100755 --- a/devui/checkbox/demo/checkbox-demo.component.ts +++ b/devui/checkbox/demo/checkbox-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/checkbox/demo/checkbox-demo.module.ts b/devui/checkbox/demo/checkbox-demo.module.ts index 5e9e4410..bbec70fe 100755 --- a/devui/checkbox/demo/checkbox-demo.module.ts +++ b/devui/checkbox/demo/checkbox-demo.module.ts @@ -43,7 +43,7 @@ import { CheckboxGroupBasicComponent} from './group/checkbox-group-basic.compone CheckboxConditionChangeComponent, CheckboxConditionGroupComponent ], - + }) export class CheckBoxDemoModule { } diff --git a/devui/checkbox/demo/condition-change/condition-change.component.ts b/devui/checkbox/demo/condition-change/condition-change.component.ts index a752ffee..adb20192 100644 --- a/devui/checkbox/demo/condition-change/condition-change.component.ts +++ b/devui/checkbox/demo/condition-change/condition-change.component.ts @@ -1,8 +1,8 @@ import { Component } from '@angular/core'; @Component({ - selector: 'd-demo-condition-change', - templateUrl: './condition-change.component.html', - styleUrls: ['./condition-change.component.scss'] + selector: 'd-demo-condition-change', + templateUrl: './condition-change.component.html', + styleUrls: ['./condition-change.component.scss'] }) export class CheckboxConditionChangeComponent { public checked = false; diff --git a/devui/common/clipboard.directive.ts b/devui/common/clipboard.directive.ts index adc68248..537bfc72 100644 --- a/devui/common/clipboard.directive.ts +++ b/devui/common/clipboard.directive.ts @@ -43,8 +43,8 @@ export class ClipboardDirective implements OnInit , OnDestroy { private overlayContainerRef: OverlayContainerRef, private componentFactoryResolver: ComponentFactoryResolver, @Inject(DOCUMENT) private doc: any) { - this.document = this.doc; - } + this.document = this.doc; + } ngOnInit(): void { this.setI18nText(); @@ -107,7 +107,7 @@ export class ClipboardDirective implements OnInit , OnDestroy { if (!this.elm.nativeElement.contains(event.target)) { this.destroy(); } - } + }; ngOnDestroy() { if (this.i18nSubscription) { diff --git a/devui/common/common.spec.ts b/devui/common/common.spec.ts index 63117d6a..8707d73a 100644 --- a/devui/common/common.spec.ts +++ b/devui/common/common.spec.ts @@ -64,7 +64,7 @@ class TestDownloadComponent { downloadError = (response) => { this.downError = response; - } + }; } @Component({ diff --git a/devui/common/demo/common-demo.component.ts b/devui/common/demo/common-demo.component.ts index fc5cc484..fcdaf6b7 100644 --- a/devui/common/demo/common-demo.component.ts +++ b/devui/common/demo/common-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/common/demo/helper-download/helper-download.component.ts b/devui/common/demo/helper-download/helper-download.component.ts index 9d729bf4..5668a540 100644 --- a/devui/common/demo/helper-download/helper-download.component.ts +++ b/devui/common/demo/helper-download/helper-download.component.ts @@ -29,5 +29,5 @@ export class HelperDownloadDemoComponent { downloadError = (response) => { this.downError = response; - } + }; } diff --git a/devui/common/demo/lazy-load/lazy-load.component.ts b/devui/common/demo/lazy-load/lazy-load.component.ts index c407e12b..02def05f 100644 --- a/devui/common/demo/lazy-load/lazy-load.component.ts +++ b/devui/common/demo/lazy-load/lazy-load.component.ts @@ -16,7 +16,7 @@ export class LazyLoadComponent implements OnInit { next1 = 1; showLoading1 = false; list1 = []; - target:any = window; + target: any = window; constructor() { } ngOnInit() { @@ -37,8 +37,8 @@ export class LazyLoadComponent implements OnInit { tmpList.push(this.sentence); } setTimeout(() => { - this.list = this.list.concat(tmpList); - this.showLoading = false; + this.list = this.list.concat(tmpList); + this.showLoading = false; }, 300); this.complete = this.next > this.total; @@ -55,8 +55,8 @@ export class LazyLoadComponent implements OnInit { tmpList.push(this.sentence); } setTimeout(() => { - this.list1 = this.list1.concat(tmpList); - this.showLoading1 = false; + this.list1 = this.list1.concat(tmpList); + this.showLoading1 = false; }, 300); this.complete = this.next1 > this.total; diff --git a/devui/common/helper-utils.ts b/devui/common/helper-utils.ts index 564af486..da8f6b39 100755 --- a/devui/common/helper-utils.ts +++ b/devui/common/helper-utils.ts @@ -5,100 +5,100 @@ declare type HttpObserve = 'body' | 'events' | 'response'; declare type ResponseType = 'arraybuffer' | 'blob' | 'json' | 'text'; export class HelperUtils { 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 - } + 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: string, - option?: { - method?: 'POST'| 'GET' | 'post' | 'get', - params?: {[property: string]: string}, - enctype?: 'application/x-www-form-urlencoded' | 'multipart/form-data'| 'text/plain', - iframename?: string - }, - onError?: (response) => void + url: string, + option?: { + method?: 'POST'| 'GET' | 'post' | 'get'; + params?: {[property: string]: string}; + enctype?: 'application/x-www-form-urlencoded' | 'multipart/form-data'| 'text/plain'; + iframename?: string; + }, + onError?: (response) => void ) { - 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'; + 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'; + 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); - }); - } + 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'; + const submit = document.createElement('input'); + submit.type = 'submit'; - tempform.appendChild(submit); - tempiframe.appendChild(tempform); - document.body.appendChild(tempiframe); + 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(); + // 下载错误处理。下载成功并不会响应,因为响应头中带有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: HttpClient, url: string, option?: { - method?: 'POST' | 'GET' | 'post' | 'get', - params?: {[property: string]: string}, - enctype?: 'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/plain', + method?: 'POST' | 'GET' | 'post' | 'get'; + params?: {[property: string]: string}; + enctype?: 'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/plain'; header?: { [header: string]: string | string[]; - }, - responseOption?: 'response' | 'body' | 'json', - filename?: string, - withCredentials?: boolean, - downloadWithoutDispositionHeader?: boolean + }; + responseOption?: 'response' | 'body' | 'json'; + filename?: string; + withCredentials?: boolean; + downloadWithoutDispositionHeader?: boolean; }, onError?: (response) => void, onSuccess?: (response) => void, @@ -115,7 +115,7 @@ export class HelperUtils { 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: 'response' as HttpObserve, @@ -131,36 +131,36 @@ export class HelperUtils { const handleResponse = (resOption => { switch (resOption) { - case 'response': - return (res: HttpResponse) => res; - case 'body': - return (res: HttpResponse | HttpErrorResponse) => { - const arrayBuffer = (>res).body || (res).error; + case 'response': + return (res: HttpResponse) => res; + case 'body': + return (res: HttpResponse | HttpErrorResponse) => { + const arrayBuffer = (>res).body || (res).error; + const body = HelperUtils.utf8ArrayToStr(arrayBuffer); + return body; + }; + case 'json': + default: + return (res: HttpResponse | HttpErrorResponse) => { + const arrayBuffer = (>res).body || (res).error; + let response; + try { const body = HelperUtils.utf8ArrayToStr(arrayBuffer); - return body; - }; - case 'json': - default: - return (res: HttpResponse | HttpErrorResponse) => { - 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; - } + response = JSON.parse(body); } catch (e) { - throw new Error('Parsing Error:' + e); + const parser = new DOMParser(); + const html = parser.parseFromString(body, 'text/html'); + response = html.body.textContent; } - if (!response) { - response = 'Error'; - } - return response; - }; + } catch (e) { + throw new Error('Parsing Error:' + e); + } + if (!response) { + response = 'Error'; + } + return response; + }; } })(responseOption); @@ -169,25 +169,25 @@ export class HelperUtils { return; } if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE11 support - const blob = new Blob([data], {type: contentType}); - window.navigator.msSaveOrOpenBlob(blob, filename); + 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); - } + 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); + } } }; @@ -260,10 +260,10 @@ export class HelperUtils { selector: '[dSimulateATag]' }) export class SimulateATagDirective { - @Input() href: string; - @Input() target: '_blank' | '_self' | '_parent' | '_top' | string = '_blank'; - constructor() {} - @HostListener('click') onClick() { - HelperUtils.jumpOuterUrl(this.href, this.target); - } + @Input() href: string; + @Input() target: '_blank' | '_self' | '_parent' | '_top' | string = '_blank'; + constructor() {} + @HostListener('click') onClick() { + HelperUtils.jumpOuterUrl(this.href, this.target); + } } diff --git a/devui/common/iframe-event-propagate.directive.ts b/devui/common/iframe-event-propagate.directive.ts index 60c48bd0..e91b919c 100755 --- a/devui/common/iframe-event-propagate.directive.ts +++ b/devui/common/iframe-event-propagate.directive.ts @@ -15,31 +15,31 @@ export class IframeEventPropagateDirective implements AfterViewInit { ngAfterViewInit() { this.element.addEventListener('DOMSubtreeModified', this.AddIframeContentDocumentClickListener); if (this.element.querySelector('iframe') !== null) { - this.AddIframeContentDocumentClickListener(); + this.AddIframeContentDocumentClickListener(); } } AddIframeContentDocumentClickListener = () => { - const iframe = this.element.querySelector('iframe'); + const iframe = this.element.querySelector('iframe'); - if (iframe !== null) { - if (iframe.contentDocument !== null) { + if (iframe !== null) { + if (iframe.contentDocument !== null) { + iframe.contentDocument.addEventListener(this.event, this.dispatchClickEvent); + } else { + const loadHandler = () => { 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); + iframe.removeEventListener('load', loadHandler); + }; + iframe.addEventListener('load', loadHandler); } - } + + this.element.removeEventListener('DOMSubtreeModified', this.AddIframeContentDocumentClickListener); + } + }; dispatchClickEvent = ($event) => { const event = this.document.createEvent('MouseEvents'); event.initEvent(this.event, true, true); event['originEvent'] = $event; this.element.dispatchEvent(event); - } + }; } diff --git a/devui/dashboard/dashboard.component.ts b/devui/dashboard/dashboard.component.ts index bb1493eb..c64e2f1b 100644 --- a/devui/dashboard/dashboard.component.ts +++ b/devui/dashboard/dashboard.component.ts @@ -107,7 +107,7 @@ export class DashboardComponent implements OnChanges, AfterViewInit, OnDestroy { } ngAfterViewInit() { - this.finalOption = Object.assign({}, DashBoardGridStackDefaultOption, this.initOptions, this.getTransformOption()); + this.finalOption = { ...DashBoardGridStackDefaultOption, ...this.initOptions, ...this.getTransformOption()}; this.renderer.addClass(this.el.nativeElement, 'grid-stack-' + this.finalOption.column); this.gridStackService.gridStack = GridStack.init(this.finalOption, this.el.nativeElement); this.gridStackService.resetAcceptWidget(this); @@ -192,7 +192,7 @@ export class DashboardComponent implements OnChanges, AfterViewInit, OnDestroy { widget.handleChange(node); }); }); - } + }; @HostListener('change', ['$event', '$event.detail']) public changeHandler = (event, items: GridStackNode[]) => { @@ -216,7 +216,7 @@ export class DashboardComponent implements OnChanges, AfterViewInit, OnDestroy { if (this.showGridBlock) { this.gridStackService.setBackgroundGridBlockIfColumnChange(); } - } + }; @HostListener('removed', ['$event', '$event.detail']) public removedHandler = (event, items: GridStackNode[]) => { @@ -228,7 +228,7 @@ export class DashboardComponent implements OnChanges, AfterViewInit, OnDestroy { if (isDevMode() && all.some(wd => !wd.widget)) { console.warn('remove: something wrong, not handled by dashboard'); } - } + }; handleDragInNode(node: GridStackNode, origNode: GridStackNode, widget: DashboardLibraryWidgetDirective) { this.widgetAdded.emit([{ diff --git a/devui/dashboard/doc/api-en.md b/devui/dashboard/doc/api-en.md index e2ca5b86..da373341 100644 --- a/devui/dashboard/doc/api-en.md +++ b/devui/dashboard/doc/api-en.md @@ -64,6 +64,7 @@ origNode?: GridStackNode; // add(optional) ``` +3548/5000 拼音 翻译 ### d-dashboard function Exporting a dDashboard diff --git a/devui/dashboard/grid-stack.service.ts b/devui/dashboard/grid-stack.service.ts index 3abdfa5c..8e46e033 100644 --- a/devui/dashboard/grid-stack.service.ts +++ b/devui/dashboard/grid-stack.service.ts @@ -4,6 +4,7 @@ import { DashboardComponent } from './dashboard.component'; import { DashboardLibraryTrashDirective } from './widget-library/library-trash.directive'; import { DashboardLibraryWidgetDirective } from './widget-library/library-widget.directive'; +/* eslint-disable */ @Injectable() export class GridStackService { gridStack: GridStack; diff --git a/devui/dashboard/polyfill.ts b/devui/dashboard/polyfill.ts index ec8c4816..22f8c01b 100644 --- a/devui/dashboard/polyfill.ts +++ b/devui/dashboard/polyfill.ts @@ -1,25 +1,25 @@ -/* tslint:disable */ +/* eslint-disable */ // Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/append()/append().md export default (function (arr) { - arr.forEach(function (item) { - if (item.hasOwnProperty('append')) { - return; + arr.forEach(function (item) { + if (item.hasOwnProperty('append')) { + return; + } + Object.defineProperty(item, 'append', { + configurable: true, + enumerable: true, + writable: true, + value: function append() { + const argArr = Array.prototype.slice.call(arguments); + const docFrag = document.createDocumentFragment(); + + argArr.forEach(function (argItem) { + const isNode = argItem instanceof Node; + docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); + }); + + this.appendChild(docFrag); } - Object.defineProperty(item, 'append', { - configurable: true, - enumerable: true, - writable: true, - value: function append() { - var argArr = Array.prototype.slice.call(arguments), - docFrag = document.createDocumentFragment(); - - argArr.forEach(function (argItem) { - var isNode = argItem instanceof Node; - docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); - }); - - this.appendChild(docFrag); - } - }); }); - })([Element.prototype, Document.prototype, DocumentFragment.prototype]); + }); +})([Element.prototype, Document.prototype, DocumentFragment.prototype]); diff --git a/devui/dashboard/widget-library/library-widget.directive.ts b/devui/dashboard/widget-library/library-widget.directive.ts index 3d37b9ab..90ed7d89 100644 --- a/devui/dashboard/widget-library/library-widget.directive.ts +++ b/devui/dashboard/widget-library/library-widget.directive.ts @@ -111,7 +111,7 @@ export class DashboardLibraryWidgetDirective implements OnChanges, AfterViewInit } else { return () => {}; } - } + }; helper = (event) => { if (this.dragMode === 'move') { @@ -131,10 +131,10 @@ export class DashboardLibraryWidgetDirective implements OnChanges, AfterViewInit el.classList.add('grid-stack-item-adding-item-template'); el.style.zIndex = '1060'; if (this.width !== undefined) { - el.setAttribute('data-gs-width', this.width + ''); + el.setAttribute('data-gs-width', String(this.width)); } if (this.height !== undefined) { - el.setAttribute('data-gs-height', this.height + ''); + el.setAttribute('data-gs-height', String(this.height)); } this.setDragWidthHeight(el); const domPortalOutlet = new DomPortalOutlet(el, this.cfr, this.appRef, this.injector); @@ -154,7 +154,7 @@ export class DashboardLibraryWidgetDirective implements OnChanges, AfterViewInit domPortalOutlet.dispose(); return result; } - } + }; copyCanvas(origin, target) { // 拷贝canvas的内容 diff --git a/devui/dashboard/widget/widget.component.ts b/devui/dashboard/widget/widget.component.ts index 0cc48015..acf89a46 100644 --- a/devui/dashboard/widget/widget.component.ts +++ b/devui/dashboard/widget/widget.component.ts @@ -66,7 +66,7 @@ export class DashboardWidgetComponent implements GridStackNode, OnChanges, After @Input() widgetData; @Output() widgetInit = new EventEmitter(true); - @Output() widgetResize = new EventEmitter<{width: number, height: number} | null>(true); + @Output() widgetResize = new EventEmitter<{width: number; height: number} | null>(true); @Output() widgetDestroy = new EventEmitter(); @HostBinding('class.grid-stack-item') diff --git a/devui/data-table/data-table-cell.component.ts b/devui/data-table/data-table-cell.component.ts index ebc43d1f..a63a3aa8 100755 --- a/devui/data-table/data-table-cell.component.ts +++ b/devui/data-table/data-table-cell.component.ts @@ -156,10 +156,13 @@ export class DataTableCellComponent implements OnInit, OnChanges, OnDestroy { this.dynamicEditorActive = false; this.templateEditorActive = false; - // tslint:disable-next-line:no-unused-expression - this.documentClickSubscription && this.unSubscription(this.documentClickSubscription); - // tslint:disable-next-line:no-unused-expression - this.cellEditorClickSubscription && this.unSubscription(this.cellEditorClickSubscription); + if (this.documentClickSubscription) { + this.unSubscription(this.documentClickSubscription); + } + + if (this.cellEditorClickSubscription) { + this.unSubscription(this.cellEditorClickSubscription); + } stopPropagationIfExist($event); this.dt.onCellEditEnd({ @@ -181,23 +184,33 @@ export class DataTableCellComponent implements OnInit, OnChanges, OnDestroy { } ngOnDestroy(): void { - // tslint:disable-next-line:no-unused-expression - this.forceUpdateSubscription && this.unSubscription(this.forceUpdateSubscription); - // tslint:disable-next-line:no-unused-expression - this.documentClickSubscription && this.unSubscription(this.documentClickSubscription); - // tslint:disable-next-line:no-unused-expression - this.cellEditorClickSubscription && this.unSubscription(this.cellEditorClickSubscription); - // tslint:disable-next-line:no-unused-expression - this.cellActionSubscription && this.unSubscription(this.cellActionSubscription); - // tslint:disable-next-line:no-unused-expression - this.tdMousedownSubscription && this.unSubscription(this.tdMousedownSubscription); - // tslint:disable-next-line:no-unused-expression - this.tdMouseupSubscription && this.unSubscription(this.tdMouseupSubscription); + if (this.forceUpdateSubscription) { + this.unSubscription(this.forceUpdateSubscription); + } + + if (this.documentClickSubscription) { + this.unSubscription(this.documentClickSubscription); + } + + if (this.cellEditorClickSubscription) { + this.unSubscription(this.cellEditorClickSubscription); + } + + if (this.cellActionSubscription) { + this.unSubscription(this.cellActionSubscription); + } + if (this.tdMousedownSubscription) { + this.unSubscription(this.tdMousedownSubscription); + } + if (this.tdMouseupSubscription) { + this.unSubscription(this.tdMouseupSubscription); + } } private unSubscription(sbscription: Subscription) { if (sbscription) { sbscription.unsubscribe(); + /* eslint-disable-next-line no-param-reassign */ sbscription = null; } } @@ -206,25 +219,25 @@ export class DataTableCellComponent implements OnInit, OnChanges, OnDestroy { let componentFactory; let editorComponent; switch (this.column.fieldType) { - case 'number': - editorComponent = InputNumberComponent; - break; - case 'select': - editorComponent = SelectComponent; - break; - case 'treeSelect': - editorComponent = TreeSelectComponent; - break; - default: - this.templateEditorActive = true; - break; + case 'number': + editorComponent = InputNumberComponent; + break; + case 'select': + editorComponent = SelectComponent; + break; + case 'treeSelect': + editorComponent = TreeSelectComponent; + break; + default: + this.templateEditorActive = true; + break; } if (editorComponent) { componentFactory = this.componentFactoryResolver.resolveComponentFactory(editorComponent); const viewContainerRef = this.editorHost.viewContainerRef; viewContainerRef.clear(); - const componentRef = viewContainerRef.createComponent<{ writeValue: Function, registerOnChange: Function }>(componentFactory); + const componentRef = viewContainerRef.createComponent<{ writeValue: Function; registerOnChange: Function }>(componentFactory); const componentInstance = componentRef.instance; if (this.column.extraOptions) { componentFactory.inputs.forEach((input) => { diff --git a/devui/data-table/data-table-column.spec.ts b/devui/data-table/data-table-column.spec.ts index c03e2d83..17c3e07d 100644 --- a/devui/data-table/data-table-column.spec.ts +++ b/devui/data-table/data-table-column.spec.ts @@ -134,7 +134,7 @@ class TestDataTableColumnBasicComponent { field="dob" header="Date of birth" [fieldType]="'date'" - [extraOptions]="{ dateFormat: 'MM/DD/YYYY' }" + [extraOptions]="{ dateFormat: 'MM/dd/yyyy' }" [width]="'2000px'" > hidden @@ -283,7 +283,7 @@ class TestDataTableAdvancedColumnComponent implements OnInit { this.filterListMulti = this.filterList; this.ref.detectChanges(); return true; - } + }; getCheckedRows() { return this.datatable.getCheckedRows(); @@ -344,7 +344,7 @@ class TestDataTableAdvancedColumnComponent implements OnInit { [(ngModel)]="rowItem[column.field]" dDatepicker appendToBody - [dateFormat]="YYYY / MM / DD" + [dateFormat]="yyyy / MM / DD" #datePicker="datepicker" [showTime]="true" [autoOpen]="true" @@ -426,7 +426,7 @@ class TestDataTableColumnEditComponent { field="dob" header="date" [fieldType]="'date'" - [extraOptions]="{ dateFormat: 'MM/DD/YYYY' }" + [extraOptions]="{ dateFormat: 'MM/dd/yyyy' }" [width]="'20%'" > @@ -476,7 +476,7 @@ class TestDataTableColumnWithChildrenComponent { field="dob" header="Date of birth" [fieldType]="'date'" - [extraOptions]="{ dateFormat: 'MM/DD/YYYY' }" + [extraOptions]="{ dateFormat: 'MM/dd/yyyy' }" [width]="'200px'" > diff --git a/devui/data-table/data-table-head.component.ts b/devui/data-table/data-table-head.component.ts index 79bfef80..5ee1332d 100755 --- a/devui/data-table/data-table-head.component.ts +++ b/devui/data-table/data-table-head.component.ts @@ -53,7 +53,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, dragBoxLeft; dragCellRef: HTMLElement; - searchQuery: { [key: string]: any; } = {}; + searchQuery: { [key: string]: any } = {}; multiSortArray: SortEventArg[] = []; sortField: string; sortDirection: 'ASC' | 'DESC' | ''; @@ -123,9 +123,9 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, private ref: ChangeDetectorRef, private i18n: I18nService, @Inject(DOCUMENT) private doc: any) { - this.i18nCommonText = this.i18n.getI18nText().common; - this.document = this.doc; - this.documentElement = this.doc.documentElement; + this.i18nCommonText = this.i18n.getI18nText().common; + this.document = this.doc; + this.documentElement = this.doc.documentElement; } ngOnInit() { @@ -244,8 +244,10 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, cellIndex++; } else { if (column.advancedHeader[0].colspan) { - this.cellMap[cellIndex] = { name: column.field, isAdvanceHeader: true, - sortKey: [index], headerLength: column.advancedHeader[0].colspan }; + this.cellMap[cellIndex] = { + name: column.field, isAdvanceHeader: true, + sortKey: [index], headerLength: column.advancedHeader[0].colspan + }; cellIndex++; } else { Object.keys(this.cellMap).forEach(key => { @@ -315,9 +317,9 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, onBeginResize($event) { const thRenderWidthList = []; this.thList.forEach(th => { - thRenderWidthList.push({field: th.element.getAttribute('field'), width: th.element.clientWidth}); + thRenderWidthList.push({ field: th.element.getAttribute('field'), width: th.element.clientWidth }); }); - this.beginResizeHandlerEvent.emit({event: $event, thRenderWidthList}); + this.beginResizeHandlerEvent.emit({ event: $event, thRenderWidthList }); } onResizing($event, column) { @@ -366,7 +368,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, setTimeout(() => { // fix chrome bug, mousedown的时候会错误的触发mousemove this.dispatchMousedown(); }); - } + }; grab = (e) => { e.preventDefault(); @@ -375,7 +377,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, const context = this.canStart(e.target); this.grabbed = context; this.documentElement.addEventListener('mousemove', this.startBecauseMouseMoved); - } + }; startBecauseMouseMoved = (e) => { e.preventDefault(); @@ -400,7 +402,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, this.offsetX = 15; this.offsetY = 15; this.renderMirrorImage(this.item); - } + }; release = (e) => { e.preventDefault(); @@ -423,7 +425,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, } this.sortColumn(this.originCellIndex.x, to); cancelAnimationFrame(this.animationRequestId); - } + }; sortColumn = (from, to) => { if (from === to) { @@ -453,7 +455,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, for (let i = 0; i < loopCount; i++) { this.dragTableEndEvent.emit({ from: fromCell, to: toCell }); } - } + }; sort = ({ list, from, to }) => { if (!list[from] && !list[to]) { @@ -464,7 +466,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, } else { this.insertBeforeSibling({ target: list[from], origin: list[to] }); } - } + }; appendSibling({ target, origin }) { if (!target) { @@ -570,7 +572,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, this.el.style.display = 'none'; }); } - } + }; renderFakeTable() { if (this.el && !this.dataSourceChange) { @@ -828,7 +830,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, this.animate(fixItemRect, fixItem, 300); } } - } + }; handleScroll(x, y, e) { this.scrollViewRect = this.scrollViewEl.getBoundingClientRect(); @@ -904,7 +906,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, result = rowL > resultL ? row : result; }); return result; - } + }; getColumnAsTableByIndex(table, selectedColIndex, colSpan, rowSpan) { const skipRowIndexList = this.getDataBetween(0, 0 + rowSpan); const cTable = table.cloneNode(true); @@ -1025,7 +1027,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, }); this.sizeChildColumnFake(cTable, table, index); return cTable; - } + }; sizeChildColumnFake(fakeTable, originEl, index) { // calculate width of every column @@ -1050,7 +1052,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, this.detecteChildTables(childTable); } }); - } + }; origin2DragItem(liTable) { this.css(liTable, { 'table-layout': 'fixed', width: 'initial', height: 'initial', padding: 0, margin: 0 }); ['width', 'height', 'id'].forEach((p) => { @@ -1061,9 +1063,8 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, getElementBehindPoint(point, x, y) { const p = point || {}; const state = p.className; - let el; p.className += ' gu-hide'; - el = this.document.elementFromPoint(x, y); + const el = this.document.elementFromPoint(x, y); p.className = state; return el; } @@ -1121,7 +1122,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, const reference = target !== dropTarget ? inside() : outside(); return reference; - } + }; getRectWidth(rect) { return rect.width || (rect.right - rect.left); @@ -1143,7 +1144,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, isInitialPlacement(target, s) { let sibling; - if (s !== void 0) { + if (s !== undefined) { sibling = s; } else if (this.mirror) { sibling = this.currentSibling; @@ -1170,7 +1171,7 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, return null; } return immediate; - } + }; animate(prevRect, target, time) { if (time) { @@ -1180,7 +1181,6 @@ export class DataTableHeadComponent implements OnInit, OnChanges, AfterViewInit, const currentRect = target.getBoundingClientRect(); target.style.transition = 'none'; target.style.transform = 'translate3d(' + (prevRect.left - currentRect.left) + 'px,' + (prevRect.top - currentRect.top) + 'px,0)'; - target.offsetWidth; // tslint:disable-line target.style.transition = 'all ' + time + 'ms cubic-bezier(0.755, 0.05, 0.855, 0.06)'; target.style.transform = 'translate3d(0,0,0)'; clearTimeout(target.animated); diff --git a/devui/data-table/data-table-row.component.ts b/devui/data-table/data-table-row.component.ts index bd56010f..aa5e1e67 100755 --- a/devui/data-table/data-table-row.component.ts +++ b/devui/data-table/data-table-row.component.ts @@ -40,8 +40,8 @@ export class DataTableRowComponent implements OnInit { ngOnInit(): void { this.ngZone.runOutsideAngular(() => { this.rowRef.nativeElement.addEventListener( - 'click', - this.onRowClick.bind(this) + 'click', + this.onRowClick.bind(this) ); this.rowRef.nativeElement.addEventListener( 'dblclick', diff --git a/devui/data-table/data-table.component.ts b/devui/data-table/data-table.component.ts index 6fa9d3ff..32197d02 100755 --- a/devui/data-table/data-table.component.ts +++ b/devui/data-table/data-table.component.ts @@ -1,9 +1,12 @@ -import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling'; +import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling'; import { DOCUMENT } from '@angular/common'; import { - AfterContentInit, AfterViewInit, ChangeDetectorRef, Component, ContentChild, ContentChildren, ElementRef, - EventEmitter, HostBinding, Inject, Input, NgZone, OnChanges, OnDestroy, OnInit, Output, QueryList, Renderer2, - SimpleChanges, TemplateRef, ViewChild + AfterContentInit, AfterViewInit, ChangeDetectorRef, Component, + ContentChild, ContentChildren, ElementRef, EventEmitter, + HostBinding, Inject, Input, NgZone, + OnChanges, OnDestroy, OnInit, Output, + QueryList, Renderer2, SimpleChanges, TemplateRef, + ViewChild } from '@angular/core'; import { merge, Subscription } from 'rxjs'; import { switchMap, takeUntil } from 'rxjs/operators'; @@ -133,7 +136,7 @@ export class DataTableComponent implements OnDestroy, OnInit, OnChanges, AfterCo * 【可选】是否显示排序未激活图标,默认不显示, */ @Input() showSortIcon = false; - /** + /** * 【可选】是否显示筛选未激活图标,默认不显示, */ @Input() showFilterIcon = false; @@ -298,7 +301,7 @@ export class DataTableComponent implements OnDestroy, OnInit, OnChanges, AfterCo displayDataSource: any[]; headertoggleTableSubscription: Subscription; headerCheckStatusSubscription: Subscription; - searchQueryChange = new EventEmitter<{ [key: string]: any; }>(); + searchQueryChange = new EventEmitter<{ [key: string]: any }>(); halfChecked = false; childrenTableOpen: boolean; private scrollY = 0; @@ -318,7 +321,8 @@ export class DataTableComponent implements OnDestroy, OnInit, OnChanges, AfterCo } @Input() set dataSource(dataSource: any[]) { - if (null === dataSource || !dataSource) { + if (dataSource === null || !dataSource) { + /* eslint-disable-next-line no-param-reassign */ dataSource = []; } this._dataSource = dataSource; @@ -371,8 +375,8 @@ export class DataTableComponent implements OnDestroy, OnInit, OnChanges, AfterCo private renderer: Renderer2, private cdr: ChangeDetectorRef, @Inject(DOCUMENT) private doc: any) { - this.onDocumentClickListen = this.onDocumentClick.bind(this); - this.document = this.doc; + this.onDocumentClickListen = this.onDocumentClick.bind(this); + this.document = this.doc; } initVirtualBodyHeight() { @@ -623,7 +627,7 @@ export class DataTableComponent implements OnDestroy, OnInit, OnChanges, AfterCo if (data.children) { return data.children.some(this.hasChecked); } - } + }; // 判断数据是否存在未选中状态 private hasUnChecked = (data) => { @@ -633,7 +637,7 @@ export class DataTableComponent implements OnDestroy, OnInit, OnChanges, AfterCo if (data.children) { return data.children.some(this.hasUnChecked); } - } + }; setRowCheckStatus($event: RowCheckChangeEventArg) { // 处理children的选中 @@ -646,8 +650,7 @@ export class DataTableComponent implements OnDestroy, OnInit, OnChanges, AfterCo const nestedIndexArray = $event.nestedIndex.split(','); nestedIndexArray.shift(); const nestedIndexArrayToInt = nestedIndexArray.map((value) => { - // tslint:disable-next-line:radix - return parseInt(value); + return parseInt(value, 10); }); // 通过选中行的父级索引设置父的选中状态 this.setParentCheckStatus(nestedIndexArrayToInt); @@ -733,7 +736,7 @@ export class DataTableComponent implements OnDestroy, OnInit, OnChanges, AfterCo this.checkAllChange.emit($event); } - onSearchQueryChange($event: { [key: string]: any; }) { + onSearchQueryChange($event: { [key: string]: any }) { this.searchQueryChange.emit($event); } diff --git a/devui/data-table/data-table.model.ts b/devui/data-table/data-table.model.ts index 7c30fd03..4498d2fe 100755 --- a/devui/data-table/data-table.model.ts +++ b/devui/data-table/data-table.model.ts @@ -13,6 +13,12 @@ export interface CellSelectedEventArg { rowComponent: DataTableRowComponent; } +export enum SortDirection { + ASC = 'ASC', + DESC = 'DESC', + default = '' +} + export interface RowSelectedEventArg { rowIndex: number; nestedIndex: string; @@ -74,12 +80,6 @@ export interface TableCheckStatusArg { pageHalfChecked?: boolean; } -export enum SortDirection { - ASC = 'ASC', - DESC = 'DESC', - default = '' -} - export interface TableWidthConfig { field: string; width: string; diff --git a/devui/data-table/data-table.module.ts b/devui/data-table/data-table.module.ts index 31a7f933..0fbbb6fc 100755 --- a/devui/data-table/data-table.module.ts +++ b/devui/data-table/data-table.module.ts @@ -2,7 +2,6 @@ import { ScrollingModule } from '@angular/cdk/scrolling'; import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; - import { ButtonModule } from 'ng-devui/button'; import { CheckBoxModule } from 'ng-devui/checkbox'; import { DCommonModule } from 'ng-devui/common'; @@ -36,6 +35,8 @@ import { DataTableCellTmplComponent } from './tmpl/data-table-cell-tmpl.componen import { DataTableCellViewTmplComponent } from './tmpl/data-table-cell-view-tmpl.component'; import { DataTableColumnTmplComponent } from './tmpl/data-table-column-tmpl.component'; import { DataTableHeadCellTmplComponent } from './tmpl/data-table-head-cell-tmpl.component'; +import { VirtualScrollTreeTableComponent } from './virtualScrollTreeTable.component'; + @NgModule({ imports: [ @@ -74,7 +75,8 @@ import { DataTableHeadCellTmplComponent } from './tmpl/data-table-head-cell-tmpl TableTheadComponent, TableTrComponent, TableTbodyComponent, - TableTdComponent + TableTdComponent, + VirtualScrollTreeTableComponent ], declarations: [ DataTableComponent, @@ -95,9 +97,10 @@ import { DataTableHeadCellTmplComponent } from './tmpl/data-table-head-cell-tmpl TableTheadComponent, TableTrComponent, TableTbodyComponent, - TableTdComponent + TableTdComponent, + VirtualScrollTreeTableComponent ], - + providers: [ TableTdService ], }) export class DataTableModule { diff --git a/devui/data-table/data-table.spec.ts b/devui/data-table/data-table.spec.ts index 4918af5b..c64c3478 100644 --- a/devui/data-table/data-table.spec.ts +++ b/devui/data-table/data-table.spec.ts @@ -260,7 +260,7 @@ class TestDataTableAdvancedComponent { this.filterListMulti = this.filterList; this.ref.detectChanges(); return true; - } + }; onRowCheckChange(checked, rowIndex, nestedIndex, rowItem) { rowItem.$checked = checked; @@ -371,11 +371,11 @@ class TestDataTableEditComponent { beforeEditStart = (rowItem, field): Boolean | Promise | Observable => { return Promise.resolve(true); - } + }; beforeEditEnd = (rowItem, field): Boolean | Promise | Observable => { return Promise.resolve(true); - } + }; } // data-table: has children @@ -472,7 +472,7 @@ class TestDataTableWithChildrenComponent { resolve(undefined); }, 500); }); - } + }; onChildTableToggle(event, rowItem) { this.childTableToggleEvent = event; @@ -551,48 +551,48 @@ class TestDataFixedColumnComponent { basicDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); dataTableOptions = { columns: [ - { - field: 'firstName', - header: 'First Name', - fieldType: 'text', - fixedLeft: '0px' - }, - { - field: 'lastName', - header: 'Last Name', - fieldType: 'text' - }, - { - field: 'gender', - header: 'gender', - fieldType: 'text' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date', - fixedRight: '0px' - } + { + field: 'firstName', + header: 'First Name', + fieldType: 'text', + fixedLeft: '0px' + }, + { + field: 'lastName', + header: 'Last Name', + fieldType: 'text' + }, + { + field: 'gender', + header: 'gender', + fieldType: 'text' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date', + fixedRight: '0px' + } ] }; diff --git a/devui/data-table/dataTableProperties.interface.ts b/devui/data-table/dataTableProperties.interface.ts new file mode 100644 index 00000000..9bd845cd --- /dev/null +++ b/devui/data-table/dataTableProperties.interface.ts @@ -0,0 +1,29 @@ +import { TableWidthConfig } from './data-table.model'; + +export interface DataTableProperiesInterface { + maxWidth?: string; + maxHeight?: string; + size?: string; + rowHoveredHighlight?: boolean; + generalRowHoveredData?: boolean; + cssClass?: string; + tableWidth?: string; + fixHeader?: boolean; + colDraggable?: boolean; + colDropFreezeTo?: number; + tableWidthConfig?: TableWidthConfig[]; + showSortIcon?: boolean; + showFilterIcon?: boolean; + showOperationArea?: boolean; + hideColumn?: string[]; + pageAllChecked?: boolean; + onlyOneColumnSort?: boolean; + multiSort?: any; + resizeable?: boolean; + timeout?: number; + beforeCellEdit?: any; + headerBg?: boolean; + tableLayout?: string; + borderType?: string; + striped?: boolean; +} diff --git a/devui/data-table/demo/async/data-table-demo-async.component.ts b/devui/data-table/demo/async/data-table-demo-async.component.ts index b2ad9691..0fe7287f 100755 --- a/devui/data-table/demo/async/data-table-demo-async.component.ts +++ b/devui/data-table/demo/async/data-table-demo-async.component.ts @@ -9,7 +9,7 @@ import { originSource, SourceType } from '../mock-data'; }) export class DatatableDemoAsyncComponent implements OnInit { - /*get Async DataSource*/ + /* get Async DataSource*/ remoteDataSource: Array = []; showLoading = false; loading: LoadingType; diff --git a/devui/data-table/demo/basic-old/basic-old.component.ts b/devui/data-table/demo/basic-old/basic-old.component.ts index 541302b5..a0537566 100644 --- a/devui/data-table/demo/basic-old/basic-old.component.ts +++ b/devui/data-table/demo/basic-old/basic-old.component.ts @@ -2,40 +2,40 @@ import { Component, OnInit } from '@angular/core'; import { originSource, SourceType } from '../mock-data'; @Component({ - selector: 'd-basic-old', - templateUrl: './basic-old.component.html' + selector: 'd-basic-old', + templateUrl: './basic-old.component.html' }) export class BasicOldComponent implements OnInit { - basicDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); - dataTableOptions = { - columns: [ - { - field: 'firstName', - header: 'First Name', - fieldType: 'text', - order: 1 - }, - { - field: 'lastName', - header: 'Last Name', - fieldType: 'text', - order: 2 - }, - { - field: 'gender', - header: 'Gender', - fieldType: 'text', - order: 3 - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date', - order: 4 - } - ] - }; + basicDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); + dataTableOptions = { + columns: [ + { + field: 'firstName', + header: 'First Name', + fieldType: 'text', + order: 1 + }, + { + field: 'lastName', + header: 'Last Name', + fieldType: 'text', + order: 2 + }, + { + field: 'gender', + header: 'Gender', + fieldType: 'text', + order: 3 + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date', + order: 4 + } + ] + }; - ngOnInit() { - } + ngOnInit() { + } } diff --git a/devui/data-table/demo/basic/data-table-demo-basic.component.ts b/devui/data-table/demo/basic/data-table-demo-basic.component.ts index a8626f20..8e04c226 100755 --- a/devui/data-table/demo/basic/data-table-demo-basic.component.ts +++ b/devui/data-table/demo/basic/data-table-demo-basic.component.ts @@ -3,59 +3,59 @@ import { TableWidthConfig } from 'ng-devui/data-table'; import { originSource, SourceType } from '../mock-data'; @Component({ - selector: 'd-basic', - templateUrl: './data-table-demo-basic.component.html' + selector: 'd-basic', + templateUrl: './data-table-demo-basic.component.html' }) export class DatatableDemoBasicComponent implements OnInit { - basicDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); - dataTableOptions = { - columns: [ - { - field: 'firstName', - header: 'First Name', - fieldType: 'text' - }, - { - field: 'lastName', - header: 'Last Name', - fieldType: 'text' - }, - { - field: 'gender', - header: 'Gender', - fieldType: 'text' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - } - ] - }; + basicDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); + dataTableOptions = { + columns: [ + { + field: 'firstName', + header: 'First Name', + fieldType: 'text' + }, + { + field: 'lastName', + header: 'Last Name', + fieldType: 'text' + }, + { + field: 'gender', + header: 'Gender', + fieldType: 'text' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + } + ] + }; - tableWidthConfig: TableWidthConfig[] = [ - { - field: '#', - width: '50px' - }, - { - field: 'firstName', - width: '150px' - }, - { - field: 'lastName', - width: '150px' - }, - { - field: 'gender', - width: '150px' - }, - { - field: 'dob', - width: '150px' - } - ]; - - ngOnInit() { + tableWidthConfig: TableWidthConfig[] = [ + { + field: '#', + width: '50px' + }, + { + field: 'firstName', + width: '150px' + }, + { + field: 'lastName', + width: '150px' + }, + { + field: 'gender', + width: '150px' + }, + { + field: 'dob', + width: '150px' } + ]; + + ngOnInit() { + } } diff --git a/devui/data-table/demo/data-table-demo.module.ts b/devui/data-table/demo/data-table-demo.module.ts index 397df70e..8552764a 100755 --- a/devui/data-table/demo/data-table-demo.module.ts +++ b/devui/data-table/demo/data-table-demo.module.ts @@ -3,7 +3,6 @@ import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; -import { TranslateModule } from '@ngx-translate/core'; import { DevUIModule } from 'ng-devui'; import { AutoCompleteModule } from 'ng-devui/auto-complete'; import { DataTableModule } from 'ng-devui/data-table'; @@ -14,6 +13,7 @@ import { DevUIApiModule } from 'ng-devui/shared/devui-api/devui-api.module'; import { DevUICodeboxModule } from 'ng-devui/shared/devui-codebox'; import { SplitterModule } from 'ng-devui/splitter'; import { TooltipModule } from 'ng-devui/tooltip'; +import { TranslateModule } from '@ngx-translate/core'; import { DDemoNavModule } from 'src/app/component/d-demo-nav.module'; import { DatatableDemoAsyncComponent } from './async/data-table-demo-async.component'; import { BasicOldComponent } from './basic-old/basic-old.component'; diff --git a/devui/data-table/demo/drag-column/drag-column.component.ts b/devui/data-table/demo/drag-column/drag-column.component.ts index c95c3229..85c4ac38 100644 --- a/devui/data-table/demo/drag-column/drag-column.component.ts +++ b/devui/data-table/demo/drag-column/drag-column.component.ts @@ -2,34 +2,34 @@ import { Component } from '@angular/core'; import { originSource, SourceType } from '../mock-data'; @Component({ - moduleId: module.id, - selector: 'd-drag-column', - templateUrl: 'drag-column.component.html' + moduleId: module.id, + selector: 'd-drag-column', + templateUrl: 'drag-column.component.html' }) export class DragColumnComponent { basicDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); dataTableOptions = { columns: [ - { - field: 'firstName', - header: 'First Name', - fieldType: 'text' - }, - { - field: 'lastName', - header: 'Last Name', - fieldType: 'text' - }, - { - field: 'gender', - header: 'gender', - fieldType: 'text' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - } + { + field: 'firstName', + header: 'First Name', + fieldType: 'text' + }, + { + field: 'lastName', + header: 'Last Name', + fieldType: 'text' + }, + { + field: 'gender', + header: 'gender', + fieldType: 'text' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + } ] }; diff --git a/devui/data-table/demo/drag-row/drag-row.component.ts b/devui/data-table/demo/drag-row/drag-row.component.ts index 451e3421..f9e6d8f0 100644 --- a/devui/data-table/demo/drag-row/drag-row.component.ts +++ b/devui/data-table/demo/drag-row/drag-row.component.ts @@ -72,7 +72,7 @@ export class DragRowComponent implements OnInit { let index = e.dropIndex; const fromIndex = e.dragFromIndex; if (-1 !== index) { - /*修正同一个container排序,往下拖动index多了1个位置*/ + /* 修正同一个container排序,往下拖动index多了1个位置*/ if (-1 !== fromIndex && index > fromIndex) { index--; } diff --git a/devui/data-table/demo/editable-old/editable-old.component.ts b/devui/data-table/demo/editable-old/editable-old.component.ts index d477b769..0300401b 100644 --- a/devui/data-table/demo/editable-old/editable-old.component.ts +++ b/devui/data-table/demo/editable-old/editable-old.component.ts @@ -3,13 +3,11 @@ import { OnInit, ViewChild } from '@angular/core'; - import { DataTableComponent } from 'ng-devui/data-table'; - +import { cloneDeep } from 'lodash-es'; import { editableOriginSource, - genderSource, - SourceType + genderSource } from '../mock-data'; @Component({ @@ -19,7 +17,7 @@ import { export class EditableOldComponent implements OnInit { @ViewChild(DataTableComponent, { static: true }) dataTable: DataTableComponent; genderSource = genderSource; - basicDataSource: Array = JSON.parse(JSON.stringify(editableOriginSource.slice(0, 6))); + basicDataSource = cloneDeep(editableOriginSource.slice(0, 6)); thisCellEditEnd(event) { console.log('cellEditEnd'); console.log(event.rowItem); @@ -33,7 +31,7 @@ export class EditableOldComponent implements OnInit { console.log('beforeCellEdit'); resolve(undefined); }); - } + }; finishEdit() { this.dataTable.cancelEditingStatus(); diff --git a/devui/data-table/demo/editable/data-table-demo-editable.component.ts b/devui/data-table/demo/editable/data-table-demo-editable.component.ts index a0b6fb86..913fa338 100755 --- a/devui/data-table/demo/editable/data-table-demo-editable.component.ts +++ b/devui/data-table/demo/editable/data-table-demo-editable.component.ts @@ -1,14 +1,15 @@ import { Component, OnInit } from '@angular/core'; import { EditableTip } from 'ng-devui/data-table'; -import { editableOriginSource, genderSource, SourceType } from '../mock-data'; +import { cloneDeep } from 'lodash-es'; +import { editableOriginSource, genderSource } from '../mock-data'; @Component({ - selector: 'd-editable', - templateUrl: './data-table-demo-editable.component.html' + selector: 'd-editable', + templateUrl: './data-table-demo-editable.component.html' }) export class DatatableDemoEditableComponent implements OnInit { genderSource = genderSource; - basicDataSource: Array = JSON.parse(JSON.stringify(editableOriginSource.slice(0, 6))); + basicDataSource = cloneDeep(editableOriginSource.slice(0, 6)); editableTip = EditableTip.btn; nameEditing: boolean; @@ -22,7 +23,7 @@ export class DatatableDemoEditableComponent implements OnInit { beforeEditStart = (rowItem, field) => { return true; - } + }; beforeEditEnd = (rowItem, field) => { console.log('beforeEditEnd'); @@ -31,5 +32,5 @@ export class DatatableDemoEditableComponent implements OnInit { } else { return true; } - } + }; } diff --git a/devui/data-table/demo/fix-column-old/fix-column-old.component.ts b/devui/data-table/demo/fix-column-old/fix-column-old.component.ts index c7ad5ab2..27a7f047 100644 --- a/devui/data-table/demo/fix-column-old/fix-column-old.component.ts +++ b/devui/data-table/demo/fix-column-old/fix-column-old.component.ts @@ -6,58 +6,58 @@ import { import { originSource, SourceType } from '../mock-data'; @Component({ - selector: 'd-fix-column-old', - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: './fix-column-old.component.html' + selector: 'd-fix-column-old', + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './fix-column-old.component.html' }) export class FixColumnOldComponent implements OnInit { basicDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); dataTableOptions = { columns: [ - { - field: 'firstName', - header: 'First Name', - fieldType: 'text', - fixedLeft: '36px' - }, - { - field: 'lastName', - header: 'Last Name', - fieldType: 'text' - }, - { - field: 'gender', - header: 'gender', - fieldType: 'text' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date', - fixedRight: '0px' - } + { + field: 'firstName', + header: 'First Name', + fieldType: 'text', + fixedLeft: '36px' + }, + { + field: 'lastName', + header: 'Last Name', + fieldType: 'text' + }, + { + field: 'gender', + header: 'gender', + fieldType: 'text' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date', + fixedRight: '0px' + } ] -}; + }; ngOnInit() { } diff --git a/devui/data-table/demo/fix-column/fix-column.component.ts b/devui/data-table/demo/fix-column/fix-column.component.ts index c07a7ab3..dbe946bf 100644 --- a/devui/data-table/demo/fix-column/fix-column.component.ts +++ b/devui/data-table/demo/fix-column/fix-column.component.ts @@ -8,57 +8,57 @@ import { DataTableComponent, TableWidthConfig } from 'ng-devui/data-table'; import { originSource, SourceType } from '../mock-data'; @Component({ - selector: 'd-fix-column', - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: './fix-column.component.html' + selector: 'd-fix-column', + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './fix-column.component.html' }) export class FixColumnComponent implements OnInit { @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent; basicDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); dataTableOptions = { columns: [ - { - field: 'firstName', - header: 'First Name', - fieldType: 'text', - fixedLeft: '36px' - }, - { - field: 'lastName', - header: 'Last Name', - fieldType: 'text' - }, - { - field: 'gender', - header: 'gender', - fieldType: 'text' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date' - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date', - fixedRight: '0px' - } + { + field: 'firstName', + header: 'First Name', + fieldType: 'text', + fixedLeft: '36px' + }, + { + field: 'lastName', + header: 'Last Name', + fieldType: 'text' + }, + { + field: 'gender', + header: 'gender', + fieldType: 'text' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date' + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date', + fixedRight: '0px' + } ] }; diff --git a/devui/data-table/demo/interaction-column/interaction-column.component.html b/devui/data-table/demo/interaction-column/interaction-column.component.html index 64ea3f3d..f31cbfea 100644 --- a/devui/data-table/demo/interaction-column/interaction-column.component.html +++ b/devui/data-table/demo/interaction-column/interaction-column.component.html @@ -55,7 +55,7 @@ field="dob" header="Date of birth" [fieldType]="'date'" - [extraOptions]="{ dateFormat: 'MM/DD/YYYY' }" + [extraOptions]="{ dateFormat: 'MM/dd/yyyy' }" [width]="'100px'" > diff --git a/devui/data-table/demo/interaction-column/interaction-column.component.ts b/devui/data-table/demo/interaction-column/interaction-column.component.ts index 8067086b..0a469397 100644 --- a/devui/data-table/demo/interaction-column/interaction-column.component.ts +++ b/devui/data-table/demo/interaction-column/interaction-column.component.ts @@ -117,7 +117,7 @@ export class InteractionColumnComponent implements OnInit { this.filterListMulti = this.filterList; this.ref.detectChanges(); return true; - } + }; getCheckedRows() { const rows = this.datatable.getCheckedRows(); @@ -155,17 +155,17 @@ export class InteractionColumnComponent implements OnInit { console.log(e); } cellClick(e) { - console.log('cell'); - console.log(e); + console.log('cell'); + console.log(e); } rowDBClick(e) { - console.log('rowDB'); - console.log(e); + console.log('rowDB'); + console.log(e); } rowClick(e) { - console.log('row'); - console.log(e); + console.log('row'); + console.log(e); } } diff --git a/devui/data-table/demo/interaction/interaction.component.ts b/devui/data-table/demo/interaction/interaction.component.ts index 1ac08bd8..22068a89 100644 --- a/devui/data-table/demo/interaction/interaction.component.ts +++ b/devui/data-table/demo/interaction/interaction.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core'; -import { DataTableComponent, SortDirection, SortEventArg, TableWidthConfig, FilterConfig } from 'ng-devui/data-table'; +import { DataTableComponent, SortDirection, SortEventArg, TableWidthConfig } from 'ng-devui/data-table'; import { originSource, SourceType } from '../mock-data'; @Component({ @@ -10,7 +10,7 @@ import { originSource, SourceType } from '../mock-data'; export class InteractionComponent implements OnInit { @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent; sortableDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); - filterListRadio: FilterConfig[] = [ + filterListRadio = [ { name: 'Clear', value: 'Clear', @@ -143,7 +143,7 @@ export class InteractionComponent implements OnInit { this.filterListMulti = this.firstFilterList; this.ref.detectChanges(); return true; - } + }; onRowCheckChange(checked, rowIndex, nestedIndex, rowItem) { rowItem.$checked = checked; diff --git a/devui/data-table/demo/lazy/data-table-demo-lazyloaddata.component.ts b/devui/data-table/demo/lazy/data-table-demo-lazyloaddata.component.ts index 06c81ba2..4123dc6b 100755 --- a/devui/data-table/demo/lazy/data-table-demo-lazyloaddata.component.ts +++ b/devui/data-table/demo/lazy/data-table-demo-lazyloaddata.component.ts @@ -5,72 +5,72 @@ import {LoadingType} from 'ng-devui/loading'; import { EMPTY } from 'rxjs'; import { originSource } from './../mock-data'; @Component({ - selector: 'd-datatable-demo-lazyloaddata', - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: './data-table-demo-lazyloaddata.component.html' + selector: 'd-datatable-demo-lazyloaddata', + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './data-table-demo-lazyloaddata.component.html' }) export class DatatableDemoLazyloadDataComponent implements OnInit { - showLoading = false; + showLoading = false; // Lazy Load - total = 40; - next = 1; - complete = false; - lazyDataSource = originSource; + total = 40; + next = 1; + complete = false; + lazyDataSource = originSource; - dataTableOptions = { - columns: [ - { - field: 'firstName', - header: 'First Name', - fieldType: 'text', - sortable: true, - }, - { - field: 'lastName', - header: 'Last Name', - fieldType: 'text', - sortable: true, - }, - { - field: 'gender', - header: 'gender', - fieldType: 'text', - sortable: true, - }, - { - field: 'dob', - header: 'Date of birth', - fieldType: 'date', - sortable: true, - } - ] - }; + dataTableOptions = { + columns: [ + { + field: 'firstName', + header: 'First Name', + fieldType: 'text', + sortable: true, + }, + { + field: 'lastName', + header: 'Last Name', + fieldType: 'text', + sortable: true, + }, + { + field: 'gender', + header: 'gender', + fieldType: 'text', + sortable: true, + }, + { + field: 'dob', + header: 'Date of birth', + fieldType: 'date', + sortable: true, + } + ] + }; - constructor(private cdr: ChangeDetectorRef) {} + constructor(private cdr: ChangeDetectorRef) {} - loadMore(event) { - if (this.next > this.total) { - return; - } - this.showLoading = true; - const end = this.next + 20; - const dataSource = []; - for (; this.next < end; this.next++) { - dataSource.push({ - firstName: 'Danni', - lastName: 'Yu', - gender: 'Female', - dob: new Date(1991, 3, 1) - }); - } - setTimeout(() => { - this.lazyDataSource = this.lazyDataSource.concat(dataSource); - this.showLoading = false; - this.cdr.detectChanges(); - }, 300); - this.complete = this.next > this.total; - console.log(`load more`, this.next, this.complete); + loadMore(event) { + if (this.next > this.total) { + return; } + this.showLoading = true; + const end = this.next + 20; + const dataSource = []; + for (; this.next < end; this.next++) { + dataSource.push({ + firstName: 'Danni', + lastName: 'Yu', + gender: 'Female', + dob: new Date(1991, 3, 1) + }); + } + setTimeout(() => { + this.lazyDataSource = this.lazyDataSource.concat(dataSource); + this.showLoading = false; + this.cdr.detectChanges(); + }, 300); + this.complete = this.next > this.total; + console.log(`load more`, this.next, this.complete); + } ngOnInit() { } diff --git a/devui/data-table/demo/mock-data.ts b/devui/data-table/demo/mock-data.ts index a990a13c..2e51eeea 100755 --- a/devui/data-table/demo/mock-data.ts +++ b/devui/data-table/demo/mock-data.ts @@ -116,7 +116,7 @@ export const editableOriginSource = [ gender: { id: 1, label: 'Male' }, age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -135,7 +135,7 @@ export const editableOriginSource = [ dob: new Date(1989, 1, 1), age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -154,7 +154,7 @@ export const editableOriginSource = [ dob: new Date(2018, 3, 1), age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -173,7 +173,7 @@ export const editableOriginSource = [ dob: new Date(2018, 3, 1), age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -210,7 +210,7 @@ export const editableOriginSource = [ dob: new Date(2018, 3, 1), age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -229,7 +229,7 @@ export const editableOriginSource = [ dob: new Date(2018, 3, 1), age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -248,7 +248,7 @@ export const editableOriginSource = [ dob: new Date(2018, 3, 1), age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -268,7 +268,7 @@ export const editableOriginSource = [ detail: '这是另外一个行详情', age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -287,7 +287,7 @@ export const editableOriginSource = [ dob: new Date(2018, 3, 1), age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -306,7 +306,7 @@ export const editableOriginSource = [ dob: new Date(2018, 3, 1), age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -325,7 +325,7 @@ export const editableOriginSource = [ dob: new Date(2018, 3, 1), age: 24, hobby: [{ id: 1, name: 'music' }, - { id: 2, name: 'football' }], + { id: 2, name: 'football' }], duty: [{ 'title': '前端维护', 'id': 9 @@ -391,87 +391,87 @@ export const DutySource = [ export const treeDataSource = [ { - title: 'table title0', - lastName: 'Mark', - dob: new Date(1990, 12, 1), - status: 'done', - startDate: new Date(2020, 1, 5), - endDate: new Date(2020, 1, 8), - children: [ - { - title: 'table title01', + title: 'table title0', + lastName: 'Mark', + dob: new Date(1990, 12, 1), + status: 'done', + startDate: new Date(2020, 1, 5), + endDate: new Date(2020, 1, 8), + children: [ + { + title: 'table title01', + lastName: 'Mark', + status: 'done', + dob: new Date(1989, 1, 1), + children: [ + { + title: 'table title011', lastName: 'Mark', status: 'done', dob: new Date(1989, 1, 1), + }, + { + title: 'table title012', + lastName: 'Mark', + status: 'done', + dob: new Date(1991, 3, 1), children: [ { - title: 'table title011', - lastName: 'Mark', - status: 'done', - dob: new Date(1989, 1, 1), + title: 'table title0121', + lastName: 'Mark', + status: 'done', + dob: new Date(1989, 1, 1) }, { - title: 'table title012', - lastName: 'Mark', - status: 'done', - dob: new Date(1991, 3, 1), - children: [ - { - title: 'table title0121', - lastName: 'Mark', - status: 'done', - dob: new Date(1989, 1, 1) - }, - { - title: 'table title0122', - lastName: 'Mark', - status: 'done', - dob: new Date(1989, 1, 1) - } - ] + title: 'table title0122', + lastName: 'Mark', + status: 'done', + dob: new Date(1989, 1, 1) } ] - }, - { - title: 'table title02', - lastName: 'Mark', - status: 'done', - dob: new Date(1991, 3, 1) - } - ] + } + ] + }, + { + title: 'table title02', + lastName: 'Mark', + status: 'done', + dob: new Date(1991, 3, 1) + } + ] }, { - title: 'table title1', - lastName: 'Mark', - status: 'done', - dob: new Date(1989, 1, 1), - startDate: new Date(2020, 1, 4), - endDate: new Date(2020, 1, 8), - children: [] + title: 'table title1', + lastName: 'Mark', + status: 'done', + dob: new Date(1989, 1, 1), + startDate: new Date(2020, 1, 4), + endDate: new Date(2020, 1, 8), + children: [] }, { - title: 'table title2', - lastName: 'Mark', - status: 'done', - dob: new Date(1991, 3, 1), - startDate: new Date(2020, 1, 6), - endDate: new Date(2020, 1, 9), + title: 'table title2', + lastName: 'Mark', + status: 'done', + dob: new Date(1991, 3, 1), + startDate: new Date(2020, 1, 6), + endDate: new Date(2020, 1, 9), }, { - title: 'table title3', - lastName: 'Mark', - status: 'done', - dob: new Date(1991, 3, 1), - detail: '这是一个行详情', - startDate: new Date(2020, 1, 7), - endDate: new Date(2020, 1, 10), + title: 'table title3', + lastName: 'Mark', + status: 'done', + dob: new Date(1991, 3, 1), + detail: '这是一个行详情', + startDate: new Date(2020, 1, 7), + endDate: new Date(2020, 1, 10), }, { - title: 'table title4', - lastName: 'Mark', - status: 'done', - dob: new Date(1991, 3, 1), - startDate: new Date(2020, 1, 7), - endDate: new Date(2020, 1, 12), + title: 'table title4', + lastName: 'Mark', + status: 'done', + dob: new Date(1991, 3, 1), + startDate: new Date(2020, 1, 7), + endDate: new Date(2020, 1, 12), } ]; diff --git a/devui/data-table/demo/multi-header/data-table-demo-multiheader.component.html b/devui/data-table/demo/multi-header/data-table-demo-multiheader.component.html index 0d01346d..b5d5de99 100755 --- a/devui/data-table/demo/multi-header/data-table-demo-multiheader.component.html +++ b/devui/data-table/demo/multi-header/data-table-demo-multiheader.component.html @@ -37,7 +37,7 @@ field="dob" header="Date of birth" [fieldType]="'date'" - [extraOptions]="{ dateFormat: 'YYYY/MM/DD' }" + [extraOptions]="{ dateFormat: 'yyyy/MM/dd' }" [width]="'200px'" > diff --git a/devui/data-table/demo/multi-header/data-table-demo-multiheader.component.ts b/devui/data-table/demo/multi-header/data-table-demo-multiheader.component.ts index 49e4b1db..39b310ad 100755 --- a/devui/data-table/demo/multi-header/data-table-demo-multiheader.component.ts +++ b/devui/data-table/demo/multi-header/data-table-demo-multiheader.component.ts @@ -6,30 +6,30 @@ import { import { originSource, SourceType } from '../mock-data'; @Component({ - selector: 'd-datatable-demo-multiheader', - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: './data-table-demo-multiheader.component.html' + selector: 'd-datatable-demo-multiheader', + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './data-table-demo-multiheader.component.html' }) export class DatatableDemoMultiHeaderComponent implements OnInit { basicDataSource: Array = JSON.parse(JSON.stringify(originSource.slice(0, 6))); - cellDBClick(e) { - console.log('cellDB'); - console.log(e); - } - cellClick(e) { - console.log('cell'); - console.log(e); - } - rowDBClick(e) { - console.log('rowDB'); - console.log(e); - } + cellDBClick(e) { + console.log('cellDB'); + console.log(e); + } + cellClick(e) { + console.log('cell'); + console.log(e); + } + rowDBClick(e) { + console.log('rowDB'); + console.log(e); + } - rowClick(e) { - console.log('row'); - console.log(e); - } + rowClick(e) { + console.log('row'); + console.log(e); + } ngOnInit() { } diff --git a/devui/data-table/demo/muti-drag-row/muti-drag-row.component.ts b/devui/data-table/demo/muti-drag-row/muti-drag-row.component.ts index 2a78d2a0..5e7cd7a5 100644 --- a/devui/data-table/demo/muti-drag-row/muti-drag-row.component.ts +++ b/devui/data-table/demo/muti-drag-row/muti-drag-row.component.ts @@ -103,7 +103,7 @@ export class MutiDragRowComponent implements OnInit { let index = e.dropIndex; const fromIndex = e.dragFromIndex; if (-1 !== index) { - /*修正同一个container排序,往下拖动index多了1个位置*/ + /* 修正同一个container排序,往下拖动index多了1个位置*/ if (-1 !== fromIndex && index > fromIndex) { index--; } diff --git a/devui/data-table/demo/tree-table-old/tree-table-old.component.html b/devui/data-table/demo/tree-table-old/tree-table-old.component.html index 74f49f1b..69bb3631 100644 --- a/devui/data-table/demo/tree-table-old/tree-table-old.component.html +++ b/devui/data-table/demo/tree-table-old/tree-table-old.component.html @@ -29,7 +29,7 @@ field="dob" header="date" [fieldType]="'date'" - [extraOptions]="{ dateFormat: 'MM/DD/YYYY' }" + [extraOptions]="{ dateFormat: 'MM/dd/yyyy' }" [width]="'20%'" > diff --git a/devui/data-table/demo/tree-table-old/tree-table-old.component.ts b/devui/data-table/demo/tree-table-old/tree-table-old.component.ts index c4e1afd2..f98bc806 100644 --- a/devui/data-table/demo/tree-table-old/tree-table-old.component.ts +++ b/devui/data-table/demo/tree-table-old/tree-table-old.component.ts @@ -20,13 +20,13 @@ export class TreeTableOldComponent implements OnInit { } cellClick(e) { - console.log('cell'); - console.log(e); + console.log('cell'); + console.log(e); } rowClick(e) { - console.log('row'); - console.log(e); + console.log('row'); + console.log(e); } loadChildrenTable = (rowItem) => { @@ -41,14 +41,14 @@ export class TreeTableOldComponent implements OnInit { dob: new Date(1989, 1, 1), startDate: new Date(2020, 1, 4), endDate: new Date(2020, 1, 8) - }); + }); } } resolve(rowItem); }, 500); }); - } + }; loadAllChildrenTable = () => { this.basicDataSource[0].children[0].children[1].children[0].children = []; @@ -59,15 +59,15 @@ export class TreeTableOldComponent implements OnInit { dob: new Date(1989, 1, 1), }, { - title: 'table title32', - lastName: 'Mark', - status: 'done', - dob: new Date(1991, 3, 1) + title: 'table title32', + lastName: 'Mark', + status: 'done', + dob: new Date(1991, 3, 1) }); return new Promise((resolve) => { resolve(true); }); - } + }; setUnCheckableRelation(type) { if (type === 'upward') { diff --git a/devui/data-table/demo/tree-table/tree-data.component.ts b/devui/data-table/demo/tree-table/tree-data.component.ts index c79789db..0ab6a33c 100755 --- a/devui/data-table/demo/tree-table/tree-data.component.ts +++ b/devui/data-table/demo/tree-table/tree-data.component.ts @@ -3,13 +3,11 @@ import { OnInit, ViewChild } from '@angular/core'; - import { CheckableRelation, DataTableComponent, TableWidthConfig } from 'ng-devui/data-table'; - import { SourceType, treeDataSource @@ -70,14 +68,14 @@ export class TreeDataComponent implements OnInit { dob: new Date(1989, 1, 1), startDate: new Date(2020, 1, 4), endDate: new Date(2020, 1, 8) - }); + }); } } resolve(rowItem); }, 500); }); - } + }; loadAllChildrenTable = () => { return new Promise((resolve) => { @@ -90,15 +88,15 @@ export class TreeDataComponent implements OnInit { dob: new Date(1989, 1, 1), }, { - title: 'table title01212', - lastName: 'Mark', - status: 'done', - dob: new Date(1991, 3, 1) + title: 'table title01212', + lastName: 'Mark', + status: 'done', + dob: new Date(1991, 3, 1) }); resolve(undefined); }, 500); }); - } + }; setUnCheckableRelation(type) { if (type === 'upward') { diff --git a/devui/data-table/display-cell-value.pipe.ts b/devui/data-table/display-cell-value.pipe.ts index 104b659f..83687c4f 100755 --- a/devui/data-table/display-cell-value.pipe.ts +++ b/devui/data-table/display-cell-value.pipe.ts @@ -6,8 +6,8 @@ import { DataTableColumnTmplComponent } from './tmpl/data-table-column-tmpl.comp export class DisPlayCellValuePipe implements PipeTransform { datePicker = { format: { - date: 'YYYY-MM-DD', - time: 'YYYY-MM-DD HH:mm' + date: 'y/MM/dd', + time: 'y/MM/dd HH:mm' } }; @@ -24,44 +24,45 @@ export class DisPlayCellValuePipe implements PipeTransform { const cellItem = rowItem[column.field]; switch (column.fieldType) { - case 'date': - let pattern; - if (column.extraOptions && column.extraOptions.dateFormat) { - pattern = column.extraOptions.dateFormat; - } else { - pattern = column.extraOptions && column.extraOptions.showTime ? - this.datePicker.format.time : this.datePicker.format.date; - } - return cellItem ? formatDate(new Date(cellItem), pattern) : ''; - case 'select': - case 'treeSelect': - if (column.extraOptions && column.extraOptions.multiple) { - if (cellItem && cellItem.length > 0) { - let displayValue; - if (column.extraOptions.filterKey) { - displayValue = cellItem.map(item => item[column.extraOptions.filterKey]).join(';'); - } else { - displayValue = cellItem.join(';'); - } - return displayValue; - } else { - return '--'; - } - } else { + case 'date': { + let pattern; + if (column.extraOptions && column.extraOptions.dateFormat) { + pattern = column.extraOptions.dateFormat; + } else { + pattern = column.extraOptions && column.extraOptions.showTime ? + this.datePicker.format.time : this.datePicker.format.date; + } + return cellItem ? formatDate(new Date(cellItem), pattern) : ''; + } + case 'select': + case 'treeSelect': + if (column.extraOptions && column.extraOptions.multiple) { + if (cellItem && cellItem.length > 0) { let displayValue; - if (column.extraOptions && column.extraOptions.filterKey) { - displayValue = cellItem ? cellItem[column.extraOptions.filterKey] : cellItem; + if (column.extraOptions.filterKey) { + displayValue = cellItem.map(item => item[column.extraOptions.filterKey]).join(';'); } else { - displayValue = cellItem; + displayValue = cellItem.join(';'); } - return displayValue === 0 ? 0 : (displayValue || '--'); - } - default: - if (cellItem === null || cellItem === undefined || cellItem === '') { + return displayValue; + } else { return '--'; + } + } else { + let displayValue; + if (column.extraOptions && column.extraOptions.filterKey) { + displayValue = cellItem ? cellItem[column.extraOptions.filterKey] : cellItem; } else { - return cellItem; + displayValue = cellItem; } + return displayValue === 0 ? 0 : (displayValue || '--'); + } + default: + if (cellItem === null || cellItem === undefined || cellItem === '') { + return '--'; + } else { + return cellItem; + } } } } diff --git a/devui/data-table/doc/api-cn.md b/devui/data-table/doc/api-cn.md index 0c2373fe..712befa2 100644 --- a/devui/data-table/doc/api-cn.md +++ b/devui/data-table/doc/api-cn.md @@ -446,4 +446,4 @@ advancedHeader: Array < { } ``` -注意: 空单元格也需要表示,并根据内容把rowspan/colspan置为0,如果同时使用列宽拖拽和多行表头,请为列内容附上宽度width,如果第一行的列宽度不正确,请手动为advancedHeader[rowNumber]增加一个属性$width +注意: 空单元格也需要表示,并根据内容把rowspan/colspan置为0,如果同时使用列宽拖拽和多行表头,请为列内容附上宽度width,如果第一行的列宽度不正确,请手动为advancedHeader[rowNumber]增加一个属性$width \ No newline at end of file diff --git a/devui/data-table/doc/api-en.md b/devui/data-table/doc/api-en.md index 5593ca62..318eca60 100644 --- a/devui/data-table/doc/api-en.md +++ b/devui/data-table/doc/api-en.md @@ -432,3 +432,249 @@ colspan: number; } ``` Note: Empty cells also need to be indicated. Set rowspan/colspan to 0 based on the content. If column width dragging and multi-row headers are used at the same time, attach the width to the column content. If the column width of the first row is incorrect, manually add the $width attribute for advancedHeader[rowNumber]. + +#### Tree table with a large amount of data + +## virtual-scroll-tree-table parameter +| Parameter name | Type | Default value | Description | Jump to Demo | +| :---------------: | :-----------------: | :----- | :-------------------------------------------------------------------------------------------------------: |:-----------------: | +| dataSource | `any[]` | -- | Required. It is a data source used to render table data. |[Tree table with a large amount of data](demo#virtual-scroll-tree-table)| +| editOption | `any[]` | -- | Optional. Used to configure the resource of the drop-down list box during modification. |[Tree table with a large amount of data](demo#virtual-scroll-tree-table)| +| showRowIndex | `number` | 10 | Optional. Used to configure the initial number of rows to be displayed in a table. |[Tree table with a large amount of data](demo#virtual-scroll-tree-table)| +| dataTableProperties | [`DataTableProperiesInterface`](#DataTableProperiesInterface) | -- | Optional. Support for original parameters of dataTable, Parameters defined in DataTableProperiesInterface can be supported. |[Tree table with a large amount of data](demo#virtual-scroll-tree-table)| + +## virtual-scroll-tree-table event +| Event | Type | Description | Jump to Demo | +| :-------------------: | :------------------------------------: | :------------------------------------------------------: | :------------------------------------------------------: | +| save | `EventEmitter` | Returns the data after the operation is changed. | [Tree table with a large amount of data](demo#virtual-scroll-tree-table) | + +## Customizing Templates and Operation Columns in d-column Mode + +``` xml + + + + {{ rowItem.category }} + + + + +
+ + +
+
+
+
+ + + + + + +
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+``` + +## Expanding or collapsing a tree table with a large amount of data + +Use @ViewChild to invoke the expand/collapse all function + +``` xml + +Expand All +Fold All +``` + +``` javascript +@ViewChild('VirtualTableTree') VirtualTableTree: VirtualScrollTreeTableComponent; + +toggleAllNodesExpand(e) { + this.VirtualTableTree.toggleAllNodesExpand(e); + this.isOpenAll = e; +} + +// Use @ViewChild to call toggleAllNodesExpand method in VirtualScrollTreeTableComponent +``` + +## Tree table search for a large amount of data + +Use @ViewChild to invoke the search function + +``` xml +
+ +
+ +``` + +``` javascript +@ViewChild('VirtualTableTree') VirtualTableTree: VirtualScrollTreeTableComponent; + +searchSelectChange() { + this.BigTableTree.searchAttr = this.searchAttr; + this.BigTableTree.searchSelectChange(); +} + +search(event) { + this.VirtualTableTree.search(event); + if(event) { + this.isSearch = true; + } else { + this.isSearch = false; + } +} + +// Call the searchSelectChange and search methods in VirtualScrollTreeTableComponent using @ViewChild +``` + +## Adding a large amount of data to a tree table + +Use @ViewChild to invoke the add function + +``` xml +// Global Add +Add Node +Add Folder + +// Add Operation Column +
+
+
+
+``` + +``` javascript +@ViewChild('VirtualTableTree') VirtualTableTree: VirtualScrollTreeTableComponent; + +// Users can customize data templates. +addTemplate: any = { + "property": "addPro", + "description": "addDes", + "category": "Dynamic" +} + +// Global Add +addGolbal(status) { + this.isAddGolbalData = true; + this.VirtualTableTree.addGolbal(status, this.addTemplate); + this.isAddGolbalData = false; +} + +// Call the addGolbal method in VirtualScrollTreeTableComponent using @ViewChild + +// Add Operation Column +addOperation(rowItem, status) { + this.VirtualTableTree.addOperation(rowItem, status, this.addTemplate); +} + +// Call the addOperation method in VirtualScrollTreeTableComponent using @ViewChild +``` + +## Copying and Pasting Tree Tables with a Large Amount of Data + +Use @ViewChild to invoke the copying and pasting function + +``` xml +
+
+
+
+``` + +``` javascript +@ViewChild('VirtualTableTree') VirtualTableTree: VirtualScrollTreeTableComponent; + +copyAndCut(rowItem, status) { + this.saveCopyClickNode = rowItem.node_id; + if(status === 'cut') { + this.isCut = true; + } + this.VirtualTableTree.copyAndCut(rowItem, status); +} + +paste(rowItem, status) { + this.VirtualTableTree.paste(rowItem, status); + if(this.isCut) { + this.saveCopyClickNode = ""; + this.isCut = false; + } +} + +// Use @ViewChild to call copyAndCut and paste methods in VirtualScrollTreeTableComponent +``` + +## Removing a large amount of data from a tree table + +Use @ViewChild to invoke the delete function +``` xml +
+``` + +``` javascript +@ViewChild('VirtualTableTree') VirtualTableTree: VirtualScrollTreeTableComponent; + +delete(rowItem) { + this.VirtualTableTree.delete(rowItem); +} + +// Call the delete method in VirtualScrollTreeTableComponent using @ViewChild +``` + +## DataTableProperiesInterface + +```ts +export interface DataTableProperiesInterface { + maxWidth?: string; + maxHeight?: string; + size?: string; + rowHoveredHighlight?: boolean; + generalRowHoveredData?: boolean; + cssClass?: string; + tableWidth?: string; + fixHeader?: boolean; + colDraggable?: boolean; + colDropFreezeTo?: number; + tableWidthConfig?: TableWidthConfig[]; + showSortIcon?: boolean; + showFilterIcon?: boolean; + showOperationArea?: boolean; + hideColumn?: string[]; + pageAllChecked?: boolean; + onlyOneColumnSort?: boolean; + multiSort?: any; + resizeable?: boolean; + timeout?: number; + beforeCellEdit?: any; + headerBg?: boolean; + tableLayout?: string; + borderType?: string; + striped?: boolean; +} +``` \ No newline at end of file diff --git a/devui/data-table/public-api.ts b/devui/data-table/public-api.ts index 0c7d3253..5b4fc8a7 100755 --- a/devui/data-table/public-api.ts +++ b/devui/data-table/public-api.ts @@ -1,25 +1,25 @@ -export * from './data-table.component'; -export * from './tmpl/data-table-column-tmpl.component'; -export * from './tmpl/data-table-cell-tmpl.component'; -export * from './tmpl/data-table-head-cell-tmpl.component'; -export * from './tmpl/data-table-cell-view-tmpl.component'; -export * from './tmpl/data-table-cell-edit-tmpl.component'; -export * from './data-table-cell.component'; export * from './data-table-body.component'; +export * from './data-table-cell.component'; export * from './data-table-head.component'; export * from './data-table-row.component'; -export * from './editor-host.directive'; +export * from './data-table.component'; +export * from './data-table.model'; export * from './data-table.module'; +export * from './dataTableProperties.interface'; export * from './display-cell-value.pipe'; -export * from './data-table-row.component'; -export * from './data-table-body.component'; -export * from './data-table-cell.component'; -export * from './data-table.model'; -export * from './table/head/thead.component'; -export * from './table/head/th/th.component'; -export * from './table/head/th/filter/filter.component'; -export * from './table/head/th/sort/sort.component'; +export * from './editor-host.directive'; +export * from './table/body/tbody.component'; export * from './table/body/td/td.component'; export * from './table/body/td/td.service'; -export * from './table/body/tbody.component'; +export * from './table/head/th/filter/filter.component'; +export * from './table/head/th/sort/sort.component'; +export * from './table/head/th/th.component'; +export * from './table/head/thead.component'; export * from './table/row/tr.component'; +export * from './tmpl/data-table-cell-edit-tmpl.component'; +export * from './tmpl/data-table-cell-tmpl.component'; +export * from './tmpl/data-table-cell-view-tmpl.component'; +export * from './tmpl/data-table-column-tmpl.component'; +export * from './tmpl/data-table-head-cell-tmpl.component'; +export * from './virtualScrollTreeTable.component'; + diff --git a/devui/data-table/table/body/tbody.component.ts b/devui/data-table/table/body/tbody.component.ts index 833ad1c6..41a864f7 100644 --- a/devui/data-table/table/body/tbody.component.ts +++ b/devui/data-table/table/body/tbody.component.ts @@ -3,6 +3,7 @@ import { TableWidthConfig } from '../../data-table.model'; import { TableTrComponent } from '../row/tr.component'; @Component({ + /* eslint-disable-next-line @angular-eslint/component-selector*/ selector: '[dTableBody]', templateUrl: './tbody.component.html', styleUrls: ['./tbody.component.scss'] diff --git a/devui/data-table/table/body/td/td.component.ts b/devui/data-table/table/body/td/td.component.ts index fa084c40..80a381de 100644 --- a/devui/data-table/table/body/td/td.component.ts +++ b/devui/data-table/table/body/td/td.component.ts @@ -9,6 +9,7 @@ import { EditableTip } from '../../../data-table.model'; import { TableTdService } from './td.service'; @Component({ + /* eslint-disable-next-line @angular-eslint/component-selector*/ selector: '[dTableCell]', templateUrl: './td.component.html', styleUrls: ['./td.component.scss'] diff --git a/devui/data-table/table/head/th/filter/filter.component.ts b/devui/data-table/table/head/th/filter/filter.component.ts index fa7ab481..8d20f274 100644 --- a/devui/data-table/table/head/th/filter/filter.component.ts +++ b/devui/data-table/table/head/th/filter/filter.component.ts @@ -158,17 +158,17 @@ export class FilterComponent implements OnInit, OnChanges, OnDestroy { onContainerScroll = () => { this.closeFilter(this.filterDropdown); - } + }; showFilterContent($event) { if (this.closeWhenScroll) { const tableViewElement = this.thComponent.tableViewRefElement.nativeElement.querySelector('.devui-scrollbar.scroll-view'); if ($event) { this.document.addEventListener('scroll', this.onContainerScroll); - tableViewElement?.addEventListener('scroll', this.onContainerScroll); + if (tableViewElement) { tableViewElement.addEventListener('scroll', this.onContainerScroll); } } else { this.document.removeEventListener('scroll', this.onContainerScroll); - tableViewElement?.removeEventListener('scroll', this.onContainerScroll); + if (tableViewElement) { tableViewElement.removeEventListener('scroll', this.onContainerScroll); } } } this.searchText = ''; diff --git a/devui/data-table/table/head/th/sort/sort.component.ts b/devui/data-table/table/head/th/sort/sort.component.ts index 7c1466f9..6ea7ed6b 100644 --- a/devui/data-table/table/head/th/sort/sort.component.ts +++ b/devui/data-table/table/head/th/sort/sort.component.ts @@ -18,15 +18,15 @@ export class SortComponent implements OnInit { sort() { switch (this.sortDirection) { - case SortDirection.ASC: - this.sortDirection = SortDirection.DESC; - break; - case 'DESC': - this.sortDirection = SortDirection.default; - break; - case SortDirection.default: - default: - this.sortDirection = SortDirection.ASC; + case SortDirection.ASC: + this.sortDirection = SortDirection.DESC; + break; + case 'DESC': + this.sortDirection = SortDirection.default; + break; + case SortDirection.default: + default: + this.sortDirection = SortDirection.ASC; } this.sortEvent.emit({ direction: this.sortDirection }); } diff --git a/devui/data-table/table/head/th/th.component.ts b/devui/data-table/table/head/th/th.component.ts index 98b68081..1c79f938 100644 --- a/devui/data-table/table/head/th/th.component.ts +++ b/devui/data-table/table/head/th/th.component.ts @@ -1,12 +1,13 @@ import { DOCUMENT } from '@angular/common'; import { - ChangeDetectorRef, Component, ElementRef, EventEmitter, HostBinding, HostListener, Inject, Input, - NgZone, OnChanges, OnDestroy, Output, Renderer2, SimpleChanges, TemplateRef + ChangeDetectorRef, Component, ElementRef, EventEmitter, HostBinding, HostListener, Inject, Input, + NgZone, OnChanges, OnDestroy, Output, Renderer2, SimpleChanges, TemplateRef } from '@angular/core'; import { fromEvent, Observable, Subscription } from 'rxjs'; import { FilterConfig, SortDirection, SortEventArg } from '../../../data-table.model'; @Component({ + /* eslint-disable-next-line @angular-eslint/component-selector*/ selector: '[dHeadCell]', templateUrl: './th.component.html', }) @@ -257,7 +258,7 @@ export class TableThComponent implements OnChanges, OnDestroy { bindMousemove = (e) => { this.move(e); - } + }; move(event: MouseEvent): void { diff --git a/devui/data-table/table/head/thead.component.ts b/devui/data-table/table/head/thead.component.ts index c6a5270e..4df8a05c 100644 --- a/devui/data-table/table/head/thead.component.ts +++ b/devui/data-table/table/head/thead.component.ts @@ -7,6 +7,7 @@ import { TableTrComponent } from '../row/tr.component'; import { TableThComponent } from './th/th.component'; @Component({ + /* eslint-disable-next-line @angular-eslint/component-selector*/ selector: '[dTableHead]', templateUrl: './thead.component.html' }) diff --git a/devui/data-table/table/row/tr.component.ts b/devui/data-table/table/row/tr.component.ts index ffba16cb..f6df0e89 100644 --- a/devui/data-table/table/row/tr.component.ts +++ b/devui/data-table/table/row/tr.component.ts @@ -1,8 +1,9 @@ -import { AfterContentInit, Component, ContentChildren, EventEmitter, Input, OnInit, Output, QueryList} from '@angular/core'; +import { AfterContentInit, Component, ContentChildren, EventEmitter, OnInit, Output, QueryList } from '@angular/core'; import { RowCheckChangeEventArg, TableCheckOptions } from '../../data-table.model'; import { TableThComponent } from '../head/th/th.component'; @Component({ + /* eslint-disable-next-line @angular-eslint/component-selector*/ selector: '[dTableRow]', templateUrl: './tr.component.html', styleUrls: ['./tr.component.scss'] diff --git a/devui/data-table/tmpl/data-table-cell-tmpl.component.ts b/devui/data-table/tmpl/data-table-cell-tmpl.component.ts index 69de5a35..06c057b3 100755 --- a/devui/data-table/tmpl/data-table-cell-tmpl.component.ts +++ b/devui/data-table/tmpl/data-table-cell-tmpl.component.ts @@ -3,13 +3,13 @@ import { DataTableCellEditTmplComponent } from './data-table-cell-edit-tmpl.comp import { DataTableCellViewTmplComponent } from './data-table-cell-view-tmpl.component'; @Component({ - selector: 'd-cell-template', - template: '', - changeDetection: ChangeDetectionStrategy.OnPush + selector: 'd-cell-template', + template: '', + changeDetection: ChangeDetectionStrategy.OnPush }) export class DataTableCellTmplComponent { - @Input() type: string; - @ContentChild(DataTableCellViewTmplComponent) view: DataTableCellViewTmplComponent; - @ContentChild(DataTableCellEditTmplComponent) edit: DataTableCellEditTmplComponent; + @Input() type: string; + @ContentChild(DataTableCellViewTmplComponent) view: DataTableCellViewTmplComponent; + @ContentChild(DataTableCellEditTmplComponent) edit: DataTableCellEditTmplComponent; } diff --git a/devui/data-table/tmpl/data-table-cell-view-tmpl.component.ts b/devui/data-table/tmpl/data-table-cell-view-tmpl.component.ts index d393b7a0..7f1cc8b0 100755 --- a/devui/data-table/tmpl/data-table-cell-view-tmpl.component.ts +++ b/devui/data-table/tmpl/data-table-cell-view-tmpl.component.ts @@ -7,6 +7,6 @@ import { ChangeDetectionStrategy, Component, ContentChild, TemplateRef } from '@ }) export class DataTableCellViewTmplComponent { - @ContentChild(TemplateRef) template: TemplateRef; + @ContentChild(TemplateRef) template: TemplateRef; } diff --git a/devui/data-table/tmpl/data-table-column-tmpl.component.ts b/devui/data-table/tmpl/data-table-column-tmpl.component.ts index 3ab9cadd..f81d1806 100755 --- a/devui/data-table/tmpl/data-table-column-tmpl.component.ts +++ b/devui/data-table/tmpl/data-table-column-tmpl.component.ts @@ -1,6 +1,6 @@ import { - ChangeDetectionStrategy, Component, ContentChild, EventEmitter, Input, OnChanges, - OnDestroy, OnInit, Output, SimpleChanges, TemplateRef + ChangeDetectionStrategy, Component, ContentChild, EventEmitter, Input, OnChanges, + OnDestroy, OnInit, Output, SimpleChanges, TemplateRef } from '@angular/core'; import { Observable } from 'rxjs'; import { FilterConfig } from '../data-table.model'; diff --git a/devui/data-table/utils/utils.ts b/devui/data-table/utils/utils.ts new file mode 100644 index 00000000..eefa58c4 --- /dev/null +++ b/devui/data-table/utils/utils.ts @@ -0,0 +1,135 @@ +export const simDeepClone = obj => { + if (obj === null) { return null; } + if (typeof obj === 'object') { + return JSON.parse(JSON.stringify(obj)); + } else if (typeof obj === 'string') { + try { + return JSON.parse(obj); + } catch (e) { + console.error(e); + } + } else { + return obj; + } +}; + +export const highPerformanceFilter = (arr, func) => { + let res = []; + const arrLength = arr.length; + // 经过调查,在小于10000或大于99999条数据的时候,for循环速度比filter速度会快7至8倍左右 + if (arrLength < 10000 || arrLength > 99999) { + for (let a = 0; a < arrLength; a++) { + if (func(arr[a],a)) { + res.push(arr[a]); + } + } + } else { + res = arr.filter(func); + } + return res; +}; + + +// 生成随机Id +export const generateId = () => { + let timeStamp = new Date().getTime(); + if (window.performance && typeof window.performance.now === "function") { + timeStamp += performance.now(); + } + const id = 'aaaaaaaaaaaaaaabaaaaaaaaaaaaaaa'.replace(/[ab]/g, function (item) { + const res = (timeStamp + Math.random() * 16) % 16 | 0; + timeStamp = Math.floor(timeStamp / 16); + return (item === 'a' ? res : (res & 0x3 | 0x8)).toString(16); + }); + return id; +}; + +export const highPerformanceExpandObjectInArray = (oldObj, attr) => { + oldObj[Symbol.iterator] = function() { + return { + next:function() { + const array = Reflect.ownKeys(oldObj); + if (this.index < array.length-1) { + const key = array[this.index]; + this.index++; + return { value: oldObj[key] }; + } else { + return { done: true }; + } + }, + index:0 + }; + }; + if(attr) { + const newObj=[]; + for(let i=0;i { // 找到节点在总数据中的位置的方法 + return treeTableArray.findIndex((v) => v.node_id === nodeId); +}; + +export class FindChild { // 寻找子节点 + allChildCol: any = []; + + getChildrenOfItem(node, treeTableArray) { // 找到节点下的子节点的方法 + const data: any = highPerformanceFilter(treeTableArray, item => item.parent_node_id === node.node_id); + return data; + } + + getAllChildrenOfItem(node, treeTableArray) { // 找到节点下所有子集的方法 + this.allChildCol = []; + this.getAllChildrenData(node, treeTableArray); + return this.allChildCol; + } + + getAllChildrenData(node, treeTableArray) { + const childData = this.getChildrenOfItem(node, treeTableArray); + const newArray = [...childData]; + newArray.push(node); + this.allChildCol = [...this.allChildCol, ...newArray]; + for(let i=0; i { // 数组去重的方法 + const arr = recordArr.concat(nodeArr); + const result = []; + const obj = {}; + for(const i of arr) { + if(!obj[i.node_id]) { + result.push(i); + obj[i.node_id] = 1; + } + } + return result; +}; + +export const highPerformanceMap = (arr, func) => { + let res = []; + const arrLength = arr.length; + if (arrLength < 10000 || arrLength > 99999) { + for (let a = 0; a < arrLength; a++) { + const rs=func(arr[a],a); + if (rs) { + res.push(rs); + } + } + } else { + res = arr.map(func); + } + return res; +}; diff --git a/devui/data-table/utils/virtualScrollTreeTable.factory.ts b/devui/data-table/utils/virtualScrollTreeTable.factory.ts new file mode 100644 index 00000000..e4873e49 --- /dev/null +++ b/devui/data-table/utils/virtualScrollTreeTable.factory.ts @@ -0,0 +1,720 @@ +import { + distinct, FindChild, generateId, getNodeIndex, highPerformanceExpandObjectInArray, highPerformanceFilter, simDeepClone +} from './utils'; + + +// 删除 +export class VirtualScrollTreeTableDelete { + findChild: any; + + delete(rowItem, treeTableArray, spliceArr) { + this.findChild = new FindChild(); + const allChildCol = this.findChild.getAllChildrenOfItem(rowItem, treeTableArray); + const allChild = distinct(allChildCol, []); + this.deleteChooseData(allChild, treeTableArray); + this.deleteAllRecord(allChild, spliceArr); + return {treeTableArray: treeTableArray, spliceArr: spliceArr}; + } + + deleteChooseData(allChild, treeTableArray) { + for(let i=0; i v.node_id === node_id); + if(pos !== -1) { + treeTableArray.splice(pos, 1); + } + } + } + + deleteAllRecord(allChild, spliceArr) { + spliceArr.expandArr = this.deleteRecordArrData(allChild, spliceArr.expandArr); + spliceArr.toggledArr = this.deleteRecordArrData(allChild, spliceArr.toggledArr); + spliceArr.expandClickArr = this.deleteRecordArrData(allChild, spliceArr.expandClickArr); + spliceArr.toggledClickArr = this.deleteRecordArrData(allChild, spliceArr.toggledClickArr); + spliceArr.searchRes = this.deleteRecordArrData(allChild, spliceArr.searchRes); + spliceArr.searchArr = this.deleteRecordArrData(allChild, spliceArr.searchArr); + } + + deleteRecordArrData(allChild, arr) { + if(arr.length > 0) { + const allChildNodeId = allChild.map(item => item.node_id); + let node_id; + for(let i=0; i -1) { + arr[i].node_id = ""; + } + } + arr = highPerformanceFilter(arr, item => item.node_id !== ""); + } + return arr; + } +} + + +// 新增 +export class VirtualScrollTreeTableAdd { + findChild: any; + + addGolbal(status, treeTableArray, addTemplate?) { + if(addTemplate) { + treeTableArray = this.addData(status, treeTableArray, addTemplate); + } else { + treeTableArray = this.addData(status, treeTableArray); + } + return treeTableArray; + } + + addOperation(rowItem, status, treeTableArray, addTemplate?) { + let dataObj: any; + if(addTemplate) { + dataObj = this.addData(status, treeTableArray, addTemplate); + } else { + dataObj = this.addData(status, treeTableArray); + } + const lastDataObj = this.getoperationAddData(status, rowItem, dataObj); + this.changeOperationAdd(lastDataObj, treeTableArray); + return treeTableArray; + } + + addData(type, treeTableArray, addTemplate?) { + const newType = (type==='node' || type==='addDataNode' || type==='insertDataNode') ? "node" : "folder"; + const properties = this.getAddDataProperties(newType, treeTableArray); + let obj: any = {}; + if(addTemplate) { + obj = {...properties, ...addTemplate}; + } else { + obj = { + "id": properties.id, + "type": properties.type, + "name": properties.name, + "property": "", + "description": "", + "locked": 0, + "create_user": "张三", + "create_time": "2021-08-31T00:00:00.000+00:00", + "update_user": "李四", + "update_time": "2021-08-31T00:00:00.000+00:00", + "node_type": properties.node_type, + "node_id": properties.node_id, + "by_order": properties.by_order, + "category": "Static", + "update_time_string": "2021-08-31 00:00:00", + "create_time_string": "2021-08-31 00:00:00" + }; + } + if(type === 'node' || type === 'folder') { + treeTableArray.push(obj); + return treeTableArray; + } else { + return obj; + } + } + + getAddDataProperties(type, treeTableArray) { + return { + id: generateId(), + node_id: generateId(), + node_type: type === 'node' ? 0 : 1, + type: type === 'node'? 'String' : '', + name: this.getAddName(type, treeTableArray), + by_order: treeTableArray.length + 1 + }; + } + + getAddName(type, treeTableArray) { + let name = ""; + const namePrefix = type === 'node'? 'New_Variable_' : 'New_Folder_'; + const arr = treeTableArray; + const newDataArr = highPerformanceFilter(arr, item => { + if(item.name.includes(namePrefix)) {return item;} + }); + if(newDataArr.length > 0) { + const newDataNumArr = []; + newDataArr.forEach(item => { + newDataNumArr.push(Number(item.name.split('_')[2])); + }); + newDataNumArr.sort((a, b) => { + return a - b; + }); + name = namePrefix + (newDataNumArr[newDataNumArr.length - 1] + 1).toString(); + } else { + name = namePrefix + "1"; + } + return name; + } + + getoperationAddData(type, rowItem, dataObj) { + const parent_node_id = this.getAddParentId(type, rowItem); + if(parent_node_id) { + dataObj.parent_node_id = parent_node_id; + } else { + dataObj.posId = rowItem.node_id; + } + dataObj.by_order = 0; + return dataObj; + } + + getAddParentId(type, rowItem) { + let parent_node_id = ""; + if(type === 'addDataNode' || type === 'addDataFolder') { + parent_node_id = rowItem.node_id; + } else { + if(rowItem.parent_node_id) { + parent_node_id = rowItem.parent_node_id; + } + } + return parent_node_id; + } + + changeOperationAdd(data, treeTableArray) { + const parent_node_id = data.parent_node_id; + let pos; + if(parent_node_id) { + pos = treeTableArray.findIndex((v) => v.node_id === parent_node_id); + } else { + const posId = data.posId; + pos = treeTableArray.findIndex((v) => v.node_id === posId); + } + this.insertData(data, pos, treeTableArray); + } + + insertData(data, pos, treeTableArray) { + if(pos !== -1) { + this.findChild = new FindChild(); + const allChildCol = this.findChild.getAllChildrenOfItem(treeTableArray[pos], treeTableArray); + const childData = distinct(allChildCol, []); + if(childData.length > 0) { + const realPos = pos + childData.length; + if(Array.isArray(data)) { + for(let i=0; i 0) { + copyStatus = 'cut'; + } else { + copyStatus = 'copy'; + } + this.saveCopyNode.push(this.changeCopyNodeName(this.saveCopyClickNode[0], copyStatus)); + this.saveCopyNode = this.saveCopyNode.flat(Infinity); + } + + changeCopyNodeName(rowItem, status) { + const copyRowItem = simDeepClone(rowItem); + if(copyRowItem.node_type) { + let copyRows; + if(this.isAgainCopy) { + copyRows = this.getCopyRows(copyRowItem); + this.saveCopyRowChild = copyRows; + } else { + copyRows = this.saveCopyRowChild; + } + if(status === 'copy') { + const newRows = this.changeCopyDataParent(copyRows); + return newRows; + } else { + copyRows.forEach(arr => { + arr.by_order = 0; + }); + return copyRows; + } + } else { + if(status === 'copy') { + this.changeCopyData(copyRowItem); + } else { + copyRowItem["by_order"] = 0; + } + return copyRowItem; + } + } + + getCopyRows(copyRowItem) { + this.findChild = new FindChild(); + const allChildCol = this.findChild.getAllChildrenOfItem(copyRowItem, this.treeTableArray); + const allChildLen = distinct(allChildCol, []).length; + const slicePos = (this.treeTableArray.findIndex((v) => v.node_id === copyRowItem.node_id)); + const copyRows = simDeepClone(this.treeTableArray.slice(slicePos, slicePos + allChildLen)); + return copyRows; + } + + + changeCopyDataParent(copyRows) { + const newRows = simDeepClone(copyRows); + for(let i=0; i { + if(item.parent_node_id === copyRows[i].node_id) { + newRows[index].parent_node_id = newRows[i].node_id; + } + }); + } + return newRows; + } + + changeCopyData(rowData) { + rowData["id"] = generateId(); + rowData["name"] = this.getCopyName(rowData['name']); + rowData["node_id"] = generateId(); + rowData["by_order"] = 0; + } + + getCopyName(name) { + let newName = name + '_'; + const newDataArr = highPerformanceFilter(this.treeTableArray, item => { + if(item.name.includes(newName)) {return item;} + }); + if(newDataArr.length > 0) { + const newDataNumArr = []; + newDataArr.forEach(arr => { + const numArr = arr.name.split('_'); + let num = Number(numArr[numArr.length - 1]); + if(!num) { + num = 0; + } + newDataNumArr.push(num); + }); + newDataNumArr.sort((a, b) => { + return a - b; + }); + newName = newName + (newDataNumArr[newDataNumArr.length - 1] + 1).toString(); + } else { + newName = newName + '1'; + } + return newName; + } + + pastData(rowItem, status) { + if(this.saveCutNode.length > 0) { + const cutPos = this.treeTableArray.findIndex((v) => v.node_id === this.saveCutNode[0].node_id); + this.findChild = new FindChild(); + const allChildCol = this.findChild.getAllChildrenOfItem(this.treeTableArray[cutPos], this.treeTableArray); + const childData = distinct(allChildCol, []); + for(let i=0; i v.node_id === childData[i].node_id); + if(pos !== -1) { + this.treeTableArray.splice(pos, 1); + } + } + this.spliceArr = this.deleteAllRecord(childData, this.spliceArr); + + this.pastPublicOperation(rowItem, status); + this.saveCopyClickNode = []; + this.copyRowNodeId = ""; + } else { + this.pastPublicOperation(rowItem, status); + } + } + + pastPublicOperation(rowItem, status) { + if(status === 'paste') { + this.pastChangeCopyData(rowItem); + } else { + this.pastToRootChangeCopyData(); + } + } + + pastChangeCopyData(rowItem) { + this.saveCopyNode[0].parent_node_id = rowItem.node_id; + const pos = this.treeTableArray.findIndex((v) => v.node_id === rowItem.node_id); + this.insertData(this.saveCopyNode, pos); + } + + insertData(data, pos) { + if(pos !== -1) { + this.findChild = new FindChild(); + const allChildCol = this.findChild.getAllChildrenOfItem(this.treeTableArray[pos], this.treeTableArray); + const childData = distinct(allChildCol, []); + if(childData.length > 0) { + const realPos = pos + childData.length; + if(Array.isArray(data)) { + for(let i=0; i 0) { + const allChildNodeId = allChild.map(item => item.node_id); + let node_id; + for(let i=0; i -1) { + arr[i].node_id = ""; + } + } + arr = highPerformanceFilter(arr, item => item.node_id !== ""); + } + return arr; + } +} + +// 拖拽 +export class VirtualScrollTreeTableDrop { + findChild: any; + + visibleNodes: any; + itemCount: any; + expandArr: any; + treeTableArray: any; + + onDrop(e: any, visibleNodes, itemCount, treeTableArray, expandArr) { + this.visibleNodes = visibleNodes; + this.itemCount = itemCount; + this.expandArr = expandArr; + this.treeTableArray = treeTableArray; + + const dragFromIndex = e.dragFromIndex; + let dropIndex = e.dropIndex; let realToIndex; + + if(dropIndex < 0) { + dropIndex = 0; + } else if(dropIndex > itemCount) { + dropIndex = itemCount; + } + + if (dropIndex < dragFromIndex) { + dropIndex++; + } + + const realFromIndex = getNodeIndex(e.dragData.node_id, this.treeTableArray); + realToIndex = dropIndex < this.itemCount ? + getNodeIndex(this.visibleNodes[dropIndex].node_id, this.treeTableArray) + : getNodeIndex(this.visibleNodes[dropIndex - 1].node_id, this.treeTableArray); + if (realToIndex > realFromIndex && dropIndex < dragFromIndex) { + realToIndex--; + } + if (realToIndex < realFromIndex && dropIndex > dragFromIndex) { + realToIndex++; + } + const newDropParentNode = this.visibleNodes[dropIndex - 1]; + this.changeNodeInfoByDrop(newDropParentNode, realFromIndex); + + const moveCount = dragFromIndex === dropIndex ? 0 + : !this.visibleNodes[dropIndex] || realToIndex > realFromIndex ? 1 + : getNodeIndex(this.visibleNodes[dropIndex].node_id, this.treeTableArray) + - getNodeIndex(this.visibleNodes[dropIndex - 1].node_id, this.treeTableArray); + const targetIndex = dropIndex < this.itemCount ? realToIndex - moveCount : realToIndex; + this.treeTableArray.splice( + targetIndex, + 0, + realFromIndex === -1 ? e.dragData : this.treeTableArray.splice(realFromIndex, 1)[0] + ); + + return {expandArr: this.expandArr, treeTableArray: this.treeTableArray}; + } + + changeNodeInfoByDrop(newDropParentNode, realFromIndex) { + const findIndex = this.expandArr.findIndex(value => value.node_id === this.treeTableArray[realFromIndex].node_id); + if (!newDropParentNode || !newDropParentNode.parent_node_id) { + this.dropToRoot(findIndex, realFromIndex, newDropParentNode); + } else if (newDropParentNode.parent_node_id) { + this.dropToChild(findIndex, realFromIndex, newDropParentNode); + } + } + + dropToRoot(findIndex, realFromIndex, newDropParentNode) { + if (newDropParentNode?.node_type === 1 && newDropParentNode?.expand) { + this.treeTableArray[realFromIndex].parent_node_id = newDropParentNode.node_id; + findIndex > -1 ? + this.expandArr[findIndex].parent_node_id = newDropParentNode.node_id + : + this.expandArr.push(this.treeTableArray[realFromIndex]); + } else { + if (this.treeTableArray[realFromIndex].parent_node_id) { + delete this.treeTableArray[realFromIndex].parent_node_id; + if (findIndex > -1) { + this.expandArr.splice(findIndex, 1); + } + } + } + } + + dropToChild(findIndex, realFromIndex, newDropParentNode) { + if (newDropParentNode.node_type === 1 && newDropParentNode.expand) { + this.treeTableArray[realFromIndex].parent_node_id = newDropParentNode.node_id; + findIndex > -1 ? + this.expandArr[findIndex].parent_node_id = newDropParentNode.node_id + : + this.expandArr.push(this.treeTableArray[realFromIndex]); + } else { + this.treeTableArray[realFromIndex].parent_node_id = newDropParentNode.parent_node_id; + if (findIndex > -1) { + this.expandArr[findIndex].parent_node_id = newDropParentNode.parent_node_id; + } + } + } +} + +// 搜索 +export class VirtualScrollTreeTableSearch { + beforeSearchTarget: any; + searchRes: Array = []; + searchArr: Array = []; + isSearch = false; + searchKeyArr: Array = []; + parentData: Array = []; + searchAttr: any = {}; + treeTableArray: any; + + search(searchTarget, searchAttr, treeTableArray) { + this.searchAttr = searchAttr; + this.treeTableArray = treeTableArray; + + this.beforeSearchTarget = searchTarget; + this.searchRes = []; + this.searchArr = []; + if (searchTarget) { + this.isSearch = true; + const attr = this.searchAttr.value; + if (this.treeTableArray.length < 100) { + this.getSearchDataLittle(this.treeTableArray, searchTarget, attr); + } else { + this.getSearchData(this.treeTableArray, this.treeTableArray.length, searchTarget, attr); + } + this.searchKeyArr = []; + } else { + this.isSearch = false; + } + + return {beforeSearchTarget: this.beforeSearchTarget, searchRes: this.searchRes, searchArr: this.searchArr, isSearch: this.isSearch}; + } + + getSearchDataLittle(data, searchTarget, attr) { + const lowSearchTarget = searchTarget.toLowerCase(); + if(attr === 'all') { + for(let i=0; i= loopNum) { + i += loopNum; + } else { + i = len; + } + } + } + + sliceToGroupData(data, groupNum, len, num, attr, lowSearchTarget) { + let sliceNum = groupNum; + if (len - num < groupNum) { + sliceNum = 0; + } + const preparationData = this.batchFilterData(data, num, sliceNum, attr, lowSearchTarget); + return preparationData; + } + + batchFilterData(data, num, sliceNum, attr, lowSearchTarget) { + const rtnData = []; + let everySearchData; + if (sliceNum > 0) { + everySearchData = data.slice(num, num + sliceNum); + } else { + everySearchData = data.slice(num); + } + let everySearchDataAttr; + if(attr === 'all') { + everySearchDataAttr = everySearchData.filter( + item => highPerformanceExpandObjectInArray(item, ['name', 'property', 'category', 'description']).join("丅") + ); + } else { + everySearchDataAttr = everySearchData.filter(item => highPerformanceExpandObjectInArray(item, [attr]).join("丅")); + } + const inArr = (JSON.stringify(everySearchDataAttr).toLowerCase()).includes(lowSearchTarget); + rtnData.push(everySearchData, inArr); + return rtnData; + } + + getLastSearchData(lastSearchData, attr, searchTarget, lowSearchTarget) { + let searchRes = []; + if(attr === 'all') { + for (let m = 0; m < lastSearchData.length; m++) { + const searchProper = highPerformanceExpandObjectInArray( + lastSearchData[m], ['name', 'property', 'category', 'description'] + ).join("丅"); + const searchScope = JSON.stringify(searchProper).toLowerCase().includes(lowSearchTarget); + searchRes = this.searchResData(searchTarget, searchScope, lastSearchData[m], searchRes); + } + } else { + for (let m = 0; m < lastSearchData.length; m++) { + const searchProper = highPerformanceExpandObjectInArray(lastSearchData[m], [attr]).join("丅"); + const searchScope = JSON.stringify(searchProper).toLowerCase().includes(lowSearchTarget); + searchRes = this.searchResData(searchTarget, searchScope, lastSearchData[m], searchRes); + } + } + return searchRes; + } + + searchResData(searchTarget, searchScope, data, searchRes?) { + if (searchTarget && searchScope) { + this.getLastSearchParentData(data); + if (this.parentData.length > 0) { + if(searchRes) { + searchRes = [...searchRes, ...this.parentData]; + } else { + this.searchRes = [...this.searchRes, ...this.parentData]; + } + this.parentData = []; + } + if (this.searchKeyArr.indexOf(data.node_id) === -1) { + if(searchRes) { + searchRes.push(data); + } else { + this.searchRes.push(data); + } + this.searchKeyArr.push(data.node_id); + } + } + if(searchRes) { + return searchRes; + } + } + + getLastSearchParentData(data) { + const parent_node_id = data.parent_node_id; + if (parent_node_id) { + const getData = highPerformanceFilter(this.treeTableArray, item => item.node_id === parent_node_id); + if (this.searchKeyArr.indexOf(getData[0].node_id) === -1) { + this.parentData.push(getData[0]); + this.searchKeyArr.push(getData[0].node_id); + } + if (getData[0].parent_node_id) { + this.getLastSearchParentData(getData[0]); + } else { + this.parentData.reverse(); + } + } + } + + calculationDataNum(len) { + const lenStr = len.toString(); + const countNum = lenStr.substr(0, 1); + const remainderNum = lenStr.substr(1, lenStr.length - 1); + let loopNum = '1'; + if (Number(remainderNum) === 0 && Number(countNum) === 1) { + for (let i = 0; i < remainderNum.length - 1; i++) { + loopNum += '0'; + } + } else { + for (let i = 0; i < remainderNum.length; i++) { + loopNum += '0'; + } + } + return Number(loopNum); + } +} diff --git a/devui/data-table/virtualScrollTreeTable.component.html b/devui/data-table/virtualScrollTreeTable.component.html new file mode 100644 index 00000000..c2f2f3cb --- /dev/null +++ b/devui/data-table/virtualScrollTreeTable.component.html @@ -0,0 +1,17 @@ +
+
+ +
+
+ + +
+
diff --git a/devui/data-table/virtualScrollTreeTable.component.scss b/devui/data-table/virtualScrollTreeTable.component.scss new file mode 100644 index 00000000..169fc1b3 --- /dev/null +++ b/devui/data-table/virtualScrollTreeTable.component.scss @@ -0,0 +1,17 @@ +.devui-cdk-scroll-container { + position: relative; + + #data-table-virtual-tree-scroll { + width: calc(100% - 3px); + } + + #data-table-virtual-tree { + position: absolute; + z-index: 1; + left: 0; + top: 0; + right: 5px; + bottom: 0; + width: calc(100% - 8px); + } +} diff --git a/devui/data-table/virtualScrollTreeTable.component.ts b/devui/data-table/virtualScrollTreeTable.component.ts new file mode 100644 index 00000000..f87aef83 --- /dev/null +++ b/devui/data-table/virtualScrollTreeTable.component.ts @@ -0,0 +1,779 @@ +import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling'; +import { + AfterContentInit, ChangeDetectorRef, Component, ContentChildren, + EventEmitter, Input, OnChanges, OnInit, Output, QueryList, ViewChild +} from '@angular/core'; +import { DataTableComponent } from './data-table.component'; +import { DataTableProperiesInterface } from './dataTableProperties.interface'; +import { DataTableColumnTmplComponent } from './tmpl/data-table-column-tmpl.component'; +import { + distinct, FindChild, highPerformanceFilter, highPerformanceMap, simDeepClone +} from './utils/utils'; +import { + VirtualScrollTreeTableAdd, VirtualScrollTreeTableCopy, + VirtualScrollTreeTableDelete, VirtualScrollTreeTableDrop, VirtualScrollTreeTableSearch +} from './utils/virtualScrollTreeTable.factory'; + +export interface TreeNodeInterface { + key: string; + title: string; + level: number; + parentKey?: string; + expand?: boolean; + isLeaf: boolean; + isDelete?: boolean; + isMatch?: boolean; + _children?: string[]; + [prop: string]: any; +} + +@Component({ + selector: 'd-virtual-scroll-tree-table', + templateUrl: './virtualScrollTreeTable.component.html', + styleUrls: ['./virtualScrollTreeTable.component.scss'] +}) +export class VirtualScrollTreeTableComponent implements OnInit, AfterContentInit, OnChanges { + @ContentChildren(DataTableColumnTmplComponent) columns: QueryList; + @ViewChild('dataTable', { static: true }) dataTable: DataTableComponent; + + @Input() dataSource: any; + @Input() editOption: any; + @Input() showRowIndex = 10; + @Input() dataTableProperties: DataTableProperiesInterface; + + @Output() save = new EventEmitter(); + + virtualScrollTreeTableDelete: any; + virtualScrollTreeTableAdd: any; + virtualScrollTreeTableCopy: any; + virtualScrollTreeTableDrop: any; + virtualScrollTreeTableSearch: any; + + findChild: any; + itemSize = 40; + itemCount = 10; + virtualScrollPadding = ''; + + get initData() { + return highPerformanceFilter(this.treeTableArray, item => !item.parent_node_id); + } + get allTableData() { + return highPerformanceFilter(this.treeTableArray, item => item); + } + get copySearchRes() { + return highPerformanceFilter(this.searchRes, item => item); + } + get dataTableEvent() { + return this.dataTable; + } + isOpenAll = false; + treeTableMap: { [key: string]: TreeNodeInterface } = {}; + treeTableArray: TreeNodeInterface[] = []; + visibleNodes: TreeNodeInterface[] = []; + iconParentOpen: string; + iconParentClose: string; + basicDataSource: any = []; + expandArr: Array = []; + expandClickArr: Array = []; + expandItemKeys: Array = []; + toggledArr: Array = []; + toggledClickArr: Array = []; + toggledItemKeys: Array = []; + countNum: any = 0; + totleItem: Number = 0; + scrollArray: Array = []; + @ViewChild(CdkVirtualScrollViewport) viewPort: CdkVirtualScrollViewport; + + isSearch = false; + searchRes: Array = []; + searchAttr: any = { + name: '全部', + value: 'all' + }; + beforeSearchTarget: any; + parentData: Array = []; + searchKeyArr: Array = []; + searchArr: Array = []; + + itemLevel: any = 1; + peersNum = 0; + + allChildCol: Array = []; + + saveCopyClickNode: any = []; + saveCopyNode: any = []; + copyRowNodeId = ''; + saveCutNode: any = []; + saveCopyRowChild: any = []; + + isAgainCopy = false; + + isDragMove = false; + dragLine: any; + dragMouseTipWidth: any; + + constructor(private ref: ChangeDetectorRef) { } + + ngAfterContentInit() { + this.dataTable.columns = this.columns; + this.dataTable.updateColumns(); + setTimeout(() => { + const dataTableHead = this.dataTable.fixHeaderContainerRefElement.nativeElement.clientHeight; + this.virtualScrollPadding = dataTableHead + 'px'; + }); + } + + ngOnChanges(changes): void { + if(this.dataSource) { + new Promise((resolve, reject) => { + try { + this.basicDataSource = this.dataSource; + this.basicDataSource = simDeepClone(this.basicDataSource); + this.treeTableArray = this.basicDataSource; + this.totleItem = this.treeTableArray.length; + this.countNum = this.initData.length; + this.scrollArray = Array.from(this.initData.keys()); + this.itemCount = this.showRowIndex; + resolve(true); + } catch (error) { + reject(error); + } + }).then(() => { + this.visibleNodes = simDeepClone(this.initData.slice(0, this.itemCount)); + this.visibleNodes.forEach(arr => { + arr.expand = false; + }); + this.getVisibleDataOrder(this.visibleNodes); + this.getVisibleDataLevel(this.visibleNodes); + }); + } else { + this.treeTableArray = []; + this.visibleNodes = []; + } + + if ( + (changes['dataTableProperties']) + ) { + const params = changes['dataTableProperties']['currentValue']; + this.copyAttribute(this.dataTable, params); + } + } + + ngOnInit() { + this.virtualScrollTreeTableDelete = new VirtualScrollTreeTableDelete(); + this.virtualScrollTreeTableAdd = new VirtualScrollTreeTableAdd(); + this.virtualScrollTreeTableCopy = new VirtualScrollTreeTableCopy(); + this.virtualScrollTreeTableDrop = new VirtualScrollTreeTableDrop(); + this.virtualScrollTreeTableSearch = new VirtualScrollTreeTableSearch(); + this.findChild = new FindChild(); + } + + copyAttribute(target, updateParams) { + if(!target) {return;} + const updateKeys = Object.keys(updateParams); + if(updateKeys.length) { + updateKeys.forEach(key => { + if(key === 'size') { + if(updateParams[key] === 'md') { + this.itemSize = 48; + } else if(updateParams[key] === 'lg') { + this.itemSize = 56; + } else { + this.itemSize = 40; + } + } + target[key] = updateParams[key]; + }); + } + } + + batchUpdateTable(key, val) { + const saveArr = this.treeTableArray; + if(saveArr.length) { + highPerformanceMap(saveArr, obj => { + obj[key] = val; + }); + } + this.getVisiableNodes(); + } + + updateRowData(id, key, val) { + for (let i = 0; i < this.visibleNodes.length; i++) { + if(this.visibleNodes[i].node_id === id) { + this.visibleNodes[i][key] = val; + } + } + + const pos = this.treeTableArray.findIndex((v) => v.node_id === id); + if(pos !== -1) { + this.treeTableArray[pos][key] = val; + } + } + + removeAll() { + this.expandArr = []; + this.toggledArr = []; + this.expandClickArr = []; + this.toggledClickArr = []; + this.searchRes = []; + this.searchArr = []; + } + + setScrollLength(countNum) { + this.countNum = countNum; + this.scrollArray = Array.from(new Array(this.countNum).keys()); + } + setVisibleNodes(data, flag) { + this.visibleNodes = simDeepClone(data); + for (let i = 0; i < this.visibleNodes.length; i++) { + this.visibleNodes[i].expand = flag; + } + } + getVisiableNodes() { + const scrollOffset = this.viewPort.measureScrollOffset(); + const firstVisibleIndex = Math.ceil(scrollOffset / this.itemSize); + const originalDataLength = this.treeTableArray.length; + if (this.isSearch) { + if (this.searchArr.length > 0) { + this.setScrollLength(this.searchRes.length - this.searchArr.length); + const newSearchRes = this.assemblyToggledData(this.copySearchRes, this.searchArr); + this.setVisibleNodes(newSearchRes.slice(firstVisibleIndex, firstVisibleIndex + this.itemCount), true); + this.singleExpend(this.searchArr, 'search'); + } else { + this.setScrollLength(this.searchRes.length); + this.setVisibleNodes(this.searchRes.slice(firstVisibleIndex, firstVisibleIndex + this.itemCount), true); + } + } else { + if (this.isOpenAll) { + this.expandArr = []; + this.expandClickArr = []; + if (this.toggledClickArr.length > 0) { + const newTreeTableArray = this.assemblyToggledData(this.allTableData, this.toggledArr); + this.setScrollLength(originalDataLength - this.toggledArr.length); + this.setVisibleNodes(newTreeTableArray.slice(firstVisibleIndex, firstVisibleIndex + this.itemCount), true); + this.singleExpend(this.toggledClickArr, 'away'); + } else { + this.setScrollLength(this.treeTableArray.length); + this.setVisibleNodes(this.treeTableArray.slice(firstVisibleIndex, firstVisibleIndex + this.itemCount), true); + } + } else { + this.toggledArr = []; + this.toggledClickArr = []; + if (this.expandClickArr.length > 0) { + const newInitData = this.assemblyExpandData(this.initData, this.expandArr); + this.setScrollLength(this.initData.length + this.expandArr.length); + this.visibleNodes = simDeepClone(newInitData.slice(firstVisibleIndex, firstVisibleIndex + this.itemCount)); + this.singleToggled(); + } else { + this.setScrollLength(this.initData.length); + this.setVisibleNodes(this.initData.slice(firstVisibleIndex, firstVisibleIndex + this.itemCount), false); + } + } + } + + this.getVisibleDataOrder(this.visibleNodes); + this.getVisibleDataLevel(this.visibleNodes); + this.dataTable.cancelEditingStatus(); + } + + getVisibleDataOrder(visibleNodes) { + for (let i = 0; i < visibleNodes.length; i++) { + const index = this.treeTableArray.findIndex((v) => v.node_id === visibleNodes[i].node_id); + visibleNodes[i].by_order = index + 1; + } + } + + getVisibleDataLevel(visibleNodes) { + visibleNodes.forEach(arr => { + this.itemLevel = 1; + if (arr.parent_node_id) { + this.getParentNodeLevel(arr.parent_node_id, 1); + arr.level = this.itemLevel; + } else { + arr.level = 1; + } + }); + } + + getParentNodeLevel(parent_node_id, level) { + this.itemLevel = level + 1; + const data: any = highPerformanceFilter(this.treeTableArray, item => item.node_id === parent_node_id); + if (data.length > 0) { + this.getParentNodeLevel(data[0].parent_node_id, this.itemLevel); + } + } + + singleExpend(recordArr, status) { + const keyArr = []; + for (let i = 0; i < recordArr.length; i++) { + if (status === 'search') { + keyArr.push(recordArr[i].parent_node_id); + } else { + keyArr.push(recordArr[i].node_id); + } + } + for (let i = 0; i < this.visibleNodes.length; i++) { + if (keyArr.includes(this.visibleNodes[i].node_id)) { this.visibleNodes[i].expand = false; } + } + } + + singleToggled() { + const visibleNodesKeys = this.visibleNodes.map(item => item.node_id); + let node_id; + for (let i = 0; i < this.expandClickArr.length; i++) { + node_id = this.expandClickArr[i].node_id; + if (node_id && visibleNodesKeys.indexOf(node_id) > -1) { + this.visibleNodes.filter(o => o.node_id === node_id)[0].expand = true; + } + } + } + + assemblyExpandData(InitData, expandArr) { + const newExpandArr = []; + let parent_node_id; + for (let i = 0; i < expandArr.length; i++) { + parent_node_id = expandArr[i].parent_node_id; + const pos = InitData.findIndex((v) => v.node_id === parent_node_id); + if (pos !== -1) { + this.getPeersDataNum(InitData, pos, parent_node_id); + const realDataPos = this.treeTableArray.findIndex((v) => v.node_id === expandArr[i].node_id); + if (realDataPos !== -1) { + const realExpandData = this.treeTableArray[realDataPos]; + InitData.splice(pos + 1 + this.peersNum, 0, realExpandData); + this.peersNum = 0; + } + } else { + newExpandArr.push(expandArr[i]); + } + } + if (newExpandArr.length > 0) { + this.assemblyExpandData(InitData, newExpandArr); + } else { + return InitData; + } + } + + getPeersDataNum(InitData, pos, parent_node_id) { + const checkDataPos = pos + 1; + if (InitData[checkDataPos]) { + const checkDataParent = InitData[checkDataPos].parent_node_id; + if (checkDataParent === parent_node_id) { + this.peersNum++; + this.getPeersDataNum(InitData, checkDataPos, parent_node_id); + } else { + return; + } + } else { + return; + } + } + + assemblyToggledData(arrayData, toggledArr) { + let node_id; + for (let i = 0; i < toggledArr.length; i++) { + node_id = toggledArr[i].node_id; + const pos = arrayData.findIndex((v) => v.node_id === node_id); + if (pos !== -1) { + arrayData.splice(pos, 1); + } + } + return arrayData; + } + + scroll(e) { + e.preventDefault(); + const event = e; + const wheelDelta = event.wheelDelta; + const step = (wheelDelta === 0 ? 0 : wheelDelta / Math.abs(wheelDelta)) * (-this.itemSize); + document.getElementById('data-table-virtual-tree-scroll').scrollBy(0, step); + } + onBodyScroll() { + this.getVisiableNodes(); + } + toggleAllNodesExpand(e) { + this.isOpenAll = e; + this.getVisiableNodes(); + } + + + toggleNodeExpand(node: TreeNodeInterface, $event: boolean, isRefresh = true): void { + if (this.isSearch) { + this.operationSearchArr(node, $event ? 'add' : 'del'); + } else { + this.isOpenAll ? this.operationToggledArr(node, $event ? 'add' : 'del') : this.operationExpandArr(node, $event ? 'add' : 'del'); + } + isRefresh && this.getVisiableNodes(); + + if (!node.expand && node.node_id === this.visibleNodes[this.visibleNodes.length - 1].node_id) { + this.scrollToLastItem(); + } + } + + scrollToLastItem() { + document.getElementById('data-table-virtual-tree-scroll').scrollBy(0, this.itemSize * (this.itemCount - 1)); + } + + operationSearchArr(node, status) { + if (status === 'add') { + this.publicSingleRecordAdd(node, this.searchArr); + } else { + this.publicSingleRecordDel(node, 'search'); + } + } + + operationExpandArr(node, status) { + if (status === 'add') { + const showNodes = this.findChild.getChildrenOfItem(node, this.treeTableArray); + this.expandArr = distinct(this.expandArr, showNodes); + this.expandClickArr = distinct(this.expandClickArr, [node]); + } else { + const inNodeData = []; + inNodeData.push(node); + this.spliceExpandArrData(inNodeData); + const allChild = this.getAllChildArr(node); + let node_id; + for (let i = 0; i < allChild.length; i++) { + node_id = allChild[i].node_id; + const pos = this.expandClickArr.findIndex((v) => v.node_id === node_id); + if (pos !== -1) { + this.expandClickArr.splice(pos, 1); + } + } + } + } + + spliceExpandArrData(inNodeData) { + let nodeChildData = []; + for (let i = 0; i < inNodeData.length; i++) { + const selectData = this.expandArr.filter(item => { + if (item.parent_node_id === inNodeData[i].node_id) { + return item; + } + }); + nodeChildData = [...nodeChildData, ...selectData]; + } + if (nodeChildData.length > 0) { + for (let i = 0; i < nodeChildData.length; i++) { + const node_id = nodeChildData[i].node_id; + const index = this.expandArr.findIndex((v) => v.node_id === node_id); + this.expandArr.splice(index, 1); + } + this.spliceExpandArrData(nodeChildData); + } else { + return; + } + } + + operationToggledArr(node, status) { + if (status === 'add') { + this.publicSingleRecordAdd(node, this.toggledArr); + for (let i = 0; i < this.toggledClickArr.length; i++) { + if (node.node_id === this.toggledClickArr[i].node_id) { + this.toggledClickArr.splice(i, 1); + } + } + } else { + this.publicSingleRecordDel(node, 'away'); + const allChild = this.getAllChildArr(node); + this.toggledClickArr = distinct(this.toggledClickArr, allChild); + } + } + + getAllChildArr(node) { + const allChildCol = this.findChild.getAllChildrenOfItem(node, this.treeTableArray); + let allChild = distinct(allChildCol, []); + allChild = allChild.filter(item => item.node_type === 1); + return allChild; + } + + publicSingleRecordAdd(node, recordArr) { + const showNodes = this.findChild.getChildrenOfItem(node, this.treeTableArray); + const toggledArrKey = recordArr.map(item => item.node_id); + let node_id; + for (let i = 0; i < showNodes.length; i++) { + node_id = showNodes[i].node_id; + if (node_id && toggledArrKey.indexOf(node_id) > -1) { + const index = recordArr.findIndex((v) => v.node_id === node_id); + recordArr.splice(index, 1); + } + } + } + + publicSingleRecordDel(node, status) { + const inNodeData = []; + inNodeData.push(node); + this.spliceToggledArrData(inNodeData, status); + } + + spliceToggledArrData(inNodeData, status) { + let nodeChild = []; + for (let i = 0; i < inNodeData.length; i++) { + const inNodeDataChild = this.findChild.getChildrenOfItem(inNodeData[i], this.treeTableArray); + if (status === 'away') { + nodeChild = this.toggledArrChange(inNodeDataChild, nodeChild); + } else { + nodeChild = this.searchArrChange(inNodeDataChild, nodeChild); + } + } + + if (nodeChild.length > 0) { + this.spliceToggledArrData(nodeChild, status); + } else { + return; + } + } + + toggledArrChange(inNodeDataChild, nodeChild) { + this.toggledArr = distinct(this.toggledArr, inNodeDataChild); + nodeChild = this.getNodeChild(inNodeDataChild, nodeChild); + return nodeChild; + } + + searchArrChange(inNodeDataChild, nodeChild) { + const searchNode = []; + for (let k = 0; k < inNodeDataChild.length; k++) { + const node_id = inNodeDataChild[k].node_id; + const pos = this.searchRes.findIndex((v) => v.node_id === node_id); + if (pos !== -1) { + searchNode.push(inNodeDataChild[k]); + } + } + this.searchArr = distinct(this.searchArr, searchNode); + nodeChild = this.getNodeChild(searchNode, nodeChild); + return nodeChild; + } + + getNodeChild(childData, nodeChild) { + for (let k = 0; k < childData.length; k++) { + if (childData[k].node_type) { + nodeChild.push(childData[k]); + } + } + return nodeChild; + } + + beforeEditStart = (rowItem, field) => { + return true; + }; + + beforeEditEnd = (rowItem, field) => { + return rowItem && rowItem[field].length >= 3; + }; + + onEditEnd(rowItem, field) { + const cloneRow = simDeepClone(rowItem); + + const editSelectField = []; + Object.keys(this.editOption).forEach(arr => { + editSelectField.push(arr + 'Edit'); + }); + + if (editSelectField.includes(field)) { + this.dataTable.cancelEditingStatus(); + } + + const treeTablePos = this.treeTableArray.findIndex((v) => v.node_id === cloneRow.node_id); + this.treeTableArray.splice(treeTablePos, 1, cloneRow); + } + + searchSelectChange() { + this.search(this.beforeSearchTarget); + } + + search(searchTarget) { + const res = this.virtualScrollTreeTableSearch.search(searchTarget, this.searchAttr, this.treeTableArray); + this.beforeSearchTarget = res.beforeSearchTarget; + this.searchRes = res.searchRes; + this.searchArr = res.searchArr; + this.isSearch = res.isSearch; + this.getVisiableNodes(); + } + + addGolbal(status, addTemplate?) { + event.stopPropagation(); + if(addTemplate) { + this.treeTableArray = this.virtualScrollTreeTableAdd.addGolbal(status, this.treeTableArray, addTemplate); + } else { + this.treeTableArray = this.virtualScrollTreeTableAdd.addGolbal(status, this.treeTableArray); + } + this.getVisiableNodes(); + setTimeout(() => { + this.addAutoScroll(); + }); + } + + addOperation(rowItem, status, addTemplate?) { + if(addTemplate) { + this.treeTableArray = this.virtualScrollTreeTableAdd.addOperation(rowItem, status, this.treeTableArray, addTemplate); + } else { + this.treeTableArray = this.virtualScrollTreeTableAdd.addOperation(rowItem, status, this.treeTableArray); + } + this.getVisiableNodes(); + + if (!this.isOpenAll) { + const changeStatus = (status === 'addDataFolder' || status === 'addDataNode') ? 'add' : 'insert'; + this.againExpandNode(changeStatus, rowItem); + } + } + + againExpandNode(changeStatus, rowItem) { + let recordExpNode = []; + if (changeStatus === 'add') { + recordExpNode = this.recordExpandChild(rowItem); + this.changeSingleExpand(rowItem); + } else { + const parent_node_id = rowItem.parent_node_id; + if (parent_node_id) { + const pos = this.treeTableArray.findIndex((v) => v.node_id === parent_node_id); + recordExpNode = this.recordExpandChild(this.treeTableArray[pos]); + this.changeSingleExpand(this.treeTableArray[pos]); + } + } + + for (let i = 0; i < recordExpNode.length; i++) { + this.toggleNodeExpand(recordExpNode[i], true); + } + } + + changeSingleExpand(row) { + this.toggleNodeExpand(row, false); + this.toggleNodeExpand(row, true); + } + + recordExpandChild(row) { + const recordExpNode = []; + const allChildCol = this.findChild.getAllChildrenOfItem(row, this.treeTableArray); + const allChild = highPerformanceFilter(distinct(allChildCol, []), item => (item.node_id !== row.node_id && item.node_type)); + const allChildNodeId = allChild.map(item => item.node_id); + for (let i = 0; i < this.expandClickArr.length; i++) { + const node_id = this.expandClickArr[i].node_id; + if (node_id && allChildNodeId.indexOf(node_id) > -1) { + recordExpNode.push(this.expandClickArr[i]); + } + } + return recordExpNode; + } + + addAutoScroll() { + document.getElementById('data-table-virtual-tree-scroll').scrollTo(0, (this.itemSize * this.scrollArray.length)); + } + + copyAndCut(rowItem, status) { + this.saveCopyClickNode = []; + this.saveCutNode = []; + const res = this.virtualScrollTreeTableCopy.copyAndCut(rowItem, status); + this.saveCopyClickNode = res.saveCopyClickNode; + this.saveCutNode = res.saveCutNode; + this.copyRowNodeId = res.copyRowNodeId; + } + + paste(rowItem, status) { + const spliceArr = { + expandArr: this.expandArr, + toggledArr: this.toggledArr, + expandClickArr: this.expandClickArr, + toggledClickArr: this.toggledClickArr, + searchRes: this.searchRes, + searchArr: this.searchArr + }; + + const res = this.virtualScrollTreeTableCopy.paste(rowItem, status, this.treeTableArray, spliceArr); + this.saveCopyClickNode = res.saveCopyClickNode; + this.copyRowNodeId = res.copyRowNodeId; + this.treeTableArray = res.treeTableArray; + + if (this.saveCutNode.length > 0) { + this.expandArr = res.spliceArr.expandArr; + this.toggledArr = res.spliceArr.toggledArr; + this.expandClickArr = res.spliceArr.expandClickArr; + this.toggledClickArr = res.spliceArr.toggledClickArr; + this.searchRes = res.spliceArr.searchRes; + this.searchArr = res.spliceArr.searchArr; + } + + this.getVisiableNodes(); + if (status === 'paste') { + this.changeSingleExpand(rowItem); + } else { + setTimeout(() => { + this.addAutoScroll(); + }); + } + } + + delete(rowItem) { + const spliceArr = { + expandArr: this.expandArr, + toggledArr: this.toggledArr, + expandClickArr: this.expandClickArr, + toggledClickArr: this.toggledClickArr, + searchRes: this.searchRes, + searchArr: this.searchArr + }; + const res = this.virtualScrollTreeTableDelete.delete(rowItem, this.treeTableArray, spliceArr); + this.treeTableArray = res.treeTableArray; + this.expandArr = res.spliceArr.expandArr; + this.toggledArr = res.spliceArr.toggledArr; + this.expandClickArr = res.spliceArr.expandClickArr; + this.toggledClickArr = res.spliceArr.toggledClickArr; + this.searchRes = res.spliceArr.searchRes; + this.searchArr = res.spliceArr.searchArr; + this.getVisiableNodes(); + } + + onDragOver(e: any) { + const scrollBoxY = document.getElementById('data-table-virtual-tree-scroll').getBoundingClientRect().y; + if (scrollBoxY - e.y > 0) { + document.getElementById('data-table-virtual-tree-scroll').scrollBy(0, -this.itemSize); + } + if (e.y - scrollBoxY > this.itemSize * (this.itemCount - 1) - 10) { + document.getElementById('data-table-virtual-tree-scroll').scrollBy(0, this.itemSize); + } + } + + onDrop(e: any) { + const res = this.virtualScrollTreeTableDrop.onDrop(e, this.visibleNodes, this.itemCount, this.treeTableArray, this.expandArr); + this.expandArr = res.expandArr; + this.treeTableArray = res.treeTableArray; + + const newDropParentNode = this.visibleNodes[e.dropIndex - 1]; + if (!newDropParentNode || !newDropParentNode.parent_node_id) { + if (newDropParentNode ?.node_type === 1 && newDropParentNode ?.expand) { + this.dropUpdateExpandFolder(newDropParentNode, true); + } else { + this.getVisiableNodes(); + } + } else if (newDropParentNode.parent_node_id) { + if (newDropParentNode.node_type === 1 && newDropParentNode.expand) { + this.dropUpdateExpandFolder(newDropParentNode, true); + } else { + this.dropUpdateExpandFolder(newDropParentNode, false); + } + } + } + + dropUpdateExpandFolder(newDropParentNode, isParent) { + setTimeout(() => { + let recordExpNode = []; + if (!isParent) { + const parent_node_id = newDropParentNode.parent_node_id; + if (parent_node_id) { + const pos = this.treeTableArray.findIndex((v) => v.node_id === parent_node_id); + recordExpNode = this.recordExpandChild(this.treeTableArray[pos]); + this.changeSingleExpand(this.treeTableArray[pos]); + } + } else { + recordExpNode = this.recordExpandChild(newDropParentNode); + this.changeSingleExpand(newDropParentNode); + } + + for (let i = 0; i < recordExpNode.length; i++) { + this.toggleNodeExpand(recordExpNode[i], true); + } + }); + } + + saveBtn() { + this.save.emit(this.treeTableArray); + } +} diff --git a/devui/datepicker-pro/datepicker-panel.component.scss b/devui/datepicker-pro/datepicker-panel.component.scss index 1a935b9d..6196b737 100644 --- a/devui/datepicker-pro/datepicker-panel.component.scss +++ b/devui/datepicker-pro/datepicker-panel.component.scss @@ -10,6 +10,10 @@ border-left: 1px solid $devui-dividing-line; } +.devui-datepicker-pro-panel { + width: max-content; +} + :host { font-size: 0; } diff --git a/devui/datepicker-pro/datepicker-pro-calendar.component.ts b/devui/datepicker-pro/datepicker-pro-calendar.component.ts index 8894a5c0..bd11c91f 100644 --- a/devui/datepicker-pro/datepicker-pro-calendar.component.ts +++ b/devui/datepicker-pro/datepicker-pro-calendar.component.ts @@ -123,7 +123,9 @@ export class DatepickerProCalendarComponent implements OnInit, AfterViewInit, On } clear(event?: MouseEvent) { - event?.stopPropagation(); + if (event) { + event.stopPropagation(); + } this.pickerSrv.updateDateValue.next({ type: this.isRangeType ? 'range' : 'single', value: this.isRangeType ? [] : null @@ -223,11 +225,15 @@ export class DatepickerProCalendarComponent implements OnInit, AfterViewInit, On this.pickerSrv.activeInputChange.next(type); if (type === 'start') { setTimeout(() => { - this.datepickerInputStart?.nativeElement?.focus(); + if (this.datepickerInputStart?.nativeElement) { + this.datepickerInputStart.nativeElement.focus(); + } }); } else { setTimeout(() => { - this.datepickerInputEnd?.nativeElement?.focus(); + if (this.datepickerInputEnd?.nativeElement) { + this.datepickerInputEnd.nativeElement.focus(); + } }); } } diff --git a/devui/datepicker-pro/datepicker-pro.component.html b/devui/datepicker-pro/datepicker-pro.component.html index 0f7eb6f6..3db7959e 100644 --- a/devui/datepicker-pro/datepicker-pro.component.html +++ b/devui/datepicker-pro/datepicker-pro.component.html @@ -1,5 +1,6 @@
- -
- - - - - - - - -
-
- - - - - - - -
-
-
-
+ + +
+
+ +
+ +
+ + +
+
+
+ + +
+ + + + + + + + +
+
+ + + + + + + +
+
+
+
diff --git a/devui/datepicker-pro/datepicker-pro.component.ts b/devui/datepicker-pro/datepicker-pro.component.ts index 15c53ebb..cc165796 100644 --- a/devui/datepicker-pro/datepicker-pro.component.ts +++ b/devui/datepicker-pro/datepicker-pro.component.ts @@ -42,6 +42,7 @@ export class DatepickerProComponent implements OnInit, AfterViewInit, OnDestroy, @Input() format: string; @Input() cssClass: string; @Input() showAnimation = true; + @Input() appendToBody = true; @Input() width: string; @Output() dropdownToggle = new EventEmitter(); @Output() confirmEvent = new EventEmitter(); @@ -131,7 +132,7 @@ export class DatepickerProComponent implements OnInit, AfterViewInit, OnDestroy, takeUntil(this.unsubscribe$) ).subscribe(time => { if (this.dateValue) { - const curTime = this.datepickerConvert.parse(this.dateValue).setHours(time.hour, time.min, time.seconds); + const curTime = this.datepickerConvert.parse(this.dateValue, this.curFormat).setHours(time.hour, time.min, time.seconds); const curDate = new Date(curTime); this.pickerSrv.curDate = curDate; this.dateValue = this.formatDateToString(curDate); @@ -224,7 +225,10 @@ export class DatepickerProComponent implements OnInit, AfterViewInit, OnDestroy, } clear(event?: MouseEvent) { - event?.stopPropagation(); + if (event) { + event.stopPropagation(); + } + if (this.disabled) { return; } @@ -261,7 +265,7 @@ export class DatepickerProComponent implements OnInit, AfterViewInit, OnDestroy, this.isOpen = true; setTimeout(() => { - this.datepickerInput?.nativeElement?.focus(); + if (this.datepickerInput?.nativeElement) { this.datepickerInput.nativeElement.focus(); } }); } diff --git a/devui/datepicker-pro/datepicker-pro.service.ts b/devui/datepicker-pro/datepicker-pro.service.ts index 16631ab3..4a29debc 100644 --- a/devui/datepicker-pro/datepicker-pro.service.ts +++ b/devui/datepicker-pro/datepicker-pro.service.ts @@ -13,22 +13,20 @@ export class DatepickerProService implements OnDestroy { calendarRange = [1970, 2099]; currentActiveInput: 'start' | 'end' = 'start'; _minDate: Date = new Date(this.calendarRange[0], 0, 1); - _maxDate: Date = new Date(this.calendarRange[1], 11, 31); - document: Document; - set minDate(value: Date) { this._minDate = new Date(value) || new Date(this.calendarRange[0], 0, 1); } - set maxDate(value: Date) { - this._maxDate = new Date(value) || new Date(this.calendarRange[1], 11, 31); - } - get minDate(): Date { return this._minDate; } + _maxDate: Date = new Date(this.calendarRange[1], 11, 31); + set maxDate(value: Date) { + this._maxDate = new Date(value) || new Date(this.calendarRange[1], 11, 31); + } get maxDate(): Date { return this._maxDate; } + document: Document; get closeAfterSelected(): boolean { return !this.isRange && !this.showTime; } @@ -66,13 +64,13 @@ export class DatepickerProService implements OnDestroy { value: Date | Date[]; }>(); readonly selectedTimeChange = new Subject<{ - activeInput?: 'start' | 'end', + activeInput?: 'start' | 'end'; hour: number; min: number; seconds: number; }>(); readonly updateTimeChange = new Subject<{ - activeInput?: 'start' | 'end', + activeInput?: 'start' | 'end'; hour: number; min: number; seconds: number; diff --git a/devui/datepicker-pro/demo/basic/basic-datepicker-pro.component.html b/devui/datepicker-pro/demo/basic/basic-datepicker-pro.component.html index 23195c0c..0cd15ad6 100644 --- a/devui/datepicker-pro/demo/basic/basic-datepicker-pro.component.html +++ b/devui/datepicker-pro/demo/basic/basic-datepicker-pro.component.html @@ -1,4 +1,4 @@ - +
format
diff --git a/devui/datepicker-pro/demo/basic/basic-datepicker-pro.component.ts b/devui/datepicker-pro/demo/basic/basic-datepicker-pro.component.ts index 90fcd534..b9f57efa 100644 --- a/devui/datepicker-pro/demo/basic/basic-datepicker-pro.component.ts +++ b/devui/datepicker-pro/demo/basic/basic-datepicker-pro.component.ts @@ -3,8 +3,8 @@ import { } from '@angular/core'; @Component({ -selector: 'd-basic-datepicker-pro', -templateUrl: './basic-datepicker-pro.component.html', + selector: 'd-basic-datepicker-pro', + templateUrl: './basic-datepicker-pro.component.html', }) export class BasicDatepickerProComponent { value1; diff --git a/devui/datepicker-pro/demo/datepicker-pro-demo.component.ts b/devui/datepicker-pro/demo/datepicker-pro-demo.component.ts index 5f9fad09..3e9c8b82 100644 --- a/devui/datepicker-pro/demo/datepicker-pro-demo.component.ts +++ b/devui/datepicker-pro/demo/datepicker-pro-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox/devui-source-data'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'd-datepicker-pro-demo', @@ -61,7 +61,7 @@ export class DatepickerProDemoComponent implements OnInit, OnDestroy { { title: 'TS', language: 'typescript', code: require('./tab-type/datepicker-pro-tab-type.component.ts?raw') }, { title: 'SCSS', language: 'css', code: require('./tab-type/datepicker-pro-tab-type.component.scss?raw') }, ]; - navItems = []; + navItems = []; subs: Subscription = new Subscription(); constructor(private translate: TranslateService) {} diff --git a/devui/datepicker-pro/demo/datepicker-pro-demo.module.ts b/devui/datepicker-pro/demo/datepicker-pro-demo.module.ts index b7afd0e8..ee02b5f3 100644 --- a/devui/datepicker-pro/demo/datepicker-pro-demo.module.ts +++ b/devui/datepicker-pro/demo/datepicker-pro-demo.module.ts @@ -71,6 +71,6 @@ import { DatepickerProTemplateComponent } from './template/datepicker-template.c DatepickerProTabTypeComponent ], providers: [], - + }) export class DatepickerProDemoModule {} diff --git a/devui/datepicker-pro/demo/host-template/datepicker-host-template.component.ts b/devui/datepicker-pro/demo/host-template/datepicker-host-template.component.ts index fe2f25b9..e4c74200 100644 --- a/devui/datepicker-pro/demo/host-template/datepicker-host-template.component.ts +++ b/devui/datepicker-pro/demo/host-template/datepicker-host-template.component.ts @@ -4,8 +4,8 @@ import { import { DatepickerProComponent, RangeDatepickerProComponent } from 'ng-devui/datepicker-pro'; @Component({ -selector: 'd-datepicker-pro-host', -templateUrl: './datepicker-host-template.component.html', + selector: 'd-datepicker-pro-host', + templateUrl: './datepicker-host-template.component.html', }) export class DatepickerProHostComponent { @ViewChild(RangeDatepickerProComponent) rangePicker: RangeDatepickerProComponent; diff --git a/devui/datepicker-pro/demo/month-year-picker/month-year-picker.component.ts b/devui/datepicker-pro/demo/month-year-picker/month-year-picker.component.ts index e93a3e06..078a2051 100644 --- a/devui/datepicker-pro/demo/month-year-picker/month-year-picker.component.ts +++ b/devui/datepicker-pro/demo/month-year-picker/month-year-picker.component.ts @@ -3,8 +3,8 @@ import { } from '@angular/core'; @Component({ -selector: 'd-month-year-datepicker-pro', -templateUrl: './month-year-picker.component.html', + selector: 'd-month-year-datepicker-pro', + templateUrl: './month-year-picker.component.html', }) export class MonthYearDatepickerProComponent { value1 = new Date(); diff --git a/devui/datepicker-pro/demo/range-type/range-type-picker.component.html b/devui/datepicker-pro/demo/range-type/range-type-picker.component.html index f0769c14..8591f7f3 100644 --- a/devui/datepicker-pro/demo/range-type/range-type-picker.component.html +++ b/devui/datepicker-pro/demo/range-type/range-type-picker.component.html @@ -4,7 +4,12 @@
basic range picker
time range picker
- +
week range picker
diff --git a/devui/datepicker-pro/demo/range-type/range-type-picker.component.ts b/devui/datepicker-pro/demo/range-type/range-type-picker.component.ts index e6079349..193cb2dd 100644 --- a/devui/datepicker-pro/demo/range-type/range-type-picker.component.ts +++ b/devui/datepicker-pro/demo/range-type/range-type-picker.component.ts @@ -3,8 +3,8 @@ import { } from '@angular/core'; @Component({ -selector: 'd-range-type-picker', -templateUrl: './range-type-picker.component.html', + selector: 'd-range-type-picker', + templateUrl: './range-type-picker.component.html', }) export class RangeTypepickerProComponent { value1 = [new Date('2020/03/01'), new Date('2020/04/20')]; diff --git a/devui/datepicker-pro/demo/show-time/show-time-picker.component.html b/devui/datepicker-pro/demo/show-time/show-time-picker.component.html index c5cebc55..12cfa6cf 100644 --- a/devui/datepicker-pro/demo/show-time/show-time-picker.component.html +++ b/devui/datepicker-pro/demo/show-time/show-time-picker.component.html @@ -1,2 +1,9 @@ - + diff --git a/devui/datepicker-pro/demo/show-time/show-time-picker.component.ts b/devui/datepicker-pro/demo/show-time/show-time-picker.component.ts index 4b1cafe5..c159fcb2 100644 --- a/devui/datepicker-pro/demo/show-time/show-time-picker.component.ts +++ b/devui/datepicker-pro/demo/show-time/show-time-picker.component.ts @@ -3,8 +3,8 @@ import { } from '@angular/core'; @Component({ -selector: 'd-show-time-datepicker-pro', -templateUrl: './show-time-picker.component.html', + selector: 'd-show-time-datepicker-pro', + templateUrl: './show-time-picker.component.html', }) export class ShowTimeDatepickerProComponent { value = new Date(); diff --git a/devui/datepicker-pro/demo/tab-type/datepicker-pro-tab-type.component.ts b/devui/datepicker-pro/demo/tab-type/datepicker-pro-tab-type.component.ts index 824fd2a4..5280a7e4 100644 --- a/devui/datepicker-pro/demo/tab-type/datepicker-pro-tab-type.component.ts +++ b/devui/datepicker-pro/demo/tab-type/datepicker-pro-tab-type.component.ts @@ -91,13 +91,13 @@ export class DatepickerProTabTypeComponent implements OnInit { onToggle(isOpen) { this.isOpen = isOpen; - if (isOpen) { - this.calendarCmp?.updateCurPosition(); + if (isOpen && this.calendarCmp) { + this.calendarCmp.updateCurPosition(); } } getTimeStr(date: Date) { - // tslint:disable-next-line - return `${date.toLocaleDateString()} ${padStart(date.getHours() + '', 2, '0')}:${padStart(date.getMinutes() + '', 2, '0')}:${padStart(date.getSeconds() + '', 2, '0')}`; + /* eslint-disable-next-line max-len*/ + return `${date.toLocaleDateString()} ${padStart(String(date.getHours()), 2, '0')}:${padStart(String(date.getMinutes()), 2, '0')}:${padStart(String(date.getSeconds()), 2, '0')}`; } } diff --git a/devui/datepicker-pro/demo/template/datepicker-template.component.ts b/devui/datepicker-pro/demo/template/datepicker-template.component.ts index a6f734a1..2f67c0ef 100644 --- a/devui/datepicker-pro/demo/template/datepicker-template.component.ts +++ b/devui/datepicker-pro/demo/template/datepicker-template.component.ts @@ -4,9 +4,9 @@ import { import { DatepickerProComponent } from 'ng-devui/datepicker-pro'; @Component({ -selector: 'd-datepicker-pro-template', -styleUrls: ['./datepicker-template.component.scss'], -templateUrl: './datepicker-template.component.html', + selector: 'd-datepicker-pro-template', + styleUrls: ['./datepicker-template.component.scss'], + templateUrl: './datepicker-template.component.html', }) export class DatepickerProTemplateComponent { @ViewChild('datepicker') datepickerPro: DatepickerProComponent; diff --git a/devui/datepicker-pro/lib/timepicker-panel.component.ts b/devui/datepicker-pro/lib/timepicker-panel.component.ts index 6c5e684b..091f561f 100644 --- a/devui/datepicker-pro/lib/timepicker-panel.component.ts +++ b/devui/datepicker-pro/lib/timepicker-panel.component.ts @@ -115,41 +115,41 @@ export class TimepickerPanelComponent implements OnInit, OnDestroy { chooseTime(type: string, index: number, handle = false, justScroll = false) { switch (type) { - case 'hour': - this.hourIndex = index; - this.firstList = new Array(24).fill(1).map((t, i) => { - return { - time: i < 10 ? `0${i}` : i + '', - type: 'hour', - active: this.hourIndex === i, - disabled: false - }; - }); - this.setAllScroll(index, this.pickSrv.curMin, this.pickSrv.curSec, justScroll); - break; - case 'min': - this.minIndex = index; - this.secondList = new Array(60).fill(1).map((t, i) => { - return { - time: i < 10 ? `0${i}` : i + '', - type: 'min', - active: this.minIndex === i, - disabled: false - }; - }); - this.setAllScroll(this.pickSrv.curHour, index, this.pickSrv.curSec, justScroll); - break; - case 'sec': - this.secIndex = index; - this.thirdList = new Array(60).fill(1).map((t, i) => { - return { - time: i < 10 ? `0${i}` : i + '', - type: 'sec', - active: this.secIndex === i, - disabled: false - }; - }); - this.setAllScroll(this.pickSrv.curHour, this.pickSrv.curMin, index, justScroll); + case 'hour': + this.hourIndex = index; + this.firstList = new Array(24).fill(1).map((t, i) => { + return { + time: i < 10 ? `0${i}` : String(i), + type: 'hour', + active: this.hourIndex === i, + disabled: false + }; + }); + this.setAllScroll(index, this.pickSrv.curMin, this.pickSrv.curSec, justScroll); + break; + case 'min': + this.minIndex = index; + this.secondList = new Array(60).fill(1).map((t, i) => { + return { + time: i < 10 ? `0${i}` : String(i), + type: 'min', + active: this.minIndex === i, + disabled: false + }; + }); + this.setAllScroll(this.pickSrv.curHour, index, this.pickSrv.curSec, justScroll); + break; + case 'sec': + this.secIndex = index; + this.thirdList = new Array(60).fill(1).map((t, i) => { + return { + time: i < 10 ? `0${i}` : String(i), + type: 'sec', + active: this.secIndex === i, + disabled: false + }; + }); + this.setAllScroll(this.pickSrv.curHour, this.pickSrv.curMin, index, justScroll); } if (handle) { diff --git a/devui/datepicker-pro/range-datepicker-pro.component.html b/devui/datepicker-pro/range-datepicker-pro.component.html index a00bb0fe..6f09fef3 100644 --- a/devui/datepicker-pro/range-datepicker-pro.component.html +++ b/devui/datepicker-pro/range-datepicker-pro.component.html @@ -1,5 +1,6 @@
- -
- - - - - - - - - {{ splitter }} - -
-
-
- - - - - - - -
-
-
-
+ + +
+
+ +
+ +
+ + +
+
+
+ + +
+ + + + + + + + + {{ splitter }} + +
+
+
+ + + + + + + +
+
+
+
diff --git a/devui/datepicker-pro/range-datepicker-pro.component.ts b/devui/datepicker-pro/range-datepicker-pro.component.ts index b7eb42bb..4b7a6fb4 100644 --- a/devui/datepicker-pro/range-datepicker-pro.component.ts +++ b/devui/datepicker-pro/range-datepicker-pro.component.ts @@ -46,6 +46,7 @@ export class RangeDatepickerProComponent implements OnInit, OnDestroy, AfterView @Input() splitter = '-'; @Input() width: string; @Input() startIndexOfWeek = 0; + @Input() appendToBody = true; @Input() set calenderRange (value) { this.pickerSrv.calendarRange = value || [1970, 2099]; } @@ -295,34 +296,38 @@ export class RangeDatepickerProComponent implements OnInit, OnDestroy, AfterView } } - } + }; inputBlurCallback = (type) => { const targetValue = type === 'start' ? this.dateValue[0] : this.dateValue[1]; if (!this.validateDate(targetValue)) { if (type === 'start') { this.dateValue[0] = this.pickerSrv.curRangeDate[0] ? - this.datepickerConvert.format(this.pickerSrv.curRangeDate[0], this.curFormat, this.locale || this.i18nLocale) : - ''; + this.datepickerConvert.format(this.pickerSrv.curRangeDate[0], this.curFormat, this.locale || this.i18nLocale) : + ''; } else { this.dateValue[1] = this.pickerSrv.curRangeDate[1] ? - this.datepickerConvert.format(this.pickerSrv.curRangeDate[1], this.curFormat, this.locale || this.i18nLocale) : - ''; + this.datepickerConvert.format(this.pickerSrv.curRangeDate[1], this.curFormat, this.locale || this.i18nLocale) : + ''; } } this.getStrWidth(); - } + }; public focusChange(type: 'start' | 'end') { this.currentActiveInput = type; this.pickerSrv.activeInputChange.next(type); if (type === 'start') { setTimeout(() => { - this.datepickerInputStart?.nativeElement?.focus(); + if (this.datepickerInputStart?.nativeElement) { + this.datepickerInputStart.nativeElement.focus(); + } }); } else { setTimeout(() => { - this.datepickerInputEnd?.nativeElement?.focus(); + if (this.datepickerInputEnd?.nativeElement) { + this.datepickerInputEnd.nativeElement.focus(); + } }); } } @@ -358,7 +363,9 @@ export class RangeDatepickerProComponent implements OnInit, OnDestroy, AfterView } clear(event?: MouseEvent) { - event?.stopPropagation(); + if (event) { + event.stopPropagation(); + } if (this.disabled) { return; } diff --git a/devui/datepicker/date-range-picker.component.ts b/devui/datepicker/date-range-picker.component.ts index 1df71ba7..9d1a755f 100644 --- a/devui/datepicker/date-range-picker.component.ts +++ b/devui/datepicker/date-range-picker.component.ts @@ -38,6 +38,7 @@ export class DateRangePickerComponent implements OnChanges, OnInit, ControlValue @Input() disabled: boolean; @Input() dateConverter: DateConverter; @Input() selectedRange = [null, null]; + @Input() dateFormat: string; @Input() customViewTemplate: TemplateRef; @Output() selectedRangeChange = new EventEmitter(); @Output() hide = new EventEmitter(); @@ -79,7 +80,7 @@ export class DateRangePickerComponent implements OnChanges, OnInit, ControlValue } @Input() set maxDate(date: Date | any) { - const parseDate = this.dateConverter.parse(date) || null; + const parseDate = this.dateConverter.parse(date, this.dateFormat) || null; if (parseDate) { this._maxDate = parseDate; } @@ -90,7 +91,7 @@ export class DateRangePickerComponent implements OnChanges, OnInit, ControlValue } @Input() set minDate(date: Date | any) { - const parseDate = this.dateConverter.parse(date) || null; + const parseDate = this.dateConverter.parse(date, this.dateFormat) || null; if (parseDate) { this._minDate = parseDate; } @@ -164,7 +165,7 @@ export class DateRangePickerComponent implements OnChanges, OnInit, ControlValue const currentReason = typeof reason === 'number' ? reason : SelectDateRangeChangeReason.custom; this.writeValue(range); this.notifyValueChange(range, currentReason); - } + }; selectingDate(event) { this.hoverOnDate.next(event); @@ -189,12 +190,12 @@ export class DateRangePickerComponent implements OnChanges, OnInit, ControlValue syncPickerPair(currentCalender: object, orientation: string) { switch (orientation) { - case 'left': - this.currentCalendars[0] = currentCalender; - break; - case 'right': - this.currentCalendars[1] = currentCalender; - break; + case 'left': + this.currentCalendars[0] = currentCalender; + break; + case 'right': + this.currentCalendars[1] = currentCalender; + break; } } @@ -232,6 +233,6 @@ export class DateRangePickerComponent implements OnChanges, OnInit, ControlValue clearAll = (reason?: SelectDateRangeChangeReason) => { const currentReason = typeof reason === 'number' ? reason : SelectDateRangeChangeReason.custom; this.chooseDate([null, null], currentReason); - } + }; } diff --git a/devui/datepicker/date-range-picker.directive.html b/devui/datepicker/date-range-picker.directive.html index de3fbbd6..40cda442 100644 --- a/devui/datepicker/date-range-picker.directive.html +++ b/devui/datepicker/date-range-picker.directive.html @@ -15,6 +15,7 @@ [customViewTemplate]="customViewTemplate" [minDate]="minDate" [maxDate]="maxDate" + [dateFormat]="dateFormat" [showTime]="showTime" [selectedRange]="selectedRange" (selectedRangeChange)="notifyValueChange($event)" diff --git a/devui/datepicker/date-range-picker.directive.ts b/devui/datepicker/date-range-picker.directive.ts index e37d4c66..7fb2aaf6 100644 --- a/devui/datepicker/date-range-picker.directive.ts +++ b/devui/datepicker/date-range-picker.directive.ts @@ -35,6 +35,7 @@ import { SelectDateRangeChangeEventArgs, SelectDateRangeChangeReason } from './d import { DateRangePickerComponent } from './date-range-picker.component'; @Component({ + /* eslint-disable-next-line @angular-eslint/component-selector*/ selector: '[dDateRangePicker]', providers: [{ provide: NG_VALUE_ACCESSOR, @@ -261,7 +262,7 @@ export class DateRangePickerDirective implements OnInit, ControlValueAccessor, O }); } if (!this.showTime && this.hideOnRangeSelected && hide) { this.hide(); } - } + }; updateCdkConnectedOverlayOrigin() { if (this.elementRef.nativeElement) { @@ -312,16 +313,16 @@ export class DateRangePickerDirective implements OnInit, ControlValueAccessor, O this.isOpen = false; } this.cdr.markForCheck(); - } + }; onPositionChange(position: ConnectedOverlayPositionChange) { switch (position.connectionPair.overlayY) { - case 'top': - case 'center': - this.datepickerPosition = 'bottom'; - break; - case 'bottom': - this.datepickerPosition = 'top'; + case 'top': + case 'center': + this.datepickerPosition = 'bottom'; + break; + case 'bottom': + this.datepickerPosition = 'top'; } } @@ -419,13 +420,15 @@ export class DateRangePickerDirective implements OnInit, ControlValueAccessor, O if (this.i18nSubscription) { this.i18nSubscription.unsubscribe(); } - this.valueChangeSubscrip?.unsubscribe(); + if (this.valueChangeSubscrip) { + this.valueChangeSubscrip.unsubscribe(); + } this.document.removeEventListener('click', this.onDocumentClick); } clearAll = (reason?: SelectDateRangeChangeReason, hide?: boolean) => { const currentReason = typeof reason === 'number' ? reason : SelectDateRangeChangeReason.custom; this.chooseDate([null, null], currentReason, hide); - } + }; } diff --git a/devui/datepicker/dateRangePicker.spec.ts b/devui/datepicker/dateRangePicker.spec.ts index da20364d..392727ca 100644 --- a/devui/datepicker/dateRangePicker.spec.ts +++ b/devui/datepicker/dateRangePicker.spec.ts @@ -1,4 +1,3 @@ -// tslint:disable: max-line-length import { Component, DebugElement, ElementRef, TemplateRef, ViewChild } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; @@ -71,7 +70,7 @@ class TestDateRangePickerComponent { fn([new Date(), new Date()], undefined, false); } - constructor() {} + constructor() { } } @Component({ @@ -92,7 +91,7 @@ class TestDateRangePickerOriginComponent { placeHolderHeight = false; isOrigin = false; - constructor() {} + constructor() { } } @Component({ @@ -114,7 +113,7 @@ class TestDateRangePickerCmpComponent { customViewTemplate; reason; @ViewChild('myCustomView') myCustomView: TemplateRef; - constructor() {} + constructor() { } today() { return [new Date(), new Date()]; } @@ -417,7 +416,7 @@ describe('dateRangePickerComponent', () => { }); function padZero(value) { - return (value + '').padStart(2, '0'); + return (String(value)).padStart(2, '0'); } function resolveMonth(str) { @@ -537,7 +536,7 @@ function testNgModelAndYearMonth(fixture, wrapperEle, component) { if (time === 'month') { currentMonth = currentMonth % 12 || 12; } - expect(fun[`${time}Show`](showEle[side][time])).toBe((currentMonth) + ''); + expect(fun[`${time}Show`](showEle[side][time])).toBe(String(currentMonth)); } } } @@ -587,7 +586,7 @@ function testNgModelAndYearMonth(fixture, wrapperEle, component) { closeDatePicker(fixture); component.inputEle.nativeElement.value = `${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`; - tickEvent(component.inputEle.nativeElement, new KeyboardEvent('keyup', {key: 'Enter'}), fixture, 1000); + tickEvent(component.inputEle.nativeElement, new KeyboardEvent('keyup', { key: 'Enter' }), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); openDatePicker(fixture); leftDayListEle = wrapperEle.querySelectorAll('tbody')[0]; @@ -681,7 +680,7 @@ function testInputParam(fixture, wrapperEle, component) { } } const rightMonth = resolveMonth(wrapperEle.querySelectorAll('.devui-date-title')[3].textContent.trim()); - if (component.maxDate.getMonth() + 1 + '' !== rightMonth) { + if (String(component.maxDate.getMonth() + 1) !== rightMonth) { const nextMonthBtn = wrapperEle.querySelectorAll('.devui-calender-header')[1].querySelectorAll('.devui-btn-link')[2]; tickEvent(nextMonthBtn, new Event('click'), fixture); } @@ -741,7 +740,12 @@ function testTimePicker(fixture, wrapperEle, component) { expect(picker['right'].querySelector('.devui-timepicker')).toBeTruthy(); closeDatePicker(fixture); - component.dateRange = [new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate())]; + component.dateRange = [new Date(new Date().getFullYear(), + new Date().getMonth(), + new Date().getDate()), + new Date(new Date().getFullYear(), + new Date().getMonth() + 1, + new Date().getDate())]; fixture.detectChanges(); tick(); fixture.detectChanges(); @@ -844,7 +848,8 @@ function testTimePicker(fixture, wrapperEle, component) { for (const time in timeInputEle[side]) { if (time) { const arr = ['hours', 'minutes', 'seconds']; - testTimePickerBtn(picker[side].querySelectorAll('.devui-btn-nav')[arr.indexOf(time)], fixture, timeEvent, timeInputEle[side][time], component); + testTimePickerBtn(picker[side].querySelectorAll('.devui-btn-nav')[arr.indexOf(time)], + fixture, timeEvent, timeInputEle[side][time], component); } } } @@ -855,12 +860,17 @@ function testTimePicker(fixture, wrapperEle, component) { expect(component.getValue).toHaveBeenCalled(); expect(component.inputEle.nativeElement.value).toBe( + /* eslint-disable-next-line max-len*/ `${strDate(0, 0, 0)} 0${timeEvent}:0${timeEvent}:0${timeEvent}${component.splitter}${strDate(0, 1, 0)} 0${timeEvent}:0${timeEvent}:0${timeEvent}` ); expect(component.dateRange).toEqual( [ - new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), Number(timeEvent), Number(timeEvent), Number(timeEvent)), - new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate(), Number(timeEvent), Number(timeEvent), Number(timeEvent)) + new Date(new Date().getFullYear(), + new Date().getMonth(), + new Date().getDate(), Number(timeEvent), Number(timeEvent), Number(timeEvent)), + new Date(new Date().getFullYear(), + new Date().getMonth() + 1, + new Date().getDate(), Number(timeEvent), Number(timeEvent), Number(timeEvent)) ] ); } @@ -899,7 +909,8 @@ function testTimePickerBtn(btnWrapperEle, fixture, timeEvent, inputEle, componen } function testDateConfig(fixture, wrapperEle, component) { - component.dateRange = [new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate())]; + component.dateRange = [new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), + new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate())]; fixture.detectChanges(); tick(); fixture.detectChanges(); @@ -911,6 +922,7 @@ function testDateConfig(fixture, wrapperEle, component) { tickEvent(confirmBtn, new Event('click'), fixture); expect(component.inputEle.nativeElement.value).toBe( + /* eslint-disable-next-line max-len*/ `${strDate(0, 0, 0, undefined, ['mm', 'dd', 'yy'], '.')} 00-00-00${component.splitter}${strDate(0, 1, 0, undefined, ['mm', 'dd', 'yy'], '.')} 00-00-00` ); } diff --git a/devui/datepicker/datepicker-cdk-overlay.component.ts b/devui/datepicker/datepicker-cdk-overlay.component.ts index 1d3c8621..6adfebd4 100755 --- a/devui/datepicker/datepicker-cdk-overlay.component.ts +++ b/devui/datepicker/datepicker-cdk-overlay.component.ts @@ -36,6 +36,7 @@ import { SelectDateChangeEventArgs, SelectDateChangeReason } from './date-change import { DatePickerConfigService as DatePickerConfig } from './date-picker.config.service'; @Component({ + /* eslint-disable-next-line @angular-eslint/component-selector*/ selector: '[dDatepicker][appendToBody]', providers: [{ provide: NG_VALUE_ACCESSOR, @@ -314,16 +315,16 @@ export class DatePickerAppendToBodyComponent implements OnInit, OnChanges, OnDes this.isOpen = false; this.cdr.markForCheck(); } - } + }; onPositionChange(position: ConnectedOverlayPositionChange) { switch (position.connectionPair.overlayY) { - case 'top': - case 'center': - this.datepickerPosition = 'bottom'; - break; - case 'bottom': - this.datepickerPosition = 'top'; + case 'top': + case 'center': + this.datepickerPosition = 'bottom'; + break; + case 'bottom': + this.datepickerPosition = 'top'; } } @@ -400,7 +401,7 @@ export class DatePickerAppendToBodyComponent implements OnInit, OnChanges, OnDes reason: currentReason, selectedDate: null }); - } + }; ngOnDestroy() { if (this.i18nSubscription) { diff --git a/devui/datepicker/datepicker.component.ts b/devui/datepicker/datepicker.component.ts index 97643933..cff955bb 100755 --- a/devui/datepicker/datepicker.component.ts +++ b/devui/datepicker/datepicker.component.ts @@ -46,6 +46,7 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro @Input() customViewTemplate: TemplateRef; @Input() selectedDate: Date; @Input() mode: 'year'|'month'|'date' = 'date'; + @Input() dateFormat: string; yearNumber = 12; _yearNumber = 12; _dateConfig: any; @@ -161,35 +162,33 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro } @Input() set minDate(date: Date | any) { - const parseDate = this.dateConverter.parse(date); + const parseDate = this.dateConverter.parse(date, this.dateFormat); if (parseDate) { this._minDate = parseDate; this.onYearRangeChange(); } } + get minDate() { + return this._minDate; + } @Input() set maxDate(date: Date | any) { - const parseDate = this.dateConverter.parse(date); + const parseDate = this.dateConverter.parse(date, this.dateFormat); if (parseDate) { this._maxDate = parseDate; this.onYearRangeChange(); } } - get maxDate() { return this._maxDate; } - get minDate() { - return this._minDate; - } - set currentHour(hour: number | string) { this._currentHour = hour; } get currentHour() { - return unshiftString(this._currentHour + '', 2, '0'); + return unshiftString(String(this._currentHour), 2, '0'); } set currentMinute(min: number | string) { @@ -197,7 +196,7 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro } get currentMinute() { - return unshiftString(this._currentMinute + '', 2, '0'); + return unshiftString(String(this._currentMinute), 2, '0'); } set currentSecond(sec: number | string) { @@ -205,7 +204,7 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro } get currentSecond() { - return unshiftString(this._currentSecond + '', 2, '0'); + return unshiftString(String(this._currentSecond), 2, '0'); } protected resetYearOptions() { @@ -255,7 +254,7 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro if (!obj) { return; } - this.selectedDate = this.dateConverter.parse(obj); + this.selectedDate = this.dateConverter.parse(obj, this.dateFormat); this.onSelectDateChanged(); this.onDisplayWeeksChange(); this.availableMonths = this.onDisplayMonthsChange(); @@ -444,15 +443,15 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro }); if (this.currentYear < this.minDate.getFullYear() || this.currentYear > this.maxDate.getFullYear()) { - all.map(month => month.disabled = true); + all.map(month => {month.disabled = true; }); } if (this.currentYear === this.minDate.getFullYear()) { - all.map(month => month.disabled = month.index < this.minDate.getMonth()); + all.map(month => {month.disabled = month.index < this.minDate.getMonth(); }); } if (this.currentYear === this.maxDate.getFullYear()) { - all.map(month => month.disabled = month.index > this.maxDate.getMonth()); + all.map(month => {month.disabled = month.index > this.maxDate.getMonth(); }); } return all; } @@ -524,19 +523,19 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro const min = 0; let max = 59; switch (type) { - case 'h': { - timeType = 'currentHour'; - max = 23; - break; - } - case 'm': { - timeType = 'currentMinute'; - break; - } - case 's': { - timeType = 'currentSecond'; - break; - } + case 'h': { + timeType = 'currentHour'; + max = 23; + break; + } + case 'm': { + timeType = 'currentMinute'; + break; + } + case 's': { + timeType = 'currentSecond'; + break; + } } let value = event.target['value']; const selectionStart = event.target['selectionStart']; @@ -588,36 +587,36 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro timeUp(type) { switch (type) { - case 'h': { - Number(this.currentHour) < 23 ? this.currentHour = (Number(this.currentHour) + 1) : this.currentHour = 0; - break; - } - case 'm': { - Number(this.currentMinute) < 59 ? this.currentMinute = (Number(this.currentMinute) + 1) : this.currentMinute = 0; - break; - } - case 's': { - Number(this.currentSecond) < 59 ? this.currentSecond = (Number(this.currentSecond) + 1) : this.currentSecond = 0; - break; - } + case 'h': { + Number(this.currentHour) < 23 ? this.currentHour = (Number(this.currentHour) + 1) : this.currentHour = 0; + break; + } + case 'm': { + Number(this.currentMinute) < 59 ? this.currentMinute = (Number(this.currentMinute) + 1) : this.currentMinute = 0; + break; + } + case 's': { + Number(this.currentSecond) < 59 ? this.currentSecond = (Number(this.currentSecond) + 1) : this.currentSecond = 0; + break; + } } this.onTimeChange(); } timeDown(type) { switch (type) { - case 'h': { - Number(this.currentHour) > 0 ? this.currentHour = (Number(this.currentHour) - 1) : this.currentHour = 23; - break; - } - case 'm': { - Number(this.currentMinute) > 0 ? this.currentMinute = (Number(this.currentMinute) - 1) : this.currentMinute = 59; - break; - } - case 's': { - Number(this.currentSecond) > 0 ? this.currentSecond = (Number(this.currentSecond) - 1) : this.currentSecond = 59; - break; - } + case 'h': { + Number(this.currentHour) > 0 ? this.currentHour = (Number(this.currentHour) - 1) : this.currentHour = 23; + break; + } + case 'm': { + Number(this.currentMinute) > 0 ? this.currentMinute = (Number(this.currentMinute) - 1) : this.currentMinute = 59; + break; + } + case 's': { + Number(this.currentSecond) > 0 ? this.currentSecond = (Number(this.currentSecond) - 1) : this.currentSecond = 59; + break; + } } this.onTimeChange(); } @@ -633,7 +632,7 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro // 清空时将null作为ngModelChange参数传出 this.onChange(dateObj); this.selectedDateChange.emit(dateObj); - } + }; toggle($event: Event, which) { $event.stopPropagation(); @@ -710,11 +709,11 @@ export class DatepickerComponent implements OnInit, OnChanges, OnDestroy, Contro } chooseDate = (date: string, event = {}, reason = SelectDateChangeReason.custom) => { - const parseDate = this.dateConverter.parse(date); + const parseDate = this.dateConverter.parse(date, this.dateFormat); this.selectedDate = parseDate || new Date(); this.onSelectDateChanged(); this.onSelectDate(event, parseDate, undefined, reason); - } + }; get minDateDefined() { return this.minDate.getTime() !== new Date(this.dateConfig.min, 0, 1, 0, 0, 0).getTime(); diff --git a/devui/datepicker/datepicker.directive.ts b/devui/datepicker/datepicker.directive.ts index ea22462c..f0e180d0 100755 --- a/devui/datepicker/datepicker.directive.ts +++ b/devui/datepicker/datepicker.directive.ts @@ -126,7 +126,7 @@ export class DatepickerDirective implements OnInit, OnDestroy, ControlValueAcces } @Input() set maxDate(date: Date | any) { - const parseDate = this.dateConverter.parse(date); + const parseDate = this.dateConverter.parse(date, this.dateFormat); if (parseDate) { this._maxDate = parseDate; } @@ -137,7 +137,7 @@ export class DatepickerDirective implements OnInit, OnDestroy, ControlValueAcces } @Input() set minDate(date: Date | any) { - const parseDate = this.dateConverter.parse(date); + const parseDate = this.dateConverter.parse(date, this.dateFormat); if (parseDate) { this._minDate = parseDate; } @@ -194,6 +194,7 @@ export class DatepickerDirective implements OnInit, OnDestroy, ControlValueAcces const target = this.cmpRef.location.nativeElement; this.applyPopupStyling(target); const component = this.cmpRef.instance; + component.dateFormat = this.dateFormat; this.renderer2.setStyle(target, 'display', 'none'); component.writeValue(this.selectedDate); this.fillPopupData(); @@ -224,7 +225,7 @@ export class DatepickerDirective implements OnInit, OnDestroy, ControlValueAcces } else { curDate = obj; } - this.selectedDate = curDate ? this.dateConverter.parse(curDate) : null; + this.selectedDate = curDate ? this.dateConverter.parse(curDate, this.dateFormat) : null; this.writeModelValue(obj); } @@ -353,7 +354,7 @@ export class DatepickerDirective implements OnInit, OnDestroy, ControlValueAcces this.hide(); this.cdr.markForCheck(); } - } + }; clearAll(reason?: SelectDateChangeReason) { if (this.disabled) { @@ -365,45 +366,45 @@ export class DatepickerDirective implements OnInit, OnDestroy, ControlValueAcces private popIn(direction): AnimationMetadata[] { switch (direction) { - case 'top': - return [ - style({ transform: 'scaleY(0.8) translateY(4px)', opacity: 0.8, transformOrigin: '0% 100%', display: 'block' }), - animate( - `${AnimationDuration.BASE} ${AnimationCurves.EASE_OUT}`, - style({ transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 100%', display: 'block' }) - ), - ]; - case 'bottom': - default: - return [ - style({ transform: 'scaleY(0.8) translateY(-4px)', opacity: 0.8, transformOrigin: '0% 0%', display: 'block' }), - animate( - `${AnimationDuration.BASE} ${AnimationCurves.EASE_OUT}`, - style({ transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 0%', display: 'block' }) - ), - ]; + case 'top': + return [ + style({ transform: 'scaleY(0.8) translateY(4px)', opacity: 0.8, transformOrigin: '0% 100%', display: 'block' }), + animate( + `${AnimationDuration.BASE} ${AnimationCurves.EASE_OUT}`, + style({ transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 100%', display: 'block' }) + ), + ]; + case 'bottom': + default: + return [ + style({ transform: 'scaleY(0.8) translateY(-4px)', opacity: 0.8, transformOrigin: '0% 0%', display: 'block' }), + animate( + `${AnimationDuration.BASE} ${AnimationCurves.EASE_OUT}`, + style({ transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 0%', display: 'block' }) + ), + ]; } } private popOut(direction): AnimationMetadata[] { switch (direction) { - case 'top': - return [ - style({ transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 100%', display: 'block' }), - animate( - `${AnimationDuration.BASE} ${AnimationCurves.EASE_IN}`, - style({ transform: 'scaleY(0.8) translateY(4px)', opacity: 0.8, transformOrigin: '0% 100%', display: 'block' }) - ), - ]; - case 'bottom': - default: - return [ - style({ transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 0%', display: 'block' }), - animate( - `${AnimationDuration.BASE} ${AnimationCurves.EASE_IN}`, - style({ transform: 'scaleY(0.8) translateY(-4px)', opacity: 0.8, transformOrigin: '0% 0%', display: 'block' }) - ), - ]; + case 'top': + return [ + style({ transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 100%', display: 'block' }), + animate( + `${AnimationDuration.BASE} ${AnimationCurves.EASE_IN}`, + style({ transform: 'scaleY(0.8) translateY(4px)', opacity: 0.8, transformOrigin: '0% 100%', display: 'block' }) + ), + ]; + case 'bottom': + default: + return [ + style({ transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 0%', display: 'block' }), + animate( + `${AnimationDuration.BASE} ${AnimationCurves.EASE_IN}`, + style({ transform: 'scaleY(0.8) translateY(-4px)', opacity: 0.8, transformOrigin: '0% 0%', display: 'block' }) + ), + ]; } } @@ -413,14 +414,14 @@ export class DatepickerDirective implements OnInit, OnDestroy, ControlValueAcces } let direction = ''; switch (this.direction) { - case 'down': - direction = 'bottom'; - break; - case 'up': - direction = 'top'; - break; - default: - direction = 'bottom'; + case 'down': + direction = 'bottom'; + break; + case 'up': + direction = 'top'; + break; + default: + direction = 'bottom'; } if (this.showAnimation) { const metadata = this.isOpen ? this.popIn(direction) : this.popOut(direction); diff --git a/devui/datepicker/datepicker.module.ts b/devui/datepicker/datepicker.module.ts index 44c70ede..0b84cb6a 100755 --- a/devui/datepicker/datepicker.module.ts +++ b/devui/datepicker/datepicker.module.ts @@ -47,7 +47,7 @@ import { TwoDatePickerComponent } from './two-datepicker/two-datepicker.componen TwoDatePickerStartDirective, TwoDatePickerEndDirective ], - + providers: [DatePickerConfigService] }) export class DatepickerModule { diff --git a/devui/datepicker/datepicker.spec.ts b/devui/datepicker/datepicker.spec.ts index fdd3f3c4..b567261f 100644 --- a/devui/datepicker/datepicker.spec.ts +++ b/devui/datepicker/datepicker.spec.ts @@ -535,7 +535,7 @@ describe('datePicker', () => { fixture.detectChanges(); expect( debugEl.query(By.css('.devui-day.active')).query(By.css('.devui-calendar-date') - ).nativeElement.innerText).toBe((now.getDate() + '').padStart(2, '0')); + ).nativeElement.innerText).toBe((String(now.getDate())).padStart(2, '0')); })); it('test selectedDate smaller than min', fakeAsync(() => { @@ -545,7 +545,7 @@ describe('datePicker', () => { fixture.detectChanges(); expect( debugEl.query(By.css('.devui-day.active')).query(By.css('.devui-calendar-date') - ).nativeElement.innerText).toBe((now.getDate() + '').padStart(2, '0')); + ).nativeElement.innerText).toBe((String(now.getDate())).padStart(2, '0')); })); }); @@ -741,7 +741,7 @@ describe('datePicker', () => { }); function padZero(value) { - return (value + '').padStart(2, '0'); + return (String(value)).padStart(2, '0'); } function resolveMonth(str) { @@ -926,7 +926,7 @@ function testNgModelAndYearMonth(fixture, wrapperEle, component) { fixture.detectChanges(); yearEle = wrapperEle.querySelectorAll('.devui-date-title')[0]; - expect(yearEle.innerText.trim().slice(0, 4)).toBe(new Date().getFullYear() - 1 + ''); + expect(yearEle.innerText.trim().slice(0, 4)).toBe(String(new Date().getFullYear() - 1)); const lastMonthEle = wrapperEle.querySelector('.devui-date-header').querySelectorAll('.devui-btn-link')[1]; lastMonthEle.dispatchEvent(new Event('click')); @@ -937,7 +937,7 @@ function testNgModelAndYearMonth(fixture, wrapperEle, component) { trueMonth = 13; } - expect(resolveMonth(monthEle.innerText.trim())).toBe(trueMonth - 1 + ''); + expect(resolveMonth(monthEle.innerText.trim())).toBe(String(trueMonth - 1)); closeDatePicker(fixture); @@ -1024,7 +1024,7 @@ function testInputParam(fixture, wrapperEle, component) { if (nextAvailable.getDate() !== 1) { availableDayNumberList.push(nextAvailable); } - availableDayNumberList.forEach((date, index) => availableDayNumberList[index] = (date.getDate() + '').padStart(2, '0')); + availableDayNumberList.forEach((date, index) => { availableDayNumberList[index] = (String(date.getDate())).padStart(2, '0'); }); for (const dayEl of dayListEle.querySelectorAll('.devui-in-month-day')) { const dayNumber = dayEl.querySelector('.devui-calendar-date').innerText.trim(); if ( @@ -1086,7 +1086,7 @@ function testTimePicker(fixture, wrapperEle, component) { tickEvent(confirmBtn, new Event('click'), fixture); expect(component.getValue).toHaveBeenCalled(); - // tslint:disable-next-line: max-line-length + /* eslint-disable-next-line max-len*/ expect(component.inputEle.nativeElement.value).toBe(`${new Date().getFullYear()}/${padZero(new Date().getMonth() + 1)}/${padZero(new Date().getDate())} 0${timeEvent}:0${timeEvent}:0${timeEvent}`); expect(component.selectedDate1).toEqual( new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), Number(timeEvent), Number(timeEvent), Number(timeEvent)) @@ -1096,7 +1096,7 @@ function testTimePicker(fixture, wrapperEle, component) { tickEvent(component.inputEle.nativeElement, new Event('input'), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); fixture.detectChanges(); - // tslint:disable-next-line: max-line-length + /* eslint-disable-next-line max-len*/ expect(component.inputEle.nativeElement.value).toBe(`${new Date().getFullYear()}/${padZero(new Date().getMonth() + 1)}/${padZero(new Date().getDate())} 0${timeEvent}:0${timeEvent}:0${timeEvent}`); } @@ -1141,6 +1141,7 @@ function testDateConfig(fixture, wrapperEle, component) { fixture.detectChanges(); tickEvent(confirmBtn, new Event('click'), fixture); - // tslint:disable-next-line: max-line-length MM.dd.y mm-ss-HH + // MM.dd.y mm-ss-HH + /* eslint-disable-next-line max-len*/ expect(component.inputEle.nativeElement.value).toBe(`${padZero(new Date().getMonth() + 1)}.${padZero(new Date().getDate())}.${new Date().getFullYear()} ${padZero(new Date().getMinutes())}-${padZero(new Date().getSeconds())}-${padZero(new Date().getHours())}`); } diff --git a/devui/datepicker/demo/append-to-body/append-to-body.component.ts b/devui/datepicker/demo/append-to-body/append-to-body.component.ts index dac5a61b..b4f3a281 100644 --- a/devui/datepicker/demo/append-to-body/append-to-body.component.ts +++ b/devui/datepicker/demo/append-to-body/append-to-body.component.ts @@ -2,10 +2,10 @@ import { ChangeDetectionStrategy, Component } from '@angular/core'; import { AppendToBodyDirection } from 'ng-devui/utils'; @Component({ - selector: 'd-append-to-body', - styleUrls: [`./append-to-body.component.scss`], - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: './append-to-body.component.html' + selector: 'd-append-to-body', + styleUrls: [`./append-to-body.component.scss`], + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './append-to-body.component.html' }) export class DatepickerDemoAppendToBodyComponent { selectedDate1 = null; diff --git a/devui/datepicker/demo/basic/basic.component.ts b/devui/datepicker/demo/basic/basic.component.ts index 426fdd4f..cca22cdd 100755 --- a/devui/datepicker/demo/basic/basic.component.ts +++ b/devui/datepicker/demo/basic/basic.component.ts @@ -1,13 +1,13 @@ import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ - selector: 'd-basic', - styleUrls: [`./basic.component.scss`], - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: './basic.component.html' + selector: 'd-basic', + styleUrls: [`./basic.component.scss`], + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './basic.component.html' }) export class DatepickerDemoBasicComponent { - selectedDate1 = null; + selectedDate1 = new Date(); selectedDate2 = null; selectedDate3 = null; disabled = true; diff --git a/devui/datepicker/demo/button/button.component.ts b/devui/datepicker/demo/button/button.component.ts index d5297e12..8d6cea3b 100644 --- a/devui/datepicker/demo/button/button.component.ts +++ b/devui/datepicker/demo/button/button.component.ts @@ -1,4 +1,4 @@ -import { ChangeDetectionStrategy, Component, HostBinding, OnInit } from '@angular/core'; +import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; @Component({ selector: 'd-datepicker-button', @@ -14,7 +14,6 @@ export class DatepickerButtonComponent implements OnInit { } getValue(value) { - // tslint:disable-next-line:no-console - console.info(value); + console.log(value); } } diff --git a/devui/datepicker/demo/clear-button/clear-button.component.ts b/devui/datepicker/demo/clear-button/clear-button.component.ts index 6bfba9b1..4ec0165e 100644 --- a/devui/datepicker/demo/clear-button/clear-button.component.ts +++ b/devui/datepicker/demo/clear-button/clear-button.component.ts @@ -1,8 +1,6 @@ import { ChangeDetectionStrategy, - Component, - HostBinding, - OnInit + Component, OnInit } from '@angular/core'; import { SelectDateChangeReason } from 'ng-devui/datepicker'; @@ -19,8 +17,7 @@ export class DatepickerClearButtonComponent implements OnInit { ngOnInit() { } getValue(value) { - // tslint:disable-next-line:no-console - console.info(value); + console.log(value); } getDay(num: number, str = '-') { const day = new Date(); diff --git a/devui/datepicker/demo/datepicker-demo.component.ts b/devui/datepicker/demo/datepicker-demo.component.ts index 74845f4c..e5b14b3d 100755 --- a/devui/datepicker/demo/datepicker-demo.component.ts +++ b/devui/datepicker/demo/datepicker-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/datepicker/demo/datepicker-demo.module.ts b/devui/datepicker/demo/datepicker-demo.module.ts index e8a8d22d..545cd48c 100755 --- a/devui/datepicker/demo/datepicker-demo.module.ts +++ b/devui/datepicker/demo/datepicker-demo.module.ts @@ -71,7 +71,7 @@ import { TwoDatepickerFormatComponent } from './two-datepicker-format/two-datepi TwoDatepickerBasicComponent, TwoDatepickerFormatComponent, ], - + providers: [], }) export class DatepickerDemoModule { } diff --git a/devui/datepicker/demo/format/datepicker-format.component.ts b/devui/datepicker/demo/format/datepicker-format.component.ts index 4ac87e42..22f6e9be 100644 --- a/devui/datepicker/demo/format/datepicker-format.component.ts +++ b/devui/datepicker/demo/format/datepicker-format.component.ts @@ -1,9 +1,9 @@ import { Component, OnInit } from '@angular/core'; @Component({ - selector: 'd-datepicker-format', - templateUrl: './datepicker-format.component.html', - styleUrls: [`./datepicker-format.component.scss`] + selector: 'd-datepicker-format', + templateUrl: './datepicker-format.component.html', + styleUrls: [`./datepicker-format.component.scss`] }) export class DatepickerFormatComponent implements OnInit { dateFormatOptions = ['y/MM/dd HH:mm:ss', 'y-MM-dd HH:mm:ss', 'yy.MM.dd HH:mm', 'MM/dd/y HH:mm:ss', 'MM/dd/yy HH:mm']; diff --git a/devui/datepicker/demo/min-max/min-max.component.ts b/devui/datepicker/demo/min-max/min-max.component.ts index 608c825e..5463b6a9 100644 --- a/devui/datepicker/demo/min-max/min-max.component.ts +++ b/devui/datepicker/demo/min-max/min-max.component.ts @@ -1,10 +1,10 @@ import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ - selector: 'd-min-max', - styleUrls: [`./min-max.component.scss`], - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: './min-max.component.html' + selector: 'd-min-max', + styleUrls: [`./min-max.component.scss`], + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './min-max.component.html' }) export class DatepickerDemoMinMaxComponent { selectedDate1 = null; diff --git a/devui/datepicker/demo/range-clear-button/range-clear-button.component.ts b/devui/datepicker/demo/range-clear-button/range-clear-button.component.ts index 32b25367..054870b6 100644 --- a/devui/datepicker/demo/range-clear-button/range-clear-button.component.ts +++ b/devui/datepicker/demo/range-clear-button/range-clear-button.component.ts @@ -6,10 +6,10 @@ import { import { SelectDateRangeChangeReason } from 'ng-devui/datepicker'; @Component({ - selector: 'd-range-clear-button', - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: 'range-clear-button.component.html', - styleUrls: ['./range-clear-button.component.scss'] + selector: 'd-range-clear-button', + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: 'range-clear-button.component.html', + styleUrls: ['./range-clear-button.component.scss'] }) export class RangeClearButtonComponent { dateRange = [null, null]; diff --git a/devui/datepicker/demo/set-mode/set-mode.component.html b/devui/datepicker/demo/set-mode/set-mode.component.html index 606afd6e..ae62105d 100644 --- a/devui/datepicker/demo/set-mode/set-mode.component.html +++ b/devui/datepicker/demo/set-mode/set-mode.component.html @@ -41,7 +41,6 @@
mode="month"
[(ngModel)]="selectedDate2" autocomplete="off" dDatepicker - [maxDate]="maxDate" #datePicker2="datepicker" (selectedDateChange)="getValue($event)" [cssClass]="'custom-css-class'" diff --git a/devui/datepicker/demo/set-mode/set-mode.component.ts b/devui/datepicker/demo/set-mode/set-mode.component.ts index b19fc806..3c6620ba 100644 --- a/devui/datepicker/demo/set-mode/set-mode.component.ts +++ b/devui/datepicker/demo/set-mode/set-mode.component.ts @@ -8,7 +8,6 @@ import { Component } from '@angular/core'; export class SetModeComponent { selectedDate1 = null; selectedDate2 = null; - maxDate = new Date().setMonth(8); getValue(value) { // 当[mode]="'year'",返回值是当年第一天的日期对象,请右键检查打开console查看 // 当[mode]="'month'",返回值是当月第一天的日期对象,请右键检查打开console查看 diff --git a/devui/datepicker/single-date-range-picker.component.ts b/devui/datepicker/single-date-range-picker.component.ts index 4d7f9603..bffb254b 100644 --- a/devui/datepicker/single-date-range-picker.component.ts +++ b/devui/datepicker/single-date-range-picker.component.ts @@ -220,36 +220,36 @@ export class SingleDateRangePickerComponent extends SingleDatepickerComponent im timeUp(type) { switch (type) { - case 'h': { - Number(this.currentHour) < 23 ? this.currentHour = (Number(this.currentHour) + 1) : this.currentHour = 0; - break; - } - case 'm': { - Number(this.currentMinute) < 59 ? this.currentMinute = (Number(this.currentMinute) + 1) : this.currentMinute = 0; - break; - } - case 's': { - Number(this.currentSecond) < 59 ? this.currentSecond = (Number(this.currentSecond) + 1) : this.currentSecond = 0; - break; - } + case 'h': { + Number(this.currentHour) < 23 ? this.currentHour = (Number(this.currentHour) + 1) : this.currentHour = 0; + break; + } + case 'm': { + Number(this.currentMinute) < 59 ? this.currentMinute = (Number(this.currentMinute) + 1) : this.currentMinute = 0; + break; + } + case 's': { + Number(this.currentSecond) < 59 ? this.currentSecond = (Number(this.currentSecond) + 1) : this.currentSecond = 0; + break; + } } this.timeChange(); } timeDown(type) { switch (type) { - case 'h': { - Number(this.currentHour) > 0 ? this.currentHour = (Number(this.currentHour) - 1) : this.currentHour = 23; - break; - } - case 'm': { - Number(this.currentMinute) > 0 ? this.currentMinute = (Number(this.currentMinute) - 1) : this.currentMinute = 59; - break; - } - case 's': { - Number(this.currentSecond) > 0 ? this.currentSecond = (Number(this.currentSecond) - 1) : this.currentSecond = 59; - break; - } + case 'h': { + Number(this.currentHour) > 0 ? this.currentHour = (Number(this.currentHour) - 1) : this.currentHour = 23; + break; + } + case 'm': { + Number(this.currentMinute) > 0 ? this.currentMinute = (Number(this.currentMinute) - 1) : this.currentMinute = 59; + break; + } + case 's': { + Number(this.currentSecond) > 0 ? this.currentSecond = (Number(this.currentSecond) - 1) : this.currentSecond = 59; + break; + } } this.timeChange(); } @@ -262,19 +262,19 @@ export class SingleDateRangePickerComponent extends SingleDatepickerComponent im const min = 0; let max = 59; switch (type) { - case 'h': { - timeType = 'currentHour'; - max = 23; - break; - } - case 'm': { - timeType = 'currentMinute'; - break; - } - case 's': { - timeType = 'currentSecond'; - break; - } + case 'h': { + timeType = 'currentHour'; + max = 23; + break; + } + case 'm': { + timeType = 'currentMinute'; + break; + } + case 's': { + timeType = 'currentSecond'; + break; + } } let value = event.target['value']; const selectionStart = event.target['selectionStart']; @@ -645,18 +645,18 @@ export class SingleDateRangePickerComponent extends SingleDatepickerComponent im this.currentMonthIndex = date.getMonth(); if (!this.showTime) { return; } switch (this.isAuxiliary) { - case false: - // Left panel - this.currentHour = this.rangeStart ? this.rangeStart.getHours() : 0; - this.currentMinute = this.rangeStart ? this.rangeStart.getMinutes() : 0; - this.currentSecond = this.rangeStart ? this.rangeStart.getSeconds() : 0; - break; - case true: - // Right panel - this.currentHour = this.rangeEnd ? this.rangeEnd.getHours() : 23; - this.currentMinute = this.rangeEnd ? this.rangeEnd.getMinutes() : 59; - this.currentSecond = this.rangeEnd ? this.rangeEnd.getSeconds() : 59; - break; + case false: + // Left panel + this.currentHour = this.rangeStart ? this.rangeStart.getHours() : 0; + this.currentMinute = this.rangeStart ? this.rangeStart.getMinutes() : 0; + this.currentSecond = this.rangeStart ? this.rangeStart.getSeconds() : 0; + break; + case true: + // Right panel + this.currentHour = this.rangeEnd ? this.rangeEnd.getHours() : 23; + this.currentMinute = this.rangeEnd ? this.rangeEnd.getMinutes() : 59; + this.currentSecond = this.rangeEnd ? this.rangeEnd.getSeconds() : 59; + break; } } diff --git a/devui/datepicker/two-datepicker/two-datepicker-end.directive.ts b/devui/datepicker/two-datepicker/two-datepicker-end.directive.ts index b8c1ae8f..00911615 100644 --- a/devui/datepicker/two-datepicker/two-datepicker-end.directive.ts +++ b/devui/datepicker/two-datepicker/two-datepicker-end.directive.ts @@ -96,7 +96,7 @@ export class TwoDatePickerEndDirective implements OnInit, OnDestroy, ControlValu clear = () => { this.twoDatePicker.clear('end'); - } + }; transUserInputToDatePicker(value?: string) { if (!this.twoDatePicker.showTime) { @@ -148,6 +148,8 @@ export class TwoDatePickerEndDirective implements OnInit, OnDestroy, ControlValu this.switchOriginSub.unsubscribe(); } - this.valueChangeSubscrip?.unsubscribe(); + if (this.valueChangeSubscrip) { + this.valueChangeSubscrip.unsubscribe(); + } } } diff --git a/devui/datepicker/two-datepicker/two-datepicker-start.directive.ts b/devui/datepicker/two-datepicker/two-datepicker-start.directive.ts index 8e6e862d..3872991e 100644 --- a/devui/datepicker/two-datepicker/two-datepicker-start.directive.ts +++ b/devui/datepicker/two-datepicker/two-datepicker-start.directive.ts @@ -93,7 +93,7 @@ export class TwoDatePickerStartDirective implements OnInit, OnDestroy, ControlVa clear = () => { this.twoDatePicker.clear('start'); - } + }; transUserInputToDatePicker(value?: string) { if (!this.twoDatePicker.showTime) { @@ -148,7 +148,8 @@ export class TwoDatePickerStartDirective implements OnInit, OnDestroy, ControlVa if (this.switchOriginSub) { this.switchOriginSub.unsubscribe(); } - - this.valueChangeSubscrip?.unsubscribe(); + if (this.valueChangeSubscrip) { + this.valueChangeSubscrip.unsubscribe(); + } } } diff --git a/devui/datepicker/two-datepicker/two-datepicker.component.ts b/devui/datepicker/two-datepicker/two-datepicker.component.ts index c7ffb724..6761e97d 100644 --- a/devui/datepicker/two-datepicker/two-datepicker.component.ts +++ b/devui/datepicker/two-datepicker/two-datepicker.component.ts @@ -21,6 +21,7 @@ import { distinctUntilChanged } from 'rxjs/operators'; import { DatePickerConfigService as DatePickerConfig } from '../date-picker.config.service'; @Component({ + /* eslint-disable-next-line @angular-eslint/component-selector*/ selector: '[dTwoDatePicker]', exportAs: 'twoDatePicker', templateUrl: 'two-datepicker.component.html', @@ -45,7 +46,7 @@ export class TwoDatePickerComponent implements OnInit, OnDestroy { @ViewChild('templateWrap') templateWrap: ElementRef; datePosition: VerticalConnectionPos = 'bottom'; - selectDateSubject = new Subject<{side: string, date: Date, onlyWrite?: boolean}>(); + selectDateSubject = new Subject<{side: string; date: Date; onlyWrite?: boolean}>(); hoverOnDate: Subject = new Subject(); switchOriginPositionSub: Subject<'start'|'end'|false> = new Subject<'start'|'end'|false>(); today = new Date(); @@ -66,7 +67,6 @@ export class TwoDatePickerComponent implements OnInit, OnDestroy { private _maxDate: Date; private _minDate: Date; document: Document; - @Input() set dateConfig(dateConfig: any) { if (this.checkDateConfig(dateConfig)) { this._dateConfig = dateConfig; @@ -75,27 +75,42 @@ export class TwoDatePickerComponent implements OnInit, OnDestroy { } this._dateFormat = this.showTime ? this._dateConfig.format.time : this._dateConfig.format.date; } + get dateConfig() { + return this._dateConfig; + } @Input() set dateFormat(dateFormat: string) { if (dateFormat && this._dateFormat !== dateFormat) { this._dateFormat = dateFormat; } } + get dateFormat() { + return this._dateFormat || this.datePickerConfig.defaultFormat; + } @Input() set maxDate(date: Date | any) { const parseDate = this.convertDate(date); if (parseDate) { this._maxDate = parseDate; } } + get maxDate() { + return this._maxDate; + } @Input() set minDate(date: Date | any) { const parseDate = this.convertDate(date); if (parseDate) { this._minDate = parseDate; } } + get minDate() { + return this._minDate; + } set whichOpen(side: 'start'|'end'|false) { this._whichOpen = side; this.switchOriginPositionSub.next(side); } + get whichOpen() { + return this._whichOpen; + } set isOpen(isOpen: boolean) { this._isOpen = isOpen; if (!isOpen) { @@ -109,22 +124,6 @@ export class TwoDatePickerComponent implements OnInit, OnDestroy { }); } } - - get dateConfig() { - return this._dateConfig; - } - get dateFormat() { - return this._dateFormat || this.datePickerConfig.defaultFormat; - } - get maxDate() { - return this._maxDate; - } - get minDate() { - return this._minDate; - } - get whichOpen() { - return this._whichOpen; - } get isOpen() { return this._isOpen; } @@ -157,7 +156,7 @@ export class TwoDatePickerComponent implements OnInit, OnDestroy { this.isOpen = false; } this.cdr.markForCheck(); - } + }; ngOnInit() { this._minDate = this.minDate ? new Date(this.minDate) : new Date(this.dateConfig.min, 0, 1, 0, 0, 0); @@ -195,23 +194,23 @@ export class TwoDatePickerComponent implements OnInit, OnDestroy { this.whichOpen = side; this.isOpen = true; } - } + }; onPositionChange(position: ConnectedOverlayPositionChange) { switch (position.connectionPair.overlayY) { - case 'top': - case 'center': - this.datePosition = 'bottom'; - break; - case 'bottom': - this.datePosition = 'top'; + case 'top': + case 'center': + this.datePosition = 'bottom'; + break; + case 'bottom': + this.datePosition = 'top'; } this.switchOriginPositionSub.next(this.whichOpen); } convertDate(date) { return date ? - this.dateConverter.parse(date) : null; + this.dateConverter.parse(date, this.dateFormat) : null; } formatDate(date) { @@ -229,12 +228,12 @@ export class TwoDatePickerComponent implements OnInit, OnDestroy { syncPickerPair(currentCalender: object, orientation: string) { switch (orientation) { - case 'left': - this.currentCalendars[0] = currentCalender; - break; - case 'right': - this.currentCalendars[1] = currentCalender; - break; + case 'left': + this.currentCalendars[0] = currentCalender; + break; + case 'right': + this.currentCalendars[1] = currentCalender; + break; } } @@ -250,7 +249,7 @@ export class TwoDatePickerComponent implements OnInit, OnDestroy { [this.rangeStart, this.rangeEnd] = this.selectedRange; this.notifyValueChange(); } - } + }; notifyValueChange() { this.selectedRangeChange.emit(this.selectedRange); @@ -336,7 +335,7 @@ export class TwoDatePickerComponent implements OnInit, OnDestroy { this.selectEnd(null); } [this.rangeStart, this.rangeEnd] = this.selectedRange; - } + }; setI18nText() { this.i18nText = this.i18n.getI18nText().datePicker; diff --git a/devui/datepicker/twoDatePicker.spec.ts b/devui/datepicker/twoDatePicker.spec.ts index cbd0df84..8a45b603 100644 --- a/devui/datepicker/twoDatePicker.spec.ts +++ b/devui/datepicker/twoDatePicker.spec.ts @@ -1,4 +1,3 @@ -// tslint:disable: max-line-length import { Component, DebugElement, ElementRef, ViewChild } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; @@ -48,7 +47,7 @@ class CommonFunctions { static resolveMonth(str) { const monthArray = this.i18nText().datePicker.monthsOfYear; const monthIndex = monthArray.indexOf(`${str}`); - return monthIndex + 1 + ''; + return String(monthIndex + 1); } static strDateOrFromNow(date: Date | Array, day?, arr = ['yy', 'mm', 'dd'], splitter = '/') { @@ -66,7 +65,7 @@ class CommonFunctions { } static padZero(value) { - return (value + '').padStart(2, '0'); + return (String(value)).padStart(2, '0'); } } @@ -143,7 +142,7 @@ class TestFunctions { if (time === 'month') { currentMonth = currentMonth % 12 || 12; } - expect(commonEles[`${time}Show`](yearMonthEles[side][time])).toBe((currentMonth) + ''); + expect(commonEles[`${time}Show`](yearMonthEles[side][time])).toBe(String(currentMonth)); } } } @@ -251,9 +250,9 @@ class TestFunctions { CommonFunctions.closeDatePicker(fixture); component.leftInputEle.nativeElement.value = `${CommonFunctions.strDateOrFromNow([0, 0, 0], '05')}`; component.rightInputEle.nativeElement.value = `${CommonFunctions.strDateOrFromNow([0, 1, 0], '05')}`; - CommonFunctions.tickEvent(component.leftInputEle.nativeElement, new KeyboardEvent('keyup', {key: 'Enter'}), fixture, 1000); + CommonFunctions.tickEvent(component.leftInputEle.nativeElement, new KeyboardEvent('keyup', { key: 'Enter' }), fixture, 1000); CommonFunctions.tickEvent(component.leftInputEle.nativeElement, new Event('blur'), fixture, 1000); - CommonFunctions.tickEvent(component.rightInputEle.nativeElement, new KeyboardEvent('keyup', {key: 'Enter'}), fixture, 1000); + CommonFunctions.tickEvent(component.rightInputEle.nativeElement, new KeyboardEvent('keyup', { key: 'Enter' }), fixture, 1000); CommonFunctions.tickEvent(component.rightInputEle.nativeElement, new Event('blur'), fixture, 1000); CommonFunctions.openDatePicker(fixture); leftDayListEle = wrapperEle.querySelectorAll('tbody')[0]; @@ -271,9 +270,9 @@ class TestFunctions { component.leftInputEle.nativeElement.value = `${CommonFunctions.strDateOrFromNow([0, 0, 0], '05')}`; component.rightInputEle.nativeElement.value = `${CommonFunctions.strDateOrFromNow([0, 1, 0], '05')}`; - CommonFunctions.tickEvent(component.leftInputEle.nativeElement, new KeyboardEvent('keyup', {key: 'Enter'}), fixture, 1000); + CommonFunctions.tickEvent(component.leftInputEle.nativeElement, new KeyboardEvent('keyup', { key: 'Enter' }), fixture, 1000); CommonFunctions.tickEvent(component.leftInputEle.nativeElement, new Event('blur'), fixture, 1000); - CommonFunctions.tickEvent(component.rightInputEle.nativeElement, new KeyboardEvent('keyup', {key: 'Enter'}), fixture, 1000); + CommonFunctions.tickEvent(component.rightInputEle.nativeElement, new KeyboardEvent('keyup', { key: 'Enter' }), fixture, 1000); CommonFunctions.tickEvent(component.rightInputEle.nativeElement, new Event('blur'), fixture, 1000); fixture.detectChanges(); tick(); @@ -330,8 +329,10 @@ class TestFunctions { CommonFunctions.tickEvent(leftCurrentDayInListEle, new Event('click'), fixture); CommonFunctions.tickEvent(rightCurrentDayInListEle, new Event('click'), fixture); expect(component.getValue).toHaveBeenCalled(); - expect(component.leftInputEle.nativeElement.value).toBe(`${CommonFunctions.strDateOrFromNow([0, 0, 0], undefined, ['mm', 'dd', 'yy'], '.')}`); - expect(component.rightInputEle.nativeElement.value).toBe(`${CommonFunctions.strDateOrFromNow([0, 1, 0], undefined, ['mm', 'dd', 'yy'], '.')}`); + expect(component.leftInputEle.nativeElement.value) + .toBe(`${CommonFunctions.strDateOrFromNow([0, 0, 0], undefined, ['mm', 'dd', 'yy'], '.')}`); + expect(component.rightInputEle.nativeElement.value) + .toBe(`${CommonFunctions.strDateOrFromNow([0, 1, 0], undefined, ['mm', 'dd', 'yy'], '.')}`); CommonFunctions.closeDatePicker(fixture); // 今天不在minDate、maxDate之中 @@ -344,14 +345,16 @@ class TestFunctions { const footer = document.querySelector('.devui-two-date-footer'); const todayBtn = footer.querySelector('a'); CommonFunctions.tickEvent(todayBtn, new Event('click'), fixture); - expect(component.leftInputEle.nativeElement.value).toBe(`${CommonFunctions.strDateOrFromNow([0, 0, 0], undefined, ['mm', 'dd', 'yy'], '.')}`); + expect(component.leftInputEle.nativeElement.value) + .toBe(`${CommonFunctions.strDateOrFromNow([0, 0, 0], undefined, ['mm', 'dd', 'yy'], '.')}`); CommonFunctions.tickEvent(todayBtn, new Event('click'), fixture); - expect(component.rightInputEle.nativeElement.value).toBe(`${CommonFunctions.strDateOrFromNow([0, 1, 0], undefined, ['mm', 'dd', 'yy'], '.')}`); + expect(component.rightInputEle.nativeElement.value) + .toBe(`${CommonFunctions.strDateOrFromNow([0, 1, 0], undefined, ['mm', 'dd', 'yy'], '.')}`); CommonFunctions.closeDatePicker(fixture); } - static testDateConfig(fixture, wrapperEle, component, year: number = 2020, shouldWorks: boolean = true) { + static testDateConfig(fixture, wrapperEle, component, year = 2020, shouldWorks = true) { const minDate = new Date(year, 0, 1, 0, 0, 0); const maxDate = new Date(year, 11, 31, 23, 59, 59); component.rangeStart = minDate; @@ -367,11 +370,15 @@ class TestFunctions { CommonFunctions.tickEvent(rightCurrentDayInListEle, new Event('click'), fixture); expect(component.getValue).toHaveBeenCalled(); if (shouldWorks) { - expect(component.leftInputEle.nativeElement.value).toBe(`${CommonFunctions.strDateOrFromNow(minDate, undefined, ['mm', 'dd', 'yy'], '.')}`); - expect(component.rightInputEle.nativeElement.value).toBe(`${CommonFunctions.strDateOrFromNow(maxDate, undefined, ['mm', 'dd', 'yy'], '.')}`); + expect(component.leftInputEle.nativeElement.value) + .toBe(`${CommonFunctions.strDateOrFromNow(minDate, undefined, ['mm', 'dd', 'yy'], '.')}`); + expect(component.rightInputEle.nativeElement.value) + .toBe(`${CommonFunctions.strDateOrFromNow(maxDate, undefined, ['mm', 'dd', 'yy'], '.')}`); } else { - expect(component.leftInputEle.nativeElement.value).not.toBe(`${CommonFunctions.strDateOrFromNow(minDate, undefined, ['mm', 'dd', 'yy'], '.')}`); - expect(component.rightInputEle.nativeElement.value).not.toBe(`${CommonFunctions.strDateOrFromNow(maxDate, undefined, ['mm', 'dd', 'yy'], '.')}`); + expect(component.leftInputEle.nativeElement.value) + .not.toBe(`${CommonFunctions.strDateOrFromNow(minDate, undefined, ['mm', 'dd', 'yy'], '.')}`); + expect(component.rightInputEle.nativeElement.value) + .not.toBe(`${CommonFunctions.strDateOrFromNow(maxDate, undefined, ['mm', 'dd', 'yy'], '.')}`); } CommonFunctions.closeDatePicker(fixture); } @@ -390,7 +397,7 @@ class TestFunctions { } } const rightMonth = CommonFunctions.resolveMonth(wrapperEle.querySelectorAll('.devui-date-title')[3].textContent.trim()); - if (maxDate.getMonth() + 1 + '' !== rightMonth) { + if (String(maxDate.getMonth() + 1) !== rightMonth) { const nextMonthBtn = wrapperEle.querySelectorAll('.devui-calender-header')[1].querySelectorAll('.devui-btn-link')[2]; CommonFunctions.tickEvent(nextMonthBtn, new Event('click'), fixture); } @@ -436,7 +443,9 @@ class TestFunctions { (click)="startPicker.toggle()" #leftInputEle /> -
+
@@ -481,7 +490,7 @@ class TestTwoDatePickerComponent { getValue = jasmine.createSpy('get value'); - constructor() {} + constructor() { } } @Component({ @@ -520,7 +529,7 @@ class TestTwoDatePickerDivComponent { getValue = jasmine.createSpy('get value'); - constructor() {} + constructor() { } } describe('twoDatePicker', () => { diff --git a/devui/design-token/border-radius/demo/border-radius/border-radius.component.ts b/devui/design-token/border-radius/demo/border-radius/border-radius.component.ts index bc28d53b..f96275f7 100644 --- a/devui/design-token/border-radius/demo/border-radius/border-radius.component.ts +++ b/devui/design-token/border-radius/demo/border-radius/border-radius.component.ts @@ -39,7 +39,7 @@ export class BorderRadiusComponent implements OnInit, OnDestroy { } }); this.borderRadius = cloneDeep(this.borderRadius); - } + }; setI18n() { this.subs.add( diff --git a/devui/design-token/color/demo/color/color.component.ts b/devui/design-token/color/demo/color/color.component.ts index 82eff5d9..b20e1f1b 100644 --- a/devui/design-token/color/demo/color/color.component.ts +++ b/devui/design-token/color/demo/color/color.component.ts @@ -50,7 +50,7 @@ export class ColorComponent implements OnInit, OnDestroy { } } }); - } + }; toggleExpand(rowItem, index) { rowItem.expand = !rowItem.expand; diff --git a/devui/design-token/font/demo/font/font.component.ts b/devui/design-token/font/demo/font/font.component.ts index 0191c64d..81b55657 100644 --- a/devui/design-token/font/demo/font/font.component.ts +++ b/devui/design-token/font/demo/font/font.component.ts @@ -44,7 +44,7 @@ export class FontComponent implements OnInit, OnDestroy { } }); this.fonts = cloneDeep(this.fonts); - } + }; setI18n() { this.subs.add( diff --git a/devui/design-token/link/demo/design-link-demo.component.ts b/devui/design-token/link/demo/design-link-demo.component.ts index 17ad4e19..10ac811b 100644 --- a/devui/design-token/link/demo/design-link-demo.component.ts +++ b/devui/design-token/link/demo/design-link-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/design-token/shadow/demo/shadow/shadow.component.ts b/devui/design-token/shadow/demo/shadow/shadow.component.ts index d7c316fa..d73b9ed5 100644 --- a/devui/design-token/shadow/demo/shadow/shadow.component.ts +++ b/devui/design-token/shadow/demo/shadow/shadow.component.ts @@ -43,7 +43,7 @@ export class ShadowComponent implements OnInit, OnDestroy { } }); this.shadows = cloneDeep(this.shadows); - } + }; setI18n() { this.subs.add( diff --git a/devui/devui.module.ts b/devui/devui.module.ts index 8f92b296..d9cf08fc 100755 --- a/devui/devui.module.ts +++ b/devui/devui.module.ts @@ -192,7 +192,7 @@ export * from './version'; DatepickerProModule, MentionModule, NavSpriteModule, - ReadTipModule, + ReadTipModule ], declarations: [], }) diff --git a/devui/dragdrop/demo/basic/basic.component.ts b/devui/dragdrop/demo/basic/basic.component.ts index 2119a17c..818fe34e 100755 --- a/devui/dragdrop/demo/basic/basic.component.ts +++ b/devui/dragdrop/demo/basic/basic.component.ts @@ -22,7 +22,7 @@ export class BasicComponent { const fromIndex = e.dragFromIndex; const item = e.dragData.item; if (-1 !== index) { - /*修正同一个container排序,往下拖动index多了1个位置*/ + /* 修正同一个container排序,往下拖动index多了1个位置*/ if (-1 !== fromIndex && index > fromIndex) { index--; } @@ -30,7 +30,7 @@ export class BasicComponent { } else { targetArray.push(item); } - if (-1 === fromIndex) { + if (fromIndex === -1) { this.removeItem(item, e.dragData.parent); } } diff --git a/devui/dragdrop/demo/batch-drag/batch-drag.component.ts b/devui/dragdrop/demo/batch-drag/batch-drag.component.ts index 15a7f314..bda614c0 100644 --- a/devui/dragdrop/demo/batch-drag/batch-drag.component.ts +++ b/devui/dragdrop/demo/batch-drag/batch-drag.component.ts @@ -9,7 +9,13 @@ export class BatchDragComponent { lists = [ { name: 'IDE', - list: [{ name: 'Visual Studio Code', isSelected: false }, { name: 'WebStorm', isSelected: false }, { name: 'Sublime Text', isSelected: false }, { name: 'Atom', isSelected: false }, { name: 'Notepad++', isSelected: false }], + list: [ + { name: 'Visual Studio Code', isSelected: false }, + { name: 'WebStorm', isSelected: false }, + { name: 'Sublime Text', isSelected: false }, + { name: 'Atom', isSelected: false }, + { name: 'Notepad++', isSelected: false }, + ], }, { name: 'Browser', @@ -24,11 +30,22 @@ export class BatchDragComponent { }, { name: 'OS', - list: [{ name: 'Linux', isSelected: false }, { name: 'Windows', isSelected: false }, { name: 'Mac OS', isSelected: false }, { name: 'DOS', isSelected: false }, { name: 'Chrome OS', isSelected: false }], + list: [ + { name: 'Linux', isSelected: false }, + { name: 'Windows', isSelected: false }, + { name: 'Mac OS', isSelected: false }, + { name: 'DOS', isSelected: false }, + { name: 'Chrome OS', isSelected: false }, + ], }, { name: 'Mobile OS', - list: [{ name: 'Android', isSelected: false }, { name: 'IOS', isSelected: false }, { name: 'BlackBerry', isSelected: false }, { name: 'Symbian', isSelected: false }], + list: [ + { name: 'Android', isSelected: false }, + { name: 'IOS', isSelected: false }, + { name: 'BlackBerry', isSelected: false }, + { name: 'Symbian', isSelected: false }, + ], }, { name: 'Whatever', @@ -61,7 +78,7 @@ export class BatchDragComponent { } else { targetArray.push(item); } - if (-1 === fromIndex) { + if (fromIndex === -1) { this.removeItem(item, parentArray); } } @@ -99,6 +116,10 @@ export class BatchDragComponent { } cleanBatch() { - this.lists.forEach((list) => list.list.forEach((item) => (item['isSelected'] = false))); + this.lists.forEach((list) => + list.list.forEach((item) => { + item['isSelected'] = false; + }) + ); } } diff --git a/devui/dragdrop/demo/cross-dimension/cross-dimension.component.ts b/devui/dragdrop/demo/cross-dimension/cross-dimension.component.ts index aba8e032..81e46055 100644 --- a/devui/dragdrop/demo/cross-dimension/cross-dimension.component.ts +++ b/devui/dragdrop/demo/cross-dimension/cross-dimension.component.ts @@ -8,65 +8,65 @@ import { ChangeDetectorRef, Component } from '@angular/core'; export class CrossDimensionComponent { lists = { listA1: [ - { name: 'Visual Studio Code' }, - { name: 'WebStorm' }, - { name: 'Sublime Text' }, - { name: 'Atom' }, - { name: 'Notepad++' }, - ], + { name: 'Visual Studio Code' }, + { name: 'WebStorm' }, + { name: 'Sublime Text' }, + { name: 'Atom' }, + { name: 'Notepad++' }, + ], listA2: [ - { name: 'Chrome' }, - { name: 'Firefox' }, - { name: 'Opera' }, - { name: 'Edge' }, - { name: 'Internet Explorer' }, - { name: 'Safari' }, - ], - listA3: [], + { name: 'Chrome' }, + { name: 'Firefox' }, + { name: 'Opera' }, + { name: 'Edge' }, + { name: 'Internet Explorer' }, + { name: 'Safari' }, + ], + listA3: [], listB1: [ - {name: 'Linux'}, - {name: 'Windows'}, - {name: 'Mac OS'}, - {name: 'DOS'}, - {name: 'Chrome OS'}, - ], + {name: 'Linux'}, + {name: 'Windows'}, + {name: 'Mac OS'}, + {name: 'DOS'}, + {name: 'Chrome OS'}, + ], listB2: [ - {name: 'Android'}, - {name: 'IOS'}, - {name: 'BlackBerry'}, - {name: 'Symbian'}, - ], - listB3: [], - listC1: [], - listC2: [], - listC3: [] + {name: 'Android'}, + {name: 'IOS'}, + {name: 'BlackBerry'}, + {name: 'Symbian'}, + ], + listB3: [], + listC1: [], + listC2: [], + listC3: [] - }; - owners = [ { - id: 'not-assign', - name: 'Not Assign', - collapse: false + }; + owners = [ { + id: 'not-assign', + name: 'Not Assign', + collapse: false + }, { + id: 'available', + name: 'Available', + collapse: false + }, { + id: 'not-available', + name: 'Not Available', + collapse: false + }]; + listCol = [ + { + id: 'group1', + name: 'Group 1' }, { - id: 'available', - name: 'Available', - collapse: false + id: 'group2', + name: 'Group 2' }, { - id: 'not-available', - name: 'Not Available', - collapse: false - }]; - listCol = [ - { - id: 'group1', - name: 'Group 1' - }, { - id: 'group2', - name: 'Group 2' - }, { - id: 'group3', - name: 'Group 3' - } - ]; + id: 'group3', + name: 'Group 3' + } + ]; ownerListMap = { 'not-assign': { group1: this.lists.listA1, @@ -105,7 +105,7 @@ export class CrossDimensionComponent { } else { targetArray.push(item); } - if (-1 === fromIndex) { + if (fromIndex === -1) { this.removeItem(item, parentArray); } } @@ -142,7 +142,7 @@ export class CrossDimensionComponent { cleanBatch() { Object.keys(this.lists).map(key => this.lists[key]).forEach(list => list.forEach( - item => item['isSelected'] = false + item => {item['isSelected'] = false;} )); } } diff --git a/devui/dragdrop/demo/dragdrop-demo.component.ts b/devui/dragdrop/demo/dragdrop-demo.component.ts index ae49917e..601e3f0e 100755 --- a/devui/dragdrop/demo/dragdrop-demo.component.ts +++ b/devui/dragdrop/demo/dragdrop-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/dragdrop/demo/dragdrop-demo.module.ts b/devui/dragdrop/demo/dragdrop-demo.module.ts index cec2947a..4c8b6fa1 100755 --- a/devui/dragdrop/demo/dragdrop-demo.module.ts +++ b/devui/dragdrop/demo/dragdrop-demo.module.ts @@ -54,7 +54,7 @@ import { TreeComponent } from './tree/tree.component'; DropScrollComponent, CrossDimensionComponent ], - + }) export class DragDropDemoModule { } diff --git a/devui/dragdrop/demo/drop-scroll/drop-scroll.component.ts b/devui/dragdrop/demo/drop-scroll/drop-scroll.component.ts index 0e4dbc14..9d9b1d67 100644 --- a/devui/dragdrop/demo/drop-scroll/drop-scroll.component.ts +++ b/devui/dragdrop/demo/drop-scroll/drop-scroll.component.ts @@ -85,7 +85,7 @@ export class DropScrollComponent { } else { targetArray.push(item); } - if (-1 === fromIndex) { + if (fromIndex === -1) { this.removeItem(item, parentArray); } } diff --git a/devui/dragdrop/demo/follow/follow.component.ts b/devui/dragdrop/demo/follow/follow.component.ts index 9be98fc9..2b702368 100755 --- a/devui/dragdrop/demo/follow/follow.component.ts +++ b/devui/dragdrop/demo/follow/follow.component.ts @@ -27,7 +27,7 @@ export class FollowComponent implements OnInit { let index = e.dropIndex; const fromIndex = e.dragFromIndex; if (-1 !== index) { - /*修正同一个container排序,往下拖动index多了1个位置*/ + /* 修正同一个container排序,往下拖动index多了1个位置*/ if (-1 !== fromIndex && index > fromIndex) { index--; } @@ -35,7 +35,7 @@ export class FollowComponent implements OnInit { } else { this.list2.push(e.dragData); } - if (-1 === fromIndex) { + if (fromIndex === -1) { this.removeItem(e.dragData, this.list1); } } diff --git a/devui/dragdrop/demo/origin-placeholder/origin-placeholder.component.ts b/devui/dragdrop/demo/origin-placeholder/origin-placeholder.component.ts index 51cbd5c0..14a86449 100644 --- a/devui/dragdrop/demo/origin-placeholder/origin-placeholder.component.ts +++ b/devui/dragdrop/demo/origin-placeholder/origin-placeholder.component.ts @@ -36,7 +36,7 @@ export class OriginPlaceholderComponent { const fromIndex = e.dragFromIndex; const item = e.dragData.item; if (-1 !== index) { - /*修正同一个container排序,往下拖动index多了1个位置*/ + /* 修正同一个container排序,往下拖动index多了1个位置*/ if (-1 !== fromIndex && index > fromIndex) { index--; } @@ -44,7 +44,7 @@ export class OriginPlaceholderComponent { } else { targetArray.push(item); } - if (-1 === fromIndex) { + if (fromIndex === -1) { this.removeItem(item, e.dragData.parent); } } diff --git a/devui/dragdrop/demo/position/position.component.ts b/devui/dragdrop/demo/position/position.component.ts index bbe717c8..41c4af97 100644 --- a/devui/dragdrop/demo/position/position.component.ts +++ b/devui/dragdrop/demo/position/position.component.ts @@ -22,7 +22,7 @@ export class PositionComponent { } else { targetArray.push(item); } - if (-1 === fromIndex) { + if (fromIndex === -1) { this.removeItem(item, parentArray); } } diff --git a/devui/dragdrop/demo/switch/switch.component.ts b/devui/dragdrop/demo/switch/switch.component.ts index 58100bec..36532d7c 100644 --- a/devui/dragdrop/demo/switch/switch.component.ts +++ b/devui/dragdrop/demo/switch/switch.component.ts @@ -22,7 +22,7 @@ export class SwitchComponent { let index = e.dropIndex; const fromIndex = e.dragFromIndex; if (-1 !== index) { - /*修正同一个container排序,往下拖动index多了1个位置*/ + /* 修正同一个container排序,往下拖动index多了1个位置*/ if (-1 !== fromIndex && index > fromIndex) { index--; } @@ -30,7 +30,7 @@ export class SwitchComponent { } else { this.list2.push(e.dragData); } - if (-1 === fromIndex) { + if (fromIndex === -1) { this.removeItem(e.dragData, this.list1); } } diff --git a/devui/dragdrop/directives/batch-draggable.directive.ts b/devui/dragdrop/directives/batch-draggable.directive.ts index dcb344f4..4b41a3ce 100644 --- a/devui/dragdrop/directives/batch-draggable.directive.ts +++ b/devui/dragdrop/directives/batch-draggable.directive.ts @@ -3,8 +3,8 @@ import { DragDropService } from '../services/drag-drop.service'; import { DraggableDirective } from './draggable.directive'; export type BatchDragStyle = 'badge' | 'stack' | string; @Directive({ - selector: '[dDraggable][batchDrag]', - exportAs: 'dBatchDraggable' + selector: '[dDraggable][batchDrag]', + exportAs: 'dBatchDraggable' }) export class BatchDraggableDirective implements OnInit, OnChanges, OnDestroy, AfterViewInit { @@ -42,11 +42,11 @@ export class BatchDraggableDirective implements OnInit, OnChanges, OnDestroy, Af if (!this.initDragDataByIdentity()) { if (this.batchDragActive) { if (!this.dragData && this.allowAddToBatchGroup()) { - this.addToBatchGroup(); + this.addToBatchGroup(); } - } else { - this.removeFromBatchGroup(); - } + } else { + this.removeFromBatchGroup(); + } } } } @@ -80,7 +80,7 @@ export class BatchDraggableDirective implements OnInit, OnChanges, OnDestroy, Af restoreDragDataViewAfterViewInit() { const draggable = this.draggable; if (draggable.originPlaceholder && draggable.originPlaceholder.show !== false) { - draggable.insertOriginPlaceholder(true, false); + draggable.insertOriginPlaceholder(true, false); } draggable.el.nativeElement.style.display = 'none'; } @@ -99,7 +99,7 @@ export class BatchDraggableDirective implements OnInit, OnChanges, OnDestroy, Af dragData.dragData = this.draggable.dragData; this.dragData = dragData; } else { - this.dragData = this.dragData || { + this.dragData = this.dragData || { identity: this.draggable.dragIdentity || undefined, draggable: this.draggable, dragData: this.draggable.dragData diff --git a/devui/dragdrop/directives/drag-sync.directive.ts b/devui/dragdrop/directives/drag-sync.directive.ts index 4fbcb285..bd27d10b 100644 --- a/devui/dragdrop/directives/drag-sync.directive.ts +++ b/devui/dragdrop/directives/drag-sync.directive.ts @@ -50,7 +50,7 @@ export class DragSyncDirective extends DescendantChildren imp subDragElEvent = (bool: boolean) => { this.syncGroupDirectives.forEach(dir => this.renderDisplay(dir.el.nativeElement, bool)); - } + }; renderDisplay(nativeEl: HTMLElement, bool: boolean) { nativeEl.style.display = bool ? '' : 'none'; diff --git a/devui/dragdrop/directives/dragdrop-sync-box.directive.ts b/devui/dragdrop/directives/dragdrop-sync-box.directive.ts index c58da340..647ed440 100644 --- a/devui/dragdrop/directives/dragdrop-sync-box.directive.ts +++ b/devui/dragdrop/directives/dragdrop-sync-box.directive.ts @@ -24,7 +24,7 @@ export class DragDropSyncBoxDirective implements OnInit, AfterViewInit, OnDestro constructor(private dragDropSyncService: DragDropSyncService, private dragSyncDrs: DragSyncDescendantRegisterService, private dropSortSyncDrs: DropSortSyncDescendantRegisterService) { - } + } ngOnInit() { this.dragSyncList = new DescendantRoot(this.dragSyncDrs); diff --git a/devui/dragdrop/directives/draggable.directive.ts b/devui/dragdrop/directives/draggable.directive.ts index f77eaaa0..986e8f75 100755 --- a/devui/dragdrop/directives/draggable.directive.ts +++ b/devui/dragdrop/directives/draggable.directive.ts @@ -10,7 +10,7 @@ import { PreserveNextEventEmitter } from './../shared/preserve-next-event-emitte import { DragPreviewDirective } from './drag-preview.directive'; @Directive({ - selector: '[dDraggable]' + selector: '[dDraggable]' }) /** * Makes an element draggable by adding the draggable html attribute @@ -68,19 +68,19 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { @Output() dropEndEvent: PreserveNextEventEmitter = new PreserveNextEventEmitter(); @Input() public get disabled(): boolean { - return this._disabled; + return this._disabled; } public set disabled(value: boolean) { - this._disabled = value; - this.draggable = !this._disabled; + this._disabled = value; + this.draggable = !this._disabled; } private _disabled: boolean; @Input() enableDragFollow = false; // 默认false使用浏览器H5API拖拽, 否则使用原dom定位偏移 @Input() dragFollowOptions: { - appendToBody?: boolean; - }; + appendToBody?: boolean; + }; @Input() originPlaceholder: { show?: boolean; tag?: string; @@ -106,8 +106,8 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { constructor(public el: ElementRef, private renderer: Renderer2, private dragDropService: DragDropService, private ngZone: NgZone, @Optional() @Self() public dragPreviewDirective: DragPreviewDirective, @Inject(DOCUMENT) private doc: any - ) { - this.document = this.doc; + ) { + this.document = this.doc; } ngOnInit() { @@ -140,7 +140,7 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { this.dragDropService.draggedElIdentity = undefined; } this.dragDropService.subscription.unsubscribe(); - })).add( + })).add( this.dragDropService.dragElShowHideEvent.subscribe(this.dragElShowHideEvent) ); } @@ -150,7 +150,7 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { if (this.dragIdentity) { if (this.dragDropService.draggedEl && this.dragIdentity === this.dragDropService.draggedElIdentity) { if (this.originPlaceholder && this.originPlaceholder.show !== false) { - this.insertOriginPlaceholder(); + this.insertOriginPlaceholder(); } this.dragDropService.draggedEl = this.el.nativeElement; this.el.nativeElement.style.display = 'none'; // recovery don't need to emit event @@ -252,7 +252,7 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { if (this.dragDropService.batchDragging && this.dragDropService.batchDragData && this.dragDropService.batchDragData.length > 1) { this.dragDropService.batchDragData.map(dragData => dragData.draggable) - .filter(draggable => draggable && draggable !== this) + .filter(draggable => draggable && draggable !== this) .forEach((draggable) => { if (draggable.originPlaceholder && draggable.originPlaceholder.show !== false) { draggable.insertOriginPlaceholder(true, false); @@ -263,13 +263,13 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { }); } // Firefox requires setData() to be called otherwise the drag does not work. - if (e.dataTransfer != null) { - e.dataTransfer.setData('text', ''); + if (e.dataTransfer !== null) { + e.dataTransfer.setData('text', ''); } e.dataTransfer.effectAllowed = this.dragEffect; this.dropSubscription(); if (this.dragDropService.dragFollow) { - if ('function' === typeof DataTransfer.prototype.setDragImage) { + if (typeof DataTransfer.prototype.setDragImage === 'function') { e.dataTransfer.setDragImage(this.dragDropService.dragEmptyImage, 0 , 0); } else { e.srcElement.style.display = 'none'; @@ -298,7 +298,7 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { } if (this.dragDropService.batchDragging && this.dragDropService.batchDragData && this.dragDropService.batchDragData.length > 1) { this.dragDropService.batchDragData.map(dragData => dragData.draggable) - .filter(draggable => draggable && draggable !== this) + .filter(draggable => draggable && draggable !== this) .forEach((draggable) => { if (draggable.originPlaceholder && draggable.originPlaceholder.show !== false) { draggable.el.nativeElement.style.display = ''; @@ -338,9 +338,9 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { if (!this.draggable) { return false; } - if (this.batchDraggable && !this.batchDraggable.allowAddToBatchGroup()) { // 批量拖拽判断group是否相同 + if (this.batchDraggable && !this.batchDraggable.allowAddToBatchGroup()) { // 批量拖拽判断group是否相同 return false; - } + } if (this.dragHandle) { if (e && e.fromTouch) {return true; } // from touchstart dispatch event if (!this.mouseOverElement) { return false; } @@ -413,7 +413,7 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { this.dragOriginPlaceholder = node; this.dragOriginPlaceholderNextSibling = this.el.nativeElement.nextSibling; this.el.nativeElement.parentElement.insertBefore(node, this.el.nativeElement.nextSibling); - } + }; public removeOriginPlaceholder = (updateService = true) => { if (this.dragOriginPlaceholder) { @@ -425,7 +425,7 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { } this.dragOriginPlaceholder = undefined; this.dragOriginPlaceholderNextSibling = undefined; - } + }; public delayRemoveOriginPlaceholder = (updateService = true) => { const timeout = this.originPlaceholder.removeDelay; const delayOriginPlaceholder = this.dragOriginPlaceholder; @@ -462,7 +462,7 @@ export class DraggableDirective implements OnInit, AfterViewInit, OnDestroy { this.dragOriginPlaceholder = undefined; this.dragOriginPlaceholderNextSibling = undefined; }); - } + }; findNextSibling(currentNextSibling) { if (!this.dragDropService.batchDragData) { return currentNextSibling; diff --git a/devui/dragdrop/directives/drop-scroll-enhance.directive.ts b/devui/dragdrop/directives/drop-scroll-enhance.directive.ts index faeba053..3bcaaef6 100644 --- a/devui/dragdrop/directives/drop-scroll-enhance.directive.ts +++ b/devui/dragdrop/directives/drop-scroll-enhance.directive.ts @@ -77,39 +77,39 @@ export class DropScrollEnhancedDirective implements AfterViewInit, OnDestroy { // 滚动过程计算区域有效性,滚动条贴到边缘的时候无效,无效的时候设置鼠标事件可用为none this.subscription.add( fromEvent(this.el.nativeElement, 'scroll', {passive: true}) - .pipe(throttleTime(300, undefined, {leading: true, trailing: true})) - .subscribe(event => { - this.toggleScrollToOneEnd(this.el.nativeElement, this.forwardScrollArea, this.direction, DropScrollOrientation.forward); - this.toggleScrollToOneEnd(this.el.nativeElement, this.backwardScrollArea, this.direction, DropScrollOrientation.backward); - }) + .pipe(throttleTime(300, undefined, {leading: true, trailing: true})) + .subscribe(event => { + this.toggleScrollToOneEnd(this.el.nativeElement, this.forwardScrollArea, this.direction, DropScrollOrientation.forward); + this.toggleScrollToOneEnd(this.el.nativeElement, this.backwardScrollArea, this.direction, DropScrollOrientation.backward); + }) ); // 窗口缩放的时候重绘有效性区域 this.subscription.add( fromEvent(window, 'resize', {passive: true}) - .pipe(throttleTime(300, undefined, {leading: true, trailing: true})) - .subscribe(event => this.resizeArea()) + .pipe(throttleTime(300, undefined, {leading: true, trailing: true})) + .subscribe(event => this.resizeArea()) ); // dragstart的时候显示拖拽滚动边缘面板 this.subscription.add( this.dragDropService.dragStartEvent.subscribe(() => { - if (!this.allowScroll()) {return; } - this.zone.runOutsideAngular(() => { - setTimeout(() => { - // 立马出现会打断边缘元素的拖拽 - this.forwardScrollArea.style.display = 'block'; - this.backwardScrollArea.style.display = 'block'; - }); + if (!this.allowScroll()) {return; } + this.zone.runOutsideAngular(() => { + setTimeout(() => { + // 立马出现会打断边缘元素的拖拽 + this.forwardScrollArea.style.display = 'block'; + this.backwardScrollArea.style.display = 'block'; }); + }); }) ); // dragEnd或drop的时候结束了拖拽,滚动区域影藏起来 this.subscription.add( - mergeStatic(this.dragDropService.dragEndEvent, this.dragDropService.dropEvent) + mergeStatic(this.dragDropService.dragEndEvent, this.dragDropService.dropEvent) .subscribe(() => { this.forwardScrollArea.style.display = 'none'; this.backwardScrollArea.style.display = 'none'; this.lastScrollTime = undefined; - }) + }) ); }); setTimeout(() => { @@ -158,7 +158,7 @@ export class DropScrollEnhancedDirective implements AfterViewInit, OnDestroy { + (scrollElement.getBoundingClientRect())[rectWidthAttr] - scrollElement[offsetWidthAttr] + scrollElement[clientWidthAttr] - ) === scrollElement[scrollWidthAttr] + ) === scrollElement[scrollWidthAttr] && orientation === DropScrollOrientation.forward) ) { compareTarget.style.pointerEvents = 'none'; @@ -268,12 +268,12 @@ export class DropScrollEnhancedDirective implements AfterViewInit, OnDestroy { resizeArea() { [{area: this.forwardScrollArea, orientation: DropScrollOrientation.forward}, - {area: this.backwardScrollArea, orientation: DropScrollOrientation.backward} + {area: this.backwardScrollArea, orientation: DropScrollOrientation.backward} ] - .forEach(item => { - this.setAreaSize(item.area, this.direction, item.orientation); - this.setAreaStyleLayout(item.area, this.direction, item.orientation); - }); + .forEach(item => { + this.setAreaSize(item.area, this.direction, item.orientation); + this.setAreaStyleLayout(item.area, this.direction, item.orientation); + }); } toggleScrollToOneEnd(scrollElement: any, toggleElement: HTMLElement, direction: DropScrollDirection, orientation: DropScrollOrientation) { diff --git a/devui/dragdrop/directives/drop-sort-sync.directive.ts b/devui/dragdrop/directives/drop-sort-sync.directive.ts index 8f44fb41..a1602ea2 100644 --- a/devui/dragdrop/directives/drop-sort-sync.directive.ts +++ b/devui/dragdrop/directives/drop-sort-sync.directive.ts @@ -49,12 +49,12 @@ export class DropSortSyncDirective extends DescendantChildren { + subRenderEvent = (nativeStyle: {width: number; height: number}) => { this.syncGroupDirectives = this.dragDropSyncService.getDropSyncByGroup(this.dropSyncGroup).filter(directive => directive !== this); this.syncGroupDirectives.forEach(dir => { dir.renderPlaceholder(nativeStyle, this.droppable); }); - } + }; subInsertionEvent = (cmd: DragPlaceholderInsertionIndexEvent) => { this.syncGroupDirectives = this.dragDropSyncService.getDropSyncByGroup(this.dropSyncGroup).filter(directive => directive !== this); @@ -65,7 +65,7 @@ export class DropSortSyncDirective extends DescendantChildren = new EventEmitter(); + @Output() dragEnterEvent: EventEmitter = new EventEmitter(); - /** + /** * Event fired when an element is being dragged over a valid drop target */ - @Output() dragOverEvent: EventEmitter = new EventEmitter(); + @Output() dragOverEvent: EventEmitter = new EventEmitter(); - /** + /** * Event fired when a dragged element leaves a valid drop target. */ - @Output() dragLeaveEvent: EventEmitter = new EventEmitter(); + @Output() dragLeaveEvent: EventEmitter = new EventEmitter(); - /** + /** * Event fired when an element is dropped on a valid drop target. */ - @Output() dropEvent: EventEmitter = new EventEmitter(); // 注意使用了虚拟滚动后,DropEvent中的dragFromIndex无效 + @Output() dropEvent: EventEmitter = new EventEmitter(); // 注意使用了虚拟滚动后,DropEvent中的dragFromIndex无效 - /** + /** * CSS class applied on the draggable that is applied when the item is being dragged. */ - @Input() dragOverClass: string; + @Input() dragOverClass: string; - /** + /** * Defines compatible drag drop pairs. Values must match both in draggable and droppable.dropScope. */ - @Input() dropScope: string | Array = 'default'; + @Input() dropScope: string | Array = 'default'; - @Input() placeholderTag = 'div'; + @Input() placeholderTag = 'div'; - @Input() placeholderStyle: any = {backgroundColor: ['#859bff', `var(--devui-brand-foil, #859bff)`], opacity: '.4'}; + @Input() placeholderStyle: any = {backgroundColor: ['#859bff', `var(--devui-brand-foil, #859bff)`], opacity: '.4'}; - /** + /** * 设置placeholder的提示性文字,仅支持文本(安全起见) */ - @Input() placeholderText = ''; + @Input() placeholderText = ''; - /** + /** * 用于允许拖动到元素上,方便树形结构的拖动可以成为元素的子节点 */ - @Input() allowDropOnItem = false; + @Input() allowDropOnItem = false; - /** + /** * allowDropOnItem为true时,才有效,用于允许拖动到元素上后,被命中的元素增加样式 */ - @Input() dragOverItemClass: string; + @Input() dragOverItemClass: string; - /** + /** * 用于修正有内嵌列表后,父项高度被撑大,此处height,width为父项自己的高度(用于纵向拖动),宽度(用于横向拖动) * */ - @Input() nestingTargetRect: {height?: number, width?: number}; + @Input() nestingTargetRect: {height?: number; width?: number}; - /** + /** * 是否启用越过立即交换位置的算法, 不能与allowDropOnItem一起用,allowDropOnItem为true时,此规则无效 * */ - @Input() switchWhileCrossEdge = false; + @Input() switchWhileCrossEdge = false; - /** + /** * sortable的情况下,拖动到可以drop但不在sortContainer里的时候默认drop的位置 * */ - @Input() defaultDropPosition: 'closest' | 'before' | 'after' = 'closest'; + @Input() defaultDropPosition: 'closest' | 'before' | 'after' = 'closest'; - /** + /** * sortable的情况下,列表如果使用了virtual scroll等部分加载技术时候返回正确的dropIndex * */ - @Input() dropSortCountSelector: string; - @Input() dropSortVirtualScrollOption: { - totalLength?: number; - startIndex?: number; - // innerSortContainer?: HTMLElement | string; // 用于虚拟滚动列表结构发生内嵌 - }; - private dropFlag: DropIndexFlag; - - private sortContainer: any; - private sortDirection: 'v' | 'h'; - private sortDirectionZMode: boolean; - private placeholder: any; - - // 用于修复dragleave多次触发 - private dragCount = 0; - - private dropIndex = undefined; - - private dragStartSubscription: Subscription; - private dragEndSubscription: Subscription; - private dropEndSubscription: Subscription; - - // 记录上一次悬停的元素,用于对比悬停的元素等是否发生变化 - private overElement; - - private dragPartEventSub: Subscription; - private allowDropCache: boolean; - private dragElIndex; - /* 协同拖拽需要 */ - placeholderInsertionEvent = new Subject(); - placeholderRenderEvent = new Subject(); - document: Document; + @Input() dropSortCountSelector: string; + @Input() dropSortVirtualScrollOption: { + totalLength?: number; + startIndex?: number; + // innerSortContainer?: HTMLElement | string; // 用于虚拟滚动列表结构发生内嵌 + }; + private dropFlag: DropIndexFlag; + + private sortContainer: any; + private sortDirection: 'v' | 'h'; + private sortDirectionZMode: boolean; + private placeholder: any; + + // 用于修复dragleave多次触发 + private dragCount = 0; + + private dropIndex = undefined; + + private dragStartSubscription: Subscription; + private dragEndSubscription: Subscription; + private dropEndSubscription: Subscription; + + // 记录上一次悬停的元素,用于对比悬停的元素等是否发生变化 + private overElement; + + private dragPartEventSub: Subscription; + private allowDropCache: boolean; + private dragElIndex; + /* 协同拖拽需要 */ + placeholderInsertionEvent = new Subject(); + placeholderRenderEvent = new Subject(); + document: Document; + + constructor(protected el: ElementRef, private renderer: Renderer2, private dragDropService: DragDropService, private ngZone: NgZone, + @Inject(DOCUMENT) private doc: any) { + this.document = this.doc; + } - constructor(protected el: ElementRef, private renderer: Renderer2, private dragDropService: DragDropService, private ngZone: NgZone, - @Inject(DOCUMENT) private doc: any) { - this.document = this.doc; + ngOnInit() { + this.placeholder = this.document.createElement(this.placeholderTag); + this.placeholder.className = 'drag-placeholder'; + this.placeholder.innerText = this.placeholderText; + this.dragStartSubscription = this.dragDropService.dragStartEvent.subscribe(() => this.setPlaceholder()); + if (this.dragDropService.draggedEl) { + this.setPlaceholder(); // 虚拟滚动生成元素过程中 } - - ngOnInit() { - this.placeholder = this.document.createElement(this.placeholderTag); - this.placeholder.className = 'drag-placeholder'; - this.placeholder.innerText = this.placeholderText; - this.dragStartSubscription = this.dragDropService.dragStartEvent.subscribe(() => this.setPlaceholder()); + this.dropEndSubscription = this.dragDropService.dropEvent.subscribe(() => { if (this.dragDropService.draggedEl) { - this.setPlaceholder(); // 虚拟滚动生成元素过程中 - } - this.dropEndSubscription = this.dragDropService.dropEvent.subscribe(() => { - if (this.dragDropService.draggedEl) { - if (!this.dragDropService.dragFollow) { - this.renderer.setStyle(this.dragDropService.draggedEl, 'display', ''); - this.dragDropService.dragElShowHideEvent.next(true); - } + if (!this.dragDropService.dragFollow) { + this.renderer.setStyle(this.dragDropService.draggedEl, 'display', ''); + this.dragDropService.dragElShowHideEvent.next(true); } - this.removePlaceholder(); - this.overElement = undefined; - this.allowDropCache = undefined; - this.dragElIndex = undefined; - this.dropIndex = undefined; - }); - this.dragEndSubscription = this.dragDropService.dragEndEvent.subscribe(() => { - if (this.dragDropService.draggedEl) { - if (!this.dragDropService.dragFollow) { - this.renderer.setStyle(this.dragDropService.draggedEl, 'display', ''); - this.dragDropService.dragElShowHideEvent.next(true); - } + } + this.removePlaceholder(); + this.overElement = undefined; + this.allowDropCache = undefined; + this.dragElIndex = undefined; + this.dropIndex = undefined; + }); + this.dragEndSubscription = this.dragDropService.dragEndEvent.subscribe(() => { + if (this.dragDropService.draggedEl) { + if (!this.dragDropService.dragFollow) { + this.renderer.setStyle(this.dragDropService.draggedEl, 'display', ''); + this.dragDropService.dragElShowHideEvent.next(true); } - this.removePlaceholder(); - this.dragCount = 0; - this.overElement = undefined; - this.allowDropCache = undefined; - this.dragElIndex = undefined; - this.dropIndex = undefined; - }); - this.ngZone.runOutsideAngular (() => { - this.dragPartEventSub = new Subscription(); - this.dragPartEventSub.add(fromEvent(this.el.nativeElement, 'dragover') - .pipe( - filter(event => this.allowDrop(event)), - distinctUntilChanged((prev , current) => { - const bool = (prev.clientX === current.clientX && prev.clientY === current.clientY && prev.target === current.target); - if (bool) { current.preventDefault(); current.stopPropagation(); } - return bool; - }) - ) - .subscribe((event) => this.dragOver(event)) - ); - this.dragPartEventSub.add( - fromEvent(this.el.nativeElement, 'dragenter').subscribe((event) => this.dragEnter(event)) - ); - this.dragPartEventSub.add( - fromEvent(this.el.nativeElement, 'dragleave').subscribe((event) => this.dragLeave(event)) - ); - }); - } - - ngAfterViewInit() { - if (this.el.nativeElement.hasAttribute('d-sortable')) { - this.sortContainer = this.el.nativeElement; - } else { - this.sortContainer = this.el.nativeElement.querySelector('[d-sortable]'); } - this.sortDirection = this.sortContainer ? this.sortContainer.getAttribute('dsortable') || 'v' : 'v'; - this.sortDirectionZMode = this.sortContainer ? (this.sortContainer.getAttribute('d-sortable-zmode') === 'true' || false) : false; - } + this.removePlaceholder(); + this.dragCount = 0; + this.overElement = undefined; + this.allowDropCache = undefined; + this.dragElIndex = undefined; + this.dropIndex = undefined; + }); + this.ngZone.runOutsideAngular (() => { + this.dragPartEventSub = new Subscription(); + this.dragPartEventSub.add(fromEvent(this.el.nativeElement, 'dragover') + .pipe( + filter(event => this.allowDrop(event)), + distinctUntilChanged((prev , current) => { + const bool = (prev.clientX === current.clientX && prev.clientY === current.clientY && prev.target === current.target); + if (bool) { current.preventDefault(); current.stopPropagation(); } + return bool; + }) + ) + .subscribe((event) => this.dragOver(event)) + ); + this.dragPartEventSub.add( + fromEvent(this.el.nativeElement, 'dragenter').subscribe((event) => this.dragEnter(event)) + ); + this.dragPartEventSub.add( + fromEvent(this.el.nativeElement, 'dragleave').subscribe((event) => this.dragLeave(event)) + ); + }); + } - ngOnDestroy() { - this.dragStartSubscription.unsubscribe(); - this.dragEndSubscription.unsubscribe(); - this.dropEndSubscription.unsubscribe(); - if (this.dragPartEventSub) {this.dragPartEventSub.unsubscribe(); } + ngAfterViewInit() { + if (this.el.nativeElement.hasAttribute('d-sortable')) { + this.sortContainer = this.el.nativeElement; + } else { + this.sortContainer = this.el.nativeElement.querySelector('[d-sortable]'); } + this.sortDirection = this.sortContainer ? this.sortContainer.getAttribute('dsortable') || 'v' : 'v'; + this.sortDirectionZMode = this.sortContainer ? (this.sortContainer.getAttribute('d-sortable-zmode') === 'true' || false) : false; + } - dragEnter(e) { - this.dragCount++; - e.preventDefault(); // ie11 dragenter需要preventDefault否则dragover无效 - this.dragEnterEvent.emit(e); - } + ngOnDestroy() { + this.dragStartSubscription.unsubscribe(); + this.dragEndSubscription.unsubscribe(); + this.dropEndSubscription.unsubscribe(); + if (this.dragPartEventSub) {this.dragPartEventSub.unsubscribe(); } + } - dragOver(e) { - if (this.allowDrop(e)) { - if (this.dragDropService.dropTargets.indexOf(this.el) === -1) { - this.dragDropService.dropTargets.forEach(el => { - const placeHolderEl = el.nativeElement.querySelector('.drag-placeholder'); - if (placeHolderEl) { - placeHolderEl.parentElement.removeChild(placeHolderEl); - } - Utils.removeClass(el, this.dragOverClass); - this.removeDragoverItemClass(el.nativeElement); - }); - this.dragDropService.dropTargets = [this.el]; - this.overElement = undefined; // 否则会遇到上一次position= 这一次的然后不刷新和插入。 - } - Utils.addClass(this.el, this.dragOverClass); - const hitPlaceholder + dragEnter(e) { + this.dragCount++; + e.preventDefault(); // ie11 dragenter需要preventDefault否则dragover无效 + this.dragEnterEvent.emit(e); + } + + dragOver(e) { + if (this.allowDrop(e)) { + if (this.dragDropService.dropTargets.indexOf(this.el) === -1) { + this.dragDropService.dropTargets.forEach(el => { + const placeHolderEl = el.nativeElement.querySelector('.drag-placeholder'); + if (placeHolderEl) { + placeHolderEl.parentElement.removeChild(placeHolderEl); + } + Utils.removeClass(el, this.dragOverClass); + this.removeDragoverItemClass(el.nativeElement); + }); + this.dragDropService.dropTargets = [this.el]; + this.overElement = undefined; // 否则会遇到上一次position= 这一次的然后不刷新和插入。 + } + Utils.addClass(this.el, this.dragOverClass); + const hitPlaceholder = this.dragDropService.dragOriginPlaceholder && this.dragDropService.dragOriginPlaceholder.contains(e.target); - if (this.sortContainer && ( - (hitPlaceholder && this.overElement === undefined) + if (this.sortContainer && ( + (hitPlaceholder && this.overElement === undefined) || !(e.target.contains(this.placeholder) || hitPlaceholder) || (this.switchWhileCrossEdge && !this.placeholder.contains(e.target) && !hitPlaceholder) // 越边交换回折的情况需要重新计算 || (!this.sortContainer.contains(e.target) && this.defaultDropPosition === 'closest') // 就近模式需要重新计算 - )) { - const overElement = this.findSortableEl(e); - if (!(this.overElement && overElement) || this.overElement.index !== overElement.index + )) { + const overElement = this.findSortableEl(e); + if (!(this.overElement && overElement) || this.overElement.index !== overElement.index || (this.allowDropOnItem && this.overElement.position !== overElement.position && (this.overElement.position === 'inside' || overElement.position === 'inside')) - ) { - // overElement的参数有刷新的时候才进行插入等操作 - this.overElement = overElement; + ) { + // overElement的参数有刷新的时候才进行插入等操作 + this.overElement = overElement; - this.insertPlaceholder(overElement); + this.insertPlaceholder(overElement); - this.removeDragoverItemClass(this.sortContainer, overElement); - if (overElement.position === 'inside' && this.dragOverItemClass) { - Utils.addClass(overElement.el, this.dragOverItemClass); - } - } else { - this.overElement = overElement; + this.removeDragoverItemClass(this.sortContainer, overElement); + if (overElement.position === 'inside' && this.dragOverItemClass) { + Utils.addClass(overElement.el, this.dragOverItemClass); } } else { - if (this.sortContainer && this.overElement && this.overElement.el) { - if (!this.overElement.el.contains(e.target)) { - this.overElement.realEl = e.target; - } else { - this.overElement.realEl = undefined; - } - } + this.overElement = overElement; } - if (this.dragDropService.draggedEl) { - if (!this.dragDropService.dragFollow) { - this.renderer.setStyle(this.dragDropService.draggedEl, 'display', 'none'); - this.dragDropService.dragElShowHideEvent.next(false); - if (this.dragDropService.dragOriginPlaceholder) { - this.renderer.setStyle(this.dragDropService.dragOriginPlaceholder, 'display', 'block'); - } + } else { + if (this.sortContainer && this.overElement && this.overElement.el) { + if (!this.overElement.el.contains(e.target)) { + this.overElement.realEl = e.target; + } else { + this.overElement.realEl = undefined; } } - e.preventDefault(); - e.stopPropagation(); - this.dragOverEvent.emit(e); - } - } - - dragLeave(e) { - // 用于修复包含子元素时,多次触发dragleave - this.dragCount--; - - if (0 === this.dragCount) { - if (this.dragDropService.dropTargets.indexOf(this.el) !== -1) { - this.dragDropService.dropTargets = []; + } + if (this.dragDropService.draggedEl) { + if (!this.dragDropService.dragFollow) { + this.renderer.setStyle(this.dragDropService.draggedEl, 'display', 'none'); + this.dragDropService.dragElShowHideEvent.next(false); + if (this.dragDropService.dragOriginPlaceholder) { + this.renderer.setStyle(this.dragDropService.dragOriginPlaceholder, 'display', 'block'); + } } - Utils.removeClass(this.el, this.dragOverClass); - this.removePlaceholder(); - this.removeDragoverItemClass(this.el.nativeElement); - this.overElement = undefined; - this.dragElIndex = undefined; - this.dropIndex = undefined; } e.preventDefault(); - this.dragLeaveEvent.emit(e); + e.stopPropagation(); + this.dragOverEvent.emit(e); } + } - @HostListener('drop', ['$event']) - drop(e) { - if (!this.allowDrop(e)) { return; } - this.dragCount = 0; + dragLeave(e) { + // 用于修复包含子元素时,多次触发dragleave + this.dragCount--; + + if (this.dragCount === 0) { + if (this.dragDropService.dropTargets.indexOf(this.el) !== -1) { + this.dragDropService.dropTargets = []; + } Utils.removeClass(this.el, this.dragOverClass); - this.removeDragoverItemClass(this.sortContainer); this.removePlaceholder(); - e.preventDefault(); - e.stopPropagation(); - this.dragDropService.dropOnOrigin = this.isDragPlaceholderPosition(this.dropIndex); - const draggedElIdentity = this.dragDropService.draggedElIdentity; - this.dragDropService.draggedElIdentity = undefined; // 需要提前清除,避免新生成的节点复用了id 刷新了dragOriginPlaceholder - let batchDraggble: Array = []; - if (this.dragDropService.batchDragData && this.dragDropService.batchDragData.length > 1) { - batchDraggble = this.dragDropService.batchDragData.map(dragData => dragData.draggable) - .filter(draggable => draggable && draggable.el.nativeElement !== this.dragDropService.draggedEl); - } - this.dropEvent.emit( - new DropEvent( - e, - this.dragDropService.dragData, - this.dragDropService.dropEvent, - this.dropSortVirtualScrollOption ? this.getRealIndex(this.dropIndex, this.dropFlag) : this.dropIndex, - this.sortContainer ? this.checkSelfFromIndex(this.dragDropService.draggedEl) : -1, - this.dragDropService.dropOnItem, - this.dragDropService.dropOnOrigin, - (this.dragDropService.batchDragging) - ? this.dragDropService.getBatchDragData(draggedElIdentity) - : undefined - ) - ); - // 如果drop之后drag元素被删除,则不会发生dragend事件,需要代替dragend清理 - if (this.dragDropService.dragFollow) { - this.dragDropService.disableDraggedCloneNodeFollowMouse(); - } else { - this.renderer.setStyle(this.dragDropService.draggedEl, 'display', ''); - this.dragDropService.dragElShowHideEvent.next(false); - } - if (batchDraggble.length > 0 && this.dragDropService.batchDragging) { - batchDraggble.forEach((draggable) => { - if (!draggable.originPlaceholder || draggable.originPlaceholder.show === false) { - draggable.el.nativeElement.style.display = ''; - } else if (draggable.originPlaceholder.removeDelay > 0 && !this.dragDropService.dropOnOrigin) { - draggable.delayRemoveOriginPlaceholder(false); - } else { - draggable.el.nativeElement.style.display = ''; - draggable.removeOriginPlaceholder(false); - } - }); - } - this.dragDropService.dropEvent.next(e); - this.dragDropService.dragData = undefined; - this.dragDropService.scope = undefined; - this.dragDropService.draggedEl = undefined; - this.dragDropService.dragFollow = undefined; - this.dragDropService.dragFollowOptions = undefined; - this.dragDropService.dragOffset = undefined; - this.dragDropService.dropOnOrigin = undefined; - this.dragDropService.batchDragging = false; - this.dragDropService.batchDragStyle = undefined; - this.dragDropService.dragPreviewDirective = undefined; + this.removeDragoverItemClass(this.el.nativeElement); + this.overElement = undefined; + this.dragElIndex = undefined; + this.dropIndex = undefined; } + e.preventDefault(); + this.dragLeaveEvent.emit(e); + } + + @HostListener('drop', ['$event']) + drop(e) { + if (!this.allowDrop(e)) { return; } + this.dragCount = 0; + Utils.removeClass(this.el, this.dragOverClass); + this.removeDragoverItemClass(this.sortContainer); + this.removePlaceholder(); + e.preventDefault(); + e.stopPropagation(); + this.dragDropService.dropOnOrigin = this.isDragPlaceholderPosition(this.dropIndex); + const draggedElIdentity = this.dragDropService.draggedElIdentity; + this.dragDropService.draggedElIdentity = undefined; // 需要提前清除,避免新生成的节点复用了id 刷新了dragOriginPlaceholder + let batchDraggble: Array = []; + if (this.dragDropService.batchDragData && this.dragDropService.batchDragData.length > 1) { + batchDraggble = this.dragDropService.batchDragData.map(dragData => dragData.draggable) + .filter(draggable => draggable && draggable.el.nativeElement !== this.dragDropService.draggedEl); + } + this.dropEvent.emit( + new DropEvent( + e, + this.dragDropService.dragData, + this.dragDropService.dropEvent, + this.dropSortVirtualScrollOption ? this.getRealIndex(this.dropIndex, this.dropFlag) : this.dropIndex, + this.sortContainer ? this.checkSelfFromIndex(this.dragDropService.draggedEl) : -1, + this.dragDropService.dropOnItem, + this.dragDropService.dropOnOrigin, + (this.dragDropService.batchDragging) + ? this.dragDropService.getBatchDragData(draggedElIdentity) + : undefined + ) + ); + // 如果drop之后drag元素被删除,则不会发生dragend事件,需要代替dragend清理 + if (this.dragDropService.dragFollow) { + this.dragDropService.disableDraggedCloneNodeFollowMouse(); + } else { + this.renderer.setStyle(this.dragDropService.draggedEl, 'display', ''); + this.dragDropService.dragElShowHideEvent.next(false); + } + if (batchDraggble.length > 0 && this.dragDropService.batchDragging) { + batchDraggble.forEach((draggable) => { + if (!draggable.originPlaceholder || draggable.originPlaceholder.show === false) { + draggable.el.nativeElement.style.display = ''; + } else if (draggable.originPlaceholder.removeDelay > 0 && !this.dragDropService.dropOnOrigin) { + draggable.delayRemoveOriginPlaceholder(false); + } else { + draggable.el.nativeElement.style.display = ''; + draggable.removeOriginPlaceholder(false); + } + }); + } + this.dragDropService.dropEvent.next(e); + this.dragDropService.dragData = undefined; + this.dragDropService.scope = undefined; + this.dragDropService.draggedEl = undefined; + this.dragDropService.dragFollow = undefined; + this.dragDropService.dragFollowOptions = undefined; + this.dragDropService.dragOffset = undefined; + this.dragDropService.dropOnOrigin = undefined; + this.dragDropService.batchDragging = false; + this.dragDropService.batchDragStyle = undefined; + this.dragDropService.dragPreviewDirective = undefined; + } allowDrop(e): boolean { if (!e) { return false; } @@ -366,10 +366,10 @@ export class DroppableDirective implements OnInit, AfterViewInit, OnDestroy { let allowed = false; if (typeof this.dropScope === 'string') { if (typeof this.dragDropService.scope === 'string') { - allowed = this.dragDropService.scope === this.dropScope; + allowed = this.dragDropService.scope === this.dropScope; } if (this.dragDropService.scope instanceof Array) { - allowed = this.dragDropService.scope.indexOf(this.dropScope) > -1; + allowed = this.dragDropService.scope.indexOf(this.dropScope) > -1; } } if (this.dropScope instanceof Array) { @@ -390,9 +390,10 @@ export class DroppableDirective implements OnInit, AfterViewInit, OnDestroy { return Utils.matches(value, this.dropSortCountSelector) || value.contains(this.placeholder) || value === this.dragDropService.dragOriginPlaceholder; - } + }; // 查询需要插入placeholder的位置 + /* eslint-disable-next-line complexity*/ private findSortableEl(event) { const moveElement = event.target; let overElement = null; @@ -418,7 +419,7 @@ export class DroppableDirective implements OnInit, AfterViewInit, OnDestroy { ); } // 要先删除clonenode否则placeholderindex是错的 - if (this.dragDropService.dragFollow && this.dragDropService.dragCloneNode) { + if (this.dragDropService.dragFollow && this.dragDropService.dragCloneNode) { const cloneNodeIndex = childEls.findIndex(value => value === this.dragDropService.dragCloneNode); if (-1 !== cloneNodeIndex) { childEls.splice(cloneNodeIndex, 1); @@ -448,10 +449,10 @@ export class DroppableDirective implements OnInit, AfterViewInit, OnDestroy { } const positionIndex = -1 !== placeholderIndex ? placeholderIndex : this.dragElIndex; const currentIndex = childEls.findIndex(value => ( - value.contains(moveElement) + value.contains(moveElement) || value.nextElementSibling === moveElement && value.nextElementSibling.classList.contains('drag-origin-placeholder')) - ); + ); if (this.switchWhileCrossEdge && !this.allowDropOnItem && childEls.length && -1 !== positionIndex && currentIndex > -1 @@ -567,8 +568,8 @@ export class DroppableDirective implements OnInit, AfterViewInit, OnDestroy { }; const threeQuartersOfHeight = dropOnItemEdge.height * 3 / 4; const threeQuartersOfWidth = dropOnItemEdge.width * 3 / 4; - const AQuarterOfHeight = dropOnItemEdge.height * 1 / 4; - const AQuarterOfWidth = dropOnItemEdge.width * 1 / 4; + const AQuarterOfHeight = Number(dropOnItemEdge.height) / 4; + const AQuarterOfWidth = Number(dropOnItemEdge.width) / 4; if (this.sortDirectionZMode) { const slashPosition = (relY / dropOnItemEdge.height + relX / dropOnItemEdge.width); @@ -609,7 +610,7 @@ export class DroppableDirective implements OnInit, AfterViewInit, OnDestroy { return 'after'; } return 'before'; - } + } private calcPositionOutside(event: any, targetElement: any) { const rect = this.getBoundingRectAndRealPosition(targetElement); // targetElement.getBoundingClientRect(); @@ -638,7 +639,7 @@ export class DroppableDirective implements OnInit, AfterViewInit, OnDestroy { Utils.addElStyles(this.placeholder, this.placeholderStyle); this.placeholderRenderEvent.next({width: this.dragDropService.dragOffset.width, height: this.dragDropService.dragOffset.height}); }); - } + }; // 插入placeholder private insertPlaceholder(overElement) { @@ -655,7 +656,7 @@ export class DroppableDirective implements OnInit, AfterViewInit, OnDestroy { el => el !== this.dragDropService.dragCloneNode ); - if (null === overElement.el) { + if (overElement.el === null) { cmd = { command: 'append' }; diff --git a/devui/dragdrop/directives/sortable.directive.ts b/devui/dragdrop/directives/sortable.directive.ts index de224643..8720e2c8 100755 --- a/devui/dragdrop/directives/sortable.directive.ts +++ b/devui/dragdrop/directives/sortable.directive.ts @@ -1,7 +1,7 @@ import { Directive, ElementRef, HostBinding, Input } from '@angular/core'; @Directive({ - selector: '[dSortable]' + selector: '[dSortable]' }) /** * Makes an element draggable by adding the draggable html attribute diff --git a/devui/dragdrop/drag-drop.module.ts b/devui/dragdrop/drag-drop.module.ts index 2879f8d0..cd822e62 100755 --- a/devui/dragdrop/drag-drop.module.ts +++ b/devui/dragdrop/drag-drop.module.ts @@ -45,9 +45,9 @@ import { DragDropService } from './services/drag-drop.service'; DragPreviewCloneDomRefComponent, ], providers: [ - DragDropService + DragDropService ], - + }) export class DragDropModule { } diff --git a/devui/dragdrop/services/drag-drop-desc-reg.service.ts b/devui/dragdrop/services/drag-drop-desc-reg.service.ts index 0f6cdf1b..0b989308 100644 --- a/devui/dragdrop/services/drag-drop-desc-reg.service.ts +++ b/devui/dragdrop/services/drag-drop-desc-reg.service.ts @@ -31,7 +31,7 @@ export class DescendantRegisterService { } @Directive() -// tslint:disable-next-line +/* eslint-disable-next-line @angular-eslint/directive-class-suffix */ export class DescendantChildren implements OnInit, OnDestroy { constructor (private drs: DescendantRegisterService) {} protected descendantItem: T; diff --git a/devui/dragdrop/services/drag-drop.service.ts b/devui/dragdrop/services/drag-drop.service.ts index 8bb54a9f..322dba46 100755 --- a/devui/dragdrop/services/drag-drop.service.ts +++ b/devui/dragdrop/services/drag-drop.service.ts @@ -51,22 +51,24 @@ export class DragDropService { dragOriginPlaceholderNextSibling: any; touchInstance; - /*协同拖拽需要 */ + /* 协同拖拽需要 */ dragElShowHideEvent = new Subject(); dragSyncGroupDirectives; - /*预览功能 */ + /* 预览功能 */ dragPreviewDirective: DragPreviewDirective; document: Document; constructor(private ngZone: NgZone, @Inject(DOCUMENT) private doc: any) { this.touchInstance = DragDropTouch.getInstance(); // service not support OnInit, only support OnDestroy, so write in constructor - // tslint:disable-next-line: max-line-length - this.dragEmptyImage.src = 'data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=='; // safari的img必须要有src + // safari的img必须要有src + this.dragEmptyImage.src + = 'data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=='; this.document = this.doc; } newSubscription() { this.subscription.unsubscribe(); + // eslint-disable-next-line no-return-assign return this.subscription = new Subscription(); } @@ -119,7 +121,7 @@ export class DragDropService { /* 计数样式定位 */ if (this.batchDragStyle && this.batchDragStyle.length && this.batchDragStyle.indexOf('badge') > -1) { const badge = this.document.createElement('div'); - badge.innerText = this.batchDragData.length + ''; + badge.innerText = String(this.batchDragData.length); badge.classList.add('batch-dragged-node-count'); node.style.position = 'relative'; const style = { @@ -151,7 +153,7 @@ export class DragDropService { position: 'absolute', left: -5 * (i + 1) + 'px', top: -5 * (i + 1) + 'px', - zIndex: - (i + 1) + '', + zIndex: String(- (i + 1)), width: this.dragOffset.width + 'px', height: this.dragOffset.height + 'px', background: '#fff', @@ -238,7 +240,7 @@ export class DragDropService { this.dragCloneNode.style.left = clientX - offsetLeft + 'px'; this.dragCloneNode.style.top = clientY - offsetTop + 'px'; }); - } + }; getBatchDragData(identity?, order: ((a: any, b: any) => number) | 'select' | 'draggedElFirst' = 'draggedElFirst') { const result = this.batchDragData.map(dragData => dragData.dragData); @@ -266,7 +268,7 @@ export class DragDropService { this.batchDragData .filter(dragData => dragData.draggable) .map(dragData => dragData.draggable) - .forEach(draggable => draggable.batchDraggable.dragData = undefined); + .forEach(draggable => {draggable.batchDraggable.dragData = undefined;}); this.batchDragData = undefined; this.batchDragGroup = undefined; } diff --git a/devui/dragdrop/shared/preserve-next-event-emitter.ts b/devui/dragdrop/shared/preserve-next-event-emitter.ts index 39026e49..fa6c43c7 100644 --- a/devui/dragdrop/shared/preserve-next-event-emitter.ts +++ b/devui/dragdrop/shared/preserve-next-event-emitter.ts @@ -6,7 +6,7 @@ export class PreserveNextEventEmitter extends EventEmitter { private _isAsync: boolean; get schedulerFns() { return this._schedulerFns; } - constructor(isAsync: boolean = false) { + constructor(isAsync = false) { super(isAsync); this._isAsync = isAsync; } @@ -36,7 +36,7 @@ export class PreserveNextEventEmitter extends EventEmitter { } : (value: any) => { generatorOrNext.next(value); }; } else { schedulerFn = this._isAsync ? (value: any) => { setTimeout(() => generatorOrNext(value)); } : - (value: any) => { generatorOrNext(value); }; + (value: any) => { generatorOrNext(value); }; } if (!this._schedulerFns) { this._schedulerFns = new Set(); diff --git a/devui/dragdrop/shared/utils.ts b/devui/dragdrop/shared/utils.ts index b67aa801..58197b51 100755 --- a/devui/dragdrop/shared/utils.ts +++ b/devui/dragdrop/shared/utils.ts @@ -17,12 +17,12 @@ export class Utils { proto.oMatchesSelector || proto.webkitMatchesSelector || function (s) { - const matches = (this.document || this.ownerDocument).querySelectorAll(s); - let i = matches.length; - while (--i >= 0 && matches.item(i) !== this) { - // do nothing - } - return i > -1; + const matches = (this.document || this.ownerDocument).querySelectorAll(s); + let i = matches.length; + while (--i >= 0 && matches.item(i) !== this) { + // do nothing + } + return i > -1; }; return func.call(element, selectorName); @@ -52,7 +52,7 @@ export class Utils { const e = this.getElementWithValidClassList(elementRef); if (e) { - e.classList.remove(className); + e.classList.remove(className); } } @@ -66,7 +66,7 @@ export class Utils { const e = elementRef instanceof ElementRef ? elementRef.nativeElement : elementRef; if (e.classList !== undefined && e.classList !== null) { - return e; + return e; } return null; @@ -76,7 +76,7 @@ export class Utils { const ret = []; let len = args.length; - if (0 === len) { return ret; } + if (len === 0) { return ret; } const start = slice < 0 ? Math.max(0, slice + len) diff --git a/devui/dragdrop/touch-support/dragdrop-touch.ts b/devui/dragdrop/touch-support/dragdrop-touch.ts index fc59fc36..40e9c11c 100644 --- a/devui/dragdrop/touch-support/dragdrop-touch.ts +++ b/devui/dragdrop/touch-support/dragdrop-touch.ts @@ -26,7 +26,7 @@ export class DragDropTouch { lastTarget: HTMLElement; // touched draggble element dragSource: HTMLElement; - ptDown: {x: number, y: number}; + ptDown: {x: number; y: number}; isDragEnabled: boolean; isDropZone: boolean; pressHoldInterval; @@ -53,8 +53,8 @@ export class DragDropTouch { if (typeof document !== 'undefined') { document.addEventListener('test', () => {}, { get passive() { - supportsPassive = true; - return true; + supportsPassive = true; + return true; } }); // listen to touch events @@ -139,9 +139,9 @@ export class DragDropTouch { // raise double-click and prevent zooming if (Date.now() - this.lastClick < DragDropTouch.DBLCLICK) { if (this.dispatchEvent(e, 'dblclick', e.target)) { - e.preventDefault(); - this.reset(); - return; + e.preventDefault(); + this.reset(); + return; } } // clear all variables @@ -153,91 +153,91 @@ export class DragDropTouch { this.ptDown = this.getPoint(e); this.lastTouch = e; if (DragDropTouch.IS_PRESS_HOLD_MODE) { - this.pressHoldInterval = setTimeout(() => { - this.bindTouchmoveTouchend(e); - this.isDragEnabled = true; - this.touchmove(e); - }, DragDropTouch.PRESS_HOLD_AWAIT); - } else { - e.preventDefault(); + this.pressHoldInterval = setTimeout(() => { this.bindTouchmoveTouchend(e); + this.isDragEnabled = true; + this.touchmove(e); + }, DragDropTouch.PRESS_HOLD_AWAIT); + } else { + e.preventDefault(); + this.bindTouchmoveTouchend(e); } } } - } + }; touchmoveOnDocument = (e) => { if (this.shouldCancelPressHoldMove(e)) { this.reset(); return; } - } + }; touchmove = (e: TouchEvent) => { if (this.shouldCancelPressHoldMove(e)) { this.reset(); return; } if (this.shouldHandleMove(e) || this.shouldHandlePressHoldMove(e)) { - const target = this.getTarget(e); - // start dragging - if (this.dragSource && !this.img && this.shouldStartDragging(e)) { - this.dispatchEvent(e, 'dragstart', this.dragSource); - this.createImage(e); - } - // continue dragging - if (this.img) { - this.clearDragoverInterval(); - this.lastTouch = e; - e.preventDefault(); // prevent scrolling - if (target !== this.lastTarget) { - // according to drag drop implementation of the browser, dragenterB is supposed to fired before dragleaveA - this.dispatchEvent(e, 'dragenter', target); - this.dispatchEvent(this.lastTouch, 'dragleave', this.lastTarget); - this.lastTarget = target; - } - this.moveImage(e); - this.isDropZone = this.dispatchEvent(e, 'dragover', target); - // should continue dispatch dragover event when touch position stay still - this.setDragoverInterval(e); + const target = this.getTarget(e); + // start dragging + if (this.dragSource && !this.img && this.shouldStartDragging(e)) { + this.dispatchEvent(e, 'dragstart', this.dragSource); + this.createImage(e); + } + // continue dragging + if (this.img) { + this.clearDragoverInterval(); + this.lastTouch = e; + e.preventDefault(); // prevent scrolling + if (target !== this.lastTarget) { + // according to drag drop implementation of the browser, dragenterB is supposed to fired before dragleaveA + this.dispatchEvent(e, 'dragenter', target); + this.dispatchEvent(this.lastTouch, 'dragleave', this.lastTarget); + this.lastTarget = target; } + this.moveImage(e); + this.isDropZone = this.dispatchEvent(e, 'dragover', target); + // should continue dispatch dragover event when touch position stay still + this.setDragoverInterval(e); + } } - } + }; touchendOnDocument = (e) => { if (this.shouldHandle(e)) { if (!this.img) { - this.dragSource = null; - this.lastClick = Date.now(); + this.dragSource = null; + this.lastClick = Date.now(); } // finish dragging this.destroyImage(); if (this.dragSource) { - this.reset(); + this.reset(); } } - } + }; touchend = (e) => { if (this.shouldHandle(e)) { // user clicked the element but didn't drag, so clear the source and simulate a click if (!this.img) { - this.dragSource = null; - // browser will dispatch click event after trigger touchend, since touchstart didn't preventDefault - // this._dispatchEvent(this._lastTouch, 'click', e.target); - this.lastClick = Date.now(); + this.dragSource = null; + // browser will dispatch click event after trigger touchend, since touchstart didn't preventDefault + // this._dispatchEvent(this._lastTouch, 'click', e.target); + this.lastClick = Date.now(); } // finish dragging this.destroyImage(); if (this.dragSource) { - if (e.type.indexOf('cancel') < 0 && this.isDropZone) { - this.dispatchEvent(this.lastTouch, 'drop', this.lastTarget); - } - this.dispatchEvent(this.lastTouch, 'dragend', this.dragSource); - this.reset(); + if (e.type.indexOf('cancel') < 0 && this.isDropZone) { + this.dispatchEvent(this.lastTouch, 'drop', this.lastTarget); + } + this.dispatchEvent(this.lastTouch, 'dragend', this.dragSource); + this.reset(); } } - } + }; // ** utilities // ignore events that have been handled or that involve more than one touch shouldHandle(e) { - return e && + return e && !e.defaultPrevented && e.touches && e.touches.length < 2; } @@ -260,7 +260,7 @@ export class DragDropTouch { const dragHandleSelector = this.getDragHandle(); // start dragging when mouseover element matches drag handler selector if (dragHandleSelector && !this.matchSelector(e.target, dragHandleSelector)) { - return false; + return false; } // start dragging when specified delta is detected const delta = this.getDelta(e); @@ -335,25 +335,25 @@ export class DragDropTouch { } // create drag image from source element createImage(e) { - // just in case... - if (this.img) { + // just in case... + if (this.img) { this.destroyImage(); } // create drag image from custom element or drag source - const src = this.imgCustom || this.dragSource; - this.img = src.cloneNode(true); - this.copyStyle(src, this.img); - this.img.style.top = this.img.style.left = '-9999px'; + const src = this.imgCustom || this.dragSource; + this.img = src.cloneNode(true); + this.copyStyle(src, this.img); + this.img.style.top = this.img.style.left = '-9999px'; // if creating from drag source, apply offset and opacity - if (!this.imgCustom) { - const rc = src.getBoundingClientRect(); - const pt = this.getPoint(e); - this.imgOffset = { x: pt.x - rc.left, y: pt.y - rc.top }; - this.img.style.opacity = DragDropTouch.OPACITY.toString(); + if (!this.imgCustom) { + const rc = src.getBoundingClientRect(); + const pt = this.getPoint(e); + this.imgOffset = { x: pt.x - rc.left, y: pt.y - rc.top }; + this.img.style.opacity = DragDropTouch.OPACITY.toString(); } // add image to document - this.moveImage(e); - document.body.appendChild(this.img); + this.moveImage(e); + document.body.appendChild(this.img); } // dispose of drag image element destroyImage() { @@ -392,11 +392,11 @@ export class DragDropTouch { }); // copy canvas content if (src instanceof HTMLCanvasElement) { - const canSrc = src; - const canDst = dst; - canDst.width = canSrc.width; - canDst.height = canSrc.height; - canDst.getContext('2d').drawImage(canSrc, 0, 0); + const canSrc = src; + const canDst = dst; + canDst.width = canSrc.width; + canDst.height = canSrc.height; + canDst.getContext('2d').drawImage(canSrc, 0, 0); } // copy canvas content for nested canvas element const srcCanvases = src.querySelectorAll('canvas'); @@ -413,7 +413,7 @@ export class DragDropTouch { for (let i = 0; i < cs.length; i++) { const key = cs[i]; if (key.indexOf('transition') < 0) { - dst.style[key] = cs[key]; + dst.style[key] = cs[key]; } } dst.style.pointerEvents = 'none'; @@ -457,13 +457,13 @@ export class DragDropTouch { // repeat dispatch dragover event when touch point stay still setDragoverInterval(e) { this.dragoverTimer = setInterval(() => { - const target = this.getTarget(e); - if (target !== this.lastTarget) { - this.dispatchEvent(e, 'dragenter', target); - this.dispatchEvent(e, 'dragleave', this.lastTarget); - this.lastTarget = target; - } - this.isDropZone = this.dispatchEvent(e, 'dragover', target); + const target = this.getTarget(e); + if (target !== this.lastTarget) { + this.dispatchEvent(e, 'dragenter', target); + this.dispatchEvent(e, 'dragleave', this.lastTarget); + this.lastTarget = target; + } + this.isDropZone = this.dispatchEvent(e, 'dragover', target); }, DragDropTouch.DRAG_OVER_TIME); } clearDragoverInterval() { @@ -474,6 +474,7 @@ export class DragDropTouch { } } +/* eslint-disable-next-line @typescript-eslint/no-namespace */ export namespace DragDropTouch { /** * Object used to hold the data that is being dragged during drag and drop operations. @@ -536,9 +537,9 @@ export namespace DragDropTouch { */ clearData (type) { if (type !== null) { - delete this._data[type]; + delete this._data[type]; } else { - this._data = null; + this._data = null; } } /** @@ -571,9 +572,9 @@ export namespace DragDropTouch { * @param offsetY The vertical offset within the image. */ setDragImage (img, offsetX, offsetY) { - const ddt = DragDropTouch.getInstance(); - ddt.imgCustom = img; - ddt.imgOffset = { x: offsetX, y: offsetY }; + const ddt = DragDropTouch.getInstance(); + ddt.imgCustom = img; + ddt.imgOffset = { x: offsetX, y: offsetY }; } } diff --git a/devui/drawer/demo/drawer-demo.component.ts b/devui/drawer/demo/drawer-demo.component.ts index ededea5b..5120e4c6 100755 --- a/devui/drawer/demo/drawer-demo.component.ts +++ b/devui/drawer/demo/drawer-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'd-drawer-demo', diff --git a/devui/drawer/demo/drawer-demo.module.ts b/devui/drawer/demo/drawer-demo.module.ts index 091d9ea0..80a4ebb6 100755 --- a/devui/drawer/demo/drawer-demo.module.ts +++ b/devui/drawer/demo/drawer-demo.module.ts @@ -42,6 +42,6 @@ import { UndestroyableComponent } from './undestroyable/undestroyable.component' ], exports: [], declarations: [DrawerDemoComponent, BasicComponent, UndestroyableComponent, DrawerContentComponent, TemplateComponent], - + }) export class DrawerDemoModule {} diff --git a/devui/drawer/drawer.moudule.ts b/devui/drawer/drawer.moudule.ts index 79f75b1c..f7bf9925 100755 --- a/devui/drawer/drawer.moudule.ts +++ b/devui/drawer/drawer.moudule.ts @@ -19,7 +19,7 @@ import { DrawerService } from './drawer.service'; DrawerContentDirective ], providers: [DrawerService], - + }) export class DrawerModule { } diff --git a/devui/drawer/drawer.spec.ts b/devui/drawer/drawer.spec.ts index 027446d5..7c6eda4c 100644 --- a/devui/drawer/drawer.spec.ts +++ b/devui/drawer/drawer.spec.ts @@ -66,7 +66,7 @@ describe('Drawer', () => { declarations: [TestDrawerComponent, DrawerContentComponent] }).overrideModule(BrowserDynamicTestingModule, { set: { - + } }) .compileComponents(); diff --git a/devui/dropdown/demo/basic/basic.component.ts b/devui/dropdown/demo/basic/basic.component.ts index 6b41cff7..a6325f7b 100755 --- a/devui/dropdown/demo/basic/basic.component.ts +++ b/devui/dropdown/demo/basic/basic.component.ts @@ -15,6 +15,6 @@ export class BasicComponent implements OnInit { onToggle(event) { console.log(event); -} + } } diff --git a/devui/dropdown/demo/dropdown-demo.component.ts b/devui/dropdown/demo/dropdown-demo.component.ts index 862f594c..142f2046 100755 --- a/devui/dropdown/demo/dropdown-demo.component.ts +++ b/devui/dropdown/demo/dropdown-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/dropdown/demo/dropdown-demo.module.ts b/devui/dropdown/demo/dropdown-demo.module.ts index 6c972f04..c4353960 100755 --- a/devui/dropdown/demo/dropdown-demo.module.ts +++ b/devui/dropdown/demo/dropdown-demo.module.ts @@ -54,7 +54,7 @@ import { DropdownSetIsOpenComponent } from './set-is-open/dropdown-set-is-open.c DropDownDemoManuallyComponent, DropdownSetIsOpenComponent, ], - + }) export class DropdownDemoModule { } diff --git a/devui/dropdown/demo/hover/hover.component.ts b/devui/dropdown/demo/hover/hover.component.ts index f5b90bd0..95ea2aae 100755 --- a/devui/dropdown/demo/hover/hover.component.ts +++ b/devui/dropdown/demo/hover/hover.component.ts @@ -7,7 +7,7 @@ import { Component } from '@angular/core'; }) export class DropDownDemoHoverComponent { - onToggle(event) { - console.log(event); - } + onToggle(event) { + console.log(event); + } } diff --git a/devui/dropdown/dropdown-menu.directive.ts b/devui/dropdown/dropdown-menu.directive.ts index 826721fd..a034d1cb 100755 --- a/devui/dropdown/dropdown-menu.directive.ts +++ b/devui/dropdown/dropdown-menu.directive.ts @@ -144,41 +144,41 @@ export class DropDownMenuDirective implements OnInit, OnDestroy { private fadeIn(direction): AnimationMetadata[] { switch (direction) { - case 'top': - return [ - style({transform: 'scaleY(0.8) translateY(4px)', opacity: 0.8, transformOrigin: '0% 100%'}), - animate(`200ms ${AnimationCurves.EASE_IN}`, - style({transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 100%'})), - ]; - case 'bottom': - default: - return [ - style({transform: 'scaleY(0.8) translateY(-4px)', opacity: 0.8, transformOrigin: '0% 0%'}), - animate(`200ms ${AnimationCurves.EASE_OUT}`, - style({transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 0%'})), - ]; + case 'top': + return [ + style({transform: 'scaleY(0.8) translateY(4px)', opacity: 0.8, transformOrigin: '0% 100%'}), + animate(`200ms ${AnimationCurves.EASE_IN}`, + style({transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 100%'})), + ]; + case 'bottom': + default: + return [ + style({transform: 'scaleY(0.8) translateY(-4px)', opacity: 0.8, transformOrigin: '0% 0%'}), + animate(`200ms ${AnimationCurves.EASE_OUT}`, + style({transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 0%'})), + ]; } } public hide = (event: Event) => { this.dropdown.toggle(); - } + }; private fadeOut(direction): AnimationMetadata[] { switch (direction) { - case 'top': - return [ - style({transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 100%'}), - animate(`${AnimationDuration.BASE} ${AnimationCurves.EASE_IN}`, - style({transform: 'scaleY(0.8) translateY(4px)', opacity: 0.8, transformOrigin: '0% 100%'})) - ]; - case 'bottom': - default: - return [ - style({transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 0%'}), - animate(`${AnimationDuration.BASE} ${AnimationCurves.EASE_IN}`, - style({transform: 'scaleY(0.8) translateY(-4px)', opacity: 0.8, transformOrigin: '0% 0%'})) - ]; + case 'top': + return [ + style({transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 100%'}), + animate(`${AnimationDuration.BASE} ${AnimationCurves.EASE_IN}`, + style({transform: 'scaleY(0.8) translateY(4px)', opacity: 0.8, transformOrigin: '0% 100%'})) + ]; + case 'bottom': + default: + return [ + style({transform: 'scaleY(0.9999) translateY(0)', opacity: 1, transformOrigin: '0% 0%'}), + animate(`${AnimationDuration.BASE} ${AnimationCurves.EASE_IN}`, + style({transform: 'scaleY(0.8) translateY(-4px)', opacity: 0.8, transformOrigin: '0% 0%'})) + ]; } } } diff --git a/devui/dropdown/dropdown.component.ts b/devui/dropdown/dropdown.component.ts index 017c10f3..041fe804 100755 --- a/devui/dropdown/dropdown.component.ts +++ b/devui/dropdown/dropdown.component.ts @@ -6,6 +6,7 @@ import { AppendToBodyDirection, AppendToBodyDirectionsConfig, fadeInOut } from ' import { DropDownDirective } from './dropdown.directive'; @Component({ + /* eslint-disable-next-line @angular-eslint/component-selector*/ selector: '[dDropDown][appendToBody]', template: ` @@ -86,12 +87,12 @@ export class DropDownAppendToBodyComponent implements OnInit, OnChanges { onPositionChange(position: ConnectedOverlayPositionChange) { switch (position.connectionPair.overlayY) { - case 'top': - case 'center': - this.menuPosition = 'bottom'; - break; - case 'bottom': - this.menuPosition = 'top'; + case 'top': + case 'center': + this.menuPosition = 'bottom'; + break; + case 'bottom': + this.menuPosition = 'top'; } } } diff --git a/devui/dropdown/dropdown.directive.ts b/devui/dropdown/dropdown.directive.ts index 0fca4357..7017fbb2 100755 --- a/devui/dropdown/dropdown.directive.ts +++ b/devui/dropdown/dropdown.directive.ts @@ -107,9 +107,9 @@ export class DropDownDirective implements OnDestroy, OnChanges, AfterContentInit private devConfigService: DevConfigService, @Optional() @SkipSelf() public parentDropdown: DropDownDirective, @Inject(DOCUMENT) private doc: any - ) { - this.document = this.doc; - } + ) { + this.document = this.doc; + } ngOnChanges(changes: SimpleChanges) { if (changes.hasOwnProperty('trigger')) { @@ -127,6 +127,7 @@ export class DropDownDirective implements OnDestroy, OnChanges, AfterContentInit } public toggle(): boolean { + // eslint-disable-next-line no-return-assign return this.isOpen = !this.isOpen; } @@ -147,7 +148,7 @@ export class DropDownDirective implements OnDestroy, OnChanges, AfterContentInit } subscribeHoverAction(observable: Observable): void { - if (!!!this.hoverSubscription) { + if (!this.hoverSubscription) { this.hoverSubscription = observable.pipe( debounceTime(50), ).subscribe(isOpen => { diff --git a/devui/dropdown/dropdown.moudule.ts b/devui/dropdown/dropdown.moudule.ts index 7bce9794..71b9f9f2 100755 --- a/devui/dropdown/dropdown.moudule.ts +++ b/devui/dropdown/dropdown.moudule.ts @@ -25,7 +25,7 @@ import { DropDownDirective } from './dropdown.directive'; DropDownToggleDirective, DropDownAppendToBodyComponent ], - + }) export class DropDownModule { } diff --git a/devui/dropdown/dropdown.spec.ts b/devui/dropdown/dropdown.spec.ts index 85fa2b37..eb168da4 100644 --- a/devui/dropdown/dropdown.spec.ts +++ b/devui/dropdown/dropdown.spec.ts @@ -51,7 +51,7 @@ import { DropDownModule } from './dropdown.moudule';
打开/关闭
`, -styles: [` + styles: [` .height-expand { height: calc( 100vh - 100px)} `] }) @@ -99,7 +99,7 @@ class TestDropdownComponent {
`, - styles: [` + styles: [` .area { width: 500px; height: 600px; @@ -622,7 +622,7 @@ describe('dropdown', () => { fixture.detectChanges(); dropdownToggleElement = debugEl.query(By.directive(DropDownToggleDirective)); expect(document.activeElement).toEqual(dropdownToggleElement.nativeElement); - })); + })); }); describe('dropdownToggle autoFocus combine toggleOnFocus', () => { // 并发会有问题,目前屏蔽 diff --git a/devui/editable-select/demo/disable-data/disable-data-with-source.component.ts b/devui/editable-select/demo/disable-data/disable-data-with-source.component.ts index e4f7843a..37541b69 100644 --- a/devui/editable-select/demo/disable-data/disable-data-with-source.component.ts +++ b/devui/editable-select/demo/disable-data/disable-data-with-source.component.ts @@ -20,7 +20,7 @@ export class DisableDataWithSourceComponent implements OnInit { loading3 = false; languages = ['C#', 'C', 'C++', 'CPython', 'Java', 'JavaScript', 'Go', 'Python', 'Ruby', 'F#', 'TypeScript', 'SQL', - 'LiveScript', 'CoffeeScript'].map(item => { + 'LiveScript', 'CoffeeScript'].map(item => { const newItem = {label: item}; if (item.indexOf('Script') !== -1) { newItem['disabled'] = true; diff --git a/devui/editable-select/demo/editable-select-demo.component.ts b/devui/editable-select/demo/editable-select-demo.component.ts index 7e610239..b4aacd8c 100755 --- a/devui/editable-select/demo/editable-select-demo.component.ts +++ b/devui/editable-select/demo/editable-select-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox/devui-source-data'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'd-editable-select-demo', diff --git a/devui/editable-select/demo/editable-select-demo.module.ts b/devui/editable-select/demo/editable-select-demo.module.ts index 380d8373..f2cf1fec 100755 --- a/devui/editable-select/demo/editable-select-demo.module.ts +++ b/devui/editable-select/demo/editable-select-demo.module.ts @@ -51,6 +51,6 @@ import { WithSearchFunctionComponent } from './search-function/with-search-funct LazyLoadComponent, ], providers: [], - + }) export class EditableSelectDemoModule {} diff --git a/devui/editable-select/demo/lazy-load/lazy-load.component.ts b/devui/editable-select/demo/lazy-load/lazy-load.component.ts index de09fbf8..1a5b7036 100644 --- a/devui/editable-select/demo/lazy-load/lazy-load.component.ts +++ b/devui/editable-select/demo/lazy-load/lazy-load.component.ts @@ -1,33 +1,33 @@ import { - Component, - OnInit + Component, + OnInit } from '@angular/core'; @Component({ - selector: 'd-lazy-load', - templateUrl: './lazy-load.component.html', - styles: [ - ` + selector: 'd-lazy-load', + templateUrl: './lazy-load.component.html', + styles: [ + ` section { width: 50%; } ` - ] + ] }) export class LazyLoadComponent implements OnInit { - selectItem; - count = 0; - languages = ['C#', 'C', 'C++', 'CPython', 'Java', 'JavaScript', 'Go', 'Python', 'Ruby', 'F#', 'TypeScript', 'SQL', - 'LiveScript', 'CoffeeScript']; + selectItem; + count = 0; + languages = ['C#', 'C', 'C++', 'CPython', 'Java', 'JavaScript', 'Go', 'Python', 'Ruby', 'F#', 'TypeScript', 'SQL', + 'LiveScript', 'CoffeeScript']; - constructor() { } - loadMore($event) { - this.count = this.count + 1; - this.languages = Object.assign([], [...this.languages, 'lazyLoadData' + this.count]); - setTimeout(() => { - $event.loadFinish(); - }, 2000); - } - ngOnInit() { - } + constructor() { } + loadMore($event) { + this.count = this.count + 1; + this.languages = Object.assign([], [...this.languages, 'lazyLoadData' + this.count]); + setTimeout(() => { + $event.loadFinish(); + }, 2000); + } + ngOnInit() { + } } diff --git a/devui/editable-select/demo/search-function/with-search-function.component.ts b/devui/editable-select/demo/search-function/with-search-function.component.ts index 18ce3980..47315a31 100644 --- a/devui/editable-select/demo/search-function/with-search-function.component.ts +++ b/devui/editable-select/demo/search-function/with-search-function.component.ts @@ -29,6 +29,6 @@ export class WithSearchFunctionComponent implements OnInit { onSearchLocal = (term) => { return of(this.languages.filter(lang => lang.toLowerCase().indexOf(term.toLowerCase()) !== -1)); - } + }; } diff --git a/devui/editable-select/editable-select.component.ts b/devui/editable-select/editable-select.component.ts index 7e037f71..680a6d04 100755 --- a/devui/editable-select/editable-select.component.ts +++ b/devui/editable-select/editable-select.component.ts @@ -139,6 +139,7 @@ export class EditableSelectComponent implements ControlValueAccessor, OnInit, On toggle($event: Event) { const inputString = typeof this.inputValue === 'object' ? this.inputValue.label : this.inputValue || ''; this.activeIndex = this.source + /* eslint-disable-next-line array-callback-return*/ .map((item) => { if (typeof item === 'string') { return item.toLowerCase(); diff --git a/devui/editable-select/editable-select.module.ts b/devui/editable-select/editable-select.module.ts index 3cc7145e..af6a1399 100755 --- a/devui/editable-select/editable-select.module.ts +++ b/devui/editable-select/editable-select.module.ts @@ -9,7 +9,7 @@ import { EditableSelectComponent } from './editable-select.component'; imports: [CommonModule, FormsModule, AutoCompleteModule, PositioningModule], exports: [EditableSelectComponent], declarations: [EditableSelectComponent], - + }) export class EditableSelectModule { } diff --git a/devui/form/demo/form-demo.component.ts b/devui/form/demo/form-demo.component.ts index b669ee57..ca1da5e1 100644 --- a/devui/form/demo/form-demo.component.ts +++ b/devui/form/demo/form-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox/devui-source-data'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/form/demo/form-demo.module.ts b/devui/form/demo/form-demo.module.ts index 4ffa0324..21cd00dd 100644 --- a/devui/form/demo/form-demo.module.ts +++ b/devui/form/demo/form-demo.module.ts @@ -121,6 +121,6 @@ import { ValidateUpdateComponent } from './validate-update/validate-update.compo DebounceTimeComponent, ValidateUpdateComponent, ], - + }) export class FormDemoModule {} diff --git a/devui/form/demo/label-horizontal/label-horizontal.component.ts b/devui/form/demo/label-horizontal/label-horizontal.component.ts index d391aefe..8ca78b05 100644 --- a/devui/form/demo/label-horizontal/label-horizontal.component.ts +++ b/devui/form/demo/label-horizontal/label-horizontal.component.ts @@ -3,8 +3,8 @@ import { FormLayout } from 'ng-devui/form'; @Component({ selector: 'd-form-demo-label-horizontal', -templateUrl: './label-horizontal.component.html', -styleUrls: ['./label-horizontal.component.css'] + templateUrl: './label-horizontal.component.html', + styleUrls: ['./label-horizontal.component.css'] }) export class LabelHorizontalComponent implements OnInit { @@ -104,6 +104,6 @@ export class LabelHorizontalComponent implements OnInit { multiple: 'true', labelization: {enable: true, labelMaxWidth: '120px'}, options: this.selectOptions - }; + }; } } diff --git a/devui/form/demo/validate-cross-component/child-control/child-user.component.ts b/devui/form/demo/validate-cross-component/child-control/child-user.component.ts index a074642a..a498d7af 100644 --- a/devui/form/demo/validate-cross-component/child-control/child-user.component.ts +++ b/devui/form/demo/validate-cross-component/child-control/child-user.component.ts @@ -2,7 +2,7 @@ import { Component, Input } from '@angular/core'; import { DValidateRules } from 'ng-devui/form'; @Component({ - selector: 'child-user', + selector: 'd-child-user', templateUrl: './child-user.component.html' }) export class ChildUserComponent { diff --git a/devui/form/demo/validate-cross-component/validate-cross-component.component.html b/devui/form/demo/validate-cross-component/validate-cross-component.component.html index b8bb6aec..87ccfe9a 100644 --- a/devui/form/demo/validate-cross-component/validate-cross-component.component.html +++ b/devui/form/demo/validate-cross-component/validate-cross-component.component.html @@ -25,7 +25,7 @@ Sub-user - + diff --git a/devui/form/demo/validate-template/user-register/user-register.component.ts b/devui/form/demo/validate-template/user-register/user-register.component.ts index 52283570..3665639b 100644 --- a/devui/form/demo/validate-template/user-register/user-register.component.ts +++ b/devui/form/demo/validate-template/user-register/user-register.component.ts @@ -37,7 +37,7 @@ export class UserRegisterComponent { 'zh-cn': '用户名重名', 'en-us': 'Duplicate name.' } - }], + }], }, passwordRules: { validators: [{ required: true }, { minlength: 6 }, { maxlength: 15 }, { pattern: /^[a-zA-Z0-9]+(\s+[a-zA-Z0-9]+)*$/ }], diff --git a/devui/form/demo/validate-template/validate-cross-component/child-form/child-form.component.ts b/devui/form/demo/validate-template/validate-cross-component/child-form/child-form.component.ts index ff49688c..8024294d 100644 --- a/devui/form/demo/validate-template/validate-cross-component/child-form/child-form.component.ts +++ b/devui/form/demo/validate-template/validate-cross-component/child-form/child-form.component.ts @@ -4,7 +4,7 @@ import { ControlContainer, NgForm } from '@angular/forms'; export const formInjectFactory = (form: NgForm) => form; @Component({ - selector: 'child-form-group', + selector: 'd-child-form-group', templateUrl: './child-form.component.html', viewProviders: [ { provide: ControlContainer, useExisting: NgForm }] // Inject the parent form. /* If you are not sure whether the upper-layer NgForm dependency exists, diff --git a/devui/form/demo/validate-template/validate-cross-component/validate-cross-component.component.html b/devui/form/demo/validate-template/validate-cross-component/validate-cross-component.component.html index b99893bc..a0016722 100644 --- a/devui/form/demo/validate-template/validate-cross-component/validate-cross-component.component.html +++ b/devui/form/demo/validate-template/validate-cross-component/validate-cross-component.component.html @@ -18,7 +18,7 @@ Sub User Group - + diff --git a/devui/form/demo/validate-template/validate-template-form/validate-template-form.component.html b/devui/form/demo/validate-template/validate-template-form/validate-template-form.component.html index 6c3cdd04..8cadd933 100644 --- a/devui/form/demo/validate-template/validate-template-form/validate-template-form.component.html +++ b/devui/form/demo/validate-template/validate-template-form/validate-template-form.component.html @@ -35,6 +35,7 @@ placeholder="Description" [(ngModel)]="planFormData.planDescription" [dValidateRules]="[{ maxlength: 256 }]" + style="height: 80px" > diff --git a/devui/form/form-label.component.ts b/devui/form/form-label.component.ts index c928f118..1b57498d 100644 --- a/devui/form/form-label.component.ts +++ b/devui/form/form-label.component.ts @@ -1,39 +1,39 @@ import { - ChangeDetectorRef, - Component, - ElementRef, - HostBinding, - Input, Renderer2 - } from '@angular/core'; + ChangeDetectorRef, + Component, + ElementRef, + HostBinding, + Input, Renderer2 +} from '@angular/core'; import { DFormControlStatus } from './validator-directive/validate.type'; @Component({ - selector: 'd-form-label', - templateUrl: './form-label.component.html', - styleUrls: ['./form-label.component.scss'], - preserveWhitespaces: false - }) - export class FormLabelComponent { - @Input() required = false; - @Input() hasHelp = false; - @Input() helpTips = ''; + selector: 'd-form-label', + templateUrl: './form-label.component.html', + styleUrls: ['./form-label.component.scss'], + preserveWhitespaces: false +}) +export class FormLabelComponent { + @Input() required = false; + @Input() hasHelp = false; + @Input() helpTips = ''; - feedbackStatus: DFormControlStatus | null = null; + feedbackStatus: DFormControlStatus | null = null; - @HostBinding('class.devui-form-label-has-feedback') get status() { - return this.feedbackStatus !== null; - } + @HostBinding('class.devui-form-label-has-feedback') get status() { + return this.feedbackStatus !== null; + } - constructor( - private cdr: ChangeDetectorRef, - elementRef: ElementRef, - renderer: Renderer2 - ) { - renderer.addClass(elementRef.nativeElement, 'devui-form-label'); - } + constructor( + private cdr: ChangeDetectorRef, + elementRef: ElementRef, + renderer: Renderer2 + ) { + renderer.addClass(elementRef.nativeElement, 'devui-form-label'); + } - public updateFeedbackStatus(status: DFormControlStatus | null): void { - this.feedbackStatus = status; - this.cdr.detectChanges(); - } + public updateFeedbackStatus(status: DFormControlStatus | null): void { + this.feedbackStatus = status; + this.cdr.detectChanges(); } +} diff --git a/devui/form/validator-directive/form-control-rules.directive.ts b/devui/form/validator-directive/form-control-rules.directive.ts index 2b2742fb..42efabae 100644 --- a/devui/form/validator-directive/form-control-rules.directive.ts +++ b/devui/form/validator-directive/form-control-rules.directive.ts @@ -455,7 +455,7 @@ const dControlErrorStatusHost = { @Directive({ selector: `[dValidateRules][formGroupName],[dValidateRules][formArrayName],[dValidateRules][ngModelGroup], [dValidateRules][formGroup],[dValidateRules]form:not([ngNoForm]),[dValidateRules][ngForm]`, - // tslint:disable-next-line: no-host-metadata-property + /* eslint-disable-next-line @angular-eslint/no-host-metadata-property*/ host: dControlErrorStatusHost, exportAs: 'dValidateRules', }) @@ -500,7 +500,7 @@ export class DFormGroupRuleDirective extends DAbstractControlRuleDirective imple @Directive({ selector: '[dValidateRules][formControlName],[dValidateRules][ngModel],[dValidateRules][formControl]', - // tslint:disable-next-line: no-host-metadata-property + /* eslint-disable-next-line @angular-eslint/no-host-metadata-property*/ host: dControlErrorStatusHost, exportAs: 'dValidateRules', }) @@ -523,13 +523,13 @@ export class DFormControlRuleDirective extends DAbstractControlRuleDirective imp } constructor( - @Self() cd: NgControl, - @Optional() @Host() private dFormItem: FormItemComponent, - @Optional() @Host() @SkipSelf() parentDir: DFormGroupRuleDirective, - private i18n: I18nService, - public triggerElementRef: ElementRef, - private overlayContainerRef: OverlayContainerRef, - private componentFactoryResolver: ComponentFactoryResolver + @Self() cd: NgControl, + @Optional() @Host() private dFormItem: FormItemComponent, + @Optional() @Host() @SkipSelf() parentDir: DFormGroupRuleDirective, + private i18n: I18nService, + public triggerElementRef: ElementRef, + private overlayContainerRef: OverlayContainerRef, + private componentFactoryResolver: ComponentFactoryResolver ) { super(cd, parentDir); } @@ -580,8 +580,8 @@ export class DFormControlRuleDirective extends DAbstractControlRuleDirective imp } updateStatusAndMessageToView(status: any): void { - let controlStatus = null, - message = null; + let controlStatus = null; + let message = null; if (this.showStatus) { [controlStatus, message] = this.getFormControlStatusAndMessage(status); } diff --git a/devui/form/validator-directive/validate.type.ts b/devui/form/validator-directive/validate.type.ts index 10640f5d..dcb7897a 100644 --- a/devui/form/validator-directive/validate.type.ts +++ b/devui/form/validator-directive/validate.type.ts @@ -2,45 +2,18 @@ import { AsyncValidatorFn, ValidatorFn, Validators } from '@angular/forms'; import { Observable } from 'rxjs'; import { DValidators } from './validators'; -// TODO: 还需提供一个debounceTime -export type DValidateRules = - | { - validators?: DValidateRule[]; - asyncValidators?: DAsyncValidateRule[]; - asyncDebounceTime?: number; // 异步校验器debounceTime - errorStrategy?: DValidationErrorStrategy; // error更新策略 - message?: string | { [key: string]: string }; // 统一配置的message - updateOn?: 'change' | 'blur' | 'submit'; // model更新策略 - messageShowType?: 'popover' | 'text' | 'none'; // 消息自动显示策略(当前仅单个表单组件下生效),自身附着popover | form-control下显示 | 不显示, - popPosition?: - | 'left' - | 'right' - | 'top' - | 'bottom' - | 'bottom-left' - | 'bottom-right' - | 'top-left' - | 'top-right' - | 'left-top' - | 'left-bottom' - | 'right-top' - | 'right-bottom' - | ( - | 'left' - | 'right' - | 'top' - | 'bottom' - | 'bottom-left' - | 'bottom-right' - | 'top-left' - | 'top-right' - | 'left-top' - | 'left-bottom' - | 'right-top' - | 'right-bottom' - )[]; - } - | DValidateRule[]; +/* pristine: 抛出error包括pristine状态 + ** dirty: 抛出error需在dirty状态 + */ +export type DValidationErrorStrategy = 'pristine' | 'dirty'; + +export type DFormControlStatus = 'error' | 'pending' | 'success'; + +// DForm ValidatorFn +export type DValidatorFn = (value: any) => boolean | string | { [key: string]: string } | null; + +// DForm AsyncValidatorFn +export type DAsyncValidatorFn = (value: any) => Observable; /* id: 自定义验证器必须具有(也可不必) ** validator: 自定义验证器必须传入,可支持函数与正则类型,函数必须返回true或false @@ -70,17 +43,53 @@ export interface DAsyncValidateRule { [id: string]: boolean | number | string | { [key: string]: string } | RegExp | DAsyncValidatorFn | AsyncValidatorFn | undefined; // 万能key } +// TODO: 还需提供一个debounceTime +export type DValidateRules = + | { + validators?: DValidateRule[]; + asyncValidators?: DAsyncValidateRule[]; + asyncDebounceTime?: number; // 异步校验器debounceTime + errorStrategy?: DValidationErrorStrategy; // error更新策略 + message?: string | { [key: string]: string }; // 统一配置的message + updateOn?: 'change' | 'blur' | 'submit'; // model更新策略 + messageShowType?: 'popover' | 'text' | 'none'; // 消息自动显示策略(当前仅单个表单组件下生效),自身附着popover | form-control下显示 | 不显示, + popPosition?: + | 'left' + | 'right' + | 'top' + | 'bottom' + | 'bottom-left' + | 'bottom-right' + | 'top-left' + | 'top-right' + | 'left-top' + | 'left-bottom' + | 'right-top' + | 'right-bottom' + | ( + | 'left' + | 'right' + | 'top' + | 'bottom' + | 'bottom-left' + | 'bottom-right' + | 'top-left' + | 'top-right' + | 'left-top' + | 'left-bottom' + | 'right-top' + | 'right-bottom' + )[]; + } + | DValidateRule[]; + + export interface DValidateErrorStatus { errorMessage: string | { [key: string]: string } | null; showError: boolean; errors: { [key: string]: any }; } -// DForm ValidatorFn -export type DValidatorFn = (value: any) => boolean | string | { [key: string]: string } | null; - -// DForm AsyncValidatorFn -export type DAsyncValidatorFn = (value: any) => Observable; /* TODO: 这里是否需要导出 */ export const ruleReservedWords = [ @@ -107,12 +116,6 @@ export const dDefaultValidators = { whitespace: DValidators.whiteSpace, }; -/* pristine: 抛出error包括pristine状态 - ** dirty: 抛出error需在dirty状态 - */ -export type DValidationErrorStrategy = 'pristine' | 'dirty'; - -export type DFormControlStatus = 'error' | 'pending' | 'success'; export interface DPopConfig { popMaxWidth?: number; diff --git a/devui/fullscreen/fullscreen.component.ts b/devui/fullscreen/fullscreen.component.ts index a3b1f224..f5608c53 100644 --- a/devui/fullscreen/fullscreen.component.ts +++ b/devui/fullscreen/fullscreen.component.ts @@ -97,7 +97,7 @@ export class FullscreenComponent implements OnInit, OnDestroy, AfterViewInit { }); this.isFullscreen = isFullscreen; } - } + }; public handleFullscreen = async () => { const targetElement = this.elementRef.nativeElement.querySelector('[fullscreen-target]'); @@ -126,7 +126,7 @@ export class FullscreenComponent implements OnInit, OnDestroy, AfterViewInit { this.fullscreenLaunch.emit({ isFullscreen }); - } + }; private handleKeyDown = (event) => { if (event.keyCode === ESC_KEYCODE) { // 按ESC键退出全屏 @@ -144,7 +144,7 @@ export class FullscreenComponent implements OnInit, OnDestroy, AfterViewInit { this.isFullscreen = false; } } - } + }; ngOnDestroy() { this.document.removeEventListener('fullscreenchange', this.onFullScreenChange); diff --git a/devui/gantt/demo/gantt-demo.component.ts b/devui/gantt/demo/gantt-demo.component.ts index 63903d59..97c659d3 100644 --- a/devui/gantt/demo/gantt-demo.component.ts +++ b/devui/gantt/demo/gantt-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'd-gantt-demo', @@ -18,11 +18,11 @@ export class GanttDemoComponent implements OnInit, OnDestroy { {title: 'TS', language: 'typescript', code: require('./table/table.component.ts?raw')}, {title: 'SCSS', language: 'css', code: require('./table/table.component.scss?raw')}, {title: 'reset-position-HTML', language: 'typescript', - code: require('./table/reset-position/reset-position.component.html?raw')}, + code: require('./table/reset-position/reset-position.component.html?raw')}, {title: 'reset-position-TS', language: 'xml', - code: require('./table/reset-position/reset-position.component.ts?raw')}, + code: require('./table/reset-position/reset-position.component.ts?raw')}, {title: 'reset-position-CSS', language: 'typescript', - code: require('./table/reset-position/reset-position.component.scss?raw')}, + code: require('./table/reset-position/reset-position.component.scss?raw')}, {title: 'data', language: 'typescript', code: require('./mock-data.ts?raw')} ]; diff --git a/devui/gantt/demo/mock-data.ts b/devui/gantt/demo/mock-data.ts index 1c29b3c9..25c03044 100644 --- a/devui/gantt/demo/mock-data.ts +++ b/devui/gantt/demo/mock-data.ts @@ -61,57 +61,57 @@ export const basicData = [ export const treeDataSource: SourceType[] = [ { - id: '1', - title: 'table title0', - lastName: 'Mark', - status: 'done', - startDate: new Date(curYear, 4, 5), - endDate: new Date(curYear, 4, 10), - ganttType: 'parentProgress', - $isChildTableOpen: true, - progressRate: 30, - progressDisabled: true, - children: [ - { - id: '2', - title: 'table title01', - lastName: 'Mark', - status: 'done', - startDate: new Date(curYear, 4, 5), - endDate: new Date(curYear, 4, 10), - ganttType: 'progress', - progressRate: 30, - $isChildTableOpen: true - } - ] + id: '1', + title: 'table title0', + lastName: 'Mark', + status: 'done', + startDate: new Date(curYear, 4, 5), + endDate: new Date(curYear, 4, 10), + ganttType: 'parentProgress', + $isChildTableOpen: true, + progressRate: 30, + progressDisabled: true, + children: [ + { + id: '2', + title: 'table title01', + lastName: 'Mark', + status: 'done', + startDate: new Date(curYear, 4, 5), + endDate: new Date(curYear, 4, 10), + ganttType: 'progress', + progressRate: 30, + $isChildTableOpen: true + } + ] }, { - id: '6', - title: 'table title1', - lastName: 'Mark', - status: 'done', - startDate: new Date(curYear, 4, 4), - endDate: new Date(curYear, 4, 8), - ganttType: 'progress', + id: '6', + title: 'table title1', + lastName: 'Mark', + status: 'done', + startDate: new Date(curYear, 4, 4), + endDate: new Date(curYear, 4, 8), + ganttType: 'progress', }, { - id: '7', - title: 'table title2', - lastName: 'Mark', - status: 'done', - startDate: new Date(curYear, 4, 6), - endDate: new Date(curYear, 4, 9), - ganttType: 'progress', + id: '7', + title: 'table title2', + lastName: 'Mark', + status: 'done', + startDate: new Date(curYear, 4, 6), + endDate: new Date(curYear, 4, 9), + ganttType: 'progress', }, { - id: '8', - title: 'table title3', - lastName: 'Mark', - status: 'done', - detail: 'This is a line detail', - startDate: new Date(curYear, 4, 7), - endDate: new Date(curYear, 4, 10), - ganttType: 'progress', + id: '8', + title: 'table title3', + lastName: 'Mark', + status: 'done', + detail: 'This is a line detail', + startDate: new Date(curYear, 4, 7), + endDate: new Date(curYear, 4, 10), + ganttType: 'progress', }, { id: '9', @@ -123,12 +123,12 @@ export const treeDataSource: SourceType[] = [ endDate: new Date(curYear, 4, 10), }, { - id: '10', - title: 'table title4', - lastName: 'Mark', - status: 'done', - ganttType: 'progress', - startDate: new Date(curYear, 5, 1), - endDate: new Date(curYear, 5, 3), + id: '10', + title: 'table title4', + lastName: 'Mark', + status: 'done', + ganttType: 'progress', + startDate: new Date(curYear, 5, 1), + endDate: new Date(curYear, 5, 3), } ]; diff --git a/devui/gantt/gantt-bar/gantt-bar.component.ts b/devui/gantt/gantt-bar/gantt-bar.component.ts index 184394e0..3bfde320 100644 --- a/devui/gantt/gantt-bar/gantt-bar.component.ts +++ b/devui/gantt/gantt-bar/gantt-bar.component.ts @@ -238,7 +238,7 @@ export class GanttBarComponent implements OnInit, OnChanges, AfterViewInit, OnDe } private checkStepValue() { - if (this.step < 0 || !!!this.step) { + if (this.step < 0 || !this.step) { throw new Error('step value must be greater than 0.'); } else if ((this.max - this.min) % this.step) { throw new Error('(max - min) must be divisible by step.'); diff --git a/devui/gantt/gantt-marker.directive.ts b/devui/gantt/gantt-marker.directive.ts index ff1a7f9d..3726b544 100644 --- a/devui/gantt/gantt-marker.directive.ts +++ b/devui/gantt/gantt-marker.directive.ts @@ -138,26 +138,26 @@ export class GanttMarkerDirective implements OnChanges, OnDestroy { destroyMarkElement(type = 'all') { switch (type) { - case 'monthMark': - this.removeMonthMark(); - break; - case 'weekend': - this.removeWeekendMark(); - break; - case 'today': - this.removeTodayMark(); - break; - case 'milestone': - this.removeMileStoneMark(); - break; - case 'all': - this.removeMonthMark(); - this.removeWeekendMark(); - this.removeTodayMark(); - this.removeMileStoneMark(); - break; - default: - break; + case 'monthMark': + this.removeMonthMark(); + break; + case 'weekend': + this.removeWeekendMark(); + break; + case 'today': + this.removeTodayMark(); + break; + case 'milestone': + this.removeMileStoneMark(); + break; + case 'all': + this.removeMonthMark(); + this.removeWeekendMark(); + this.removeTodayMark(); + this.removeMileStoneMark(); + break; + default: + break; } } diff --git a/devui/gantt/gantt-scale/gantt-scale.component.ts b/devui/gantt/gantt-scale/gantt-scale.component.ts index 195c53a4..abcb0c8a 100644 --- a/devui/gantt/gantt-scale/gantt-scale.component.ts +++ b/devui/gantt/gantt-scale/gantt-scale.component.ts @@ -147,20 +147,20 @@ export class GanttScaleComponent implements OnInit, OnChanges, OnDestroy { }; const dayOfMonth = date.getDate(); - dateInfo.dayOfMonthLabel = dayOfMonth + ''; + dateInfo.dayOfMonthLabel = String(dayOfMonth); if (dayOfMonth === 1) { dateInfo.monthStart = true; } const dayOfWeek = date.getDay(); - dateInfo.dayOfWeekLabel = dayOfWeek + ''; + dateInfo.dayOfWeekLabel = String(dayOfWeek); if (dayOfWeek === 6) { dateInfo.weekend = true; } const month = date.getMonth() + 1; - dateInfo.monthLabel = month + ''; + dateInfo.monthLabel = String(month); const year = date.getFullYear(); - dateInfo.yearLabel = year + ''; + dateInfo.yearLabel = String(year); if (this.ganttService.isSomeDate(date, new Date())) { dateInfo.today = true; } diff --git a/devui/gantt/gantt-tools/gantt-tools.component.ts b/devui/gantt/gantt-tools/gantt-tools.component.ts index f5bcf33b..2db6ed3f 100644 --- a/devui/gantt/gantt-tools/gantt-tools.component.ts +++ b/devui/gantt/gantt-tools/gantt-tools.component.ts @@ -51,15 +51,15 @@ export class GanttToolsComponent { avtionHandle (type) { switch (type) { - case 'today': - this.goToday.emit(); - break; - case 'reduce': - this.reduceUnit.emit(); - break; - case 'increase': - this.increaseUnit.emit(); - break; + case 'today': + this.goToday.emit(); + break; + case 'reduce': + this.reduceUnit.emit(); + break; + case 'increase': + this.increaseUnit.emit(); + break; } } diff --git a/devui/gantt/gantt.service.ts b/devui/gantt/gantt.service.ts index a03cc900..a657fb7d 100644 --- a/devui/gantt/gantt.service.ts +++ b/devui/gantt/gantt.service.ts @@ -51,17 +51,17 @@ export class GanttService { getScaleUnitPixel() { switch (this.scaleUnit) { - case GanttScaleUnit.day: - return 40; - break; - case GanttScaleUnit.week: - return 30; - break; - case GanttScaleUnit.month: - return 20; - break; - default: - break; + case GanttScaleUnit.day: + return 40; + break; + case GanttScaleUnit.week: + return 30; + break; + case GanttScaleUnit.month: + return 20; + break; + default: + break; } } diff --git a/devui/gantt/gantt.spec.ts b/devui/gantt/gantt.spec.ts index ddc6977f..e2b3e65c 100644 --- a/devui/gantt/gantt.spec.ts +++ b/devui/gantt/gantt.spec.ts @@ -2,15 +2,15 @@ import { Component, DebugElement, ElementRef, OnDestroy, OnInit, ViewChild } fro import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { - GanttBarComponent, GanttModule, GanttScaleComponent, GanttScaleUnit, - GanttService, GanttTaskInfo + GanttBarComponent, GanttModule, GanttScaleComponent, GanttScaleUnit, + GanttService, GanttTaskInfo } from 'ng-devui/gantt'; import { I18nModule } from 'ng-devui/i18n'; import { Subscription } from 'rxjs'; import { DomHelper } from '../utils/testing/dom-helper'; @Component({ - template: ` + template: `
@@ -45,230 +45,230 @@ import { DomHelper } from '../utils/testing/dom-helper';
`, - styles: [`.gantt-container {padding: 0 30px 0 30px; overflow: scroll;} + styles: [`.gantt-container {padding: 0 30px 0 30px; overflow: scroll;} .gantt-container .header {position: relative;border-bottom: 1px solid #adb0b8;} .gantt-container .body {position: relative;min-height: 400px;}.gantt-container .body .item {height: 40px;padding-top: 8px;} ::ng-deep .devui-gantt-tips .title {font-size: 14px;color: #252b3a;line-height: 24px;font-weight: bold;margin-bottom: 15px;} ::ng-deep .devui-gantt-tips .content {font-size: 12px;color: #252b3a;line-height: 24px;}`] }) class TestGanttComponent implements OnInit, OnDestroy { - @ViewChild('ganttContainer') ganttContainer: ElementRef; - curYear = 2020; - list = [{ - id: '1', - title: 'title1', - startDate: new Date(this.curYear, 4, 5), - endDate: new Date(this.curYear, 4, 10), - progressRate: 30 - }]; - ganttStartDate: Date; - ganttEndDate: Date; - unit = GanttScaleUnit.day; - ganttScaleWidth: string; - ganttSacleConfigHandler: Subscription; - currentAction: string; - - constructor(private ganttService: GanttService) { } - - ngOnInit() { - this.ganttStartDate = new Date(this.curYear, 4, 1); - this.ganttEndDate = new Date(this.curYear, 5, 1); - this.ganttService.setScaleConfig({ - startDate: this.ganttStartDate, - endDate: this.ganttEndDate, - unit: this.unit - }); + @ViewChild('ganttContainer') ganttContainer: ElementRef; + curYear = 2020; + list = [{ + id: '1', + title: 'title1', + startDate: new Date(this.curYear, 4, 5), + endDate: new Date(this.curYear, 4, 10), + progressRate: 30 + }]; + ganttStartDate: Date; + ganttEndDate: Date; + unit = GanttScaleUnit.day; + ganttScaleWidth: string; + ganttSacleConfigHandler: Subscription; + currentAction: string; + + constructor(private ganttService: GanttService) { } + + ngOnInit() { + this.ganttStartDate = new Date(this.curYear, 4, 1); + this.ganttEndDate = new Date(this.curYear, 5, 1); + this.ganttService.setScaleConfig({ + startDate: this.ganttStartDate, + endDate: this.ganttEndDate, + unit: this.unit + }); + this.ganttScaleWidth = this.ganttService.getDurationWidth(this.ganttStartDate, this.ganttEndDate) + 'px'; + this.ganttSacleConfigHandler = this.ganttService.ganttScaleConfigChange.subscribe((config) => { + if (config.startDate) { + this.ganttStartDate = config.startDate; + } + if (config.endDate) { + this.ganttEndDate = config.endDate; + } + if (config.startDate || config.endDate) { this.ganttScaleWidth = this.ganttService.getDurationWidth(this.ganttStartDate, this.ganttEndDate) + 'px'; - this.ganttSacleConfigHandler = this.ganttService.ganttScaleConfigChange.subscribe((config) => { - if (config.startDate) { - this.ganttStartDate = config.startDate; - } - if (config.endDate) { - this.ganttEndDate = config.endDate; - } - if (config.startDate || config.endDate) { - this.ganttScaleWidth = this.ganttService.getDurationWidth(this.ganttStartDate, this.ganttEndDate) + 'px'; - } - }); - } + } + }); + } - onGanttBarMoveStart(info: GanttTaskInfo) { - this.currentAction = 'onGanttBarMoveStart'; - } + onGanttBarMoveStart(info: GanttTaskInfo) { + this.currentAction = 'onGanttBarMoveStart'; + } - onGanttBarMoving(info: GanttTaskInfo) { - this.currentAction = 'onGanttBarMoving'; - } + onGanttBarMoving(info: GanttTaskInfo) { + this.currentAction = 'onGanttBarMoving'; + } - onGanttBarResizeStart(info: GanttTaskInfo) { - this.currentAction = 'onGanttBarResizeStart'; - } + onGanttBarResizeStart(info: GanttTaskInfo) { + this.currentAction = 'onGanttBarResizeStart'; + } - onGanttBarResizing(info: GanttTaskInfo) { - this.currentAction = 'onGanttBarResizing'; - } + onGanttBarResizing(info: GanttTaskInfo) { + this.currentAction = 'onGanttBarResizing'; + } - onGanttBarMove(info: GanttTaskInfo) { - this.updateData(info); - } + onGanttBarMove(info: GanttTaskInfo) { + this.updateData(info); + } - onGanttBarResize(info: GanttTaskInfo) { - this.updateData(info); - } + onGanttBarResize(info: GanttTaskInfo) { + this.updateData(info); + } - updateData(info: GanttTaskInfo) { - const index = this.list.findIndex((data) => { - return data.id === info.id; - }); - if (index > -1) { - this.list[index].startDate = info.startDate; - this.list[index].endDate = info.endDate; - } + updateData(info: GanttTaskInfo) { + const index = this.list.findIndex((data) => { + return data.id === info.id; + }); + if (index > -1) { + this.list[index].startDate = info.startDate; + this.list[index].endDate = info.endDate; } + } - onBarProgressEvent(progress: number) { - this.currentAction = 'onBarProgressEvent'; - } + onBarProgressEvent(progress: number) { + this.currentAction = 'onBarProgressEvent'; + } - ngOnDestroy() { - if (this.ganttSacleConfigHandler) { - this.ganttSacleConfigHandler.unsubscribe(); - this.ganttSacleConfigHandler = null; - } + ngOnDestroy() { + if (this.ganttSacleConfigHandler) { + this.ganttSacleConfigHandler.unsubscribe(); + this.ganttSacleConfigHandler = null; } + } } describe('gantt', () => { - describe('basic', () => { - let fixture: ComponentFixture; - let debugEl: DebugElement; - let component: TestGanttComponent; - let domHelper: DomHelper; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [GanttModule, I18nModule], - declarations: [TestGanttComponent] - }).compileComponents(); - }); - - beforeEach(() => { - fixture = TestBed.createComponent(TestGanttComponent); - debugEl = fixture.debugElement; - component = debugEl.componentInstance; - - domHelper = new DomHelper(fixture); - fixture.detectChanges(); - }); - - it('should init ok', () => { - expect(component).toBeTruthy(); - const header = debugEl.query(By.css('.header')).nativeElement; - expect(header.style.width).toBe('1280px'); - const body = debugEl.query(By.css('.body')).nativeElement; - expect(body.style.width).toBe('1280px'); - - const ganttScale = debugEl.query(By.directive(GanttScaleComponent)).nativeElement; - expect(ganttScale.clientWidth).toBe(1280); - - const scales = ganttScale.querySelectorAll('.devui-gantt-scale'); - expect(scales.length).toBe(0); - - const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; - const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); - expect(ganttBarElement.style.width).toBe('240px'); - expect(ganttBarElement.style.left).toBe('160px'); - - const ganttBarTrack = ganttBar.querySelector('.devui-gantt-bar-track'); - expect(ganttBarTrack.style.width).toBe('30%'); - - }); - - it('should mouse over&leave on bar ok', fakeAsync(() => { - const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; - const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); - ganttBarElement.dispatchEvent(new Event('mouseover')); - tick(250); - fixture.detectChanges(); - - const ganttTips = document.querySelector('.devui-gantt-tips'); - expect(ganttTips).toBeTruthy(); - - })); - - it('should drag progress ok', fakeAsync(() => { - const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; - const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); - - const ganttBarProgress = ganttBarElement.querySelector('.devui-gantt-bar-progress'); - ganttBarProgress.dispatchEvent(new MouseEvent('mousedown')); - fixture.detectChanges(); - document.dispatchEvent(new MouseEvent('mousemove', { clientX: 440 })); - fixture.detectChanges(); - - document.dispatchEvent(new MouseEvent('mouseup')); - fixture.detectChanges(); - - const ganttBarTrack = ganttBar.querySelector('.devui-gantt-bar-track'); - expect(ganttBarTrack.style.width).toBe('100%'); - expect(component.currentAction).toBe('onBarProgressEvent'); - })); - - it('should drag bar ok', fakeAsync(() => { - const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; - const ganttBarMain = ganttBar.querySelector('.devui-gantt-main'); - ganttBarMain.dispatchEvent(new MouseEvent('mousedown')); - fixture.detectChanges(); - expect(component.currentAction).toBe('onGanttBarMoveStart'); - - document.dispatchEvent(new MouseEvent('mousemove', { clientX: 440 })); - fixture.detectChanges(); - expect(component.currentAction).toBe('onGanttBarMoving'); - - document.dispatchEvent(new MouseEvent('mouseup')); - fixture.detectChanges(); - - const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); - expect(ganttBarElement.style.left).toBe('600px'); - - const ganttScale = debugEl.query(By.directive(GanttScaleComponent)).nativeElement; - expect(Number(component.list[0].startDate)).toBe(1589558400000); - })); - - it('should resize bar ok', fakeAsync(() => { - const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; - const ganttBarDraggers = ganttBar.querySelectorAll('.devui-gantt-dragger'); - const draggerLeft = ganttBarDraggers[0]; - const draggerRight = ganttBarDraggers[1]; - - const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); - - draggerRight.dispatchEvent(new MouseEvent('mousedown')); - fixture.detectChanges(); - expect(component.currentAction).toBe('onGanttBarResizeStart'); - - document.dispatchEvent(new MouseEvent('mousemove', { clientX: 40 })); - fixture.detectChanges(); - expect(component.currentAction).toBe('onGanttBarResizing'); - - document.dispatchEvent(new MouseEvent('mouseup')); - fixture.detectChanges(); - expect(ganttBarElement.style.width).toBe('280px'); - expect(Number(component.list[0].endDate)).toBe(1589126400000); - - draggerLeft.dispatchEvent(new MouseEvent('mousedown')); - fixture.detectChanges(); - expect(component.currentAction).toBe('onGanttBarResizeStart'); - - document.dispatchEvent(new MouseEvent('mousemove', { clientX: -40 })); - fixture.detectChanges(); - expect(component.currentAction).toBe('onGanttBarResizing'); - - document.dispatchEvent(new MouseEvent('mouseup')); - fixture.detectChanges(); - expect(ganttBarElement.style.left).toBe('120px'); - expect(ganttBarElement.style.width).toBe('320px'); - expect(Number(component.list[0].startDate)).toBe(1588521600000); - })); + describe('basic', () => { + let fixture: ComponentFixture; + let debugEl: DebugElement; + let component: TestGanttComponent; + let domHelper: DomHelper; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [GanttModule, I18nModule], + declarations: [TestGanttComponent] + }).compileComponents(); }); + + beforeEach(() => { + fixture = TestBed.createComponent(TestGanttComponent); + debugEl = fixture.debugElement; + component = debugEl.componentInstance; + + domHelper = new DomHelper(fixture); + fixture.detectChanges(); + }); + + it('should init ok', () => { + expect(component).toBeTruthy(); + const header = debugEl.query(By.css('.header')).nativeElement; + expect(header.style.width).toBe('1280px'); + const body = debugEl.query(By.css('.body')).nativeElement; + expect(body.style.width).toBe('1280px'); + + const ganttScale = debugEl.query(By.directive(GanttScaleComponent)).nativeElement; + expect(ganttScale.clientWidth).toBe(1280); + + const scales = ganttScale.querySelectorAll('.devui-gantt-scale'); + expect(scales.length).toBe(0); + + const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; + const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); + expect(ganttBarElement.style.width).toBe('240px'); + expect(ganttBarElement.style.left).toBe('160px'); + + const ganttBarTrack = ganttBar.querySelector('.devui-gantt-bar-track'); + expect(ganttBarTrack.style.width).toBe('30%'); + + }); + + it('should mouse over&leave on bar ok', fakeAsync(() => { + const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; + const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); + ganttBarElement.dispatchEvent(new Event('mouseover')); + tick(250); + fixture.detectChanges(); + + const ganttTips = document.querySelector('.devui-gantt-tips'); + expect(ganttTips).toBeTruthy(); + + })); + + it('should drag progress ok', fakeAsync(() => { + const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; + const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); + + const ganttBarProgress = ganttBarElement.querySelector('.devui-gantt-bar-progress'); + ganttBarProgress.dispatchEvent(new MouseEvent('mousedown')); + fixture.detectChanges(); + document.dispatchEvent(new MouseEvent('mousemove', { clientX: 440 })); + fixture.detectChanges(); + + document.dispatchEvent(new MouseEvent('mouseup')); + fixture.detectChanges(); + + const ganttBarTrack = ganttBar.querySelector('.devui-gantt-bar-track'); + expect(ganttBarTrack.style.width).toBe('100%'); + expect(component.currentAction).toBe('onBarProgressEvent'); + })); + + it('should drag bar ok', fakeAsync(() => { + const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; + const ganttBarMain = ganttBar.querySelector('.devui-gantt-main'); + ganttBarMain.dispatchEvent(new MouseEvent('mousedown')); + fixture.detectChanges(); + expect(component.currentAction).toBe('onGanttBarMoveStart'); + + document.dispatchEvent(new MouseEvent('mousemove', { clientX: 440 })); + fixture.detectChanges(); + expect(component.currentAction).toBe('onGanttBarMoving'); + + document.dispatchEvent(new MouseEvent('mouseup')); + fixture.detectChanges(); + + const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); + expect(ganttBarElement.style.left).toBe('600px'); + + const ganttScale = debugEl.query(By.directive(GanttScaleComponent)).nativeElement; + expect(Number(component.list[0].startDate)).toBe(1589558400000); + })); + + it('should resize bar ok', fakeAsync(() => { + const ganttBar = debugEl.query(By.directive(GanttBarComponent)).nativeElement; + const ganttBarDraggers = ganttBar.querySelectorAll('.devui-gantt-dragger'); + const draggerLeft = ganttBarDraggers[0]; + const draggerRight = ganttBarDraggers[1]; + + const ganttBarElement = ganttBar.querySelector('.devui-gantt-bar'); + + draggerRight.dispatchEvent(new MouseEvent('mousedown')); + fixture.detectChanges(); + expect(component.currentAction).toBe('onGanttBarResizeStart'); + + document.dispatchEvent(new MouseEvent('mousemove', { clientX: 40 })); + fixture.detectChanges(); + expect(component.currentAction).toBe('onGanttBarResizing'); + + document.dispatchEvent(new MouseEvent('mouseup')); + fixture.detectChanges(); + expect(ganttBarElement.style.width).toBe('280px'); + expect(Number(component.list[0].endDate)).toBe(1589126400000); + + draggerLeft.dispatchEvent(new MouseEvent('mousedown')); + fixture.detectChanges(); + expect(component.currentAction).toBe('onGanttBarResizeStart'); + + document.dispatchEvent(new MouseEvent('mousemove', { clientX: -40 })); + fixture.detectChanges(); + expect(component.currentAction).toBe('onGanttBarResizing'); + + document.dispatchEvent(new MouseEvent('mouseup')); + fixture.detectChanges(); + expect(ganttBarElement.style.left).toBe('120px'); + expect(ganttBarElement.style.width).toBe('320px'); + expect(Number(component.list[0].startDate)).toBe(1588521600000); + })); + }); }); diff --git a/devui/gantt/resize-handle.directive.ts b/devui/gantt/resize-handle.directive.ts index 47f073de..da6368b9 100644 --- a/devui/gantt/resize-handle.directive.ts +++ b/devui/gantt/resize-handle.directive.ts @@ -134,7 +134,7 @@ export class ResizeHandleDirective { bindMousemove = (e) => { this.move(e); - } + }; move(event: MouseEvent): void { this.moveCount++; diff --git a/devui/i18n/i18n.module.ts b/devui/i18n/i18n.module.ts index 9e197c6e..cb6cb81b 100644 --- a/devui/i18n/i18n.module.ts +++ b/devui/i18n/i18n.module.ts @@ -2,12 +2,12 @@ import { NgModule } from '@angular/core'; import { I18nDatePipe } from './i18n-date.pipe'; @NgModule({ - declarations: [ - I18nDatePipe - ], - exports: [ - I18nDatePipe - ] + declarations: [ + I18nDatePipe + ], + exports: [ + I18nDatePipe + ] }) export class I18nModule { diff --git a/devui/i18n/zh-cn.ts b/devui/i18n/zh-cn.ts index 928aa640..39e19e4a 100644 --- a/devui/i18n/zh-cn.ts +++ b/devui/i18n/zh-cn.ts @@ -65,7 +65,7 @@ export default { hour: '时', min: '分', second: '秒' - }, + }, form: { required(val): string { return '值不能为空'; diff --git a/devui/image-preview/demo/image-mock.ts b/devui/image-preview/demo/image-mock.ts index 723f0a08..e73aecc4 100644 --- a/devui/image-preview/demo/image-mock.ts +++ b/devui/image-preview/demo/image-mock.ts @@ -1,7 +1,7 @@ import { environment } from 'src/environments/environment'; const prefix = environment.deployPrefix; -// tslint:disable-next-line: max-line-length +/* eslint-disable-next-line max-len*/ const hwLogo = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAABa1BMVEX////+/v7RCS7OC%0Ai4AAAD///3//f8hGBn8///OCyv//vzSCS39%0A/f///P/OCjDRCisjGBwhGRbEwsP5//0eFRgfGRu/ABvz8PG4tbYKAADYBi4nEBnb2tj3//8lFhvm4+RkXmAZDg/HACW9ACA0Li++ACgmGBjKACHjv8ft6uMf%0AGhk7Nza/vrzDACf%0A/9vbXACfqrLTrz9YpIB0WBQ2KhoVWUlGknp6zAA3AADXqxdC5ABi0ACPanavxztG2NEmuACbFgYrCABbJcH7y4+rBYXW6JUB+d3nt2NrbqbS5UGW7KEmrABj%0AEaXS5LEHKlZuxTlv%0ASpa2oEjHousSvPUesCC2zYW++e4G3N1HSjJ7WlZzSgJXu3Ni/YWqpADmrQVe6N1K/WXHBcnPjs8m4FUX34O69SlvCfZHYh4/EipS0MT2YABavME2aIjnqq7j%0Ap2+Tp0M7ad5GTTFy%0AYMT62jJmHACjara2iPFfsvrtMR0j3U0omAAAgAElEQVR4nO2di3vTRrbA9Yjk0dthkpioKME2igxU0hoKTeK8sOPaCWEbUrN5scDdJcC9tJv74pY//54zkm3%0AZllOHJiF8n88HbW%0AJLo/npnDmPmZHguLGMZSxjGctYxjKWsYxlLGMZy1jGMpaxjGUsYxnLWMYylrGM5RsRnse/g6Lrsk44Sfra/fvzAoSEpBByhBKd//YBGUuaEjlelyRZZir+Rk%0AWSiGzgD3KtUc5Rf%0AUCFcu20UYP/c7zBSzIc+C2x8rykyoZMuKDcrG5tL/74ziG6LHfwZBAabD5dfL31bq9sOMSgvPwtAYIFqpRyQWnnmVssKEoYrq86Rj9hyTdNU/RmFrePSgEMy%0Am8JET0lrf21Xii4%0ApmDbmhV6VblPh3rwsy0Kmm1bpuv7a7sBrxtfu98jC091mtt97tmCAH8EURSVsNIAwgSiwe0VFQu+QkpLUZ7Um9SRVI58C4rkYVTVttYFSwMRIkS7sIGEbUQC%0AQ/SF5eM3KAqIv7x%0AZA+v+Flwr9J/+vl2wbDFBKGrbAd8llGSntm6LYoJQtIu/NBxH+hYIOfn3dQuxkoTKzB7XJaSG89eiYCZ1aCmi9axM1OtPCFFhtSUqGo6wrmiKtskZstQhNF5%0AZMXssYNO2t9bQDUK%0A+NsLZIhlObVsTTLGPULNbATXahDJptLQeQKZwpXAS0OuuRF4OXiiiyXov9CD6JWp0fClpeiZGw15CMfT+pkrXPGhITtO1FE0Q+wlFbaNLSLkXdgqhJpru7/R%0A6E/Kkth32oHXEWu%0AN0lsxguM/VbbFXYpdU2DcM+rUpzhLZOCiIWiqh1mrwapvwtKKlE4rurnOdYyKR326HSiqgIBSbXJTXQAJ36A0hNMWTQL++hDwhexXLGkLobRgkCom6/DJU0g%0AkF0126xpkbL9Gdg%0AmhZcaTvE+WVTNEAoeDPbStCCiEyaoUjcn2VyEt315ShhFa9FhNy5UVrGKGgXWczJdzxMmRfQjph6K+yxBpSzz3fEtMJTSVcrMny1yZBgfrA4ahB1MR0Gc99Q%0Ag8yhNDymk6sw42%0AClq5DSIbC5bKu92RuOKkj8Vc+OnlDd5YahIB3IW1EnRwWxKGEmleFIYgnGC8tIc2XMi3ay0skScgTp1zjHfmKRyfmJXTv768CA3vc/lQnB2cQWtYW8mFWsBY%0AKQ3QIhMXdnjqYp8%0Afba2XdkK+UkGVe5brnv1Ap4To65MnRmYSvA6ZB51/PoXgcTthMEvIkOPFCQOSvVofEILXXnq9VDsGiOv0hHCNMz9oExVpsEJyFo+Wi1g/YPgeybyBsZzU4GW%0AC8L4ZW4SSnG7xzh%0AYAyDd74lmbZz1cp1Tsfc+8LfSrpIXTLqH2JfioODMP2CRYQ7nF83CSUWeS3imKHSnEzIIZxdVqkhvq+IIiCFVq/HNPE1PxhQRhKaFnYdxi10qE3MAw7hGa4v%0AMTJbGhD8mM45ecY%0AfwSrcGiAfV8ZoUyaT0PBtmzFKmxSqV0M8PynmeE6tCz/gOMdwqn/5g0Atk+wzdAtwxiICWnwyivghIFVqPyDM66m/MeZMrizNivowKO4h7Q9EHn59AmMsPRh%0ACITaEdq3rEKwGK%0AZDUfPqNVmPLqTKzmZH3cI/31I1OSM5qnwBokyNLVNsEwrreyQOGJQ/dtNLJ0aoaC/YPGKwdibhfmDEhI7ejGbkcC5O9DcdcjWEMpVWXJt1CRE1+9e30bjhJC%0A4HnU8NFcyJ2D9D%0AuOBIrW4NpDQdQsHb5CNCSSJLi5rdOVJZbnJXRXjcMqMyFwmtsPAiiOxU0knVG1IAM8K1HOTepFHRhupQEGYOuchn8nzwc2h1W/PDenAlhDzlqgXTNNsXhs4t%0A7xKDLfUSvvnEtQ%0Ac6HWtHEOrzhFBSLg46mo6nEQslXGYDoyDB32bi0R5N4tj+hkrkCP5yCRuLOFvYJRQLlVOq81EK6QqamU6I1e0xRouSP5xQE+s1RijrTqliiUlCRVg/dpg/vV%0AxCIlWV3p4rivdL%0AEOmQBvuWNYxQFCqnEhDu+v0FfpJwiy2zgUt6u2bhoG4LOmNlg7AM6jIJwZGuLrIBCJfsjBHb25AMIkGJwx0NI0QlFlexgyuFYYSioPgrDhLqTrAJ+ZEWWbfA%0ArgWh/581x+hfTb%0A5wHXIbvqJYVmdlCa+uWK096kgSuJqSbw8lFGeaBO7CwcxA/dsmFLXFssMQuJViSnrkrxDjvN7mnHhghx9FResnVITtuzwoUXdqry1xOOEKxEyof4daqWifGG%0AzJnxyvWynN2CeB%0AfsmEVF11ISz3EsLosQrVwEEdknedUTZI6DHCamG4pyk20S3zXHDSmclJNoEp3eUSQmGwAbHQ6oz+rlSaEKMhgSun3vxIvAPCCAcB2zpsNaihOwZ/4KUFHVED%0AKzhvSDwvoXoiph%0AJqJnRO5YluvD6DsMpRYmylGGk0X2qLmwGVdd1ZamlKig4Vu7B5Pkd6bkJCjuuKmPDgHbEsyMng/pOuqxwkDKs8EJ6kOBp2sKlV9giVeTn4aNuKNkio2dZ+wF%0A+qDik5/RHSYCFFh%0A6ELjh5r8lrFGk7IUc7YH0boFz5CzavL4K5DqMxSdIiTrtzlWim3NyNEMzF9hNAVq1UjKpjpOysUzVRCa4fwUpBOqIFHfgKeSDVgKLO204zdA1dzPsBzx8PdY%0Ajohc5VbOoGRWF4%0APh+jQ2uHOIrRbNUdWaW7fFRWxM1h7Wih8XcLQW9F1neibijKEcEvlaLBtm6mEVuEdpQYNNhSts9jW34xVvGRCnvs0xEpRzLDe0MHZ71Ws/lXuuH8nAZSHLS2%0AFEBK2sFU2qOFAV%0AqhFi95C/1KyJiiXrUOeO30C1esQQqhvXga6rqpbljKMkCfBYhqgKSreDpUlrvZagNIs/QK2aS3Wzgl4TkKJa7h4b9M7ABHZ/eSAHkozWjrhWqAPIYTb5q5SG%0AIUHBcEcdgHNtJ7%0AVLjdaSFzumdW5/oCVKiH0QOaNgIW8NMIcT3KVNEJR8THaS6sthpJ+Acv0t/jLzWkknVY9QRlGaNmQn8JQor8XhZTFbg10SEhQTAX03CVd5eUTlvGmpYVoI0L%0AhAwe19iUSEp42Z%0A6BYEtKNCD+q7FFK754otikMfI2EfLCcknhDqNlRDUpXKhaWZkMITdtf4i63AuaJ87Y+VIf4kWLXwdhoc30YIQmWU+OhewqR4hjH6HBCUdtnm6Yuk5CTuXe+N%0AswR4Cd24T0NpGD%0ALT7XSHOHSCa0dGAHGpqeIwnBCzf8rHfZ0wwUR4kRUuTXUl0Y32l11eL7khoP8SMgPEpqmqaw3HInsrVuQ9OJWxZQLWFCF1mtQv5xTzksIVf5GYcgtjgnFk0C%0AlwVYhhfB1ADp0U%0AwitKkfU2kfNUiJJu4AVPjmUzg34JbOJteepHegSuk2qqqVK39dIuB8RDrgac73mUPmDayvDCU3LO1ETu/8umLB7HJGd0rJ1FqEirNXAn77pM9M24d3KACFkp%0ABDry3Xbts8gDC%0AsNg5fbU20jD8aR8MCFEqpH2yFw/+vRcsiWZlI1CAlYeCRRtfxU7N+j%0AaL2E+i/49/5de6b4/C411JeeKbbZ+wg1zHPW/yLF++KAk6ijIo5GGCzxhqNH63eE1+XNYmgPJYTA3FoilNsItb4EHKonmahrA/sSCyvU0H8rJj7qI4Shavvv%0AaXvnH06WvC3T0XLw0U%0Aw09x8/LzmUGBLbD0NosLk8ZOcTQzLNrUCVoYhIJxzwNCc53gnWxOGEtm0uboD/MhigodNg9+OvEBoviJDIXOlJwd1cwpsmgR55lQ+qnpW6CZHpxDS9TxKv70%0AaTaj2EYF77/TNRlZJj%0ASIeeMpxQEdYPATDmI8HeSdH+sUH0Uea/R9CgY3CHRVsruNUGR9lmepnSGozFNMKY0lo7pmqwLyhmUoc4E8Ub+1ZP6q2ZmypGWWUIIe5MsSsrqqSqEo986tLW%0AuuVrM7ujTZ2OokOd3y%0ApYEI6E1lENfA7BnbJUP6iEmpm6Wog99A7BsZd8fOKgl1DWT3oJxVbZ0ckb1/LTCSERtP7+G1OXTCiVyjtwYbzC0WgLpqMQEn3b0gRbAa9eXwkMmccFGirvtX%0AwhbdWeDS1IUqAW3nF%0ANMZGf4nypoW/1EGruB8Ogq66QpkNENC3hn0s0MHRdNzi1sdFScAsrOLpX3EiV1AiEEB5aCqvslYLlrzUDfChCVonR+CVk+fXA/D3O+ytvZJ2utrRkBu4dcFQ%0AmVStafoz+WhA8+eAZ%0AjLXkHpvoeEQUtZmTmhpQ3XAcPTh8XhBEC1eibOv1aKXiKIQkqMSBCvJipXiyJOG2NhgWtb8t46RNiqHCbYYySlU3ZpIZuLfCSSrO6se/Y5hzP1GVW5nRhJ6V%0A787NcrXKRmBQGH8OH%0AzR/Xe/UVra2blwUoar/yxW7l9eEpzunKvReVYn0aTF907Oo2MKJCunpWjKmICGfJNQwrlA4yhfFNELR1tZKquPAoCBB6aSIi4idjKdyYYR8l9AUFbiEHbrvj%0AyXwbWAm5S3XTkNUQh%0AvSU4P+xT2TUFxf0g165ArphIK7Wca9X7pjlF9GnqhL+PSiCIlOcq7SXSzEMlfzweVAXKS6kztwwbWZA9OHlmau5QxivFDMaKDCTVou4X7bQw8Xe9kYs/wDVd%0AUb9YFtblgHa6HVWg%0Alg9FHqNKqLBTF61ii+kGW3ggvyNBDmjUqnrI9dnGkW9psqCWD4G0u/zNia2EvIRop/4BBndZ0llRHhKgEdNnHTFyMUtI81sOQN3xqcnDKV8MlWmYKHIU5wUP%0Afd3mdsIHi9Ni7Ml+%0AroS5kSuz5csxUXXA4kq7ocbKwrwiAhLqOAfzgsah3CU7TS3Zk2oV3cozxdXRcGdhChf1r/K7gYw3DU5uuCialgElGzrK2Lioe8TshJIepEglA0bbNSfcs5Et%0AQRp2tsg3cfYej/J9%0Awd42OU/EBqUmxAwseVcHsfMwq/ClGA3/H8gd2Y4Iq3yqBwh8hLJ64pRoA9hIWji8ppoHYyPnhi5xmQRLrhhU//dixBPkWDw5YFBYCYLJfgg8UyDeiSa7J7Ig%0Aj1Bt/ZMSQIvtdqO%0AKqzVOkrU/Beec+bAY9rII3NGUtMm2DVvN3RloNHsVLCNwudu5yco4E8oPB8Bdw9SOOl6/cAoprdqgqBcwN3iDLCYw6qqnKRzfkrQnFXMijd0nq2TUOg0+C8Y%0AwdSGKN21MI8Pm0l%0ARyiWLy7i63Kt0hkoSUIbfKjm7ZdUSiDPLm277at3pLUK8LVtJSLcvkuA8G2FEVrim4AaTmm5lxDuW2H/1OENg+Saa76GppG6VlXPySNN8I9CKMvS6+4+oAQh%0AehBIvivVVRl0Je%0AcOWuxBiri/uPzgb4KWnBKbgBS0E5UnEqnVFXT64WJZhji3HybrJPC7hWeHOUcmxCid+L6liemEmrUJQ/iCCGE8kxU/zUqF+DFmv/4uZwQ6VVe3iiILju1vhc%0AoSqC2oAqIthC8N%0AfJtJsAZZg6U9OeRgoJUqYeeRaBwJmnt0rPKGw5WrLTNMm1nFC5qmUiwZF1YBIyFOkg4ntAV3ewXMCsbc3uuipXWSbejyG6zrjtdCsOdwE7ds4V4ZC/fC3aUQ%0A6V4JVodQs+2ZkyV%0AQOnVqB3ULVJe2a4OJaa4FZLT9XyMR8oZeNYcTos1Zhf1yoKpAebDomnb7a9OuLEHWYjRdTCmPcKaMGC89IHwKI5SQvYItCO1xaPrP/4L7OWjQ/FjQTE1MM8+%0AY0D+EROSiCLH4d%0AMqLmii0NwYPEILV2NryzjHVJarX3rWwgoMQAX3UFjehzjLUnYLAdrLjc0HVULFmPoB3wo3qVrQHELI0v3WIblniy1u+DRrETDGdT1Bs3GV2YTrk8SUIxlGhN%0A3MTehDZdf31g4C%0ACE5Qbm64rRlFONMGdqhJtPLcUd5ftv+c2PM9+FUB5IjVdVgxBNqCF7rsGBaesHldbbuSUe1rvEc1dUQP5IgnB6dXWhM6CSTqhCJno2h51KM5fbGGizBJYc1P%0AFDQiffHAOSEi4wy%0AdhpYzawvebsFJBsCovlzBAkGC37mmxdQ4lNIVXgaTyF0oIf0uLPVt2Uwhx3FTerEKKoxvBp/2iCcmXKditJcwIuE3fY8/MEH3lyfKhgYrdKzJnqVjuVgkCCd%0AyJ1ZMiuJcO4RAVC%0Ai1wpKN50lEJ2ePJ1SLmllr66mgMa1ph67CG7pAEK/u+hjsqCpvgUmQIg26DkzliOHtPoOwlEpW3Qh/iqVB83QSVGAZ/XHVxco49fDDssQ2wCq24wkHYuWBCH%0AlfnfdxPfiYhKsB%0AbKwUwohw9d1ivaLbgLy5hjizt/VeNk3VIYxr/jX6U0tK6DTl3YW23pkqOIUu72/jaIVM5m1DTvJ1AH30ZcXRCIh9/NAWx30r7CGGMhJ6/eQw+VSfS3fctCAe%0AFdxhxZD6HRTmBg%0AHIXB6ETbEEeUKjjzJauOs7qzz5kBX9IaGruK7SASyCUdL1Wx7eUnEnIRpDlLR6AI0BbrR09D63FGj7SZZAoVaaEhzFIyakrumDSFD43uNpRxbZFQTyTkF1gZ%0Aiunw5BNf0nanyJEN%0AR7vQ/6iWEMIu3YEpeDanozOQJKCjcXld4jXviB+iHvC3xRaGwEHeOCY/vHUC5UYre1OBpu1LcssvgiMdscvnlCnxzuuHYZDnhJNElpC8V2DB2OEnK2x8T+6n%0ALwgIkLR+f4t3AQqS%0A+TtCw8nZv6Q0PIs910tevfb5RDC7Q6azwr2H+sQJ0y97U845UhVmSQSLGwRVYjT5pjAQGKzUrcgPxiFsLi9hwsXcTsjAZ6X0ODVxs66GSF2XvWQEJFlrrjvQ%0ArPsymYjUHmVSpL%0ARo0QkJJKEs8q6U94Ch4ubx5U+ETrPdbAJd2iwWK3pOIgHO3ZhhDy+s1L6fWsdN+RrVlthiRvfKR1RBOt5M8DQPsS3644TfGiJLESI0VRoL6EQE0IKYHnr1dV%0AA1VXU/3nk/ISGSu%0A+ebizOFPDBEjY7ayck7p0VS7j4ZlXFDRSphETfO3FtzGvM9kndUztNhFYhDJ++PoIgKkny5RMComwYNFf6sLX44/LyjOd5MwnxvL4Piv+LG/LSCbm3/+u7Fb%0A8IMjOzPPOkV+IG%0Aln98Wq+uNKKVElWVLp8wqvEggeaD2mmp1Gw2/9IrvzWbe6WuYNnID9k7oZdLfyzlQJcJ4XFOLwK8dMJICMF5s4FXcpLuKxYI/gy/4dptusTv/2Q/QqWAx7ML%0A9HVNNtSY7UoJsT/%0AtKA4/YdHkYAmBu6bwOUpC8Ek81qvhhHAcJ7HJSAdOxj0QmAfhuRLFk9irCHVZjwmvTIdDjsKnr4Mgl5uvvS2jnK7+/mnlcDcnDSHENLy80vz0++oqHv6vGpP%0AASGmfcXFXpUNdZ%0Aj05Pm6UoWure82VA5Cj6ibIy5PXa9vb9fqii66jUHBd/3ljGCEI3fsPfxn8jF/03cU6yLO1k5OXIDvVg4MPH1aae0vl1dPT00YMD97mCgi50//Gviwuui527%0AckTz8O/XhjanSf%0AazGhyQrCWT1bpcCuVqfGP1wWMfJ1oEaJAY5bozxQjZwz0eMH69uv/K0tXoENC8RFrG186qkCosjopldDZkIa/slAmFA/vEnIGIU+dWrWIC+Wi0De5pbS360C%0AQtWyMlGGhGlD1C%0AuKhTMpPlXadZLK3AZi4lhSt5ydyktD7WCYQC4cTohZBjX93BSuxaoD/6T6xb+If9lv49xrkDldgpVDorcyE4rA5lChNtUXNLG4EI8xogmOpvSkWEs+pDEwix%0AqVM5bfLeqdC/ym%0AUBG/MobNEkYS2uFZSsc75o/yYvRa6+UzoPtXYJew85ocf+VV67idkv5AQgtbbj+bZhF7rKIACGAP6H9uUTOjbzfXkk+kDOhRF/6TmnPsp5y8jlHDa7/TZwDv%0AlEqLMnOwRcAr8i%0AA/PG4Toze0CuuK4OOlrT/T9Z/i2gXM/TvJFhLhkqtK9wZ%0AfKMWHLwK3DgNfP8wSWzhtS430lxL1tTItJDeJ7lL36uZ/o+jOEHAEH+XvLClMINVupvIQ657z32gCvuneyHNoDhIpmCwwwZcBcGiHudaNLv6aNRdP99fdAMg%0Az+nD6dGLhvdKXlmsoA%0AoVhZazjGFRKyF+CBFb598wTcHIuGbMcQblRUcP1IVtGizkcoY+EJbb5bx3QC2/LZKoEIaU7xZeCw7clXRBifBw7QWFkU7bBTjGuW93yjoao9L5g/pxBudUe0%0ABPZCenwlvaWJuBeC8O%0AeYXLsgQizoHL22US/4WjzZUFzbaBAHUpgv8eltcaixWl0saKaJ06NhOFPfaFCH574KIeiKQvnzZhsy8JlifXO3plIYgOSL4nIsumHIKm0c7C9iNu/Wt5rHEF%0AZp3NMvavKLCZGRBx%0A7OqDWwvKsZHE428l/q1LuCb28JGuW9Zqlcg5KQ777U72p1yPoS/WsAbLqCi379UqzeVnUW2vGpAEkiiYmRL2nuTxJ2qLAfFwPIt28balPqIfyi5v4U4UC3Lk%0ASieS6MH0SSvrIOr%0A0T+bFfGhNeK8M+ePyb8RmVMOCZkous6f95JvjOESH+Q+hE2pzhifnhROjz3NOZwSSz5JEXXOw9UkkhGa240wj7UeHGmswom9U22D9yXgVvV+5vMD3zJ8XLcs%0AtqV6NNOgxdJmJs%0AHybXb5PhgHj+JrzZ/F6Q72c5FByc1Ch/lcvOdX/HrXK7bQQNPSEDOswbwsnf7JPoY6jZ2/Qvbm0gk7v69Bw8mbnT6wN2ayGaz0zJTb+4BfDl7S1Kj1x3I3M2%0AJ6ezU7cRUsKo+ms%0ARDok84+TacMPmIi1UNJ+TZt/GbSTn1873p6dnH8P2NiQd9MnuDHTI/kZm+9+DC9tMA4Z385GQv4dzcXJ6PCKfz9yYneginph4mCaGnk5OTsz/Fk8NwwL3J/G%0AyOY7tG4ITbs/DtD/%0AGv2HgmM5WfZ+fdm8qgTE7Cn8nJhYWJDuFU/t6FEk4OEn73XdSh3PQUfHlLHU7II8JkJj8vRR/O35vMLEzclKIXsYARwK/5+2ybDDb+Axydf8SpjDDD0GIBwl%0Attwsy9iyXMZzKph%0ACBACF/eUuVhhNAf7F4G1KSzdXpQ2sJC/jYX7b6D46HrGTBTpkNOf5SfXJh43CWcTUhXhxdKyHN3phhh5yQgzH73XfQPP+SyGdQhH+sQezyNhJHIhsGUAgqYv%0AHNXjfbWfD+Rmcvc%0Ai52Rcfsh2OE94GfA0i1m0nCoDITwzZ0fEvJTW4fTIJdMOHcWYTZBKOdgEE+CXiYnbvLsmXoud2dqLjNxM2ovN8fG2tTn6DXP3OPYSGPC/KOef1FXja1iOnvp%0AhJEO+QFCuV+H3OO%0AJhcn8/Uno7OeAEcrcTw/nFh7e5uIbwpxJZKbgSR+hV7spdQnxJLUTF6+OcG5EQtm4M4Ue4s4CekKJEUo3Zufmpu7kMKABbTaTyS5kmJnGg3YCWZKEEWA7rbh%0AoQug0WBU6anxASIYr%0A9RHOLSzMDiWEQZfN5m+D8aF3iQ6Sc3cg2kCDkMzkABYlO/U5wNzmMRDC4QlCtWOhbM8Jx0WEU5dC2Jb5iezIhJ8fzmUnvudyE6jEW9GaPijuu7mHPyHhTbhZ%0AD3+4P5XNwpfgax89%0AzEzC4V3Czzdi+T6IttVcFmF27sGdjjyADo1GyNQ99RmC3U95OOyH2MxiM42MNDsx/3h2Ojv7GL7MTYDRMyNt+9KpibYEuFP18ghBpqZYXJvMT8Gw7NFhpo+w%0A60u52/ns3MRjGEO%0A3QImZCQgR+IJ6eRrsktk9WMPD+8EtOCeP9+ExEM7+JCUIUe6BZIDwsnSoA2EWh0oWHGIGjA3/lyTMZiaGEc7Pghbu5IBQfoRpw2OObYmDGJmdhjwOILJz4GO%0A4yEw57lEeGrvBzD%0AFByCQi5C6DkI8Is6i6DDjGhTz80LXSzABhpk0oAclCFgjQPeHnmUy06Q+Mdyo7dT+HRjo3cUtG3YGZwmjNZuGGJAm7Vpq7VE8DirpzvytJwuzUcB3m7kwuzG%0AXmWTvq5zyL8zI77%0AwFTmjE7lf3us8GTefS496Wb8L+HP3AJwqnPN7+P5VJ9KQy/ie9zHUlEC15+wAi7mffjWejlbbZZEVQDur/zUySfYRzn73OqFKUucNTjG5HqIAkAG743MX8b/%0Ac6NJGEiWkg98fD%0ACCbG26ORPiZyGmTCqJibUuR8eMj1gRqeD2mD4PnwISfPDh1NZ1kz0T9FhwJn6jEQPb2GaA2YKuWkmi7Yr9RAGUlIumbB9TkKHUClAUpK/3SZUVbQ/0Asmreh%0AHgLAjkyyaR4if4%0ATCw/Wz+EVvVgXLh3r085NMQUdReHV4lIf5KmJ9IEIK9sZyOEUrM/NAtUkKgbABAFmemWLxhRdS81DFTFOZeAfF2HmPCvWmcLvgKhFFemrBS6Pd3MuqJ3X0wu%0APwN9i3zFdP5zzk%0AejsYbkUVIrHWQMo8Z9g9Rz8BMFzDy5KPZDeZNQfKf25Vlm7Cnj5dN2D4jQcgKWggD0xO3H9+8+fgz4GansTKCwhlKCMzNuoJ1xNSDu6wd+fZDAMTqKOoIVNK%0AxSvkk4dT9x0m5%0A2a4Pr4aQ1YdwvVnUzb38LMQsMLVMdvaRjCXJ/CwmLrdYEsNWOllh2GbAqgpk9iZaHjaKXgdG8K1ewsw0VPbdGv/RpRDyfYSR+c3NyWi2RNKhfGCIcYaVeXh/%0AHrgxbwEbfcTeW%0ABDP34KfnVvIf44ePpufYjqcZ09jsNkMZqSdfseEcMsyC1m0aJz9un0JhBhlY8L261FRhwuZqcSAecAYmeQnHjFfwulgdu3JsfhecfNAiC3JOLtxO4/DrNNqD%0ApzwHKTf3b71Zm%0A2YMHYIs9D4CBs7R9Shyk1i0tRDiNJeuEdf//gOfIBmOvHoJpaqHFZ6IHeCxFUgWN5mh8iM8Cb+fDN6rSx8En03333LLBAOSNtKUS6OUFZvoeTUzsVz7IM2oY%0A6z/Oqtm+gJvr8%0ArcTHhPB4zn7wKPgvMztTZJg4j0SoGDHZC8p+viA7uFWY3OpsVH21rxCiE8VFqh1DHSSMp2Re9+0apkpMAAAB0SURBVM88xlv24n1aXM9LY+V4xUOPXrySaFX%0AW4+OTU/VDesOn%0ArIz8WcJvWcaEY8LrL2PCMeH1lzHhmPD6y5hwTHj9ZUw4Jrz+MiYcE15/GROOCa+/jAnHhNdfxoRjwusvY8Ix4fWXMeGY8PrLmHBMeP3l/wEeEliA+LMiTQAA%0AAABJRU5ErkJggg=='; export const images = [prefix + 'assets/image1.png', hwLogo]; diff --git a/devui/image-preview/demo/image-preview-demo.component.ts b/devui/image-preview/demo/image-preview-demo.component.ts index 17c89b0e..776bbb01 100644 --- a/devui/image-preview/demo/image-preview-demo.component.ts +++ b/devui/image-preview/demo/image-preview-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ diff --git a/devui/image-preview/demo/image-preview-demo.module.ts b/devui/image-preview/demo/image-preview-demo.module.ts index a36889d7..06dfc003 100644 --- a/devui/image-preview/demo/image-preview-demo.module.ts +++ b/devui/image-preview/demo/image-preview-demo.module.ts @@ -42,6 +42,6 @@ import { ZIndexComponent } from './z-index/z-index.component'; CustomOpenComponent, ZIndexComponent ], - + }) export class ImagePreviewDemoModule { } diff --git a/devui/image-preview/image-preview.directive.ts b/devui/image-preview/image-preview.directive.ts index 09aacbbe..2d5a0611 100644 --- a/devui/image-preview/image-preview.directive.ts +++ b/devui/image-preview/image-preview.directive.ts @@ -10,7 +10,7 @@ export class ImagePreviewDirective implements OnInit, OnDestroy { constructor( private elementRef: ElementRef, private modalService: ModalService - ) { } + ) { } @Input() customSub: Subject; @Input() disableDefault = false; @@ -23,14 +23,14 @@ export class ImagePreviewDirective implements OnInit, OnDestroy { return !this.disableDefault; } @HostListener('click', ['$event']) - onClick($event) { - if (this.disableDefault) { - return; - } - const target = $event.target; - if (target && target.nodeName.toLowerCase() === 'img') { - this.imagePreView(target as HTMLElement); - } + onClick($event) { + if (this.disableDefault) { + return; + } + const target = $event.target; + if (target && target.nodeName.toLowerCase() === 'img') { + this.imagePreView(target as HTMLElement); + } } ngOnInit(): void { diff --git a/devui/image-preview/image-preview.module.ts b/devui/image-preview/image-preview.module.ts index 0b24249a..176c56c0 100644 --- a/devui/image-preview/image-preview.module.ts +++ b/devui/image-preview/image-preview.module.ts @@ -22,7 +22,7 @@ import { ImagePreviewDirective } from './image-preview.directive'; exports: [ ImagePreviewDirective ], - + }) export class ImagePreviewModule { } diff --git a/devui/image-preview/transformable-element.ts b/devui/image-preview/transformable-element.ts index abdd8753..b2f97418 100644 --- a/devui/image-preview/transformable-element.ts +++ b/devui/image-preview/transformable-element.ts @@ -163,7 +163,7 @@ export class TransformableElement { translateX = this.translateX, translateY = this.translateY, turn = this.turn - ) { + ) { if (!target) { target = this.element; } target.style.transform = `translate(${translateX}px, ${translateY}px) scale(${zoom}) rotate(${turn}turn)`; } diff --git a/devui/input-number/demo/input-number-demo.component.ts b/devui/input-number/demo/input-number-demo.component.ts index 06762b6e..bf760b42 100755 --- a/devui/input-number/demo/input-number-demo.component.ts +++ b/devui/input-number/demo/input-number-demo.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'd-demo-input-number', diff --git a/devui/input-number/input-number.component.ts b/devui/input-number/input-number.component.ts index f3a7b37a..e0259fc5 100755 --- a/devui/input-number/input-number.component.ts +++ b/devui/input-number/input-number.component.ts @@ -20,7 +20,6 @@ import { fromEvent, Observable, Subscription } from 'rxjs'; const INPUT_NUMBER_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, - // tslint:disable-next-line useExisting: forwardRef(() => InputNumberComponent), multi: true }; @@ -83,10 +82,10 @@ export class InputNumberComponent implements ControlValueAccessor, OnChanges, On } private onTouchedCallback = () => { - } + }; private onChangeCallback = (v: any) => { - } + }; constructor(private cdr: ChangeDetectorRef, private el: ElementRef, private renderer: Renderer2, @Inject(DOCUMENT) private doc: any) { @@ -250,7 +249,7 @@ export class InputNumberComponent implements ControlValueAccessor, OnChanges, On } else { const decimals = this.getMaxDecimals(this.value); const floatValue = type === 'increase' ? (this.value + this.step) : (this.value - this.step); - if (this.matchReg(floatValue + '')) { + if (this.matchReg(String(floatValue))) { this.updateValue(parseFloat(floatValue.toFixed(decimals))); } } @@ -339,7 +338,7 @@ export class InputNumberComponent implements ControlValueAccessor, OnChanges, On this.keyBoardControl(event); } - protectInput(event) { + protectInput(event: Event) { if (this.disabled) { return; } diff --git a/devui/input-number/input-number.spec.ts b/devui/input-number/input-number.spec.ts index aad23af3..0e1458c7 100644 --- a/devui/input-number/input-number.spec.ts +++ b/devui/input-number/input-number.spec.ts @@ -357,13 +357,13 @@ describe('input-number', () => { tick(); fixture.detectChanges(); inputEl = debugEl.query(By.css('.input-container .input-box')).nativeElement; - expect(inputEl.value).toEqual(component.max + ''); + expect(inputEl.value).toEqual(String(component.max)); descBtn.dispatchEvent(new Event('click')); fixture.detectChanges(); tick(); fixture.detectChanges(); inputEl = debugEl.query(By.css('.input-container .input-box')).nativeElement; - expect(inputEl.value).toEqual(component.max + ''); + expect(inputEl.value).toEqual(String(component.max)); component.min = component.max = null; fixture.detectChanges(); @@ -384,7 +384,7 @@ describe('input-number', () => { tick(); fixture.detectChanges(); inputEl = debugEl.query(By.css('.input-container .input-box')).nativeElement; - expect(inputEl.value).toEqual(component.max + ''); + expect(inputEl.value).toEqual(String(component.max)); })); it('should not decrease when less than min number', fakeAsync(() => { @@ -402,7 +402,7 @@ describe('input-number', () => { tick(); fixture.detectChanges(); inputEl = debugEl.query(By.css('.input-container .input-box')).nativeElement; - expect(inputEl.value).toEqual(component.min + ''); + expect(inputEl.value).toEqual(String(component.min)); })); // TODO float number & data from clipBoard diff --git a/devui/karma.conf.js b/devui/karma.conf.js index 1a2ad57e..910ebea9 100755 --- a/devui/karma.conf.js +++ b/devui/karma.conf.js @@ -35,4 +35,4 @@ module.exports = function (config) { }, singleRun: false, }); -}; \ No newline at end of file +}; diff --git a/devui/layout/class.directive.ts b/devui/layout/class.directive.ts new file mode 100644 index 00000000..8df259bb --- /dev/null +++ b/devui/layout/class.directive.ts @@ -0,0 +1,63 @@ +import { Directive, ElementRef, Input, OnDestroy, OnInit, Renderer2 } from '@angular/core'; +import { Subject } from 'rxjs'; +import { takeUntil } from 'rxjs/operators'; +import { DBreakpoints, DResponseParameter } from './layout.types'; +import { DScreenMediaQueryService } from './screen-media-query.service'; + +@Directive({ + selector: `[dClass]`, +}) + +export class DClassDirective implements OnInit, OnDestroy { + @Input() dClass: DResponseParameter; + + private destroy$ = new Subject(); + private executedClassList: string[] = []; + + constructor( + private elementRef: ElementRef, + private renderer: Renderer2, + private screenQueryService: DScreenMediaQueryService + ) { } + + ngOnInit(): void { + this.screenQueryService.getPoint() + .pipe(takeUntil(this.destroy$)) + .subscribe(({ currentPoint }) => { + this.updateClass(currentPoint); + }); + } + + /* TODO: 参数需要优化,不仅可以设置断点,还可以设置通用 */ + updateClass(currentPoint) { + let finalClassList = []; + + if (!Array.isArray(this.dClass)) { + for (const point of DBreakpoints) { + if (this.dClass[point]) { + finalClassList = [...finalClassList, ...this.dClass[point]]; + } + if (currentPoint === point) { + break; + } + } + } else if (this.dClass) { + finalClassList = [...this.dClass]; + } + + this.executedClassList.forEach(className => { + this.renderer.removeClass(this.elementRef.nativeElement, className); + }); + + finalClassList.forEach(className => { + this.renderer.addClass(this.elementRef.nativeElement, className); + }); + + this.executedClassList = finalClassList; + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } +} diff --git a/devui/layout/col.component.ts b/devui/layout/col.component.ts new file mode 100644 index 00000000..1a052490 --- /dev/null +++ b/devui/layout/col.component.ts @@ -0,0 +1,40 @@ +import { ChangeDetectionStrategy, Component, ElementRef, HostBinding, Input, OnChanges, OnInit, Renderer2 } from '@angular/core'; +import { updateClassList } from './layout-utils'; +import { DResponseParameter } from './layout.types'; + +@Component({ + selector: 'd-col', + changeDetection: ChangeDetectionStrategy.OnPush, + template: ` + + `, + styles: [` + :host.d-col { + padding: 0; + } + `] +}) +export class DColComponent implements OnInit, OnChanges { + + /* TODO: d-hide如何对外提供 */ + + @HostBinding('class.d-col') dCol = true; + + @Input() dSpan: DResponseParameter = 'auto'; + @Input() dOffset: DResponseParameter; + @Input() dPush: DResponseParameter; + @Input() dPull: DResponseParameter; + + constructor( + private elementRef: ElementRef, + private renderer: Renderer2, + ) { } + + ngOnInit(): void { + updateClassList(this, this.elementRef, this.renderer); + } + + ngOnChanges(): void { + updateClassList(this, this.elementRef, this.renderer); + } +} diff --git a/devui/layout/demo/basic/layout-basic.component.html b/devui/layout/demo/basic/layout-basic.component.html index 3020a6f2..12ad489a 100644 --- a/devui/layout/demo/basic/layout-basic.component.html +++ b/devui/layout/demo/basic/layout-basic.component.html @@ -1,10 +1,10 @@ - + Header Content Footer - + Header Aside @@ -13,7 +13,7 @@ Footer - + Header Content @@ -22,7 +22,7 @@ Footer - + Aside Header diff --git a/devui/layout/demo/basic/layout-basic.component.scss b/devui/layout/demo/basic/layout-basic.component.scss index 2550cbe3..2f1a8062 100644 --- a/devui/layout/demo/basic/layout-basic.component.scss +++ b/devui/layout/demo/basic/layout-basic.component.scss @@ -1,7 +1,7 @@ @import '~ng-devui/styles-var/devui-var.scss'; -.basic-usage { - box-shadow: $devui-shadow-length-base; // TODO: color not variable +.layout-wrapper { + box-shadow: $devui-shadow-length-base $devui-light-shadow; margin-top: 36px; &:first-child { @@ -23,13 +23,13 @@ d-aside { display: flex; justify-content: center; align-items: center; - background-color: $devui-area; + background-color: $devui-base-bg; } d-content { line-height: 200px; text-align: center; - background-color: $devui-global-bg-normal; + background-color: $devui-global-bg; } d-footer { diff --git a/devui/layout/demo/grid/alone-flex/alone-flex.component.html b/devui/layout/demo/grid/alone-flex/alone-flex.component.html new file mode 100644 index 00000000..6c711e4d --- /dev/null +++ b/devui/layout/demo/grid/alone-flex/alone-flex.component.html @@ -0,0 +1,33 @@ +

Grid

+

Basic

+ + col-6 + col-6 + col-2 + flex-1 + +

Responsive

+ + col-6 + col-6 + col-2 + flex-1 + + +

No Grid

+

Basic

+
+
col
+
+
item
+
item
+
+
+

Responsive

+
+
col
+
+
item
+
item
+
+
diff --git a/devui/layout/demo/grid/alone-flex/alone-flex.component.ts b/devui/layout/demo/grid/alone-flex/alone-flex.component.ts new file mode 100644 index 00000000..85656783 --- /dev/null +++ b/devui/layout/demo/grid/alone-flex/alone-flex.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-alone-flex', + templateUrl: './alone-flex.component.html', +}) +export class AloneFlexComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/alone-space-gutter/alone-space-gutter.component.html b/devui/layout/demo/grid/alone-space-gutter/alone-space-gutter.component.html new file mode 100644 index 00000000..fb7c00e4 --- /dev/null +++ b/devui/layout/demo/grid/alone-space-gutter/alone-space-gutter.component.html @@ -0,0 +1,42 @@ +

Baisc

+

Gutter

+
+
+
col
+
+
+
item
+
item
+
+
+

Space

+
+
+
col
+
+
+
item
+
item
+
+
+

Responsive

+

Gutter

+
+
+
col
+
+
+
item
+
item
+
+
+

Space

+
+
+
col
+
+
+
item
+
item
+
+
diff --git a/devui/layout/demo/grid/alone-space-gutter/alone-space-gutter.component.ts b/devui/layout/demo/grid/alone-space-gutter/alone-space-gutter.component.ts new file mode 100644 index 00000000..c2757d1e --- /dev/null +++ b/devui/layout/demo/grid/alone-space-gutter/alone-space-gutter.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-alone-space-gutter', + templateUrl: './alone-space-gutter.component.html', +}) +export class AloneSpaceGutterComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/class-demo/class-demo.component.html b/devui/layout/demo/grid/class-demo/class-demo.component.html new file mode 100644 index 00000000..34e1473e --- /dev/null +++ b/devui/layout/demo/grid/class-demo/class-demo.component.html @@ -0,0 +1,35 @@ +

Grid

+

Basic

+ + col-8 + col-8 + col-8 + +

Responsive

+ + col-8 + col-8 + col-8 + + +

No Grid

+

Basic

+
+
+
col
+
+
+
item
+
item
+
+
+

Responsive

+
+
+
col
+
+
+
item
+
item
+
+
diff --git a/devui/layout/demo/grid/class-demo/class-demo.component.scss b/devui/layout/demo/grid/class-demo/class-demo.component.scss new file mode 100644 index 00000000..892c0416 --- /dev/null +++ b/devui/layout/demo/grid/class-demo/class-demo.component.scss @@ -0,0 +1,9 @@ +@import '~ng-devui/styles-var/devui-var.scss'; + +.col-green-color { + background: $devui-success !important; +} + +.font-size-price { + font-size: $devui-font-size-price; +} diff --git a/devui/layout/demo/grid/class-demo/class-demo.component.ts b/devui/layout/demo/grid/class-demo/class-demo.component.ts new file mode 100644 index 00000000..15469514 --- /dev/null +++ b/devui/layout/demo/grid/class-demo/class-demo.component.ts @@ -0,0 +1,15 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-class-demo', + templateUrl: './class-demo.component.html', + styleUrls: ['./class-demo.component.scss'] +}) +export class ClassDemoComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/configurator-demo/configurator-demo.component.html b/devui/layout/demo/grid/configurator-demo/configurator-demo.component.html new file mode 100644 index 00000000..f72bc718 --- /dev/null +++ b/devui/layout/demo/grid/configurator-demo/configurator-demo.component.html @@ -0,0 +1 @@ +

configurator-demo works!

diff --git a/devui/layout/demo/grid/configurator-demo/configurator-demo.component.ts b/devui/layout/demo/grid/configurator-demo/configurator-demo.component.ts new file mode 100644 index 00000000..5257c7c0 --- /dev/null +++ b/devui/layout/demo/grid/configurator-demo/configurator-demo.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-configurator-demo', + templateUrl: './configurator-demo.component.html', +}) +export class ConfiguratorDemoComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/flex-align-justify/flex-align-justify.component.html b/devui/layout/demo/grid/flex-align-justify/flex-align-justify.component.html new file mode 100644 index 00000000..7c224c3f --- /dev/null +++ b/devui/layout/demo/grid/flex-align-justify/flex-align-justify.component.html @@ -0,0 +1,88 @@ +

Basic

+

Justify Left

+ + col-6 + col-6 + col-6 + +

Justify Center

+ + col-6 + col-6 + col-6 + +

Justify Right

+ + col-6 + col-6 + col-6 + +

Justify Around

+ + col-6 + col-6 + col-6 + +

Justify Between

+ + col-6 + col-6 + col-6 + +

Align Top

+ + col-6 + col-6 + col-6 + col-6 + +

Align Center

+ + col-6 + col-6 + col-6 + col-6 + +

Align Bottom

+ + col-6 + col-6 + col-6 + col-6 + +

Align Baseline

+ + col-6 + col-6 + col-6 + col-6 + +

Align Stretch

+ + col-6 + col-6 + col-6 + col-6 + +

Col Align Self

+ + col-6 + col-6 + col-6、align-self-center + col-6 + + +

Responsive

+

Justify Responsive

+ + col-6 + col-6 + col-6 + +

Align Responsive

+ + col-6 + col-6 + col-6 + col-6 + diff --git a/devui/layout/demo/grid/flex-align-justify/flex-align-justify.component.ts b/devui/layout/demo/grid/flex-align-justify/flex-align-justify.component.ts new file mode 100644 index 00000000..b13e0437 --- /dev/null +++ b/devui/layout/demo/grid/flex-align-justify/flex-align-justify.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-flex-align-justify', + templateUrl: './flex-align-justify.component.html', +}) +export class FlexAlignJustifyComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/flex-order/flex-order.component.html b/devui/layout/demo/grid/flex-order/flex-order.component.html new file mode 100644 index 00000000..d2eddce0 --- /dev/null +++ b/devui/layout/demo/grid/flex-order/flex-order.component.html @@ -0,0 +1,13 @@ +

Basic

+ + col-4、order-3 + col-8、order-2 + col-12、order-1 + + +

Responsive

+ + col-4 + col-8 + col-12 + diff --git a/devui/layout/demo/grid/flex-order/flex-order.component.ts b/devui/layout/demo/grid/flex-order/flex-order.component.ts new file mode 100644 index 00000000..77d4181b --- /dev/null +++ b/devui/layout/demo/grid/flex-order/flex-order.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-flex-order', + templateUrl: './flex-order.component.html', +}) +export class FlexOrderComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/flex-wrap/flex-wrap.component.html b/devui/layout/demo/grid/flex-wrap/flex-wrap.component.html new file mode 100644 index 00000000..33363fd3 --- /dev/null +++ b/devui/layout/demo/grid/flex-wrap/flex-wrap.component.html @@ -0,0 +1 @@ +

flex-wrap works!

diff --git a/devui/layout/demo/grid/flex-wrap/flex-wrap.component.ts b/devui/layout/demo/grid/flex-wrap/flex-wrap.component.ts new file mode 100644 index 00000000..88765521 --- /dev/null +++ b/devui/layout/demo/grid/flex-wrap/flex-wrap.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-flex-wrap', + templateUrl: './flex-wrap.component.html', +}) +export class FlexWrapComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/grid-basic/grid-basic.component.html b/devui/layout/demo/grid/grid-basic/grid-basic.component.html new file mode 100644 index 00000000..e87a245b --- /dev/null +++ b/devui/layout/demo/grid/grid-basic/grid-basic.component.html @@ -0,0 +1,26 @@ +

Basic

+ + col-12 + col-12 + + + + col-8 + col-8 + col-8 + + + + col-6 + col-6 + col-6 + col-6 + + +

Responsive

+ + col-12, col-xs-6 + col-12, col-xs-6 + col-12, col-xs-6 + col-12, col-xs-6 + diff --git a/devui/layout/demo/grid/grid-basic/grid-basic.component.ts b/devui/layout/demo/grid/grid-basic/grid-basic.component.ts new file mode 100644 index 00000000..cef9a97a --- /dev/null +++ b/devui/layout/demo/grid/grid-basic/grid-basic.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-grid-basic', + templateUrl: './grid-basic.component.html', +}) +export class GridBasicComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/grid-cols/grid-cols.component.html b/devui/layout/demo/grid/grid-cols/grid-cols.component.html new file mode 100644 index 00000000..3bc0d77a --- /dev/null +++ b/devui/layout/demo/grid/grid-cols/grid-cols.component.html @@ -0,0 +1 @@ +

grid-cols works!

diff --git a/devui/layout/demo/grid/grid-cols/grid-cols.component.ts b/devui/layout/demo/grid/grid-cols/grid-cols.component.ts new file mode 100644 index 00000000..d417c79a --- /dev/null +++ b/devui/layout/demo/grid/grid-cols/grid-cols.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-grid-cols', + templateUrl: './grid-cols.component.html', +}) +export class GridColsComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/grid-gutter/grid-gutter.component.html b/devui/layout/demo/grid/grid-gutter/grid-gutter.component.html new file mode 100644 index 00000000..085a178d --- /dev/null +++ b/devui/layout/demo/grid/grid-gutter/grid-gutter.component.html @@ -0,0 +1,73 @@ +

Basic

+

Horizontal

+ + +
col-8
+
+ +
col-8
+
+ +
col-8
+
+
+

Vertical

+ + +
col-12
+
+ +
col-12
+
+ +
col-12
+
+ +
col-12
+
+
+

Horizontal & Vertical

+ + +
col-12
+
+ +
col-12
+
+ +
col-12
+
+ +
col-12
+
+
+

Parent No Outer

+ + +
col-12
+
+ +
col-12
+
+ +
col-12
+
+ +
col-12
+
+
+

Responsive

+ + +
col-12
+
+ +
col-12
+
+ +
col-12
+
+ +
col-12
+
+
diff --git a/devui/layout/demo/grid/grid-gutter/grid-gutter.component.ts b/devui/layout/demo/grid/grid-gutter/grid-gutter.component.ts new file mode 100644 index 00000000..73676ca6 --- /dev/null +++ b/devui/layout/demo/grid/grid-gutter/grid-gutter.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-grid-gutter', + templateUrl: './grid-gutter.component.html', +}) +export class GridGutterComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/grid-offset/grid-offset.component.html b/devui/layout/demo/grid/grid-offset/grid-offset.component.html new file mode 100644 index 00000000..906beff0 --- /dev/null +++ b/devui/layout/demo/grid/grid-offset/grid-offset.component.html @@ -0,0 +1,11 @@ +

Basic

+ + col-8 + col-8、offset-8 + + +

Responsive

+ + col + col + diff --git a/devui/layout/demo/grid/grid-offset/grid-offset.component.ts b/devui/layout/demo/grid/grid-offset/grid-offset.component.ts new file mode 100644 index 00000000..dc6a1cc2 --- /dev/null +++ b/devui/layout/demo/grid/grid-offset/grid-offset.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-grid-offset', + templateUrl: './grid-offset.component.html', +}) +export class GridOffsetComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/grid-pull-push/grid-pull-push.component.html b/devui/layout/demo/grid/grid-pull-push/grid-pull-push.component.html new file mode 100644 index 00000000..7606d596 --- /dev/null +++ b/devui/layout/demo/grid/grid-pull-push/grid-pull-push.component.html @@ -0,0 +1,4 @@ + + col-16、push-8 + col-8、pull-16 + diff --git a/devui/layout/demo/grid/grid-pull-push/grid-pull-push.component.ts b/devui/layout/demo/grid/grid-pull-push/grid-pull-push.component.ts new file mode 100644 index 00000000..8955b892 --- /dev/null +++ b/devui/layout/demo/grid/grid-pull-push/grid-pull-push.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-grid-pull-push', + templateUrl: './grid-pull-push.component.html', +}) +export class GridPullPushComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/grid-space/grid-space.component.html b/devui/layout/demo/grid/grid-space/grid-space.component.html new file mode 100644 index 00000000..4f699f2c --- /dev/null +++ b/devui/layout/demo/grid/grid-space/grid-space.component.html @@ -0,0 +1,58 @@ +

Basic

+

Horizontal

+ + +
col-7
+
+ +
col-7
+
+ +
col-7
+
+
+

Vertical

+ + +
col-12
+
+ +
col-12
+
+ +
col-12
+
+ +
col-12
+
+
+

Horizontal & Vertical

+ + +
col-11
+
+ +
col-11
+
+ +
col-11
+
+ +
col-11
+
+
+

Responsive

+ + +
col-11
+
+ +
col-11
+
+ +
col-11
+
+ +
col-11
+
+
diff --git a/devui/layout/demo/grid/grid-space/grid-space.component.ts b/devui/layout/demo/grid/grid-space/grid-space.component.ts new file mode 100644 index 00000000..ac5080cc --- /dev/null +++ b/devui/layout/demo/grid/grid-space/grid-space.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-grid-space', + templateUrl: './grid-space.component.html', +}) +export class GridSpaceComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/resposive-demo/resposive-demo.component.html b/devui/layout/demo/grid/resposive-demo/resposive-demo.component.html new file mode 100644 index 00000000..e82cfa78 --- /dev/null +++ b/devui/layout/demo/grid/resposive-demo/resposive-demo.component.html @@ -0,0 +1 @@ +

resposive-demo works!

diff --git a/devui/layout/demo/grid/resposive-demo/resposive-demo.component.ts b/devui/layout/demo/grid/resposive-demo/resposive-demo.component.ts new file mode 100644 index 00000000..f1121adb --- /dev/null +++ b/devui/layout/demo/grid/resposive-demo/resposive-demo.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-resposive-demo', + templateUrl: './resposive-demo.component.html', +}) +export class ResposiveDemoComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/grid/style-demo/style-demo.component.html b/devui/layout/demo/grid/style-demo/style-demo.component.html new file mode 100644 index 00000000..7e9adcaa --- /dev/null +++ b/devui/layout/demo/grid/style-demo/style-demo.component.html @@ -0,0 +1,37 @@ +

Grid

+

Basic

+ + col-8 + col-8 + col-8 + +

Responsive

+ + col-8 + col-8 + col-8 + + +

No Grid

+

Basic

+
+
+
col
+
+
+
item
+
item
+
+
+

Responsive

+
+
+
col
+
+
+
+ item +
+
item
+
+
diff --git a/devui/layout/demo/grid/style-demo/style-demo.component.ts b/devui/layout/demo/grid/style-demo/style-demo.component.ts new file mode 100644 index 00000000..ee1ecaca --- /dev/null +++ b/devui/layout/demo/grid/style-demo/style-demo.component.ts @@ -0,0 +1,14 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'd-style-demo', + templateUrl: './style-demo.component.html', +}) +export class StyleDemoComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devui/layout/demo/layout-demo.component.html b/devui/layout/demo/layout-demo.component.html index 3cdf0380..19fdd59b 100644 --- a/devui/layout/demo/layout-demo.component.html +++ b/devui/layout/demo/layout-demo.component.html @@ -2,22 +2,100 @@
{{ 'components.layout.basicDemo.title' | translate }}
+
{{ 'components.layout.basicDemo.description' | translate }}
+ + + +
+ +
+
{{ 'components.layout.gutterDemo.title' | translate }}
+
{{ 'components.layout.gutterDemo.description' | translate }}
+ + + +
+ +
+
{{ 'components.layout.spaceDemo.title' | translate }}
+
{{ 'components.layout.spaceDemo.description' | translate }}
+ + + +
+ +
+
{{ 'components.layout.offsetDemo.title' | translate }}
+ + + +
+ +
+
{{ 'components.layout.alignJustifyDemo.title' | translate }}
+ + + +
+ +
+
{{ 'components.layout.orderDemo.title' | translate }}
+
{{ 'components.layout.orderDemo.description' | translate }}
+ + + +
+ +
+
{{ 'components.layout.flexDemo.title' | translate }}
+
{{ 'components.layout.flexDemo.description' | translate }}
+ + + +
+ +
+
{{ 'components.layout.spaceGutterDemo.title' | translate }}
+
{{ 'components.layout.spaceGutterDemo.description' | translate }}
+ + + +
+ +
+
{{ 'components.layout.classDemo.title' | translate }}
+
{{ 'components.layout.classDemo.description' | translate }}
+ + + +
+ +
+
{{ 'components.layout.styleDemo.title' | translate }}
+
{{ 'components.layout.styleDemo.description' | translate }}
+ + + +
+ +
+
{{ 'components.layout.layoutContainerDemo.title' | translate }}
-
-
{{ 'components.layout.appDemo1.title' | translate }}
-
{{ 'components.layout.appDemo1.description' | translate }}
+
+
{{ 'components.layout.layoutContainerDemo1.title' | translate }}
+
{{ 'components.layout.layoutContainerDemo1.description' | translate }}
-
-
{{ 'components.layout.appDemo2.title' | translate }}
-
{{ 'components.layout.appDemo2.description' | translate }}
+
+
{{ 'components.layout.layoutContainerDemo2.title' | translate }}
+
{{ 'components.layout.layoutContainerDemo2.description' | translate }}
diff --git a/devui/layout/demo/layout-demo.component.scss b/devui/layout/demo/layout-demo.component.scss new file mode 100644 index 00000000..b75b5845 --- /dev/null +++ b/devui/layout/demo/layout-demo.component.scss @@ -0,0 +1,63 @@ +@import '~ng-devui/styles-var/devui-var.scss'; + +::ng-deep { + d-row { + text-align: center; + + &.base-container { + background: $devui-global-bg; + height: 100px; + } + + d-col { + &.full-height { + height: 100%; + } + + line-height: 60px; + color: $devui-light-text; + } + } + + .d-common-layout d-col { + background: $devui-brand; + } + + .d-stripe-layout d-row { + margin: 12px !important; + + d-col:nth-child(2n + 1) { + background: $devui-brand-hover; + } + + d-col:nth-child(2n + 2) { + background: $devui-brand; + } + } + + d-col .content-box { + background: $devui-brand; + + &.color-hover { + background: $devui-brand-hover; + } + } + + .brand-content { + background: $devui-brand; + color: $devui-light-text; + text-align: center; + line-height: 30px; + } + + .hover-content { + background: $devui-brand-hover; + color: $devui-light-text; + text-align: center; + line-height: 30px; + } + + .base-container { + background: $devui-global-bg; + } +} diff --git a/devui/layout/demo/layout-demo.component.ts b/devui/layout/demo/layout-demo.component.ts index c04765ba..fbd3f8bd 100644 --- a/devui/layout/demo/layout-demo.component.ts +++ b/devui/layout/demo/layout-demo.component.ts @@ -1,12 +1,57 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { DevuiSourceData } from 'ng-devui/shared/devui-codebox'; +import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'd-demo-input-number', templateUrl: './layout-demo.component.html', + styleUrls: [ + './layout-demo.component.scss' + ] }) export class LayoutDemoComponent implements OnInit, OnDestroy { + GridBasic: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/grid-basic/grid-basic.component.html?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/grid-basic/grid-basic.component.ts?raw') }, + ]; + GridGutter: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/grid-gutter/grid-gutter.component.html?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/grid-gutter/grid-gutter.component.ts?raw') }, + ]; + GridSpace: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/grid-space/grid-space.component.html?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/grid-space/grid-space.component.ts?raw') }, + ]; + GridOffset: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/grid-offset/grid-offset.component.html?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/grid-offset/grid-offset.component.ts?raw') }, + ]; + FlexAlignjustify: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/flex-align-justify/flex-align-justify.component.html?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/flex-align-justify/flex-align-justify.component.ts?raw') }, + ]; + FlexOrder: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/flex-order/flex-order.component.html?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/flex-order/flex-order.component.ts?raw') }, + ]; + AloneFlex: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/alone-flex/alone-flex.component.html?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/alone-flex/alone-flex.component.ts?raw') }, + ]; + AloneSpaceGutter: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/alone-space-gutter/alone-space-gutter.component.html?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/alone-space-gutter/alone-space-gutter.component.ts?raw') }, + ]; + ClassDemo: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/class-demo/class-demo.component.html?raw') }, + { title: 'SCSS', language: 'css', code: require('./grid/class-demo/class-demo.component.scss?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/class-demo/class-demo.component.ts?raw') }, + ]; + StyleDemo: Array = [ + { title: 'HTML', language: 'xml', code: require('./grid/style-demo/style-demo.component.html?raw') }, + { title: 'TS', language: 'typescript', code: require('./grid/style-demo/style-demo.component.ts?raw') }, + ]; + LayoutBasic: Array = [ { title: 'HTML', language: 'xml', code: require('./basic/layout-basic.component.html?raw') }, { title: 'TS', language: 'typescript', code: require('./basic/layout-basic.component.ts?raw') }, @@ -47,8 +92,18 @@ export class LayoutDemoComponent implements OnInit, OnDestroy { setNavValues(values) { this.navItems = [ { dAnchorLink: 'basic-usage', value: values['basic-usage'] }, - { dAnchorLink: 'application-scenario1', value: values['application-scenario1'] }, - { dAnchorLink: 'application-scenario2', value: values['application-scenario2'] } + { dAnchorLink: 'gutter', value: values['gutter'] }, + { dAnchorLink: 'space', value: values['space'] }, + { dAnchorLink: 'offset', value: values['offset'] }, + { dAnchorLink: 'align-justify', value: values['align-justify'] }, + { dAnchorLink: 'order', value: values['order'] }, + { dAnchorLink: 'flex', value: values['flex'] }, + { dAnchorLink: 'space-gutter', value: values['space-gutter'] }, + { dAnchorLink: 'class', value: values['class'] }, + { dAnchorLink: 'style', value: values['style'] }, + { dAnchorLink: 'layout-container', value: values['layout-container'] }, + { dAnchorLink: 'layout-container-scenario1', value: values['layout-container-scenario1'] }, + { dAnchorLink: 'layout-container-scenario2', value: values['layout-container-scenario2'] }, ]; } diff --git a/devui/layout/demo/layout-demo.module.ts b/devui/layout/demo/layout-demo.module.ts index a91633d6..0c50cccd 100644 --- a/devui/layout/demo/layout-demo.module.ts +++ b/devui/layout/demo/layout-demo.module.ts @@ -10,6 +10,21 @@ import { DevUICodeboxModule } from 'ng-devui/shared/devui-codebox'; import { TranslateModule } from '@ngx-translate/core'; import { DDemoNavModule } from 'src/app/component/d-demo-nav.module'; import { LayoutBasicComponent } from './basic/layout-basic.component'; +import { AloneFlexComponent } from './grid/alone-flex/alone-flex.component'; +import { AloneSpaceGutterComponent } from './grid/alone-space-gutter/alone-space-gutter.component'; +import { ClassDemoComponent } from './grid/class-demo/class-demo.component'; +import { ConfiguratorDemoComponent } from './grid/configurator-demo/configurator-demo.component'; +import { FlexAlignJustifyComponent } from './grid/flex-align-justify/flex-align-justify.component'; +import { FlexOrderComponent } from './grid/flex-order/flex-order.component'; +import { FlexWrapComponent } from './grid/flex-wrap/flex-wrap.component'; +import { GridBasicComponent } from './grid/grid-basic/grid-basic.component'; +import { GridColsComponent } from './grid/grid-cols/grid-cols.component'; +import { GridGutterComponent } from './grid/grid-gutter/grid-gutter.component'; +import { GridOffsetComponent } from './grid/grid-offset/grid-offset.component'; +import { GridPullPushComponent } from './grid/grid-pull-push/grid-pull-push.component'; +import { GridSpaceComponent } from './grid/grid-space/grid-space.component'; +import { ResposiveDemoComponent } from './grid/resposive-demo/resposive-demo.component'; +import { StyleDemoComponent } from './grid/style-demo/style-demo.component'; import { LayoutDemoComponent } from './layout-demo.component'; import { LayoutTopAsideComponent } from './top-aside/top-aside.component'; import { LayoutTopComponent } from './top/top.component'; @@ -37,6 +52,26 @@ import { LayoutTopComponent } from './top/top.component'; }, ]), ], - declarations: [LayoutDemoComponent, LayoutBasicComponent, LayoutTopComponent, LayoutTopAsideComponent], + declarations: [ + LayoutDemoComponent, + LayoutBasicComponent, + LayoutTopComponent, + LayoutTopAsideComponent, + GridBasicComponent, + GridColsComponent, + GridOffsetComponent, + GridPullPushComponent, + FlexAlignJustifyComponent, + FlexOrderComponent, + FlexWrapComponent, + AloneSpaceGutterComponent, + StyleDemoComponent, + ClassDemoComponent, + ResposiveDemoComponent, + ConfiguratorDemoComponent, + GridGutterComponent, + GridSpaceComponent, + AloneFlexComponent + ], }) -export class LayoutDemoModule {} +export class LayoutDemoModule { } diff --git a/devui/layout/doc/api-cn.md b/devui/layout/doc/api-cn.md index 85336386..258ad129 100644 --- a/devui/layout/doc/api-cn.md +++ b/devui/layout/doc/api-cn.md @@ -6,9 +6,49 @@ import { LayoutModule } from 'ng-devui'; ``` +在全局样式中,引入: +```css +@import '~ng-devui/devui-layout.css'; +``` + 在页面中使用: ```html + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -16,6 +56,63 @@ import { LayoutModule } from 'ng-devui'; ``` + +# d-row +栅格布局行容器,已默认绑定`dFlex`指令,并设定为行容器,可使用 `dFlex(已默认绑定)、dPace、dGutter、dClass、dStyle` 指令进行更多布局设置。 + +# d-col +栅格布局列容器,预期为 `d-row` 的子元素,已默认绑定 `dFlex` 指令,可使用 `dFlex(已默认绑定)、dPace、dGutter、dClass、dStyle` 指令进行更多布局设置。 + +## d-col 参数 +| 参数 | 类型 | 默认 | 说明 | 跳转 Demo |全局配置项| +| :----------------: | :---------: | :------------: | :-----: | :------------------ | | +| dSpan | [`DResponseParameter`](#dresponseparameter)`<[0 - 24] \| 'auto'>` | -- | 设置栅格所占份数(0 - 24)| [栅格基本用法](demo#basic-usage) | +| dOffset | [`DResponseParameter`](#dresponseparameter)`<[0 - 24]>` | -- | 设置元素间隔栅格份数(0 - 24)| [左右偏移](demo#offset) | + +# dFlex +用于快速设置 `Flex` 布局属性的指令,已默认绑定到 `d-row`、`d-col` 容器,也使用于其他任何需要使用 `flex` 布局的元素上。 +## dFlex 参数 +| 参数 | 类型 | 默认 | 说明 | 跳转 Demo |全局配置项| +| :----------------: | :---------: | :------------: | :-----: | :------------------ | | +| dFlex | [`DResponseParameter`](#dresponseparameter)`` | -- | 设置元素flex属性 | [Flex使用](demo#flex) | +| dFlexContainer | `'row' \| 'column'` | -- | 设置元素是否为flex容器且设置子元素排列方向 | [Flex使用](demo#flex) | +| dAlign | [`DResponseParameter`](#dresponseparameter)`<`[`DAlign`](#dalign)`>` | -- | 设置子元素交叉轴对齐方式 | [对齐](demo#align-justify) | +| dJustify | [`DResponseParameter`](#dresponseparameter)`<`[`DJustify`](#djustify)`>` | -- | 设置子元素主轴对齐方式 | [对齐](demo#align-justify) | +| dAlignSelf | [`DResponseParameter`](#dresponseparameter)`<`[`DAlignSelf`](#dalignself)`>` | -- | 设置元素自身交叉轴对齐方式 | [对齐](demo#align-justify) | +| dOrder | [`DResponseParameter`](#dresponseparameter)`<[0 - 24]>` | -- | 设置元素排序(0 - 24)| [排序](demo#order) | + +# dSpace +以设置子元素margin值方式,实现子元素间距控制。 +## dSpace 参数 +| 参数 | 类型 | 默认 | 说明 | 跳转 Demo |全局配置项| +| :----------------: | :---------: | :------------: | :-----: | :------------------ | | +| dSpace | [`DResponseParameter`](#dresponseparameter)`` | -- | 设置子级元素间距值 | [栅格间距(Space)](demo#space) | +| dSpaceDirection | [`DResponseParameter`](#dresponseparameter)`<'vertical' \| 'horizontal'>` | 'vertical' | 设置默认间距方向 | [栅格间距(Space)](demo#space) | + +# dGutter +以设置子元素padding值方式,实现子元素间间距控制。 +## dGutter 参数 +| 参数 | 类型 | 默认 | 说明 | 跳转 Demo |全局配置项| +| :----------------: | :---------: | :------------: | :-----: | :------------------ | | +| dGutter | [`DResponseParameter`](#dresponseparameter)`` | -- | 设置子级元素间距值 | [栅格间距(Gutter)](demo#gutter) | +| dGutterDirection | [`DResponseParameter`](#dresponseparameter)`<'vertical' \| 'horizontal'>` | 'horizontal' | 设置默认间距方向 | [栅格间距(Gutter)](demo#gutter) | +| dGutterNoOuter | [`DResponseParameter`](#dresponseparameter)`` | false | 设置是否消除设置子元素padding对整体布局外层产生的边距 | [间距(通用)](demo#space-gutter) | + +# dClass +可使用[dClass]对元素进行 `class` 名绑定设置,支持响应式并可在不同断点下 `class` 合并。 +## dClass 参数 +| 参数 | 类型 | 默认 | 说明 | 跳转 Demo |全局配置项| +| :----------------: | :---------: | :------------: | :-----: | :------------------ | | +| dClass | [`DResponseParameter`](#dresponseparameter)`` | -- | 设置需要的class名数组 | [响应式Class](demo#class) | + +# dStyle +可使用[dStyle]对元素进行 `style` 名绑定设置,支持响应式并可在不同断点下 `style` 合并。 + +## dStyle 参数 +| 参数 | 类型 | 默认 | 说明 | 跳转 Demo |全局配置项| +| :----------------: | :---------: | :------------: | :-----: | :------------------ | | +| dStyle | [`DResponseParameter`](#dresponseparameter)`` | -- | 设置需要的class名数组 | [响应式Style](demo#style) | + # d-layout 布局容器,可以与`d-header`, `d-content`, `d-footer`, `d-aside`组合实现布局; @@ -37,3 +134,51 @@ import { LayoutModule } from 'ng-devui'; # d-aside 侧边栏,只能放在`d-layout`容器中,作为`d-layout`容器的侧边栏部分。 + + +# 接口 & 类型定义 + +### DJustify +```ts +export type DJustify = 'start' | 'end' | 'center' | 'around' | 'between'; +``` + +### DAlign +```ts +export type DAlign = 'start' | 'center' | 'end' | 'baseline' | 'stretch'; +``` + +### DAlignSelf +``` ts +export type DAlignSelf = 'start' | 'center' | 'end' | 'baseline' | 'stretch'; +``` + +### DBreakpointsMap +```ts +export const DBreakpointsMap = { + ss: 0, + ms: 360, + mm: 768, + ml: 1024, + xs: 1280, + sm: 1440, + md: 1600, + lg: 1760, + xl: 1920, +}; +``` + +### DResponseParameter +```ts +export type DResponseParameter = T | { + ss?: T, + ms?: T, + mm?: T, + ml?: T, + xs?: T, + sm?: T, + md?: T, + lg?: T, + xl?: T, +} +``` diff --git a/devui/layout/doc/api-en.md b/devui/layout/doc/api-en.md index 3eb653e0..edcfb589 100644 --- a/devui/layout/doc/api-en.md +++ b/devui/layout/doc/api-en.md @@ -1,14 +1,54 @@ -# How to use +# How to Use -Import into module: +Used in the module: ```ts -import { LayoutModule } from 'ng-devui'; +import {LayoutModule} from 'ng-devui'; ``` -In the page: +In Global Styles, introduce: +```css +@import '~ng-devui/devui-layout.css'; +``` + +Use in the page: ```html + + + + + + + + + + + + + + + + + + + + + + + + +