refactor(devtools): vendor dependencies and remove redundancies

This commit is contained in:
mgechev
2020-05-14 19:31:10 -07:00
committed by Minko Gechev
parent c4b141c6ea
commit 3d0aee942e
14 changed files with 2293 additions and 1000 deletions
+1 -5
View File
@@ -45,16 +45,11 @@
"@angular/platform-browser": "github:angular/platform-browser-builds#77ea10310c138f2fedf5fd625b567d8097ef8bf8",
"@angular/platform-browser-dynamic": "github:angular/platform-browser-dynamic-builds#d4a24f6679d86655a650ded46d78b4e290529f94",
"@swimlane/ngx-charts": "^14.0.0",
"angular-split": "^3.0.3",
"clone-deep": "^4.0.1",
"document-register-element": "^1.7.2",
"file-saver": "^2.0.2",
"memo-decorator": "^2.0.1",
"ngx-flamegraph": "0.0.7",
"rxjs": "~6.5.3",
"semver-dsl": "^1.0.1",
"tslib": "^2.0.0",
"uuid": "^8.0.0",
"webtreemap": "^2.0.1",
"zone.js": "~0.10.2"
},
@@ -77,6 +72,7 @@
"cypress": "^4.0.0",
"cypress-browser-extension-plugin": "^0.1.0",
"cypress-iframe": "^1.0.1",
"document-register-element": "^1.7.2",
"husky": "^4.2.1",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~5.0.0",
@@ -9,9 +9,9 @@ import { MatTreeModule } from '@angular/material/tree';
import { MatButtonModule } from '@angular/material/button';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { PropertyTabModule } from './property-tab/property-tab.module';
import { AngularSplitModule } from 'angular-split';
import { DirectiveForestModule } from './directive-forest/directive-forest.module';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { AngularSplitModule } from '../../vendor/angular-split/lib/module';
@NgModule({
declarations: [DirectiveExplorerComponent, DirectiveForestComponent, FilterComponent],
@@ -1,6 +1,6 @@
import { Subject } from 'rxjs';
import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import { saveAs } from './vendor/filesaver';
@Injectable({
providedIn: 'root',
@@ -10,7 +10,7 @@ export class FileApiService {
publishFileUpload(parentEvent: InputEvent): void {
const reader = new FileReader();
reader.onload = event => {
reader.onload = (event) => {
try {
this.uploadedData.next(JSON.parse((event.target as any).result));
} catch (e) {
@@ -23,6 +23,6 @@ export class FileApiService {
saveObjectAsJSON(object: object): void {
const blob = new Blob([JSON.stringify(object)], { type: 'application/json' });
FileSaver.saveAs(blob, `${Date.now()}.json`);
saveAs(blob, `${Date.now()}.json`);
}
}
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017 Bertrand Gaillard
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,100 @@
:host {
display: flex;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: stretch;
overflow: hidden;
width: 100%;
height: 100%;
& > .as-split-gutter {
flex-grow: 0;
flex-shrink: 0;
background-color: #eeeeee;
display: flex;
align-items: center;
justify-content: center;
& > .as-split-gutter-icon {
width: 100%;
height: 100%;
background-position: center center;
background-repeat: no-repeat;
}
}
::ng-deep > .as-split-area {
flex-grow: 0;
flex-shrink: 0;
overflow-x: hidden;
overflow-y: auto;
/* When <as-split-area [visible]="false"> force size to 0. */
&.as-hidden {
flex: 0 1 0 !important;
overflow-x: hidden;
overflow-y: hidden;
}
}
&.as-horizontal {
flex-direction: row;
& > .as-split-gutter {
flex-direction: row;
cursor: col-resize;
height: 100%; // <- Fix safari bug about gutter height when direction is horizontal.
& > .as-split-gutter-icon {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAIklEQVQoU2M4c+bMfxAGAgYYmwGrIIiDjrELjpo5aiZeMwF+yNnOs5KSvgAAAABJRU5ErkJggg==');
}
}
::ng-deep > .as-split-area {
height: 100%;
}
}
&.as-vertical {
flex-direction: column;
& > .as-split-gutter {
flex-direction: column;
cursor: row-resize;
width: 100%;
.as-split-gutter-icon {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAFCAMAAABl/6zIAAAABlBMVEUAAADMzMzIT8AyAAAAAXRSTlMAQObYZgAAABRJREFUeAFjYGRkwIMJSeMHlBkOABP7AEGzSuPKAAAAAElFTkSuQmCC');
}
}
::ng-deep > .as-split-area {
width: 100%;
&.as-hidden {
max-width: 0;
}
}
}
/* When disabled remove gutters background image and specific cursor. */
&.as-disabled {
& > .as-split-gutter {
cursor: default;
.as-split-gutter-icon {
}
}
}
/* Add transition only when transition enabled + split initialized + not currently dragging. */
&.as-transition.as-init:not(.as-dragging) {
& > .as-split-gutter,
::ng-deep > .as-split-area {
transition: flex-basis 0.3s;
}
}
}
@@ -0,0 +1,765 @@
// tslint:disable
import {
Component,
Input,
Output,
ChangeDetectionStrategy,
ChangeDetectorRef,
Renderer2,
AfterViewInit,
OnDestroy,
ElementRef,
NgZone,
ViewChildren,
QueryList,
EventEmitter,
} from '@angular/core';
import { Observable, Subscriber, Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { IArea, IPoint, ISplitSnapshot, IAreaSnapshot, IOutputData, IOutputAreaSizes } from '../interface';
import { SplitAreaDirective } from '../directive/splitArea.directive';
import {
getInputPositiveNumber,
getInputBoolean,
isUserSizesValid,
getAreaMinSize,
getAreaMaxSize,
getPointFromEvent,
getElementPixelSize,
getGutterSideAbsorptionCapacity,
updateAreaSize,
} from '../utils';
/**
* angular-split
*
*
* PERCENT MODE ([unit]="'percent'")
* ___________________________________________________________________________________________
* | A [g1] B [g2] C [g3] D [g4] E |
* |-------------------------------------------------------------------------------------------|
* | 20 30 20 15 15 | <-- [size]="x"
* | 10px 10px 10px 10px | <-- [gutterSize]="10"
* |calc(20% - 8px) calc(30% - 12px) calc(20% - 8px) calc(15% - 6px) calc(15% - 6px)| <-- CSS flex-basis property (with flex-grow&shrink at 0)
* | 152px 228px 152px 114px 114px | <-- el.getBoundingClientRect().width
* |___________________________________________________________________________________________|
* 800px <-- el.getBoundingClientRect().width
* flex-basis = calc( { area.size }% - { area.size/100 * nbGutter*gutterSize }px );
*
*
* PIXEL MODE ([unit]="'pixel'")
* ___________________________________________________________________________________________
* | A [g1] B [g2] C [g3] D [g4] E |
* |-------------------------------------------------------------------------------------------|
* | 100 250 * 150 100 | <-- [size]="y"
* | 10px 10px 10px 10px | <-- [gutterSize]="10"
* | 0 0 100px 0 0 250px 1 1 auto 0 0 150px 0 0 100px | <-- CSS flex property (flex-grow/flex-shrink/flex-basis)
* | 100px 250px 200px 150px 100px | <-- el.getBoundingClientRect().width
* |___________________________________________________________________________________________|
* 800px <-- el.getBoundingClientRect().width
*
*/
@Component({
selector: 'as-split',
exportAs: 'asSplit',
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrls: [`./split.component.scss`],
template: ` <ng-content></ng-content>
<ng-template ngFor [ngForOf]="displayedAreas" let-index="index" let-last="last">
<div
*ngIf="last === false"
#gutterEls
class="as-split-gutter"
[style.flex-basis.px]="gutterSize"
[style.order]="index * 2 + 1"
(mousedown)="startDragging($event, index * 2 + 1, index + 1)"
(touchstart)="startDragging($event, index * 2 + 1, index + 1)"
(mouseup)="clickGutter($event, index + 1)"
(touchend)="clickGutter($event, index + 1)"
>
<div class="as-split-gutter-icon"></div>
</div>
</ng-template>`,
})
export class SplitComponent implements AfterViewInit, OnDestroy {
private _direction: 'horizontal' | 'vertical' = 'horizontal';
@Input() set direction(v: 'horizontal' | 'vertical') {
this._direction = v === 'vertical' ? 'vertical' : 'horizontal';
this.renderer.addClass(this.elRef.nativeElement, `as-${this._direction}`);
this.renderer.removeClass(
this.elRef.nativeElement,
`as-${this._direction === 'vertical' ? 'horizontal' : 'vertical'}`
);
this.build(false, false);
}
get direction(): 'horizontal' | 'vertical' {
return this._direction;
}
////
private _unit: 'percent' | 'pixel' = 'percent';
@Input() set unit(v: 'percent' | 'pixel') {
this._unit = v === 'pixel' ? 'pixel' : 'percent';
this.renderer.addClass(this.elRef.nativeElement, `as-${this._unit}`);
this.renderer.removeClass(this.elRef.nativeElement, `as-${this._unit === 'pixel' ? 'percent' : 'pixel'}`);
this.build(false, true);
}
get unit(): 'percent' | 'pixel' {
return this._unit;
}
////
private _gutterSize: number = 11;
@Input() set gutterSize(v: number | null) {
this._gutterSize = getInputPositiveNumber(v, 11);
this.build(false, false);
}
get gutterSize(): number | null {
return this._gutterSize;
}
////
private _gutterStep: number = 1;
@Input() set gutterStep(v: number) {
this._gutterStep = getInputPositiveNumber(v, 1);
}
get gutterStep(): number {
return this._gutterStep;
}
////
private _restrictMove: boolean = false;
@Input() set restrictMove(v: boolean) {
this._restrictMove = getInputBoolean(v);
}
get restrictMove(): boolean {
return this._restrictMove;
}
////
private _useTransition: boolean = false;
@Input() set useTransition(v: boolean) {
this._useTransition = getInputBoolean(v);
if (this._useTransition) this.renderer.addClass(this.elRef.nativeElement, 'as-transition');
else this.renderer.removeClass(this.elRef.nativeElement, 'as-transition');
}
get useTransition(): boolean {
return this._useTransition;
}
////
private _disabled: boolean = false;
@Input() set disabled(v: boolean) {
this._disabled = getInputBoolean(v);
if (this._disabled) this.renderer.addClass(this.elRef.nativeElement, 'as-disabled');
else this.renderer.removeClass(this.elRef.nativeElement, 'as-disabled');
}
get disabled(): boolean {
return this._disabled;
}
////
private _dir: 'ltr' | 'rtl' = 'ltr';
@Input() set dir(v: 'ltr' | 'rtl') {
this._dir = v === 'rtl' ? 'rtl' : 'ltr';
this.renderer.setAttribute(this.elRef.nativeElement, 'dir', this._dir);
}
get dir(): 'ltr' | 'rtl' {
return this._dir;
}
////
private _gutterDblClickDuration: number = 0;
@Input() set gutterDblClickDuration(v: number) {
this._gutterDblClickDuration = getInputPositiveNumber(v, 0);
}
get gutterDblClickDuration(): number {
return this._gutterDblClickDuration;
}
////
@Output() dragStart = new EventEmitter<IOutputData>(false);
@Output() dragEnd = new EventEmitter<IOutputData>(false);
@Output() gutterClick = new EventEmitter<IOutputData>(false);
@Output() gutterDblClick = new EventEmitter<IOutputData>(false);
private transitionEndSubscriber: Subscriber<IOutputAreaSizes>;
@Output() get transitionEnd(): Observable<IOutputAreaSizes> {
return new Observable((subscriber) => (this.transitionEndSubscriber = subscriber)).pipe(
debounceTime<IOutputAreaSizes>(20)
);
}
private dragProgressSubject: Subject<IOutputData> = new Subject();
dragProgress$: Observable<IOutputData> = this.dragProgressSubject.asObservable();
////
private isDragging: boolean = false;
private dragListeners: Array<Function> = [];
private snapshot: ISplitSnapshot | null = null;
private startPoint: IPoint | null = null;
private endPoint: IPoint | null = null;
public readonly displayedAreas: Array<IArea> = [];
private readonly hidedAreas: Array<IArea> = [];
@ViewChildren('gutterEls') private gutterEls: QueryList<ElementRef>;
constructor(
private ngZone: NgZone,
private elRef: ElementRef,
private cdRef: ChangeDetectorRef,
private renderer: Renderer2
) {
// To force adding default class, could be override by user @Input() or not
this.direction = this._direction;
}
public ngAfterViewInit() {
this.ngZone.runOutsideAngular(() => {
// To avoid transition at first rendering
setTimeout(() => this.renderer.addClass(this.elRef.nativeElement, 'as-init'));
});
}
private getNbGutters(): number {
return this.displayedAreas.length === 0 ? 0 : this.displayedAreas.length - 1;
}
public addArea(component: SplitAreaDirective): void {
const newArea: IArea = {
component,
order: 0,
size: 0,
minSize: null,
maxSize: null,
};
if (component.visible === true) {
this.displayedAreas.push(newArea);
this.build(true, true);
} else {
this.hidedAreas.push(newArea);
}
}
public removeArea(component: SplitAreaDirective): void {
if (this.displayedAreas.some((a) => a.component === component)) {
const area = this.displayedAreas.find((a) => a.component === component);
this.displayedAreas.splice(this.displayedAreas.indexOf(area!), 1);
this.build(true, true);
} else if (this.hidedAreas.some((a) => a.component === component)) {
const area = this.hidedAreas.find((a) => a.component === component);
this.hidedAreas.splice(this.hidedAreas.indexOf(area!), 1);
}
}
public updateArea(component: SplitAreaDirective, resetOrders: boolean, resetSizes: boolean): void {
if (component.visible === true) {
this.build(resetOrders, resetSizes);
}
}
public showArea(component: SplitAreaDirective): void {
const area = this.hidedAreas.find((a) => a.component === component);
if (area === undefined) {
return;
}
const areas = this.hidedAreas.splice(this.hidedAreas.indexOf(area), 1);
this.displayedAreas.push(...areas);
this.build(true, true);
}
public hideArea(comp: SplitAreaDirective): void {
const area = this.displayedAreas.find((a) => a.component === comp);
if (area === undefined) {
return;
}
const areas = this.displayedAreas.splice(this.displayedAreas.indexOf(area), 1);
areas.forEach((area) => {
area.order = 0;
area.size = 0;
});
this.hidedAreas.push(...areas);
this.build(true, true);
}
public getVisibleAreaSizes(): IOutputAreaSizes {
return this.displayedAreas.map((a) => (a.size === null ? '*' : a.size));
}
public setVisibleAreaSizes(sizes: IOutputAreaSizes): boolean {
if (sizes.length !== this.displayedAreas.length) {
return false;
}
const formatedSizes = sizes.map((s) => getInputPositiveNumber(s, null));
const isValid = isUserSizesValid(this.unit, formatedSizes);
if (isValid === false) {
return false;
}
// @ts-ignore
this.displayedAreas.forEach((area, i) => (area.component._size = formatedSizes[i]));
this.build(false, true);
return true;
}
private build(resetOrders: boolean, resetSizes: boolean): void {
this.stopDragging();
// ¤ AREAS ORDER
if (resetOrders === true) {
// If user provided 'order' for each area, use it to sort them.
if (this.displayedAreas.every((a) => a.component.order !== null)) {
this.displayedAreas.sort((a, b) => <number>a.component.order - <number>b.component.order);
}
// Then set real order with multiples of 2, numbers between will be used by gutters.
this.displayedAreas.forEach((area, i) => {
area.order = i * 2;
area.component.setStyleOrder(area.order);
});
}
// ¤ AREAS SIZE
if (resetSizes === true) {
const useUserSizes = isUserSizesValid(
this.unit,
this.displayedAreas.map((a) => a.component.size)
);
switch (this.unit) {
case 'percent': {
const defaultSize = 100 / this.displayedAreas.length;
this.displayedAreas.forEach((area) => {
area.size = useUserSizes ? <number>area.component.size : defaultSize;
area.minSize = getAreaMinSize(area);
area.maxSize = getAreaMaxSize(area);
});
break;
}
case 'pixel': {
if (useUserSizes) {
this.displayedAreas.forEach((area) => {
area.size = area.component.size;
area.minSize = getAreaMinSize(area);
area.maxSize = getAreaMaxSize(area);
});
} else {
const wildcardSizeAreas = this.displayedAreas.filter((a) => a.component.size === null);
// No wildcard area > Need to select one arbitrarily > first
if (wildcardSizeAreas.length === 0 && this.displayedAreas.length > 0) {
this.displayedAreas.forEach((area, i) => {
area.size = i === 0 ? null : area.component.size;
area.minSize = i === 0 ? null : getAreaMinSize(area);
area.maxSize = i === 0 ? null : getAreaMaxSize(area);
});
}
// More than one wildcard area > Need to keep only one arbitrarly > first
else if (wildcardSizeAreas.length > 1) {
let alreadyGotOne = false;
this.displayedAreas.forEach((area) => {
if (area.component.size === null) {
if (alreadyGotOne === false) {
area.size = null;
area.minSize = null;
area.maxSize = null;
alreadyGotOne = true;
} else {
area.size = 100;
area.minSize = null;
area.maxSize = null;
}
} else {
area.size = area.component.size;
area.minSize = getAreaMinSize(area);
area.maxSize = getAreaMaxSize(area);
}
});
}
}
break;
}
}
}
this.refreshStyleSizes();
this.cdRef.markForCheck();
}
private refreshStyleSizes(): void {
///////////////////////////////////////////
// PERCENT MODE
if (this.unit === 'percent') {
// Only one area > flex-basis 100%
if (this.displayedAreas.length === 1) {
this.displayedAreas[0].component.setStyleFlex(0, 0, `100%`, false, false);
}
// Multiple areas > use each percent basis
else {
const sumGutterSize = this.getNbGutters() * this.gutterSize!;
this.displayedAreas.forEach((area) => {
area.component.setStyleFlex(
0,
0,
`calc( ${area.size}% - ${(<number>area.size / 100) * sumGutterSize}px )`,
area.minSize !== null && area.minSize === area.size ? true : false,
area.maxSize !== null && area.maxSize === area.size ? true : false
);
});
}
}
///////////////////////////////////////////
// PIXEL MODE
else if (this.unit === 'pixel') {
this.displayedAreas.forEach((area) => {
// Area with wildcard size
if (area.size === null) {
if (this.displayedAreas.length === 1) {
area.component.setStyleFlex(1, 1, `100%`, false, false);
} else {
area.component.setStyleFlex(1, 1, `auto`, false, false);
}
}
// Area with pixel size
else {
// Only one area > flex-basis 100%
if (this.displayedAreas.length === 1) {
area.component.setStyleFlex(0, 0, `100%`, false, false);
}
// Multiple areas > use each pixel basis
else {
area.component.setStyleFlex(
0,
0,
`${area.size}px`,
area.minSize !== null && area.minSize === area.size ? true : false,
area.maxSize !== null && area.maxSize === area.size ? true : false
);
}
}
});
}
}
_clickTimeout: number | null = null;
public clickGutter(event: MouseEvent | TouchEvent, gutterNum: number): void {
const tempPoint = getPointFromEvent(event);
// Be sure mouseup/touchend happened at same point as mousedown/touchstart to trigger click/dblclick
if (this.startPoint && this.startPoint.x === tempPoint!.x && this.startPoint.y === tempPoint!.y) {
// If timeout in progress and new click > clearTimeout & dblClickEvent
if (this._clickTimeout !== null) {
window.clearTimeout(this._clickTimeout);
this._clickTimeout = null;
this.notify('dblclick', gutterNum);
this.stopDragging();
}
// Else start timeout to call clickEvent at end
else {
this._clickTimeout = window.setTimeout(() => {
this._clickTimeout = null;
this.notify('click', gutterNum);
this.stopDragging();
}, this.gutterDblClickDuration);
}
}
}
public startDragging(event: MouseEvent | TouchEvent, gutterOrder: number, gutterNum: number): void {
event.preventDefault();
event.stopPropagation();
this.startPoint = getPointFromEvent(event);
if (this.startPoint === null || this.disabled === true) {
return;
}
this.snapshot = {
gutterNum,
lastSteppedOffset: 0,
allAreasSizePixel: getElementPixelSize(this.elRef, this.direction) - this.getNbGutters() * this.gutterSize!,
allInvolvedAreasSizePercent: 100,
areasBeforeGutter: [],
areasAfterGutter: [],
};
this.displayedAreas.forEach((area) => {
const areaSnapshot: IAreaSnapshot = {
area,
sizePixelAtStart: getElementPixelSize(area.component.elRef, this.direction),
sizePercentAtStart: (this.unit === 'percent' ? area.size : -1) as number, // If pixel mode, anyway, will not be used.
};
if (area.order < gutterOrder) {
if (this.restrictMove === true) {
this.snapshot!.areasBeforeGutter = [areaSnapshot];
} else {
this.snapshot!.areasBeforeGutter.unshift(areaSnapshot);
}
} else if (area.order > gutterOrder) {
if (this.restrictMove === true) {
if (this.snapshot!.areasAfterGutter.length === 0) this.snapshot!.areasAfterGutter = [areaSnapshot];
} else {
this.snapshot!.areasAfterGutter.push(areaSnapshot);
}
}
});
this.snapshot.allInvolvedAreasSizePercent = [
...this.snapshot.areasBeforeGutter,
...this.snapshot.areasAfterGutter,
].reduce((t, a) => t + a.sizePercentAtStart, 0);
if (this.snapshot.areasBeforeGutter.length === 0 || this.snapshot.areasAfterGutter.length === 0) {
return;
}
this.dragListeners.push(this.renderer.listen('document', 'mouseup', this.stopDragging.bind(this)));
this.dragListeners.push(this.renderer.listen('document', 'touchend', this.stopDragging.bind(this)));
this.dragListeners.push(this.renderer.listen('document', 'touchcancel', this.stopDragging.bind(this)));
this.ngZone.runOutsideAngular(() => {
this.dragListeners.push(this.renderer.listen('document', 'mousemove', this.dragEvent.bind(this)));
this.dragListeners.push(this.renderer.listen('document', 'touchmove', this.dragEvent.bind(this)));
});
this.displayedAreas.forEach((area) => area.component.lockEvents());
this.isDragging = true;
this.renderer.addClass(this.elRef.nativeElement, 'as-dragging');
this.renderer.addClass(this.gutterEls.toArray()[this.snapshot.gutterNum - 1].nativeElement, 'as-dragged');
this.notify('start', this.snapshot.gutterNum);
}
private dragEvent(event: MouseEvent | TouchEvent): void {
event.preventDefault();
event.stopPropagation();
if (this._clickTimeout !== null) {
window.clearTimeout(this._clickTimeout);
this._clickTimeout = null;
}
if (this.isDragging === false) {
return;
}
this.endPoint = getPointFromEvent(event);
if (this.endPoint === null) {
return;
}
// Calculate steppedOffset
let offset =
this.direction === 'horizontal' ? this.startPoint!.x - this.endPoint.x : this.startPoint!.y - this.endPoint.y;
if (this.dir === 'rtl') {
offset = -offset;
}
const steppedOffset = Math.round(offset / this.gutterStep) * this.gutterStep;
if (steppedOffset === this.snapshot!.lastSteppedOffset) {
return;
}
this.snapshot!.lastSteppedOffset = steppedOffset;
// Need to know if each gutter side areas could reacts to steppedOffset
let areasBefore = getGutterSideAbsorptionCapacity(
this.unit,
this.snapshot!.areasBeforeGutter,
-steppedOffset,
this.snapshot!.allAreasSizePixel
);
let areasAfter = getGutterSideAbsorptionCapacity(
this.unit,
this.snapshot!.areasAfterGutter,
steppedOffset,
this.snapshot!.allAreasSizePixel
);
// Each gutter side areas can't absorb all offset
if (areasBefore.remain !== 0 && areasAfter.remain !== 0) {
if (Math.abs(areasBefore.remain) === Math.abs(areasAfter.remain)) {
} else if (Math.abs(areasBefore.remain) > Math.abs(areasAfter.remain)) {
areasAfter = getGutterSideAbsorptionCapacity(
this.unit,
this.snapshot!.areasAfterGutter,
steppedOffset + areasBefore.remain,
this.snapshot!.allAreasSizePixel
);
} else {
areasBefore = getGutterSideAbsorptionCapacity(
this.unit,
this.snapshot!.areasBeforeGutter,
-(steppedOffset - areasAfter.remain),
this.snapshot!.allAreasSizePixel
);
}
}
// Areas before gutter can't absorbs all offset > need to recalculate sizes for areas after gutter.
else if (areasBefore.remain !== 0) {
areasAfter = getGutterSideAbsorptionCapacity(
this.unit,
this.snapshot!.areasAfterGutter,
steppedOffset + areasBefore.remain,
this.snapshot!.allAreasSizePixel
);
}
// Areas after gutter can't absorbs all offset > need to recalculate sizes for areas before gutter.
else if (areasAfter.remain !== 0) {
areasBefore = getGutterSideAbsorptionCapacity(
this.unit,
this.snapshot!.areasBeforeGutter,
-(steppedOffset - areasAfter.remain),
this.snapshot!.allAreasSizePixel
);
}
if (this.unit === 'percent') {
// Hack because of browser messing up with sizes using calc(X% - Ypx) -> el.getBoundingClientRect()
// If not there, playing with gutters makes total going down to 99.99875% then 99.99286%, 99.98986%,..
const all = [...areasBefore.list, ...areasAfter.list];
const areaToReset = all.find(
(a) =>
a.percentAfterAbsorption !== 0 &&
a.percentAfterAbsorption !== a.areaSnapshot.area.minSize &&
a.percentAfterAbsorption !== a.areaSnapshot.area.maxSize
);
if (areaToReset) {
areaToReset.percentAfterAbsorption =
this.snapshot!.allInvolvedAreasSizePercent -
all.filter((a) => a !== areaToReset).reduce((total, a) => total + a.percentAfterAbsorption, 0);
}
}
// Now we know areas could absorb steppedOffset, time to really update sizes
areasBefore.list.forEach((item) => updateAreaSize(this.unit, item));
areasAfter.list.forEach((item) => updateAreaSize(this.unit, item));
this.refreshStyleSizes();
this.notify('progress', this.snapshot!.gutterNum);
}
private stopDragging(event?: Event): void {
if (event) {
event.preventDefault();
event.stopPropagation();
}
if (this.isDragging === false) {
return;
}
this.displayedAreas.forEach((area) => area.component.unlockEvents());
while (this.dragListeners.length > 0) {
const fct = this.dragListeners.pop();
if (fct) fct();
}
// Warning: Have to be before "notify('end')"
// because "notify('end')"" can be linked to "[size]='x'" > "build()" > "stopDragging()"
this.isDragging = false;
// If moved from starting point, notify end
if (this.endPoint && (this.startPoint!.x !== this.endPoint.x || this.startPoint!.y !== this.endPoint.y)) {
this.notify('end', this.snapshot!.gutterNum);
}
this.renderer.removeClass(this.elRef.nativeElement, 'as-dragging');
this.renderer.removeClass(this.gutterEls.toArray()[this.snapshot!.gutterNum - 1].nativeElement, 'as-dragged');
this.snapshot = null;
// Needed to let (click)="clickGutter(...)" event run and verify if mouse moved or not
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
this.startPoint = null;
this.endPoint = null;
});
});
}
public notify(type: 'start' | 'progress' | 'end' | 'click' | 'dblclick' | 'transitionEnd', gutterNum: number): void {
const sizes = this.getVisibleAreaSizes();
if (type === 'start') {
this.dragStart.emit({ gutterNum, sizes });
} else if (type === 'end') {
this.dragEnd.emit({ gutterNum, sizes });
} else if (type === 'click') {
this.gutterClick.emit({ gutterNum, sizes });
} else if (type === 'dblclick') {
this.gutterDblClick.emit({ gutterNum, sizes });
} else if (type === 'transitionEnd') {
if (this.transitionEndSubscriber) {
this.ngZone.run(() => this.transitionEndSubscriber.next(sizes));
}
} else if (type === 'progress') {
// Stay outside zone to allow users do what they want about change detection mechanism.
this.dragProgressSubject.next({ gutterNum, sizes });
}
}
public ngOnDestroy(): void {
this.stopDragging();
}
}
@@ -0,0 +1,172 @@
// tslint:disable
import { Directive, Input, ElementRef, Renderer2, OnInit, OnDestroy, NgZone } from '@angular/core';
import { SplitComponent } from '../component/split.component';
import { getInputPositiveNumber, getInputBoolean } from '../utils';
@Directive({
selector: 'as-split-area, [as-split-area]',
exportAs: 'asSplitArea',
})
export class SplitAreaDirective implements OnInit, OnDestroy {
private _order: number | null = null;
@Input() set order(v: number | null) {
this._order = getInputPositiveNumber(v, null);
this.split.updateArea(this, true, false);
}
get order(): number | null {
return this._order;
}
////
private _size: number | null = null;
@Input() set size(v: number | null) {
this._size = getInputPositiveNumber(v, null);
this.split.updateArea(this, false, true);
}
get size(): number | null {
return this._size;
}
////
private _minSize: number | null = null;
@Input() set minSize(v: number | null) {
this._minSize = getInputPositiveNumber(v, null);
this.split.updateArea(this, false, true);
}
get minSize(): number | null {
return this._minSize;
}
////
private _maxSize: number | null = null;
@Input() set maxSize(v: number | null) {
this._maxSize = getInputPositiveNumber(v, null);
this.split.updateArea(this, false, true);
}
get maxSize(): number | null {
return this._maxSize;
}
////
private _lockSize: boolean = false;
@Input() set lockSize(v: boolean) {
this._lockSize = getInputBoolean(v);
this.split.updateArea(this, false, true);
}
get lockSize(): boolean {
return this._lockSize;
}
////
private _visible: boolean = true;
@Input() set visible(v: boolean) {
this._visible = getInputBoolean(v);
if (this._visible) {
this.split.showArea(this);
this.renderer.removeClass(this.elRef.nativeElement, 'as-hidden');
} else {
this.split.hideArea(this);
this.renderer.addClass(this.elRef.nativeElement, 'as-hidden');
}
}
get visible(): boolean {
return this._visible;
}
////
private transitionListener: Function;
private readonly lockListeners: Array<Function> = [];
constructor(
private ngZone: NgZone,
public elRef: ElementRef,
private renderer: Renderer2,
private split: SplitComponent
) {
this.renderer.addClass(this.elRef.nativeElement, 'as-split-area');
}
public ngOnInit(): void {
this.split.addArea(this);
this.ngZone.runOutsideAngular(() => {
this.transitionListener = this.renderer.listen(
this.elRef.nativeElement,
'transitionend',
(event: TransitionEvent) => {
// Limit only flex-basis transition to trigger the event
if (event.propertyName === 'flex-basis') {
this.split.notify('transitionEnd', -1);
}
}
);
});
}
public setStyleOrder(value: number): void {
this.renderer.setStyle(this.elRef.nativeElement, 'order', value);
}
public setStyleFlex(grow: number, shrink: number, basis: string, isMin: boolean, isMax: boolean): void {
// Need 3 separated properties to work on IE11 (https://github.com/angular/flex-layout/issues/323)
this.renderer.setStyle(this.elRef.nativeElement, 'flex-grow', grow);
this.renderer.setStyle(this.elRef.nativeElement, 'flex-shrink', shrink);
this.renderer.setStyle(this.elRef.nativeElement, 'flex-basis', basis);
if (isMin === true) this.renderer.addClass(this.elRef.nativeElement, 'as-min');
else this.renderer.removeClass(this.elRef.nativeElement, 'as-min');
if (isMax === true) this.renderer.addClass(this.elRef.nativeElement, 'as-max');
else this.renderer.removeClass(this.elRef.nativeElement, 'as-max');
}
public lockEvents(): void {
this.ngZone.runOutsideAngular(() => {
this.lockListeners.push(this.renderer.listen(this.elRef.nativeElement, 'selectstart', (e: Event) => false));
this.lockListeners.push(this.renderer.listen(this.elRef.nativeElement, 'dragstart', (e: Event) => false));
});
}
public unlockEvents(): void {
while (this.lockListeners.length > 0) {
const fct = this.lockListeners.pop();
if (fct) fct();
}
}
public ngOnDestroy(): void {
this.unlockEvents();
if (this.transitionListener) {
this.transitionListener();
}
this.split.removeArea(this);
}
}
@@ -0,0 +1,55 @@
// tslint:disable
import { SplitAreaDirective } from './directive/splitArea.directive';
export interface IPoint {
x: number;
y: number;
}
export interface IArea {
component: SplitAreaDirective;
order: number;
size: number | null;
minSize: number | null;
maxSize: number | null;
}
// CREATED ON DRAG START
export interface ISplitSnapshot {
gutterNum: number;
allAreasSizePixel: number;
allInvolvedAreasSizePercent: number;
lastSteppedOffset: number;
areasBeforeGutter: Array<IAreaSnapshot>;
areasAfterGutter: Array<IAreaSnapshot>;
}
export interface IAreaSnapshot {
area: IArea;
sizePixelAtStart: number;
sizePercentAtStart: number;
}
// CREATED ON DRAG PROGRESS
export interface ISplitSideAbsorptionCapacity {
remain: number;
list: Array<IAreaAbsorptionCapacity>;
}
export interface IAreaAbsorptionCapacity {
areaSnapshot: IAreaSnapshot;
pixelAbsorb: number;
percentAfterAbsorption: number;
pixelRemain: number;
}
// CREATED TO SEND OUTSIDE
export interface IOutputData {
gutterNum: number;
sizes: IOutputAreaSizes;
}
export interface IOutputAreaSizes extends Array<number | '*'> {}
@@ -0,0 +1,27 @@
// tslint:disable
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SplitComponent } from './component/split.component';
import { SplitAreaDirective } from './directive/splitArea.directive';
@NgModule({
imports: [CommonModule],
declarations: [SplitComponent, SplitAreaDirective],
exports: [SplitComponent, SplitAreaDirective],
})
export class AngularSplitModule {
public static forRoot(): ModuleWithProviders<AngularSplitModule> {
return {
ngModule: AngularSplitModule,
providers: [],
};
}
public static forChild(): ModuleWithProviders<AngularSplitModule> {
return {
ngModule: AngularSplitModule,
providers: [],
};
}
}
@@ -0,0 +1,273 @@
// tslint:disable
import { ElementRef } from '@angular/core';
import { IArea, IPoint, IAreaSnapshot, ISplitSideAbsorptionCapacity, IAreaAbsorptionCapacity } from './interface';
export function getPointFromEvent(event: MouseEvent | TouchEvent): IPoint | null {
// TouchEvent
if ((<TouchEvent>event).changedTouches !== undefined && (<TouchEvent>event).changedTouches.length > 0) {
return {
x: (<TouchEvent>event).changedTouches[0].clientX,
y: (<TouchEvent>event).changedTouches[0].clientY,
};
}
// MouseEvent
else if ((<MouseEvent>event).clientX !== undefined && (<MouseEvent>event).clientY !== undefined) {
return {
x: (<MouseEvent>event).clientX,
y: (<MouseEvent>event).clientY,
};
}
return null;
}
export function getElementPixelSize(elRef: ElementRef, direction: 'horizontal' | 'vertical'): number {
const rect = (<HTMLElement>elRef.nativeElement).getBoundingClientRect();
return direction === 'horizontal' ? rect.width : rect.height;
}
export function getInputBoolean(v: any): boolean {
return typeof v === 'boolean' ? v : v === 'false' ? false : true;
}
export function getInputPositiveNumber<T>(v: any, defaultValue: T): number | T {
if (v === null || v === undefined) return defaultValue;
v = Number(v);
return !isNaN(v) && v >= 0 ? v : defaultValue;
}
export function isUserSizesValid(unit: 'percent' | 'pixel', sizes: Array<number | null>): boolean | undefined {
// All sizes have to be not null and total should be 100
if (unit === 'percent') {
const total = sizes.reduce((total, s) => (s !== null ? total! + s : total), 0);
return sizes.every((s) => s !== null) && total! > 99.9 && total! < 100.1;
}
// A size at null is mandatory but only one.
if (unit === 'pixel') {
return sizes.filter((s) => s === null).length === 1;
}
}
export function getAreaMinSize(a: IArea): null | number {
if (a.size === null) {
return null;
}
if (a.component.lockSize === true) {
return a.size;
}
if (a.component.minSize === null) {
return null;
}
if (a.component.minSize > a.size) {
return a.size;
}
return a.component.minSize;
}
export function getAreaMaxSize(a: IArea): null | number {
if (a.size === null) {
return null;
}
if (a.component.lockSize === true) {
return a.size;
}
if (a.component.maxSize === null) {
return null;
}
if (a.component.maxSize < a.size) {
return a.size;
}
return a.component.maxSize;
}
export function getGutterSideAbsorptionCapacity(
unit: 'percent' | 'pixel',
sideAreas: Array<IAreaSnapshot>,
pixels: number,
allAreasSizePixel: number
): ISplitSideAbsorptionCapacity {
return sideAreas.reduce(
(acc, area) => {
const res = getAreaAbsorptionCapacity(unit, area, acc.remain, allAreasSizePixel);
(acc.list as any).push(res);
acc.remain = res!.pixelRemain;
return acc;
},
{ remain: pixels, list: [] }
);
}
function getAreaAbsorptionCapacity(
unit: 'percent' | 'pixel',
areaSnapshot: IAreaSnapshot,
pixels: number,
allAreasSizePixel: number
): IAreaAbsorptionCapacity | undefined {
// No pain no gain
if (pixels === 0) {
return {
areaSnapshot,
pixelAbsorb: 0,
percentAfterAbsorption: areaSnapshot.sizePercentAtStart,
pixelRemain: 0,
};
}
// Area start at zero and need to be reduced, not possible
if (areaSnapshot.sizePixelAtStart === 0 && pixels < 0) {
return {
areaSnapshot,
pixelAbsorb: 0,
percentAfterAbsorption: 0,
pixelRemain: pixels,
};
}
if (unit === 'percent') {
return getAreaAbsorptionCapacityPercent(areaSnapshot, pixels, allAreasSizePixel);
}
if (unit === 'pixel') {
return getAreaAbsorptionCapacityPixel(areaSnapshot, pixels, allAreasSizePixel);
}
}
function getAreaAbsorptionCapacityPercent(
areaSnapshot: IAreaSnapshot,
pixels: number,
allAreasSizePixel: number
): IAreaAbsorptionCapacity | undefined {
const tempPixelSize = areaSnapshot.sizePixelAtStart + pixels;
const tempPercentSize = (tempPixelSize / allAreasSizePixel) * 100;
// ENLARGE AREA
if (pixels > 0) {
// If maxSize & newSize bigger than it > absorb to max and return remaining pixels
if (areaSnapshot.area.maxSize !== null && tempPercentSize > areaSnapshot.area.maxSize) {
// Use area.area.maxSize as newPercentSize and return calculate pixels remaining
const maxSizePixel = (areaSnapshot.area.maxSize / 100) * allAreasSizePixel;
return {
areaSnapshot,
pixelAbsorb: maxSizePixel,
percentAfterAbsorption: areaSnapshot.area.maxSize,
pixelRemain: areaSnapshot.sizePixelAtStart + pixels - maxSizePixel,
};
}
return {
areaSnapshot,
pixelAbsorb: pixels,
percentAfterAbsorption: tempPercentSize > 100 ? 100 : tempPercentSize,
pixelRemain: 0,
};
}
// REDUCE AREA
else if (pixels < 0) {
// If minSize & newSize smaller than it > absorb to min and return remaining pixels
if (areaSnapshot.area.minSize !== null && tempPercentSize < areaSnapshot.area.minSize) {
// Use area.area.minSize as newPercentSize and return calculate pixels remaining
const minSizePixel = (areaSnapshot.area.minSize / 100) * allAreasSizePixel;
return {
areaSnapshot,
pixelAbsorb: minSizePixel,
percentAfterAbsorption: areaSnapshot.area.minSize,
pixelRemain: areaSnapshot.sizePixelAtStart + pixels - minSizePixel,
};
}
// If reduced under zero > return remaining pixels
else if (tempPercentSize < 0) {
// Use 0 as newPercentSize and return calculate pixels remaining
return {
areaSnapshot,
pixelAbsorb: -areaSnapshot.sizePixelAtStart,
percentAfterAbsorption: 0,
pixelRemain: pixels + areaSnapshot.sizePixelAtStart,
};
}
return {
areaSnapshot,
pixelAbsorb: pixels,
percentAfterAbsorption: tempPercentSize,
pixelRemain: 0,
};
}
}
function getAreaAbsorptionCapacityPixel(
areaSnapshot: IAreaSnapshot,
pixels: number,
containerSizePixel: number
): IAreaAbsorptionCapacity | undefined {
const tempPixelSize = areaSnapshot.sizePixelAtStart + pixels;
// ENLARGE AREA
if (pixels > 0) {
// If maxSize & newSize bigger than it > absorb to max and return remaining pixels
if (areaSnapshot.area.maxSize !== null && tempPixelSize > areaSnapshot.area.maxSize) {
return {
areaSnapshot,
pixelAbsorb: areaSnapshot.area.maxSize - areaSnapshot.sizePixelAtStart,
percentAfterAbsorption: -1,
pixelRemain: tempPixelSize - areaSnapshot.area.maxSize,
};
}
return {
areaSnapshot,
pixelAbsorb: pixels,
percentAfterAbsorption: -1,
pixelRemain: 0,
};
}
// REDUCE AREA
else if (pixels < 0) {
// If minSize & newSize smaller than it > absorb to min and return remaining pixels
if (areaSnapshot.area.minSize !== null && tempPixelSize < areaSnapshot.area.minSize) {
return {
areaSnapshot,
pixelAbsorb: areaSnapshot.area.minSize + pixels - tempPixelSize,
percentAfterAbsorption: -1,
pixelRemain: tempPixelSize - areaSnapshot.area.minSize,
};
}
// If reduced under zero > return remaining pixels
else if (tempPixelSize < 0) {
return {
areaSnapshot,
pixelAbsorb: -areaSnapshot.sizePixelAtStart,
percentAfterAbsorption: -1,
pixelRemain: pixels + areaSnapshot.sizePixelAtStart,
};
}
return {
areaSnapshot,
pixelAbsorb: pixels,
percentAfterAbsorption: -1,
pixelRemain: 0,
};
}
}
export function updateAreaSize(unit: 'percent' | 'pixel', item: IAreaAbsorptionCapacity) {
if (unit === 'percent') {
item.areaSnapshot.area.size = item.percentAfterAbsorption;
} else if (unit === 'pixel') {
// Update size except for the wildcard size area
if (item.areaSnapshot.area.size !== null) {
item.areaSnapshot.area.size = item.areaSnapshot.sizePixelAtStart + item.pixelAbsorb;
}
}
}
@@ -0,0 +1,8 @@
// tslint:disable
/*
* Public API Surface of angular-split
*/
export { AngularSplitModule } from './lib/module';
export { SplitComponent } from './lib/component/split.component';
export { SplitAreaDirective } from './lib/directive/splitArea.directive';
@@ -0,0 +1,11 @@
The MIT License
Copyright © 2016 [Eli Grey][1].
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[1]: http://eligrey.com
+152
View File
@@ -0,0 +1,152 @@
// tslint:disable
function bom(blob, opts) {
if (typeof opts === 'undefined') opts = { autoBom: false };
else if (typeof opts !== 'object') {
console.warn('Deprecated: Expected third argument to be a object');
opts = { autoBom: !opts };
}
// prepend BOM for UTF-8 XML and text/* types (including HTML)
// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
if (opts.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
}
return blob;
}
function download(url, name, opts) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = function () {
saveAs(xhr.response, name, opts);
};
xhr.onerror = function () {
console.error('could not download file');
};
xhr.send();
}
function corsEnabled(url) {
var xhr = new XMLHttpRequest();
// use sync to avoid popup blocker
xhr.open('HEAD', url, false);
try {
xhr.send();
} catch (e) {}
return xhr.status >= 200 && xhr.status <= 299;
}
// `a.click()` doesn't work for all browsers (#465)
function click(node, _?: any) {
try {
node.dispatchEvent(new MouseEvent('click'));
} catch (e) {
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
node.dispatchEvent(evt);
}
}
// Detect WebKit inside a native macOS app
var isWebKit = /AppleWebKit/.test(navigator.userAgent);
var saveAs =
globalThis.saveAs ||
// probably in some web worker
(typeof window !== 'object' || window !== globalThis
? function saveAs() {
/* noop */
}
: // Use download attribute first if possible (#193 Lumia mobile) unless this is a native macOS app
'download' in HTMLAnchorElement.prototype && !isWebKit
? function saveAs(blob, name, opts) {
var URL = globalThis.URL || globalThis.webkitURL;
var a = document.createElement('a');
name = name || blob.name || 'download';
a.download = name;
a.rel = 'noopener'; // tabnabbing
// TODO: detect chrome extensions & packaged apps
// a.target = '_blank'
if (typeof blob === 'string') {
// Support regular links
a.href = blob;
if (a.origin !== location.origin) {
corsEnabled(a.href) ? download(blob, name, opts) : click(a, (a.target = '_blank'));
} else {
click(a);
}
} else {
// Support blobs
a.href = URL.createObjectURL(blob);
setTimeout(function () {
URL.revokeObjectURL(a.href);
}, 4e4); // 40s
setTimeout(function () {
click(a);
}, 0);
}
}
: // Use msSaveOrOpenBlob as a second approach
'msSaveOrOpenBlob' in navigator
? function saveAs(blob, name, opts) {
name = name || blob.name || 'download';
if (typeof blob === 'string') {
if (corsEnabled(blob)) {
download(blob, name, opts);
} else {
var a = document.createElement('a');
a.href = blob;
a.target = '_blank';
setTimeout(function () {
click(a);
});
}
} else {
navigator.msSaveOrOpenBlob(bom(blob, opts), name);
}
}
: // Fallback to using FileReader and a popup
function saveAs(blob, name, opts, popup) {
// Open a popup immediately do go around popup blocker
// Mostly only available on user interaction and the fileReader is async so...
popup = popup || open('', '_blank');
if (popup) {
popup.document.title = popup.document.body.innerText = 'downloading...';
}
if (typeof blob === 'string') return download(blob, name, opts);
var force = blob.type === 'application/octet-stream';
var isSafari = /constructor/i.test(globalThis.HTMLElement as any) || globalThis.safari;
var isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
if ((isChromeIOS || (force && isSafari) || isWebKit) && typeof FileReader !== 'undefined') {
// Safari doesn't allow downloading of blob URLs
var reader = new FileReader();
reader.onloadend = function () {
var url = reader.result;
url = isChromeIOS ? url : (url as any).replace(/^data:[^;]*;/, 'data:attachment/file;');
if (popup) popup.location.href = url;
else window.location = url as any;
popup = null; // reverse-tabnabbing #460
};
reader.readAsDataURL(blob);
} else {
var URL = globalThis.URL || globalThis.webkitURL;
var url = URL.createObjectURL(blob);
if (popup) popup.location = url;
else location.href = url;
popup = null; // reverse-tabnabbing #460
setTimeout(function () {
URL.revokeObjectURL(url);
}, 4e4); // 40s
}
});
export { saveAs };
+524 -991
View File
File diff suppressed because it is too large Load Diff