import { Component,Input, Injectable, ApplicationRef, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { Multiselect } from './multiselect.component';
import { Observable } from 'rxjs';
import { filter } from 'rxjs/operators';
import { Pipe, PipeTransform } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { DialogService, DialogComponent } from './services/dialog.service';
import { LoremIpsumService } from './services/loremIpsum.service';
@Component({
selector: 'my-app',
templateUrl: 'templates/app.html',
changeDetection: ChangeDetectionStrategy.OnPush,
entryComponents: [DialogComponent]
})
export class AppComponent implements OnInit {
public isMenuExpanded: bool = false;
constructor(private changeRef: ChangeDetectorRef, private appRef: ApplicationRef,
private route: ActivatedRoute, private router: Router, private dialogService: DialogService, private lipsumSvc: LoremIpsumService) {
}
toggleMenu() {
this.isMenuExpanded = !this.isMenuExpanded;
}
open() {
this.dialogService.open();
}
ngOnInit() {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(event => {
let currentRoute = this.route.root;
while (currentRoute.children[0] !== undefined) {
currentRoute = currentRoute.children[0];
}
console.log(currentRoute.snapshot.data);
})
}
}
@Pipe({
name: 'equal',
pure: false
})
export class EqualPipe implements PipeTransform {
transform(items: any, filter: any): any {
if (filter && Array.isArray(items)) {
let filterKeys = Object.keys(filter);
return items.filter(item =>
filterKeys.reduce((memo, keyName) => {
console.log("Comparing");
return item[keyName] === filter[keyName];}, true)
);
} else {
return items;
}
}
}
import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { JsonpModule } from '@angular/http';
import { Multiselect, FilterPipe } from './multiselect.component';
import { Tristate } from './tristate.component';
import { CustomTable, CustomTableOptions, CustomTableConfig, CustomTableColumnDefinition } from './customTable.component';
import { Pager } from './pager.component';
import { Filter, CustomFilterPipe } from './filter.component';
import { AppComponent, EqualPipe } from './app.component';
import { Route1Component } from './route1.component';
import { Route2Component } from './route2.component';
import { Route3Component } from './route3.component';
import { Route4Component } from './route4.component';
import { APP_BASE_HREF } from '@angular/common';
import { NavigationService } from './services/navigation.service';
import { ApiService } from './services/api.service';
import { DataService } from './services/data.service';
import { LoremIpsumService } from './services/loremIpsum.service';
import { IdleTimeoutService } from './services/idleTimeout.service';
import { SpinService, SpinInterceptor } from './services/spin.service';
import { DialogService, DialogComponent } from './services/dialog.service';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { routing } from './app.routing';
import { HttpClient, HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RequestOptions, XHRBackend } from '@angular/http';
@NgModule({
imports: [BrowserModule, FormsModule, ReactiveFormsModule, JsonpModule, HttpClientModule, NgbModule.forRoot(), routing],
declarations: [ AppComponent, Route1Component, Route2Component, Route3Component, Route4Component, DialogComponent, Multiselect, Tristate, CustomTable, Filter, FilterPipe, EqualPipe, Pager ],
providers: [
EqualPipe,
LoremIpsumService,
SpinService,
{ provide: APP_BASE_HREF, useValue : document.location.pathname },
{ provide: HTTP_INTERCEPTORS, useClass: SpinInterceptor, multi: true },
NavigationService, DialogService, ApiService, DataService, SpinService, IdleTimeoutService],
entryComponents: [DialogComponent],
bootstrap: [ AppComponent ],
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
import { Component, ViewEncapsulation, Input, Output, OnInit, ViewChild, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef, Renderer, ElementRef, forwardRef } from '@angular/core';
import { Pipe, PipeTransform } from '@angular/core';
import { Observable, Subscription, fromEvent } from 'rxjs';
import { debounceTime, distinctUntilChanged, throttleTime } from 'rxjs/operators';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { EqualPipe } from './app.component';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any, filter: any, isAnd: Boolean): any {
if (filter && Array.isArray(items)) {
let filterKeys = Object.keys(filter);
if (isAnd) {
return items.filter(item =>
filterKeys.reduce((memo, keyName) =>
(memo && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] === "", true));
} else {
return items.filter(item => {
return filterKeys.some((keyName) => {
console.log(keyName);
return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] === "";
});
});
}
} else {
return items;
}
}
}
const MULTISELECT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => Multiselect),
multi: true
};
@Component({
selector: 'multiselect',
templateUrl: 'templates/multiselect.component.html',
host: true ? { '(change)': 'manualChange($event)', '(document:click)': 'hostClick($event)' } : {},
providers: [MULTISELECT_VALUE_ACCESSOR],
encapsulation: ViewEncapsulation.None, // needed for styles to work
})
export class Multiselect implements OnInit, ControlValueAccessor {
public _items: Array<any>;
public _selectedItems: Array<any>;
public localHeader: string;
public isOpen: Boolean = false;
public enableFilter: Boolean;
public filterText: string;
public filterPlaceholder: string;
public filterInput = new FormControl();
private _subscription: Subscription;
@Input() items: Observable<any[]>;
@Input() header: string = "Select some stuff";
@Input() selectedHeader: string = "options selected";
// ControlValueAccessor Interface and mutator
private _onChange = (_: any) => { };
private _onTouched = () => { };
constructor(private _elRef: ElementRef, private _renderer: Renderer, private _equalPipe: EqualPipe, private _changeDetectorRef: ChangeDetectorRef) {
}
get selected(): any {
return this._selectedItems;
};
writeValue(value: any) {
console.log('writing value ' + value);
if (value !== undefined) {
this._selectedItems = value;
this.setHeaderText();
} else {
this._selectedItems = [];
this.setHeaderText();
}
}
setHeaderText() {
this.localHeader = this.header;
var isArray = this._selectedItems instanceof Array;
if (isArray && this._selectedItems.length > 1) {
this.localHeader = this._selectedItems.length + ' ' + this.selectedHeader;
} else if (isArray && this._selectedItems.length === 1) {
this.localHeader = this._selectedItems[0].label;
}
console.log("Set header text " + this.localHeader);
}
registerOnChange(fn: (value: any) => any): void { this._onChange = fn; console.log(fn); }
registerOnTouched(fn: () => any): void { this._onTouched = fn; }
setDisabledState(isDisabled: boolean): void {
this._renderer.setElementProperty(this._elRef.nativeElement, 'disabled', isDisabled);
// if (this.isOpen()) {
// this._cRef.instance.setDisabledState(isDisabled);
// }
}
manualChange() {
this._onChange(this._selectedItems);
}
select(item: any) {
item.checked = !item.checked;
this._selectedItems = this._equalPipe.transform(this._items, { checked: true });
this.setHeaderText();
this._onChange(this._selectedItems);
}
toggleSelect() {
this.isOpen = !this.isOpen;
}
clearFilter() {
this.filterText = "";
}
hostClick(event) {
if (this.isOpen && !this._elRef.nativeElement.contains(event.target))
this.isOpen = false;
}
ngOnInit() {
this._subscription = this.items.subscribe(res => this._items = res);
this.enableFilter = true;
this.filterText = "";
this.filterPlaceholder = "Filter..";
this._selectedItems = this._equalPipe.transform(this._items, { checked: true });
this.setHeaderText();
this.filterInput
.valueChanges
.pipe(debounceTime(200))
.pipe(distinctUntilChanged())
.subscribe(term => {
this.filterText = term;
this._changeDetectorRef.markForCheck();
console.log(term);
});
}
}
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Route1Component } from './route1.component';
import { Route2Component } from './route2.component';
import { Route3Component } from './route3.component';
import { Route4Component } from './route4.component';
import { NavigationService } from './services/navigation.service';
const appRoutes: Routes = [
{ path: '', component: Route1Component, data: { name: 'Route1' }, canDeactivate: [ NavigationService ] },
{ path: 'route2', component: Route2Component, data: { name: 'Route2' }, canDeactivate: [ NavigationService ] },
{ path: 'route3', component: Route3Component, data: { name: 'Route3' }, canDeactivate: [ NavigationService ] },
{ path: 'route4', component: Route4Component, data: { name: 'Route4' }, canDeactivate: [ NavigationService ] }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
import { Component, Input, Injectable, ApplicationRef, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { Pipe, PipeTransform, OnInit } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { Observable, Subject, BehaviorSubject, of } from 'rxjs';
import { FormsModule, ReactiveFormsModule, FormGroup, FormControl } from '@angular/forms';
import { Multiselect } from './multiselect.component';
import { CustomTable, CustomTableOptions, CustomTableConfig, CustomTableColumnDefinition } from './customTable.component';
import { DataService } from './services/data.service';
import { LoremIpsumService } from './services/loremIpsum.service';
@Component({
templateUrl: 'templates/route1.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class Route1Component implements OnInit {
filterOptions: {
records: BehaviorSubject<any[]>;
columns: CustomTableColumnDefinition[];
};
public hasChanges: Boolean = false;
public tableOptions: CustomTableOptions;
public filterOptins: CustomTableOptions;
public records: Array<any> = [];
public filteredData: Array<any> = [];
public pagedData: Array<any> = [];
private tableSubject: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
public tableObserve: Observable<Array<any>> = this.tableSubject.asObservable();
private filterSubject: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
public filterObserve: Observable<Array<any>> = this.filterSubject.asObservable();
constructor(private changeRef: ChangeDetectorRef, private appRef: ApplicationRef, private dataSvc: DataService, private lipsumSvc: LoremIpsumService) {
}
canDeactivate() {
console.log("Detecting changes. Has Changes: " + this.hasChanges);
return of(!this.hasChanges);
}
filterChange($event) {
this.filteredData = $event.filterData;
this.sortChange(null);
this.pushChange();
}
sortChange($event: any) {
if (this.tableOptions.config.clientSort) {
this.dataSvc.sort(this.filteredData, this.tableOptions.config.sortBy, this.tableOptions.config.sortDirection, this.tableOptions.columns);
if (this.tableOptions.config.clientPaging) {
this.pageChange(null);
} else {
this.pushChange();
}
}
}
pageChange($event: any) {
if (this.tableOptions.config.clientPaging) {
this.pagedData = this.dataSvc.pageData(this.filteredData, this.tableOptions);
this.pushChange();
}
}
initTableOptions() {
var columns: Array<CustomTableColumnDefinition> = [
{ name: 'Column 1', value: 'column1', binding: "r.column3 + \" / \" + r.column4", style: {}, isWatched: true, isAnchor: true, isComputed: true, routerLink: "['/route2', r.column2]" },
{ name: 'Column 2', value: 'column2', binding: 'column2', isWatched: true, style: {} },
{ name: 'Column 3', value: 'column3', binding: 'column3', isWatched: true, style: {} },
{ name: 'Column 4', value: 'column4', binding: 'column4', isWatched: true, style: {} },
{ name: 'Column 5', value: 'column5', binding: 'column5', style: {} },
{ name: 'Column 6', value: 'column6', binding: 'column6', filter: "currency", isWatched: true, style: {} },
{ name: 'Column 7', value: 'column7', binding: 'column7', style: {} },
{ name: 'Column 8', value: 'column8', binding: 'column8', filter: "date:\"MM/dd/yyyy\"", style: {} },
{ name: 'Column 9', value: 'column9', binding: 'column9', isHoverOver: true, hoverVisibility: 'true', hoverBinding: "'test'", filter: "date:\"MM/dd/yyyy\"", style: {} }
];
this.tableOptions = {
records: this.tableSubject,
columns: columns,
config: {
sortBy: "column1",
sortDirection: "asc",
pageSize: 10,
pageNumber: 1,
totalCount: 0,
totalPages: 0,
maxSize: 10,
showSelectCheckbox: true,
showSelectAll: true,
showSort: true,
clientSort: true,
clientPaging: true,
//displayPager: true,
//displayPageSize: true,
stickyHeader: true,
stickyHeaderOffset: 0,
stickyContainer: '.table1-container'
},
};
this.filterOptions = {
records: this.filterSubject,
columns: columns
};
this.filterChange({ filterData: this.records, filterText: "" });
// For the filter, we don't want to refresh data, so we push once.
// This allows the filter to control this.records
this.pushFilterData();
}
pushChange() {
this.tableSubject.next(this.pagedData);
}
pushFilterData() {
this.filterSubject.next(this.records);
}
addItems(count: number) {
for (var i: number = 0; i < count; i++) {
var suffix: string = this.records.length.toString();
var money = (Math.random() * 1000).toFixed(2);
var date = new Date();
date.setDate(date.getDate() + this.records.length);
//this.records.push({
// id: suffix, column2: "Column2_" + suffix, column3: "Column3_" + suffix, column4: "Column4_" + suffix, column5: "Column5_" + suffix,
// column6: money, column7: "Column7_" + suffix, column8: date, column9: "Column9_" + suffix
//});
this.records.push({
id: suffix, column2: this.lipsumSvc.singleWord(), column3: this.lipsumSvc.singleWord(), column4: this.lipsumSvc.singleWord(), column5: this.lipsumSvc.singleWord(),
column6: money, column7: this.lipsumSvc.singleWord(), column8: date, column9: this.lipsumSvc.singleWord()
});
}
}
ngOnInit() {
this.addItems(10000);
this.initTableOptions();
}
}
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable, of, from } from 'rxjs';
import { tap, delay, map, flatMap, catchError } from 'rxjs/operators';
import { DialogService } from './dialog.service';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class NavigationService implements CanDeactivate<CanComponentDeactivate>, CanActivate {
constructor(private dialogService: DialogService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
throw new Error("Method not implemented.");
}
canDeactivate(component: CanComponentDeactivate) {
if (!component.canDeactivate) {
return new Promise<boolean>(resolve => { return resolve(true); });
}
var retValue = component.canDeactivate();
if (retValue instanceof Observable) {
console.log("We have an observable");
return this.intercept(retValue);
} else {
console.log("We have a promise");
return retValue;
}
}
private intercept(observable: Observable<any>): Observable<any> {
return observable
.pipe(map((res) => { console.log("Mapped: " + res); return res; }))
.pipe(flatMap((res) => {
// Inverse logic - false means deactivate of route is not allowed (hasChanges is true)
if (res === false) {
console.log("Showing confirm dialog.");
var modalPromise = this.dialogService.confirm();
var newObservable = from(modalPromise);
newObservable.subscribe(
(res) => {
if (res === true) {
console.log("Navigation allowed.");
} else {
console.log("Navigation prevented.");
}
},
(reason) => {
console.log("Dismissed " + reason);
}
);
return newObservable;
} else {
return of(res);
}
}),
catchError(error => of(false)));
}
}
import { Injectable } from '@angular/core';
import { Component, Input, OnInit, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay, tap } from 'rxjs/operators';
import { NgbModal, NgbModalOptions, NgbActiveModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
@Component({
template: `
<div class="modal-header">
<h4 class="modal-title">{{ title }}</h4>
<button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p [innerHTML]="message"></p>
</div>
<div class="modal-footer">
<button *ngIf="showCancel" type="button" class="btn btn-secondary" (click)="activeModal.close(false)">{{ cancelText }}</button>
<button type="button" class="btn btn-secondary" (click)="activeModal.close(true)">{{ confirmText }}</button>
</div>
`
})
export class DialogComponent implements OnInit {
@Input() title;
@Input() message;
@Input() showCancel = false;
@Input() confirmText: string = "Ok";
@Input() cancelText: string = "Cancel";
constructor(public activeModal: NgbActiveModal, public changeRef: ChangeDetectorRef) {
//console.log("DialogComponent construct");
}
ngOnInit() {
//console.log("DialogComponent init");
}
}
@Injectable()
export class DialogService {
constructor(private modalService: NgbModal) { }
public confirm() {
const modalRef = this.modalService.open(DialogComponent);
let instance = (modalRef as any)._windowCmptRef.instance
instance.windowClass = '';
//setImmediate(() => {
// instance.windowClass = 'custom-show'
//})
setTimeout(() => {
instance.windowClass = 'custom-show';
}, 0)
let fx = (modalRef as any)._removeModalElements.bind(modalRef);
(modalRef as any)._removeModalElements = () => {
instance.windowClass = '';
setTimeout(fx, 250);
}
modalRef.componentInstance.title = "Discard Changes?";
modalRef.componentInstance.message = "Are you sure you want to discard your changes?";
modalRef.componentInstance.changeRef.markForCheck();
return modalRef.result;
}
public open(title: string, message: string, showCancel: boolean = false, confirmText: string = "Ok", cancelText: string = "Cancel",
options: NgbModalOptions = { size: 'sm' }) {
const modalRef = this.modalService.open(DialogComponent, options);
let instance = (modalRef as any)._windowCmptRef.instance
//setImmediate(() => {
// instance.windowClass = "custom-show";
//})
setTimeout(() => {
instance.windowClass = 'custom-show';
}, 0)
let fx = (modalRef as any)._removeModalElements.bind(modalRef);
(modalRef as any)._removeModalElements = () => {
instance.windowClass = "";
setTimeout(fx, 250);
}
modalRef.componentInstance.title = title
modalRef.componentInstance.message = message;
modalRef.componentInstance.showCancel = showCancel;
modalRef.componentInstance.confirmText = confirmText;
modalRef.componentInstance.cancelText = cancelText;
modalRef.componentInstance.changeRef.markForCheck();
return modalRef.result;
}
}
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpEvent, HttpEventType, HttpResponse, HttpHeaders, HttpParams } from "@angular/common/http";
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class ApiService {
constructor(private http: HttpClient) {
}
getUrl(url: string, search?: any): Observable<any> {
console.log("In API Service.. making arbitrary call.");
//var req = new HttpRequest('GET', url, '', {
// responseType: 'text',
// headers: new HttpHeaders()
//});
// Allow passing in HttpParams
let httpParams = new HttpParams();
for (let key in search) {
httpParams = httpParams.append(key, search[key]);
}
return this.http
.get(url, { params: httpParams })
.pipe(map((res: Response) => {
console.log('Request complete');
return res;
}));
//return this.http
// .request(req)
// .subscribe(event => {
// console.log('API Request done.');
// //// Via this API, you get access to the raw event stream.
// //// Look for upload progress events.
// //if (event.type === HttpEventType.UploadProgress) {
// // // This is an upload progress event. Compute and show the % done:
// // const percentDone = Math.round(100 * event.loaded / event.total);
// // console.log(`File is ${percentDone}% uploaded.`);
// //} else if (event instanceof HttpResponse) {
// // console.log('File is completely uploaded!');
// //}
// })
// .map((res: Response) => {
// //console.log(res);
// return res.json();
// });
}
put(url: string, body: any, search?: any): Observable<any> {
console.log("In API Service.. making put call.");
let headers: HttpHeaders = new HttpHeaders();
// Allow passing in HttpParams
let httpParams = new HttpParams();
for (let key in search) {
if (typeof (search[key]) !== 'undefined') {
httpParams = httpParams.append(key, search[key]);
}
}
return this.http
.put(url, body, { params: httpParams })
.pipe(map((res: Response) => {
console.log('Request complete');
return res;
}));
}
}
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { CustomTableOptions, CustomTableConfig, CustomTableColumnDefinition } from 'customTable.component';
@Injectable()
export class DataService {
constructor() {
}
public sort(array: Array<any>, fieldName: string, direction: string, columns: Array<CustomTableColumnDefinition>) {
// Check to see if the column exists
var filterResult = columns.filter((column) => column.value === fieldName);
if (filterResult.length === 0) {
return array;
}
var column: CustomTableColumnDefinition = filterResult[0];
var isNumeric: Boolean = (column.filter && column.filter.indexOf("currency") != -1) || (column.isNumeric === true);
var sortFunc = function (field, rev, primer) {
// Return the required a,b function
return function (a, b) {
// Reset a, b to the field
a = primer(pathValue(a, field)), b = primer(pathValue(b, field));
// Do actual sorting, reverse as needed
return ((a < b) ? -1 : ((a > b) ? 1 : 0)) * (rev ? -1 : 1);
}
};
// Have to handle deep paths
var pathValue = function (obj, path) {
for (var i = 0, path = path.split('.'), len = path.length; i < len; i++) {
obj = obj[path[i]];
};
return obj;
};
var primer = isNumeric ?
function (a) {
var retValue = parseFloat(String(a).replace(/[^0-9.-]+/g, ''));
return isNaN(retValue) ? 0.0 : retValue;
} :
function (a) { return String(a).toUpperCase(); };
var start = new Date().getTime();
array.sort(sortFunc(fieldName, direction === 'desc', primer));
var end = new Date().getTime();
var time = end - start;
console.log('Sort time: ' + time);
}
public pageData(records: Array<any>, options: CustomTableOptions): Array<any> {
console.log("Paging data..");
if (records) {
var arrLength = options.config.totalCount = records.length;
options.config.totalPages = parseInt(Math.ceil(options.config.totalCount / options.config.pageSize).toString());
if (options.config.pageNumber > options.config.totalPages) {
options.config.pageNumber = 1;
}
var startIndex: number = (options.config.pageNumber - 1) * options.config.pageSize;
var endIndex: number = (options.config.pageNumber - 1) * options.config.pageSize + options.config.pageSize;
endIndex = endIndex > arrLength ? arrLength : endIndex;
options.config.lowerRange = ((options.config.pageNumber - 1) * options.config.pageSize) + 1;
if (!options.config.clientPaging) {
options.config.upperRange = options.config.lowerRange + arrLength - 1;
} else {
options.config.upperRange = options.config.lowerRange + options.config.pageSize - 1;
if (options.config.upperRange > records.length) {
options.config.upperRange = records.length;
}
}
let arr = records.slice(startIndex, endIndex);
console.log("Number of records returned:" + arr.length);
return arr;
} else {
options.config.lowerRange = 0;
options.config.upperRange = 0;
options.config.totalPages = 0;
options.config.totalCount = 0;
}
return [];
}
}
import { Injectable, Injector, Inject } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, Subscription, timer, of, from, throwError } from "rxjs";
import { map, tap, catchError, finalize } from "rxjs/operators";
import { ApiService, DialogService, IdleTimeoutService } from "./index";
import { DOCUMENT } from '@angular/platform-browser';
declare var Spinner: any;
@Injectable()
export class SpinService {
private modal_opts: any = {
lines: 11, // The number of lines to draw
length: 23, // The length of each line
width: 8, // The line thickness
radius: 40, // The radius of the inner circle
corners: 1, // Corner roundness (0..1)
rotate: 9, // The rotation offset
color: '#FFF', // #rgb or #rrggbb
speed: 1, // Rounds per second
trail: 50, // Afterglow percentage
shadow: true, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: 'auto', // Top position relative to parent in px
left: 'auto' // Left position relative to parent in px
};
private presets: any = {
tiny: { lines: 8, length: 2, width: 2, radius: 3 },
small: { lines: 8, length: 4, width: 3, radius: 5 },
large: { lines: 10, length: 8, width: 4, radius: 8 }
}
constructor() {
}
public spin(selector: any, opts: any, color: any, bgColor: any) {
var that = this;
if (opts == "modal") opts = that.modal_opts;
var $elements = $(selector);
return $elements.each(function () {
var $this = $(this),
data = $this.data();
if (data.spinner) {
data.spinner.stop();
delete data.spinner;
if (opts == that.modal_opts) {
$("#spin_modal_overlay").remove();
return;
}
}
if (opts !== false) {
var spinElem = this;
if (opts == that.modal_opts) {
var backgroundColor = 'background-color:' + (bgColor ? bgColor : 'rgba(0, 0, 0, 0.6)');
$('body').append('<div id="spin_modal_overlay" style=\"' + backgroundColor + ';width:100%; height:100%; position:fixed; top:0px; left:0px; z-index:' + (opts.zIndex - 1) + '"/>');
spinElem = $("#spin_modal_overlay")[0];
}
opts = $.extend({}, that.presets[opts] || opts, { color: color || $this.css('color') });
data.spinner = new Spinner(opts).spin(spinElem);
}
})
}
}
@Injectable()
export class SpinInterceptor implements HttpInterceptor {
public pendingRequests: number = 0;
public showLoading: Boolean = false;
private _idleTimeoutSvc: IdleTimeoutService;
private _apiSvc: ApiService;
private _dialogSvc: DialogService;
private _configSvc: ConfigService;
private _idleTimerSubscription: Subscription;
private _dismissTimer: Observable<number>;
private _dismissSubscription: Subscription;
private document: Document;
constructor(private spinSvc: SpinService, @Inject(DOCUMENT) private doc: any, private injector: Injector) {
setTimeout(() => {
this.document = doc as Document;
this.subscribeToIdleTimeoutService();
});
}
private subscribeToIdleTimeoutService() {
this._idleTimeoutSvc = this.injector.get(IdleTimeoutService);
this._apiSvc = this.injector.get(ApiService);
this._dialogSvc = this.injector.get(DialogService);
this._configSvc = this.injector.get(ConfigService);
this._idleTimerSubscription = this._idleTimeoutSvc.timeoutExpired.subscribe(r => {
this.startDismissTimer();
let modalPromise: Promise<any> = this._dialogSvc.open("Session Expiring!", "Your session is about to expire. Do you need more time?", true, "Yes", "No");
let newObservable: Observable<any> = from(modalPromise);
newObservable.subscribe(
(res) => {
this._dismissSubscription.unsubscribe();
if (res === true) {
console.log("Extending session...");
this._apiSvc
.getUrl("/home/heartbeat")
.subscribe(() => { this._idleTimeoutSvc.startTimer(); });
} else {
console.log("Not extending session... logging out");
this.document.location.href = "/account/logout";
}
},
(reason) => {
console.log("Dismissed " + reason);
this._dismissSubscription.unsubscribe();
this.document.location.href = "/account/logout";
}
);
});
}
private startDismissTimer() {
if (this._dismissSubscription) {
this._dismissSubscription.unsubscribe();
}
// This needs to come from the config
let timeout: number = 2 * 60 * 1000;
if (this._configSvc.configData.authSettings.authDismissTimeout) {
timeout = <number>this._configSvc.configData.authSettings.authDismissTimeout;
}
this._dismissTimer = timer(timeout);
this._dismissSubscription = this._dismissTimer.subscribe(n => {
this._dismissSubscription.unsubscribe();
console.log("Dismiss timer expired ... logging out");
this.document.location.href = "/account/logout";
});
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.pendingRequests++;
let isExcluded: boolean = false;
// Determine if excluded
for (let exclusion of spinExclusions) {
let isMatch: boolean = exclusion.test(req.url);
exclusion.lastIndex = 0;
if (isMatch) {
isExcluded = true;
break;
}
}
if (!isExcluded) {
this.turnOnModal();
}
return next.handle(req).pipe(
tap((event: HttpEvent<any>) => {
// Reset the timer ..
if (this._idleTimeoutSvc) {
this._idleTimeoutSvc.startTimer();
}
if (event instanceof HttpResponse) {
}
}),
catchError(err => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
// JWT expired, go to login
// throwError(err);
}
}
console.log('Caught error', err);
return throwError(err);
}),
finalize(() => {
//console.log("Finally.. delaying, though.")
//var timer = Observable.timer(1000);
//timer.subscribe(t => {
// this.turnOffModal();
//});
this.turnOffModal();
})
);
}
private turnOnModal() {
if (!this.showLoading) {
this.showLoading = true;
this.spinSvc.spin("body", "modal", "#FFFFFF", "rgba(51, 51, 51, 0.1)");
console.log("Turned on modal");
}
this.showLoading = true;
}
private turnOffModal() {
this.pendingRequests--;
if (this.pendingRequests <= 0) {
if (this.showLoading) {
this.spinSvc.spin("body", "modal", "#FFFFFF", "rgba(51, 51, 51, 0.1)");
}
this.showLoading = false;
}
console.log("Turned off modal");
}
}
const spinExclusions: RegExp[] = [
/(home\/heartbeat)/g,
/(api\/ratePlan)/g,
///(\/api\/employee)/g,
/(\/api\/product)/g,
/(\/payment\/api\/paymentaudit)/g,
/(\/payment\/api\/transactionaudit)/g,
/(\/payment\/api\/transactiondetailaudit)/g,
/(\/api\/config)/g // for testing
];
import { Injectable } from '@angular/core';
@Injectable()
export class LoremIpsumService {
private WORDS_PER_SENTENCE_AVG: number = 24.260;
private WORDS_PER_SENTENCE_STD: number = 5.080;
private WORDS: Array<string> = [
'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur',
'adipiscing', 'elit', 'curabitur', 'vel', 'hendrerit', 'libero',
'eleifend', 'blandit', 'nunc', 'ornare', 'odio', 'ut',
'orci', 'gravida', 'imperdiet', 'nullam', 'purus', 'lacinia',
'a', 'pretium', 'quis', 'congue', 'praesent', 'sagittis',
'laoreet', 'auctor', 'mauris', 'non', 'velit', 'eros',
'dictum', 'proin', 'accumsan', 'sapien', 'nec', 'massa',
'volutpat', 'venenatis', 'sed', 'eu', 'molestie', 'lacus',
'quisque', 'porttitor', 'ligula', 'dui', 'mollis', 'tempus',
'at', 'magna', 'vestibulum', 'turpis', 'ac', 'diam',
'tincidunt', 'id', 'condimentum', 'enim', 'sodales', 'in',
'hac', 'habitasse', 'platea', 'dictumst', 'aenean', 'neque',
'fusce', 'augue', 'leo', 'eget', 'semper', 'mattis',
'tortor', 'scelerisque', 'nulla', 'interdum', 'tellus', 'malesuada',
'rhoncus', 'porta', 'sem', 'aliquet', 'et', 'nam',
'suspendisse', 'potenti', 'vivamus', 'luctus', 'fringilla', 'erat',
'donec', 'justo', 'vehicula', 'ultricies', 'varius', 'ante',
'primis', 'faucibus', 'ultrices', 'posuere', 'cubilia', 'curae',
'etiam', 'cursus', 'aliquam', 'quam', 'dapibus', 'nisl',
'feugiat', 'egestas', 'class', 'aptent', 'taciti', 'sociosqu',
'ad', 'litora', 'torquent', 'per', 'conubia', 'nostra',
'inceptos', 'himenaeos', 'phasellus', 'nibh', 'pulvinar', 'vitae',
'urna', 'iaculis', 'lobortis', 'nisi', 'viverra', 'arcu',
'morbi', 'pellentesque', 'metus', 'commodo', 'ut', 'facilisis',
'felis', 'tristique', 'ullamcorper', 'placerat', 'aenean', 'convallis',
'sollicitudin', 'integer', 'rutrum', 'duis', 'est', 'etiam',
'bibendum', 'donec', 'pharetra', 'vulputate', 'maecenas', 'mi',
'fermentum', 'consequat', 'suscipit', 'aliquam', 'habitant', 'senectus',
'netus', 'fames', 'quisque', 'euismod', 'curabitur', 'lectus',
'elementum', 'tempor', 'risus', 'cras'
];
constructor() {
}
public singleWord(): string {
var position = Math.floor(Math.random() * this.WORDS.length);
var word = this.WORDS[position];
return word.charAt(0).toUpperCase() + word.slice(1);
};
public generate(num_words: number) {
var words, ii, position, word, current, sentences, sentence_length, sentence;
/**
* @default 100
*/
num_words = num_words || 100;
words = [this.WORDS[0], this.WORDS[1]];
num_words -= 2;
for (ii = 0; ii < num_words; ii++) {
position = Math.floor(Math.random() * this.WORDS.length);
word = this.WORDS[position];
if (ii > 0 && words[ii - 1] === word) {
ii -= 1;
} else {
words[ii] = word;
}
}
sentences = [];
current = 0;
while (num_words > 0) {
sentence_length = this.getRandomSentenceLength();
if (num_words - sentence_length < 4) {
sentence_length = num_words;
}
num_words -= sentence_length;
sentence = [];
for (ii = current; ii < (current + sentence_length); ii++) {
sentence.push(words[ii]);
}
sentence = this.punctuate(sentence);
current += sentence_length;
sentences.push(sentence.join(' '));
}
return sentences.join(' ');
};
public punctuate(sentence: any) {
var word_length, num_commas, ii, position;
word_length = sentence.length;
/* End the sentence with a period. */
sentence[word_length - 1] += '.';
if (word_length < 4) {
return sentence;
}
num_commas = this.getRandomCommaCount(word_length);
for (ii = 0; ii <= num_commas; ii++) {
position = Math.round(ii * word_length / (num_commas + 1));
if (position < (word_length - 1) && position > 0) {
/* Add the comma. */
sentence[position] += ',';
}
}
/* Capitalize the first word in the sentence. */
sentence[0] = sentence[0].charAt(0).toUpperCase() + sentence[0].slice(1);
return sentence;
}
public getRandomCommaCount(word_length: number) {
var base, average, standard_deviation;
/* Arbitrary. */
base = 6;
average = Math.log(word_length) / Math.log(base);
standard_deviation = average / base;
return Math.round(this.gaussMS(average, standard_deviation));
}
public getRandomSentenceLength() {
return Math.round(
this.gaussMS(
this.WORDS_PER_SENTENCE_AVG,
this.WORDS_PER_SENTENCE_STD
)
);
}
private gauss() {
return (Math.random() * 2 - 1) +
(Math.random() * 2 - 1) +
(Math.random() * 2 - 1);
}
private gaussMS(mean: number, standard_deviation: number) {
return Math.round(this.gauss() * standard_deviation + mean);
}
}
export * from './api.service';
export * from './data.service';
export * from './dialog.service';
export * from './loremIpsum.service';
export * from './navigation.service';
export * from './spin.service';
import { Injectable } from '@angular/core';
import { Observable, Subject, Subscription, timer } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class IdleTimeoutService {
private _count: number = 0;
private _serviceId: string = 'idleTimeoutSvc-' + Math.floor(Math.random() * 10000);
private _timeoutMilliseconds: number = 5000;
private timerSubscription: Subscription;
private timer: Observable<number>;
private timer: Observable<number>;
private resetOnTrigger: boolean = false;
private lastTime: number;
private dateTimer: Observable;
private dateTimerSubscription: Subscription;
private dateTimerInterval : number = 1000 * 60 * 5;
private dateTimerTolerance: number = 1000 * 10;
public timeoutExpired: Subject<number> = new Subject<number>();
constructor() {
console.log("Constructed idleTimeoutService " + this._serviceId);
this.timeoutExpired.subscribe(n => {
console.log("timeoutExpired subject next.. " + n.toString());
});
this.startTimer();
this.startDateCompare();
}
private setSubscription() {
this._timer = timer(this._timeoutMilliseconds);
this.timerSubscription = this._timer.subscribe(n => {
this.timerComplete(n);
});
}
private startDateCompare() {
this.lastTime = (new Date()).getTime();
this.dateTimer = timer(this.dateTimerInterval); // compare every five minutes
this.dateTimerSubscription = this.dateTimer.subscribe(n => {
let currentTime: number = (new Date()).getTime();
if (currentTime > (this.lastTime + this.dateTimerInterval + this.dateTimerTolerance)) { // look for 10 sec diff
console.log("Looks like the machine just woke up.. ");
}
else {
console.log("Machine did not sleep.. ");
}
this.dateTimerSubscription.unsubscribe();
this.startDateCompare();
});
}
public startTimer() {
if (this.timerSubscription) {
this.stopTimer();
}
this.setSubscription();
}
public stopTimer() {
this.timerSubscription.unsubscribe();
}
public resetTimer() {
this.startTimer();
}
private timerComplete(n: number) {
this.timeoutExpired.next(++this._count);
if (this.resetOnTrigger) {
this.startTimer();
}
}
}
import { Component,Input, Injectable, ApplicationRef, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { Multiselect } from './multiselect.component';
import { ApiService } from './services/api.service';
import { Observable, of } from 'rxjs';
import { Pipe, PipeTransform } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { LoremIpsumService } from './services/loremIpsum.service';
@Component({
templateUrl: 'templates/route2.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class Route2Component implements OnInit {
public hasChanges: bool = true;
private _items: Array<any>;
public items: Observable<Array<any>>;
constructor(private changeRef: ChangeDetectorRef, private appRef: ApplicationRef, private apiService: ApiService, private lipsumSvc: LoremIpsumService) {
this._items = [];
this.items = of(this._items);
this.items.subscribe(res => {
console.log("Route2 subscription triggered.");
});
}
canDeactivate() {
console.log("Detecting changes. Has Changes: " + this.hasChanges);
return of(!this.hasChanges);
}
createItems() {
this._items.length = 0;
var max: int = 20;
var min: int = 10;
var numItems: int = Math.floor(Math.random() * (max - min + 1)) + min;
console.log("Adding " + numItems.toString() + " items");
max = 6;
min = 3;
var i: int;
for (i =0; i < numItems; i++) {
var numWords: int = Math.floor(Math.random() * (max - min + 1)) + min;
var label: string = this.lipsumSvc.generate(numWords);
this._items.push({ id: i, label: label, value: i.toString(), isSelected: true });
console.log(label);
}
// Randomly choose a few items
//this.randomSelect();
}
makeCall() {
this.apiService
.getUrl("index.html")
.subscribe();
}
checkAll() {
for (var i: int = 0; i < this._items.length; i++) {
this._items[i].isSelected = true;
}
}
uncheckAll() {
for (var i: int = 0; i < this._items.length; i++) {
this._items[i].isSelected = false;
}
}
ngOnInit() {
this.createItems();
}
}
import { Component,Input, Injectable, ApplicationRef, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { Multiselect } from './multiselect.component';
import { Observable, of } from 'rxjs';
import {Pipe, PipeTransform} from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { EqualPipe } from './app.component';
import { LoremIpsumService } from './services/loremIpsum.service';
@Component({
templateUrl: 'templates/route3.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class Route3Component implements OnInit {
public hasChanges: bool = true;
public items: Observable<Array<any>>;
public selectedItems: Observable<Array<any>>;
public _selectedItems: Array<any> = [];
public watchedItems: Array<any>;
private _items: Array<any>;
constructor(private changeRef: ChangeDetectorRef, private appRef: ApplicationRef, private lipsumSvc: LoremIpsumService) {
this._items = [];
this.items = of(this._items);
this.items.subscribe(res => { console.log("Items changed"); this.watchedItems = res; });
}
canDeactivate() {
console.log("Detecting changes. Has Changes: " + this.hasChanges);
return of(!this.hasChanges);
}
createItems() {
this._items.length = 0;
var max: int = 20;
var min: int = 10;
var numItems: int = Math.floor(Math.random() * (max - min + 1)) + min;
console.log("Adding " + numItems.toString() + " items");
max = 6;
min = 3;
var i: int;
for (i =0; i < numItems; i++) {
var numWords: int = Math.floor(Math.random() * (max - min + 1)) + min;
var label: string = this.lipsumSvc.generate(numWords);
this._items.push({ label: label, value: i.toString()});
console.log(label);
}
// Randomly choose a few items
this.randomSelect();
}
randomSelect() {
var numItems: int = this.getRandomInt(0, this._items.length) + 1;
var min: int = 0;
var max: int = this._items.length - 1;
var toSelectIndexes: Array<int> = [];
for (var j: int = 0; j < this.getRandomInt(1, numItems); j++) {
var randIndex: int = this.getRandomInt(min, max);
var arrIndex = toSelectIndexes.indexOf(randIndex);
if (arrIndex == -1) {
toSelectIndexes.push(randIndex);
var item: any = this._items[randIndex];
item.checked = true;
this._selectedItems.push(this._items[randIndex]);
}
}
}
getRandomInt(min: int, max: int) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
onChange(newValue) {
console.log('received change event');
}
ngOnInit() {
this.createItems();
let timer = Observable.timer(20000,20000);
timer.subscribe(t=> {
//this.createItems();
});
}
}
import { Component, Input, Output, ViewChild, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef, Renderer, ElementRef, forwardRef } from '@angular/core';
import { Pipe, PipeTransform, AfterViewInit, OnInit, OnDestroy } from '@angular/core';
import { Observable, Subscription, fromEvent } from 'rxjs';
import { debounceTime, throttleTime, distinctUntilChanged } from 'rxjs/operators';
@Component({
selector: 'tri-state-checkbox',
template: `<input #theCheckbox type="checkbox" [(ngModel)]="topLevel" (change)="topLevelChange()">`
})
export class Tristate implements AfterViewInit {
public topLevel: Boolean = false;
public _items: Array<any>;
private _subscription: Subscription;
@Input() items: Observable<any[]>;
@ViewChild("theCheckbox") checkbox;
constructor(private _changeDetectorRef: ChangeDetectorRef) { }
private setState() {
if (!this._items) return;
var count: number = 0;
for (var i: number = 0; i < this._items.length; i++) {
count += this._items[i].isSelected ? 1 : 0;
}
this.topLevel = (count === 0) ? false : true;
if (count > 0 && count < i) {
console.log("Setting indeterminate.");
this.checkbox.nativeElement.indeterminate = true;
} else {
console.log("Removing indeterminate.");
this.checkbox.nativeElement.indeterminate = false;
}
}
ngDoCheck() {
this.setState();
}
public topLevelChange() {
console.log("Clicked. " + this.topLevel);
for (var i: number = 0; i < this._items.length; i++) {
this._items[i].isSelected = this.topLevel;
}
}
ngOnInit() { }
ngOnDestroy() {
this._subscription.unsubscribe();
}
ngAfterViewInit() {
this._subscription = this.items.subscribe(res => {
console.log("Subscription triggered.");
this._items = res;
this.setState();
this._changeDetectorRef.detectChanges();
});
}
}
import { Component, Input, Output, Injectable, ApplicationRef, EventEmitter, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { PipeTransform, OnInit, OnDestroy, Optional } from '@angular/core';
import { CurrencyPipe, DatePipe, DecimalPipe, PercentPipe } from '@angular/common';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule, ReactiveFormsModule, FormGroup, FormControl } from '@angular/forms';
import { DataService } from './services/data.service';
import { LoremIpsumService } from './services/loremIpsum.service';
import { Observable, Subject, Subscription, Subscriber, BehaviorSubject } from 'rxjs';
import { CustomTableEmitter } from "./customTable.emitter";
export class CustomTableColumnDefinition {
public name: string = '';
public value: string = '';
public binding: string = '';
public filter?: string = '';
public computedClass?: any;
public isComputed?: boolean = false;
public isNumeric?: boolean = false;
public isAnchor?: boolean = false;
public isWatched?: boolean = true;
public isHoverOver?: boolean = false;
public isCheckbox?: boolean = false;
public isDisabledCheckbox?: boolean = false;
public isExclusive?: boolean = false;
public isSelected?: boolean = true;
public hoverVisibility?: string = '';
public hoverBinding?: string = '';
public routerLink?: string = '';
public style?: any;
}
export class CustomTableConfig {
public sortBy: string = '';
public sortDirection: string = 'desc';
public pageSize: number = 100;
public pageNumber?: number = 1;
public totalCount?: number = 0;
public totalPages?: number = 0;
public lowerRange?: number = 0;
public upperRange?: number = 0;
public maxSize: number = 10;
public showSelectCheckbox: boolean = true;
public showSelectAll: boolean = true;
public showSort: boolean = true;
public clientSort: boolean = false;
public clientPaging: boolean = false;
public stickyHeader: boolean = true;
public stickyHeaderOffset: number = 0;
public stickyContainer: string = '';
}
export class CustomTableOptions {
public records: Observable<Array<any>>;
public columns: Array<CustomTableColumnDefinition>;
public rowDefns?: Array<any> = [];
public config: CustomTableConfig;
public callbacks?: any;
}
@Component({
selector: 'custom-table',
templateUrl: 'templates/customTable.component.html',
//styleUrls: ['./customTable.component.css'],
providers: [CurrencyPipe, DatePipe, DecimalPipe, PercentPipe],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomTable implements OnInit {
private _subscription: Subscription;
private _start: Date;
private _end: Date;
private _isSorting: Boolean = false;
public filteredData: Array<any>;
//public filteredDataObservable: Observable<Array<any>>;
public filteredDataObservable: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
@Input() options: CustomTableOptions;
@Output() sortChange: EventEmitter<any> = new EventEmitter<any>();
constructor(@Optional() private emitter: CustomTableEmitter, private changeRef: ChangeDetectorRef, private appRef: ApplicationRef,
private dataSvc: DataService, private lipsumSvc: LoremIpsumService,
private currencyPipe: CurrencyPipe, private decimalPipe: DecimalPipe,
private datePipe: DatePipe, private percentPipe: PercentPipe) {
}
isSorting(name: string) {
return this.options.config.sortBy !== name && name !== '';
};
isSortAsc(name: string) {
var isSortAsc: Boolean = this.options.config.sortBy === name && this.options.config.sortDirection === 'asc';
return isSortAsc;
};
isSortDesc(name: string) {
var isSortDesc: Boolean = this.options.config.sortBy === name && this.options.config.sortDirection === 'desc';
return isSortDesc;
};
sortHeaderClick(headerName: string) {
if (headerName) {
if (this.options.config.sortBy === headerName) {
this.options.config.sortDirection = this.options.config.sortDirection === 'asc' ? 'desc' : 'asc';
}
this.options.config.sortBy = headerName;
this.sortChange.emit();
}
}
setCellValue(row: any, column: CustomTableColumnDefinition, value: any, $event?: Event): any {
var obj = column.binding.split('.').reduce((prev: any, curr: string) => prev[curr], row);
console.log("Old value.. " + obj);
// Presume that an exclusive checkbox requires a selection ... so, if it was true before,
// don't let it get set to false now.
if (obj === true) {
if (column.isCheckbox && column.isExclusive) {
if ($event) {
$event.preventDefault();
$event.stopPropagation();
}
return false;
}
}
var key = column.binding;
if (row.hasOwnProperty(key)) {
row[key] = value;
obj = column.binding.split('.').reduce((prev: any, curr: string) => prev[curr], row);
console.log("New value.. " + obj);
}
else {
console.log("Row doesn't contain property..");
}
if (column.isCheckbox && column.isExclusive) {
for (let r of this.filteredData) {
if (r !== row) {
r[key] = false;
}
}
if (this.emitter) {
this.emitter.next({ name: 'cellClicked', data: { row: row, column: column, value: value } });
}
}
}
getRouterLink(row: any, column: CustomTableColumnDefinition): string {
var index1 = column.routerLink.lastIndexOf('r.');
var index2 = column.routerLink.lastIndexOf(']');
var binding = column.routerLink.substring(index1, index2);
let evalfunc = new Function('r', 'return ' + binding);
let evalresult: string = evalfunc(row);
//var routerLink = column
// .routerLink
// .replace(binding, "'" + evalresult.toString() + "'")
// .replace('[', '');
var routerLink = column
.routerLink
.replace(binding, '')
.replace('[', '')
.replace(']', '')
.replace(/'/g, '')
.replace(",", '')
.trim() + '/' + evalresult;
//console.log(routerLink);
return routerLink;
}
getCellValue(row: any, column: CustomTableColumnDefinition): string {
var result: string = '';
if (column.isComputed) {
let evalfunc = new Function('r', 'return ' + column.binding);
result = evalfunc(row);
} else {
result = column.binding.split('.').reduce((prev: any, curr: string) => prev[curr], row);
}
if (column.filter) {
if (column.filter === "currency") {
result = this.currencyPipe.transform(result);
}
if (column.filter.indexOf("date=") !== -1) {
var filter = column.filter.replace("date=", "");
result = this.datePipe.transform(result, filter);
}
}
return result;
}
ngOnInit() {
this._subscription = this.options.records.subscribe(res => {
// Use a BehaviorSubject to emit to the tristate checkbox
this.filteredDataObservable.next(res);
this.filteredData = res;
this.changeRef.markForCheck();
console.log("Got data.. " + this.filteredData.length);
//this.zone = new NgZone({enableLongStackTrace: false});
//this.zone.run(() => {
// console.log('Received table data');
//});
});
}
ngOnDestroy() {
this._subscription.unsubscribe();
}
}
import { Component,Input, Injectable, ApplicationRef, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ApiService } from './services/api.service';
import { Observable, of } from 'rxjs';
import {Pipe, PipeTransform} from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
templateUrl: 'templates/route4.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class Route4Component implements OnInit {
public hasChanges: bool = true;
constructor(private changeRef: ChangeDetectorRef, private appRef: ApplicationRef, private apiService: ApiService) {
}
canDeactivate() {
console.log("Detecting changes. Has Changes: " + this.hasChanges);
return of(!this.hasChanges);
}
makeCall() {
this.apiService
.getUrl("index.html")
.subscribe();
}
ngOnInit() {
}
}
import { Component, Input, Output, OnInit, ViewChild, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef, Renderer, ElementRef, forwardRef } from '@angular/core';
import { Pipe, PipeTransform } from '@angular/core';
import { Observable, Subscription, fromEvent } from 'rxjs';
import { debounceTime, distinctUntilChanged, throttleTime, } from 'rxjs/operators';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { CustomTableOptions, CustomTableConfig, CustomTableColumnDefinition } from './customTable.component';
@Pipe({
name: 'customFilter'
})
export class CustomFilterPipe implements PipeTransform {
getCellValue(row: any, column: CustomTableColumnDefinition): string {
if (column.isComputed) {
let evalfunc = new Function('r', 'return ' + column.binding);
let evalresult: string = evalfunc(row);
return evalresult;
} else {
return column.binding.split('.').reduce((prev: any, curr: string) => prev[curr], row);
}
}
transform(items: any, columns: any, filterText: string, isAnd: Boolean): any {
if (columns && Array.isArray(items)) {
if (isAnd) {
return items.filter(item =>
columns.reduce((acc, column) => {
var evalResult: string = this.getCellValue(item, column);
var isMatch = new RegExp(filterText, 'gi').test(evalResult) || filterText === "";
return acc && isMatch;
}, true));
} else {
return items.filter(item => {
return columns.some((column) => {
var evalResult: string = this.getCellValue(item, column);
var isMatch = new RegExp(filterText, 'gi').test(evalResult) || filterText === "";
return isMatch;
});
});
}
} else {
return items;
}
}
}
@Component({
selector: 'filter',
templateUrl: 'templates/filter.html',
//pipes: [CustomFilterPipe]
})
export class Filter implements OnInit, ControlValueAccessor {
writeValue(obj: any): void {
throw new Error("Method not implemented.");
}
registerOnChange(fn: any): void {
throw new Error("Method not implemented.");
}
registerOnTouched(fn: any): void {
throw new Error("Method not implemented.");
}
setDisabledState(isDisabled: boolean): void {
throw new Error("Method not implemented.");
}
public filterText: string;
public filterPlaceholder: string;
public filterPipe: CustomFilterPipe = new CustomFilterPipe();
public filterInput = new FormControl();
private subscription: Subscription;
public filteredData: Array<any>;
@Input() public options: CustomTableOptions;
@Output() filterChange: EventEmitter<any> = new EventEmitter<any>();
constructor(private _elRef: ElementRef, private _renderer: Renderer,
private _changeDetectorRef: ChangeDetectorRef) {
}
ngOnInit() {
this.subscription = this.options.records.subscribe(res => {
this.filteredData = res;
});
this.filterText = "";
this.filterPlaceholder = "Filter..";
this.filterInput
.valueChanges
.pipe(debounceTime(400))
.pipe(distinctUntilChanged())
.subscribe(term => {
this.filterText = term;
//var newObj = this.options.columns.reduce(function(obj, column) {
// obj[column.value] = column;
// //obj[column.value + '.filterText'] = this.filterText;
// return obj;
//}, {});
var arr = this.filterPipe.transform(this.filteredData, this.options.columns, this.filterText, false);
this.filterChange.emit({ filterData: arr, filterText: this.filterText });
});
}
}
import {Component,Input,Output,OnInit,ViewChild,EventEmitter,ChangeDetectionStrategy, ChangeDetectorRef, Renderer, ElementRef, forwardRef} from '@angular/core';
import { Observable, Subscription, fromEvent } from 'rxjs';
import { debounceTime, throttleTime } from 'rxjs/operators';
import { DataService } from './services/data.service';
import { CustomTableOptions } from "./customTable.component";
@Component({
selector: 'pager',
templateUrl: 'templates/pager.html'
})
export class Pager implements OnInit {
public firstText: string = "«";
public lastText: string = "»";
public previousText: string = "‹";
public nextText: string = "›";
public boundaryLinks:boolean = true;
public directionLinks:boolean = true;
public rotate:boolean = false;
public adjacents:number = 2;
public pages: Array<any>;
@Input() public options: CustomTableOptions;
@Output() pageChange: EventEmitter<any> = new EventEmitter<any>();
constructor(private _elRef: ElementRef, private _renderer: Renderer,
private changeRef: ChangeDetectorRef) {
}
calculateTotalPages() {
var totalPages = this.options.config.pageSize < 1 ? 1 : Math.ceil(this.options.config.totalCount / this.options.config.pageSize);
this.options.config.totalPages = Math.max(totalPages || 0, 1);
return this.options.config.totalPages;
}
selectPage(page:number) {
if (this.options.config.pageNumber !== page && page > 0 && page <= this.options.config.totalPages) {
this.options.config.pageNumber = page;
this.pages = this.getPages(this.options.config.pageNumber, this.options.config.totalPages);
this.pageChange.emit();
}
}
getText(key:string) : string {
return this[key + 'Text'] || this[key + 'Text'];
}
noPrevious() : boolean {
return this.options.config.pageNumber === 1;
}
noNext() : boolean {
return this.options.config.pageNumber === this.options.config.totalPages;
}
// Create page object used in template
makePage(number: number, text:string, isActive:boolean) : any {
return {
number: number,
text: text,
active: isActive
};
}
getPages(currentPage, totalPages) {
var pages = [];
// Default page limits
var startPage: number = 1, endPage: number = totalPages;
var isMaxSized: boolean = this.options.config.maxSize < totalPages;
var calcedMaxSize:number = isMaxSized ? this.options.config.maxSize : 0;
// If we want to limit the maxSize within the constraint of the adjacents, we can do so like this.
// This adjusts the maxSize based on current page and current page and whether the front-end adjacents are added.
if (isMaxSized && !this.rotate && this.adjacents > 0 && currentPage >= (calcedMaxSize - 1) && totalPages >= (calcedMaxSize + (this.adjacents * 2))) {
calcedMaxSize = this.options.config.maxSize - this.adjacents;
}
// Adjust max size if we are going to add the adjacents
if (isMaxSized && !this.rotate && this.adjacents > 0) {
var tempStartPage = ((Math.ceil(currentPage / calcedMaxSize) - 1) * calcedMaxSize) + 1;
var tempEndPage = Math.min(tempStartPage + calcedMaxSize - 1, totalPages);
if (tempEndPage < totalPages) {
if (totalPages - this.adjacents > currentPage) { // && currentPage > adjacents) {
calcedMaxSize = calcedMaxSize - this.adjacents;
}
}
}
// recompute if maxSize
if (isMaxSized) {
if (this.rotate) {
// Current page is displayed in the middle of the visible ones
startPage = Math.max(currentPage - Math.floor(calcedMaxSize / 2), 1);
endPage = startPage + calcedMaxSize - 1;
// Adjust if limit is exceeded
if (endPage > totalPages) {
endPage = totalPages;
startPage = endPage - calcedMaxSize + 1;
}
} else {
// Visible pages are paginated with maxSize
startPage = ((Math.ceil(currentPage / calcedMaxSize) - 1) * calcedMaxSize) + 1;
// Adjust last page if limit is exceeded
endPage = Math.min(startPage + calcedMaxSize - 1, totalPages);
}
}
// Add page number links
for (var num = startPage; num <= endPage; num++) {
var page = this.makePage(num, num, num === currentPage);
pages.push(page);
}
// Add links to move between page sets
if (isMaxSized && !this.rotate) {
if (startPage > 1) {
var previousPageSet = this.makePage(startPage - 1, '...', false);
pages.unshift(previousPageSet);
if (this.adjacents > 0) {
if (totalPages >= this.options.config.maxSize + (this.adjacents * 2)) {
pages.unshift(this.makePage(2, '2', false));
pages.unshift(this.makePage(1, '1', false));
}
}
}
if (endPage < totalPages) {
var nextPageSet = this.makePage(endPage + 1, '...', false);
var addedNextPageSet = false;
if (this.adjacents > 0) {
if (totalPages - this.adjacents > currentPage) { // && currentPage > adjacents) {
var removedLast = false;
addedNextPageSet = true;
if (pages && pages.length > 1 && pages[pages.length - 1].number == totalPages - 1) {
pages.splice(pages.length - 1, 1);
removedLast = true;
}
pages.push(nextPageSet);
if (removedLast || pages[pages.length - 1].number < totalPages - 2 || pages[pages.length - 2].number < totalPages - 2) {
pages.push(this.makePage(totalPages - 1, (totalPages - 1).toString(), false));
}
pages.push(this.makePage(totalPages, (totalPages).toString(), false));
}
}
if (!addedNextPageSet) {
pages.push(nextPageSet);
}
}
}
return pages;
}
ngOnInit() {
this.options.records.subscribe(res => {
this.pages = this.getPages(this.options.config.pageNumber, this.calculateTotalPages());
this.changeRef.markForCheck();
});
}
}
import { Injectable, EventEmitter} from '@angular/core';
import { Observable, Subject, Subscription, Subscriber } from 'rxjs';
@Injectable()
export class CustomTableEmitter {
private events = new Subject();
subscribe(next, error?, complete?): Subscription {
return this.events.subscribe(next, error, complete);
}
next(event) { this.events.next(event); }
}
/* Master Styles */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
h2,
h3 {
color: #444;
font-family: Arial, Helvetica, sans-serif;
font-weight: lighter;
}
body {
margin: 2em;
}
body,
input[text],
button {
color: #888;
font-family: Cambria, Georgia;
}
a {
cursor: pointer;
cursor: hand;
}
button {
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
cursor: hand;
}
.has-error button {
border-color: #d9534f;
}
.has-error small {
color: #d9534f !important;
padding-top:10px;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled {
background-color: #eee;
color: #aaa;
cursor: auto;
}
/* Navigation link styles
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited,
a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}
*/
/* items class */
.items {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 24em;
}
.items li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.items li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.items li.selected:hover {
background-color: #BBD8DC;
color: white;
}
.items .text {
position: relative;
top: -3px;
}
.items {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 24em;
}
.items li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.items li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.items li.selected {
background-color: #CFD8DC;
color: white;
}
.items li.selected:hover {
background-color: #BBD8DC;
}
.items .text {
position: relative;
top: -3px;
}
.items .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607D8B;
line-height: 1em;
position: relative;
left: -1px;
top: -4px;
height: 1.8em;
margin-right: .8em;
border-radius: 4px 0 0 4px;
}
/* everywhere else */
* {
font-family: Arial, Helvetica, sans-serif;
}
multiselect {
display: block;
}
multiselect > .btn-group {
min-width: 180px;
}
multiselect .dropdown-toggle:after {
content: none;
}
multiselect .btn {
width: 100%;
background-color: #FFF;
}
multiselect .btn.has-error {
border: 1px solid #a94442 !important;
color: #db524b;
}
multiselect .dropdown-menu {
max-height: 300px;
min-width: 200px;
overflow-y: auto;
}
multiselect .dropdown-menu .filter > input {
width: 99%;
}
multiselect .dropdown-menu .filter .clear-filter {
cursor: pointer;
pointer-events: all;
position: absolute;
top: 0;
right: 0;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
}
multiselect .dropdown-menu {
/* width: 100%; */
box-sizing: border-box;
padding: 2px;
}
multiselect > .btn-group > button {
padding-right: 20px;
}
multiselect > .btn-group > button > .pull-left {
color: black;
}
multiselect > .btn-group > button:hover > .pull-left {
color: white;
}
multiselect > .btn-group > button > .caret {
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 4px solid black;
right: 5px;
top: 45%;
position: absolute;
}
multiselect .dropdown-menu > li > a {
padding: 3px 10px;
cursor: pointer;
}
multiselect .dropdown-menu > li > a i {
margin-right: 4px;
}
.glyphicon-none:before {
content: "\e013";
color: transparent !important;
}
body, .container-fluid, .flex-layout
{
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-orient: vertical;
-moz-box-orient: vertical;
-webkit-box-direction: normal;
-moz-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.flex-scroll-content {
overflow-y: auto;
/*for IE10*/
-ms-flex-shrink: 1;
flex-shrink: 1;
min-height: 85px;
-moz-box-flex: 2;
-moz-box-flex: 2;
-webkit-box-flex: 2;
-ms-flex: 2;
flex: 2;
margin-bottom:10px;
/*border: solid 1px;*/
/*padding:5px;*/
}
/* TABLE STYLING */
.custom-table {
margin: 0 0 25px;
background-color: #f9f9f9;
border: 1px solid #D7D7D7;
width: 100%;
}
.custom-table.sticky-header {
margin: 0;
}
.custom-table th {
background-color: #F7F7F7;
border-bottom: 1px solid #D7D7D7;
border-left: 1px solid #D7D7D7;
color: #5C5C5C;
font-size: 13px;
height: 40px;
line-height: 40px;
text-align: left;
white-space: nowrap;
}
.custom-table .header-check {
padding-left: 17px;
padding-top: 4px;
min-width: 50px;
}
.custom-table .toggle-all {
width: 15px;
}
.custom-table .th-checkbox, .custom-table .td-checkbox {
width: 20px;
}
.custom-table .btn-default {
border: none;
}
.custom-table > tbody > tr:nth-child(odd) {
background: none;
}
.custom-table > tbody > tr:nth-child(even) {
background-color: #F7F7F7;
}
.custom-table > tbody > tr:hover {
background-color: #f5f5f5;
}
.custom-table tbody td, table.no-border tbody td {
height: 50px;
font-size: 11px;
}
.custom-table tbody td .center, table.no-border tbody td .center {
text-align: center;
}
.custom-table tbody .td-checkbox {
padding: 0;
}
.custom-table tbody .td-checkbox input {
margin-left: 3px;
width: 15px;
}
.custom-table thead th span {
padding-right: 20px;
}
.custom-table tbody td {
border-right: 1px solid #d7d7d7;
padding: 0 4px 0 7px;
}
.custom-table {
background-color: white;
}
.custom-table thead th {
padding-left: 7px;
}
.custom-table thead th:first-child {
padding: 2px 2px 0 3px;
}
.footer .custom-table {
margin-bottom: 5px;
}
table thead .sorting,
table thead .sorting_asc,
table thead .sorting_desc,
table thead .sorting_asc_disabled,
table thead .sorting_desc_disabled {
background-repeat: no-repeat;
background-position: center right;
}
table thead .sorting {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAYAAAByUDbMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC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GFuY2VJRD0ieG1wLmlpZDo4MkFEQzYxOTIyQzExMUUxQTFGMUFEQUQ1QjJBNTM4QyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IE1hY2ludG9zaCI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjAyODAxMTc0MDcyMDY4MTFCMzgyRjZDNUZFRjBFMkM0IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjAxODAxMTc0MDcyMDY4MTFCMzgyRjZDNUZFRjBFMkM0Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+1fsfwAAAAJdJREFUeNpi/P//PwO1ABMDFcGoYaOG0cMwFmyC1Y33IoHUAiD+h8MBGa31SvOJddk6IN4PxBxY8FEgXkO0N4G2/gRSLUD8GU3qPRA3A+U/kxpmIBege2U9EB/ApYERX6kBDDtlILUDiFWA+AkQuwNddY2s2ARqvAukJgDxbyCehM8gnLGJBmYDsSoQTyWkkHHQFo4AAQYAAA0piq4hbqwAAAAASUVORK5CYII=);
cursor: pointer;
}
table thead .sorting_asc_disabled {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAYAAAByUDbMAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+b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c3RhbmNlSUQ9InhtcC5paWQ6NDNGQ0VGRjQyMkMxMTFFMUExRjFBREFENUIyQTUzOEMiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDNGQ0VGRjUyMkMxMTFFMUExRjFBREFENUIyQTUzOEMiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDoxNEMwMzk2QjIyQzExMUUxQTFGMUFEQUQ1QjJBNTM4QyIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDoxNEMwMzk2QzIyQzExMUUxQTFGMUFEQUQ1QjJBNTM4QyIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pnt2WfgAAACJSURBVHjaYvz//z8DtQATAxXBqGGjhtHDMBZsgnfv3o0EUguA+B8OB2QoKyvPJ9Zl64B4PxBzYMFHgXgNKd78CcQtQPwZTfw9EDdjEScYZiAXoHtlPRAfICcCQMXJJCC+A+U/AeJeqDhZsXkXiCcA8W+owddIjk00MBuIVYF4KiGFjIO2cAQIMAAzGSDTlIC38gAAAABJRU5ErkJggg==);
}
td.is-negative {
color: #FFFFFF;
background-color: #B1504A !important;
}
.is-error,
.is-error-add.is-error-add-active {
color: #FFFFFF;
background-color: #a94442;
}
.is-error a, .is-error-add.is-error-add-active a {
color: #FFFFFF;
}
.is-error-remove.is-error-remove-active {
background-color: #FFFFFF !important;
}
.is-error-add, .is-error-remove {
-webkit-transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-moz-transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-o-transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.table-striped > tbody > tr.is-error:nth-of-type(odd),
.table-striped > tbody > tr.is-error-add.is-error-add-active:nth-of-type(odd) {
color: #FFFFFF;
background-color: #a94442;
}
.table-striped > tbody > tr.is-error:nth-of-type(even),
.table-striped > tbody > tr.is-error-add.is-error-add-active:nth-of-type(even) {
color: #FFFFFF;
background-color: #b15654;
}
.table-striped.table-bordered > tbody > tr.is-error:nth-of-type(odd) td {
border-bottom: 1px solid #dc7675;
}
.table-striped.table-bordered > tbody > tr.is-error:nth-of-type(even) td {
border-bottom: 1px solid #dc7675;
}
.table-hover > tbody > tr.is-error:hover {
background-color: #dc7675;
}
.is-summary,
.is-summary-add.is-summary-add-active {
color: black;
background-color: #bfccdd;
}
.is-summary a, .is-summary-add.is-summary-add-active a {
color: black;
}
.is-summary-remove.is-summary-remove-active {
background-color: #FFFFFF !important;
}
.is-summary-add, .is-summary-remove {
-webkit-transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-moz-transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-o-transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.table-striped > tbody > tr.is-summary:nth-of-type(odd),
.table-striped > tbody > tr.is-summary-add.is-summary-add-active:nth-of-type(odd) {
color: black;
background-color: #a7b4c5;
}
.table-striped > tbody > tr.is-summary:nth-of-type(even),
.table-striped > tbody > tr.is-summary-add.is-summary-add-active:nth-of-type(even) {
color: black;
background-color: #bfccdd;
}
.table-striped.table-bordered > tbody > tr.is-summary:nth-of-type(odd) td {
border-bottom: 1px solid #99a4b2;
}
.table-striped.table-bordered > tbody > tr.is-summary:nth-of-type(even) td {
border-bottom: 1px solid #99a4b2;
}
.table-hover > tbody > tr.is-summary:hover {
background-color: #99a4b2;
}
<!DOCTYPE html>
<html>
<head>
<title>Angular Demo</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="styles.css" />
<!-- 1. Load libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="spin.js"></script>
<script src="jquery.spin.js"></script>
<!-- Polyfill(s) for older browsers -->
<script src="https://unpkg.com/core-js/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.8.26/dist/zone.js?main=browser"></script>
<script src="https://unpkg.com/reflect-metadata@0.1.12"></script>
<script src="https://unpkg.com/systemjs@0.19.47/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
### This is a demo plunker for various Angular components
This demo plnkr demonstrates many Angular concepts. Thse include a Custom Table, a Tri-state Checkbbox, a Multiselect Dropdown with Form intregration, and a Menu plus NavigationService with a DialogService. Visit [https://long2know.com](https://long2know.com) for more demos and discussion..
(function (global) {
var angularVersion = '@7.1.4';
System.config({
// DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
transpiler: 'ts',
typescriptOptions: {
// Copy of compiler options in standard tsconfig.json
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
},
meta: {
'typescript': {
"exports": "ts"
}
},
paths: {
// paths serve as alias
'npm:': 'https://unpkg.com/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
service: 'serivce',
// angular bundles
'@angular/core': 'npm:@angular/core' + angularVersion + '/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common' + angularVersion + '/bundles/common.umd.js',
'@angular/common/http': 'npm:@angular/common' + angularVersion + '/bundles/common-http.umd.js',
'@angular/compiler': 'npm:@angular/compiler' + angularVersion + '/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser-animations.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + angularVersion + '/bundles/platform-browser-dynamic.umd.js',
'@angular/platform-webworker': 'npm:@angular/platform-webworker' + angularVersion + '/bundles/platform-webworker.umd.js',
'@angular/platform-webworker-dynamic': 'npm:@angular/platform-webworker-dynamic' + angularVersion + '/bundles/platform-webworker-dynamic.umd.js',
'@angular/http': 'npm:@angular/http' + angularVersion + '/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router' + angularVersion + '/bundles/router.umd.js',
'@angular/router/upgrade': 'npm:@angular/router' + angularVersion + '/bundles/router-upgrade.umd.js',
'@angular/forms': 'npm:@angular/forms' + angularVersion + '/bundles/forms.umd.js',
'@angular/upgrade': 'npm:@angular/upgrade' + angularVersion + '/bundles/upgrade.umd.js',
'@angular/upgrade/static': 'npm:@angular/upgrade' + angularVersion + '/bundles/upgrade-static.umd.js',
'@angular/animations': 'npm:@angular/animations' + angularVersion + '/bundles/animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations' + angularVersion + '/bundles/animations-browser.umd.js',
// other libraries
'rxjs': 'npm:rxjs@6.3.3',
'rxjs-compat': 'npm:rxjs-compat@6.3.3',
'ts': 'npm:plugin-typescript@8.0.0/lib/plugin.js',
'tslib': 'npm:tslib@1.9.3',
'typescript': 'npm:typescript@3.2.2/lib/typescript.js',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api@0.8.0/bundles/in-memory-web-api.umd.js',
'@ng-bootstrap/ng-bootstrap': 'npm:@ng-bootstrap/ng-bootstrap@4.0.1/bundles/ng-bootstrap.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts',
meta: {
'./*.ts': {
loader: 'systemjs-angular-loader.js'
}
}
},
service: {
defaultExtension: 'ts'
},
'rxjs': {main: 'index.js', defaultExtension: 'js' },
'rxjs/ajax': {main: 'index.js', defaultExtension: 'js' },
'rxjs/operators': {main: 'index.js', defaultExtension: 'js' },
'rxjs/testing': {main: 'index.js', defaultExtension: 'js' },
'rxjs/webSocket': {main: 'index.js', defaultExtension: 'js' }
}
});
})(this);
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"types": []
},
"exclude": [
"node_modules/*",
"**/*-aot.ts"
]
}
<div class="container-fluid" style="padding:0; margin: 0;">
<nav class="navbar navbar-expand-lg navbar-light bg-light rounded navbar-toggleable">
<a class="navbar-brand" href="#">Navbar</a>
<button (click)="toggleMenu()" class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#containerNavbar" aria-controls="containerNavbar"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" [ngClass]="{'show': isMenuExpanded}" id="containerNavbar">
<ul class="navbar-nav mr-auto">
<li class="nav-item"><a class="nav-link" [routerLink]="['/']" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}">Custom Table</a></li>
<li class="nav-item"><a class="nav-link" [routerLink]="['route2']" [routerLinkActive]="['active']">Tristate Checkbox</a></li>
<li class="nav-item"><a class="nav-link" [routerLink]="['route3']" [routerLinkActive]="['active']">Multiselect Dropdown</a></li>
<li class="nav-item"><a class="nav-link" [routerLink]="['route4']" [routerLinkActive]="['active']">Loading Indicator</a></li>
</ul>
</div>
</nav>
<template ngbModalContainer>
</template>
</div>
<br />
<hr>
<p>
This demo plnkr demonstrates many Angular concepts. Thse include a <strong>Custom Table</strong>, a <strong>Tri-state Checkbbox</strong>, a <strong>Multiselect Dropdown with Form intregration</strong> and a <strong>Menu plus NavigationService with a DialogService</strong>. Visit <a href="https://long2know.com/" target="_blank">https://long2know.com</a> for more demos and discussion..
</p>
<hr>
<router-outlet></router-outlet>
<!--<ng2-toasty></ng2-toasty>-->
<div class="container-fluid">
<div class="row">
<strong class="float-left">Custom Table</strong>
<label class="float-right">
<input type="checkbox" name="hasChanges" [(ngModel)]="hasChanges"> Has Changes
</label>
</div>
<hr>
<div class="row">
<filter [options]="filterOptions" (filterChange)="filterChange($event)"></filter>
</div>
<div class="row">
<custom-table [options]="tableOptions" (sortChange)="sortChange($event)">Custom table here</custom-table>
</div>
<div class="row">
<pager [options]="tableOptions" (pageChange)="pageChange($event)"></pager>
</div>
</div>
<div class="container-fluid">
<div class="row">
<strong class="float-left">Tristate Checkbox</strong>
<label class="float-right">
<input type="checkbox" name="hasChanges" [(ngModel)]="hasChanges">
Has Changes
</label>
</div>
<hr>
<table>
<thead>
<tr>
<th class="header-check">
<tri-state-checkbox class="toggle-all" [items]="items"></tri-state-checkbox>
</th>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of _items">
<td class="td-checkbox"><input type="checkbox" name="ch" [(ngModel)]="item.isSelected"></td>
<td class="td-checkbox" [innerHtml]="item.id"></td>
<td class="td-checkbox" [innerHtml]="item.label"></td>
</tr>
</tbody>
</table>
<hr>
<!-- <button type="button" class="btn btn-default" (click)="makeCall()">Make API Call</button> -->
<button type="button" class="btn btn-default" (click)="checkAll()">Check All</button>
<button type="button" class="btn btn-default" (click)="uncheckAll()">Clear All</button>
</div>
<form class="container-fluid">
<div class="row">
<strong class="float-left">Multiselect Dropdown</strong>
<label class="float-right">
<input type="checkbox" name="hasChanges" [(ngModel)]="hasChanges">
Has Changes
</label>
</div>
<hr>
<hr>
<div class="form-group" [ngClass]="{'has-error':!itemsFormElement.valid}">
<multiselect id="items" name="items" #itemsFormElement="ngModel" class="pull-left" [items]="items" [(ngModel)]="_selectedItems" (ngModelChange)="onChange($event)" required></multiselect>
<small [hidden]="itemsFormElement.valid" class="form-text text-muted danger">You must select an item.</small>
</div>
<ul class="pull-right">
<li *ngFor="let item of _selectedItems">{{ item.label }}</li>
</ul>
</form>
<div class="container-fluid">
<hr>
<p>
<strong>Loading Indicator</strong>
</p>
<hr>
<label>
<input type="checkbox" name="hasChanges" [(ngModel)]="hasChanges">
Has Changes
</label>
<hr>
<button type="button" class="btn btn-primary" (click)="makeCall()">Make API Call</button>
</div>
<div class="form-group">
<input class="form-control" type="text" [value]="filterText" [placeholder]="filterPlaceholder"
[formControl]="filterInput" />
</div>
<div>
<ul class="pagination">
<li *ngIf="boundaryLinks" class="page-item" [ngClass]="{'disabled': noPrevious()}"><a class="page-link" (click)="selectPage(1)">{{getText('first')}}</a></li>
<li *ngIf="directionLinks" class="page-item" [ngClass]="{'disabled': noPrevious()}"><a class="page-link" (click)="selectPage(options.config.pageNumber - 1)">{{getText('previous')}}</a></li>
<li *ngFor="let page of pages" class="page-item" [ngClass]="{'active': page.active}"><a class="page-link" (click)="selectPage(page.number)">{{page.text}}</a></li>
<li *ngIf="directionLinks" class="page-item" [ngClass]="{'disabled': noNext()}"><a class="page-link" (click)="selectPage(options.config.pageNumber + 1)">{{getText('next')}}</a></li>
<li *ngIf="boundaryLinks" class="page-item" [ngClass]="{'disabled': noNext()}"><a class="page-link" (click)="selectPage(options.config.totalPages)">{{getText('last')}}</a></li>
</ul>
</div>
<table class="table-striped table-hover custom-table">
<thead>
<tr>
<th class="th-checkbox" *ngIf="options.config.showSelectAll">
<tri-state-checkbox class="toggle-all" [items]="filteredDataObservable"></tri-state-checkbox>
</th>
<th *ngFor="let column of options.columns" (click)="sortHeaderClick(column.value)" [ngClass]="{ 'sorting': isSorting(column.value), 'sorting_asc': isSortAsc(column.value), 'sorting_desc': isSortDesc(column.value) }">
<span [innerHTML]="column.name"></span>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of filteredData">
<td class="td-checkbox" *ngIf="options.config.showSelectCheckbox">
<input type="checkbox" [(ngModel)]="row.isSelected">
</td>
<td *ngFor="let column of options.columns">
<a *ngIf="column.isAnchor" [routerLink]="getRouterLink(row, column)" [innerHTML]="getCellValue(row, column)"></a>
<span *ngIf="!column.isDisabledCheckbox && !column.isCheckbox && !column.isAnchor" [innerHTML]="getCellValue(row, column)"></span>
<input type="checkbox" *ngIf="column.isDisabledCheckbox || column.isCheckbox" [checked]="getCellValue(row, column)"
[disabled]="column.isDisabledCheckbox" (click)="setCellValue(row, column, !getCellValue(row, column), $event)">
</td>
</tr>
</tbody>
</table>
<div class="btn-group">
<button type="button" class="btn btn-secondary dropdown-toggle" (click)="toggleSelect()">
<span class="pull-left" [innerHtml]="localHeader"></span>
<span class="caret pull-right"></span>
</button>
<ul class="dropdown-menu multi-select-popup" [ngStyle]="{display:isOpen ? 'block' : 'none'}" style="display:block;">
<li *ngIf="enableFilter" class="filter-container">
<div class="form-group has-feedback filter">
<input class="form-control" type="text" [value]="filterText" [placeholder]="filterPlaceholder" [formControl]="filterInput" />
<span class="clear-filter fa fa-times-circle-o form-control-feedback" (click)="clearFilter()"></span>
</div>
</li>
<li *ngFor="let item of _items | filter:{label:filterText}">
<a (click)="select(item)" class="dropdown-item">
<i class="fa fa-fw" [ngClass]="{'fa-check': item.checked, 'glyphicon-none': !item.checked}"></i>
<span [innerHtml]="item.label"></span>
</a>
</li>
</ul>
</div>
/**
* @fileOverview Generates "Lorem ipsum" style text.
* @author rviscomi@gmail.com Rick Viscomi,
* tinsley@tinsology.net Mathew Tinsley
* @version 1.0
*/
/**
* Copyright (c) 2009, Mathew Tinsley (tinsley@tinsology.net)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the organization nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY MATHEW TINSLEY ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @class Jibborish generator.
*/
var LoremIpsum = function () {
};
/**
* Average number of words per sentence.
* @constant {number}
*/
LoremIpsum.WORDS_PER_SENTENCE_AVG = 24.460;
/**
* Standard deviation of the number of words per sentence.
* @constant {number}
*/
LoremIpsum.WORDS_PER_SENTENCE_STD = 5.080;
/**
* List of possible words.
* @constant {Array.string}
*/
LoremIpsum.WORDS = [
'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur',
'adipiscing', 'elit', 'curabitur', 'vel', 'hendrerit', 'libero',
'eleifend', 'blandit', 'nunc', 'ornare', 'odio', 'ut',
'orci', 'gravida', 'imperdiet', 'nullam', 'purus', 'lacinia',
'a', 'pretium', 'quis', 'congue', 'praesent', 'sagittis',
'laoreet', 'auctor', 'mauris', 'non', 'velit', 'eros',
'dictum', 'proin', 'accumsan', 'sapien', 'nec', 'massa',
'volutpat', 'venenatis', 'sed', 'eu', 'molestie', 'lacus',
'quisque', 'porttitor', 'ligula', 'dui', 'mollis', 'tempus',
'at', 'magna', 'vestibulum', 'turpis', 'ac', 'diam',
'tincidunt', 'id', 'condimentum', 'enim', 'sodales', 'in',
'hac', 'habitasse', 'platea', 'dictumst', 'aenean', 'neque',
'fusce', 'augue', 'leo', 'eget', 'semper', 'mattis',
'tortor', 'scelerisque', 'nulla', 'interdum', 'tellus', 'malesuada',
'rhoncus', 'porta', 'sem', 'aliquet', 'et', 'nam',
'suspendisse', 'potenti', 'vivamus', 'luctus', 'fringilla', 'erat',
'donec', 'justo', 'vehicula', 'ultricies', 'varius', 'ante',
'primis', 'faucibus', 'ultrices', 'posuere', 'cubilia', 'curae',
'etiam', 'cursus', 'aliquam', 'quam', 'dapibus', 'nisl',
'feugiat', 'egestas', 'class', 'aptent', 'taciti', 'sociosqu',
'ad', 'litora', 'torquent', 'per', 'conubia', 'nostra',
'inceptos', 'himenaeos', 'phasellus', 'nibh', 'pulvinar', 'vitae',
'urna', 'iaculis', 'lobortis', 'nisi', 'viverra', 'arcu',
'morbi', 'pellentesque', 'metus', 'commodo', 'ut', 'facilisis',
'felis', 'tristique', 'ullamcorper', 'placerat', 'aenean', 'convallis',
'sollicitudin', 'integer', 'rutrum', 'duis', 'est', 'etiam',
'bibendum', 'donec', 'pharetra', 'vulputate', 'maecenas', 'mi',
'fermentum', 'consequat', 'suscipit', 'aliquam', 'habitant', 'senectus',
'netus', 'fames', 'quisque', 'euismod', 'curabitur', 'lectus',
'elementum', 'tempor', 'risus', 'cras'
];
LoremIpsum.prototype.singleWord = function () {
var position = Math.floor(Math.random() * LoremIpsum.WORDS.length);
var word = LoremIpsum.WORDS[position];
return word.charAt(0).toUpperCase() + word.slice(1);
}
/**
* Generate "Lorem ipsum" style words.
* @param num_words {number} Number of words to generate.
* @return {string} "Lorem ipsum..."
*/
LoremIpsum.prototype.generate = function (num_words) {
var words, ii, position, word, current, sentences, sentence_length, sentence;
/**
* @default 100
*/
num_words = num_words || 100;
words = [LoremIpsum.WORDS[0], LoremIpsum.WORDS[1]];
num_words -= 2;
for (ii = 0; ii < num_words; ii++) {
position = Math.floor(Math.random() * LoremIpsum.WORDS.length);
word = LoremIpsum.WORDS[position];
if (ii > 0 && words[ii - 1] === word) {
ii -= 1;
} else {
words[ii] = word;
}
}
sentences = [];
current = 0;
while (num_words > 0) {
sentence_length = this.getRandomSentenceLength();
if (num_words - sentence_length < 4) {
sentence_length = num_words;
}
num_words -= sentence_length;
sentence = [];
for (ii = current; ii < (current + sentence_length); ii++) {
sentence.push(words[ii]);
}
sentence = this.punctuate(sentence);
current += sentence_length;
sentences.push(sentence.join(' '));
}
return sentences.join(' ');
};
/**
* Insert commas and periods in the given sentence.
* @param {Array.string} sentence List of words in the sentence.
* @return {Array.string} Sentence with punctuation added.
*/
LoremIpsum.prototype.punctuate = function (sentence) {
var word_length, num_commas, ii, position;
word_length = sentence.length;
/* End the sentence with a period. */
sentence[word_length - 1] += '.';
if (word_length < 4) {
return sentence;
}
num_commas = this.getRandomCommaCount(word_length);
for (ii = 0; ii <= num_commas; ii++) {
position = Math.round(ii * word_length / (num_commas + 1));
if (position < (word_length - 1) && position > 0) {
/* Add the comma. */
sentence[position] += ',';
}
}
/* Capitalize the first word in the sentence. */
sentence[0] = sentence[0].charAt(0).toUpperCase() + sentence[0].slice(1);
return sentence;
};
/**
* Produces a random number of commas.
* @param {number} word_length Number of words in the sentence.
* @return {number} Random number of commas
*/
LoremIpsum.prototype.getRandomCommaCount = function (word_length) {
var base, average, standard_deviation;
/* Arbitrary. */
base = 6;
average = Math.log(word_length) / Math.log(base);
standard_deviation = average / base;
return Math.round(this.gaussMS(average, standard_deviation));
};
/**
* Produces a random sentence length based on the average word length
* of an English sentence.
* @return {number} Random sentence length
*/
LoremIpsum.prototype.getRandomSentenceLength = function () {
return Math.round(
this.gaussMS(
LoremIpsum.WORDS_PER_SENTENCE_AVG,
LoremIpsum.WORDS_PER_SENTENCE_STD
)
);
};
/**
* Produces a random number.
* @return {number} Random number
*/
LoremIpsum.prototype.gauss = function () {
return (Math.random() * 2 - 1) +
(Math.random() * 2 - 1) +
(Math.random() * 2 - 1);
};
/**
* Produces a random number with Gaussian distribution.
* @param {number} mean
* @param {number} standard_deviation
* @return {number} Random number
*/
LoremIpsum.prototype.gaussMS = function (mean, standard_deviation) {
return Math.round(this.gauss() * standard_deviation + mean);
};
this.sharedData.tabSet.select(id);
console.log(this.sharedData.tabSet);
Observable.create(observer => {
setTimeout(() => {
this.sharedData.tabSet.select(id)
observer.complete();
console.log("Observer complete");
}, 1);
})
.subscribe(
result => {
this.sharedData.tabSet.select(id);
console.log("subscription complete");
},
err => console.error(err),
() => {
this.sharedData.tabSet.select(id);
console.log(this.sharedData.tabSet.activeId);
console.log('done');
}
);
setTimeout(() => {
this._watch = Observable.from(this.ngbTabset.tabs);
this._watch.subscribe(
x => console.log('onNext: %s', x),
e => console.log('onError: %s', e),
() => {
var index = this.ngbTabset.tabs.length - 1;
var lastTab = this.ngbTabset.tabs.last;
console.log(this.ngbTabset.tabs);
console.log(index);
console.log(lastTab);
this.ngbTabset.select(lastTab.id);
console.log('onCompleted');
});
})
/**
* Copyright (c) 2011-2013 Felix Gnass
* Licensed under the MIT license
*/
/*
Basic Usage:
============
$('#el').spin(); // Creates a default Spinner using the text color of #el.
$('#el').spin({ ... }); // Creates a Spinner using the provided options.
$('#el').spin(false); // Stops and removes the spinner.
Using Presets:
==============
$('#el').spin('small'); // Creates a 'small' Spinner using the text color of #el.
$('#el').spin('large', '#fff'); // Creates a 'large' white Spinner.
Adding a custom preset:
=======================
$.fn.spin.presets.flower = {
lines: 9
length: 10
width: 20
radius: 0
}
$('#el').spin('flower', 'red');
*/
(function (factory) {
if (typeof exports == 'object') {
// CommonJS
factory(require('jquery'), require('spin'))
}
else if (typeof define == 'function' && define.amd) {
// AMD, register as anonymous module
define(['jquery', 'spin'], factory)
}
else {
// Browser globals
if (!window.Spinner) throw new Error('Spin.js not present')
factory(window.jQuery, window.Spinner)
}
}(function ($, Spinner) {
var modal_opts = {
lines: 11, // The number of lines to draw
length: 23, // The length of each line
width: 8, // The line thickness
radius: 40, // The radius of the inner circle
corners: 1, // Corner roundness (0..1)
rotate: 9, // The rotation offset
color: '#FFF', // #rgb or #rrggbb
speed: 1, // Rounds per second
trail: 50, // Afterglow percentage
shadow: true, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: 'auto', // Top position relative to parent in px
left: 'auto' // Left position relative to parent in px
};
$.fn.spin = function (opts, color, bgColor) {
if (opts == "modal") opts = modal_opts;
return this.each(function () {
var $this = $(this),
data = $this.data();
if (data.spinner) {
data.spinner.stop();
delete data.spinner;
if (opts == modal_opts) {
$("#spin_modal_overlay").remove();
return;
}
}
if (opts !== false) {
var spinElem = this;
if (opts == modal_opts) {
var backgroundColor = 'background-color:' + (bgColor ? bgColor : 'rgba(0, 0, 0, 0.6)');
$('body').append('<div id="spin_modal_overlay" style=\"' + backgroundColor + ';width:100%; height:100%; position:fixed; top:0px; left:0px; z-index:' + (opts.zIndex - 1) + '"/>');
spinElem = $("#spin_modal_overlay")[0];
}
opts = $.extend({}, $.fn.spin.presets[opts] || opts, { color: color || $this.css('color') });
data.spinner = new Spinner(opts).spin(spinElem);
}
})
}
$.fn.spin.presets = {
tiny: { lines: 8, length: 2, width: 2, radius: 3 },
small: { lines: 8, length: 4, width: 3, radius: 5 },
large: { lines: 10, length: 8, width: 4, radius: 8 }
}
}));
/**
* Copyright (c) 2011-2013 Felix Gnass
* Licensed under the MIT license
*/
(function (root, factory) {
/* CommonJS */
if (typeof exports == 'object') module.exports = factory()
/* AMD module */
else if (typeof define == 'function' && define.amd) define(factory)
/* Browser global */
else root.Spinner = factory()
}
(this, function () {
"use strict";
var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */
, animations = {} /* Animation rules keyed by their name */
, useCssAnimations /* Whether to use CSS animations or setTimeout */
/**
* Utility function to create elements. If no tag name is given,
* a DIV is created. Optionally properties can be passed.
*/
function createEl(tag, prop) {
var el = document.createElement(tag || 'div')
, n
for (n in prop) el[n] = prop[n]
return el
}
/**
* Appends children and returns the parent.
*/
function ins(parent /* child1, child2, ...*/) {
for (var i = 1, n = arguments.length; i < n; i++)
parent.appendChild(arguments[i])
return parent
}
/**
* Insert a new stylesheet to hold the @keyframe or VML rules.
*/
var sheet = (function () {
var el = createEl('style', { type: 'text/css' })
ins(document.getElementsByTagName('head')[0], el)
return el.sheet || el.styleSheet
}())
/**
* Creates an opacity keyframe animation rule and returns its name.
* Since most mobile Webkits have timing issues with animation-delay,
* we create separate rules for each line/segment.
*/
function addAnimation(alpha, trail, i, lines) {
var name = ['opacity', trail, ~~(alpha * 100), i, lines].join('-')
, start = 0.01 + i / lines * 100
, z = Math.max(1 - (1 - alpha) / trail * (100 - start), alpha)
, prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase()
, pre = prefix && '-' + prefix + '-' || ''
if (!animations[name]) {
sheet.insertRule(
'@' + pre + 'keyframes ' + name + '{' +
'0%{opacity:' + z + '}' +
start + '%{opacity:' + alpha + '}' +
(start + 0.01) + '%{opacity:1}' +
(start + trail) % 100 + '%{opacity:' + alpha + '}' +
'100%{opacity:' + z + '}' +
'}', sheet.cssRules.length)
animations[name] = 1
}
return name
}
/**
* Tries various vendor prefixes and returns the first supported property.
*/
function vendor(el, prop) {
var s = el.style
, pp
, i
prop = prop.charAt(0).toUpperCase() + prop.slice(1)
for (i = 0; i < prefixes.length; i++) {
pp = prefixes[i] + prop
if (s[pp] !== undefined) return pp
}
if (s[prop] !== undefined) return prop
}
/**
* Sets multiple style properties at once.
*/
function css(el, prop) {
for (var n in prop)
el.style[vendor(el, n) || n] = prop[n]
return el
}
/**
* Fills in default values.
*/
function merge(obj) {
for (var i = 1; i < arguments.length; i++) {
var def = arguments[i]
for (var n in def)
if (obj[n] === undefined) obj[n] = def[n]
}
return obj
}
/**
* Returns the absolute page-offset of the given element.
*/
function pos(el) {
var o = { x: el.offsetLeft, y: el.offsetTop }
while ((el = el.offsetParent))
o.x += el.offsetLeft, o.y += el.offsetTop
return o
}
/**
* Returns the line color from the given string or array.
*/
function getColor(color, idx) {
return typeof color == 'string' ? color : color[idx % color.length]
}
// Built-in defaults
var defaults = {
lines: 12, // The number of lines to draw
length: 7, // The length of each line
width: 5, // The line thickness
radius: 10, // The radius of the inner circle
rotate: 0, // Rotation offset
corners: 1, // Roundness (0..1)
color: '#000', // #rgb or #rrggbb
direction: 1, // 1: clockwise, -1: counterclockwise
speed: 1, // Rounds per second
trail: 100, // Afterglow percentage
opacity: 1 / 4, // Opacity of the lines
fps: 20, // Frames per second when using setTimeout()
zIndex: 2e9, // Use a high z-index by default
className: 'spinner', // CSS class to assign to the element
top: 'auto', // center vertically
left: 'auto', // center horizontally
position: 'relative' // element position
}
/** The constructor */
function Spinner(o) {
if (typeof this == 'undefined') return new Spinner(o)
this.opts = merge(o || {}, Spinner.defaults, defaults)
}
// Global defaults that override the built-ins:
Spinner.defaults = {}
merge(Spinner.prototype, {
/**
* Adds the spinner to the given target element. If this instance is already
* spinning, it is automatically removed from its previous target b calling
* stop() internally.
*/
spin: function (target) {
this.stop()
var self = this
, o = self.opts
, el = self.el = css(createEl(0, { className: o.className }), { position: o.position, width: 0, zIndex: o.zIndex })
, mid = o.radius + o.length + o.width
, ep // element position
, tp // target position
if (target) {
target.insertBefore(el, target.firstChild || null)
tp = pos(target)
ep = pos(el)
css(el, {
left: (o.left == 'auto' ? tp.x - ep.x + (target.offsetWidth >> 1) : parseInt(o.left, 10) + mid) + 'px',
top: (o.top == 'auto' ? tp.y - ep.y + (target.offsetHeight >> 1) : parseInt(o.top, 10) + mid) + 'px'
})
}
el.setAttribute('role', 'progressbar')
self.lines(el, self.opts)
if (!useCssAnimations) {
// No CSS animation support, use setTimeout() instead
var i = 0
, start = (o.lines - 1) * (1 - o.direction) / 2
, alpha
, fps = o.fps
, f = fps / o.speed
, ostep = (1 - o.opacity) / (f * o.trail / 100)
, astep = f / o.lines
; (function anim() {
i++;
for (var j = 0; j < o.lines; j++) {
alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity)
self.opacity(el, j * o.direction + start, alpha, o)
}
self.timeout = self.el && setTimeout(anim, ~~(1000 / fps))
})()
}
return self
},
/**
* Stops and removes the Spinner.
*/
stop: function () {
var el = this.el
if (el) {
clearTimeout(this.timeout)
if (el.parentNode) el.parentNode.removeChild(el)
this.el = undefined
}
return this
},
/**
* Internal method that draws the individual lines. Will be overwritten
* in VML fallback mode below.
*/
lines: function (el, o) {
var i = 0
, start = (o.lines - 1) * (1 - o.direction) / 2
, seg
function fill(color, shadow) {
return css(createEl(), {
position: 'absolute',
width: (o.length + o.width) + 'px',
height: o.width + 'px',
background: color,
boxShadow: shadow,
transformOrigin: 'left',
transform: 'rotate(' + ~~(360 / o.lines * i + o.rotate) + 'deg) translate(' + o.radius + 'px' + ',0)',
borderRadius: (o.corners * o.width >> 1) + 'px'
})
}
for (; i < o.lines; i++) {
seg = css(createEl(), {
position: 'absolute',
top: 1 + ~(o.width / 2) + 'px',
transform: o.hwaccel ? 'translate3d(0,0,0)' : '',
opacity: o.opacity,
animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1 / o.speed + 's linear infinite'
})
if (o.shadow) ins(seg, css(fill('#000', '0 0 4px ' + '#000'), { top: 2 + 'px' }))
ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)')))
}
return el
},
/**
* Internal method that adjusts the opacity of a single line.
* Will be overwritten in VML fallback mode below.
*/
opacity: function (el, i, val) {
if (i < el.childNodes.length) el.childNodes[i].style.opacity = val
}
})
function initVML() {
/* Utility function to create a VML tag */
function vml(tag, attr) {
return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr)
}
// No CSS transforms but VML support, add a CSS rule for VML elements:
sheet.addRule('.spin-vml', 'behavior:url(#default#VML)')
Spinner.prototype.lines = function (el, o) {
var r = o.length + o.width
, s = 2 * r
function grp() {
return css(
vml('group', {
coordsize: s + ' ' + s,
coordorigin: -r + ' ' + -r
}),
{ width: s, height: s }
)
}
var margin = -(o.width + o.length) * 2 + 'px'
, g = css(grp(), { position: 'absolute', top: margin, left: margin })
, i
function seg(i, dx, filter) {
ins(g,
ins(css(grp(), { rotation: 360 / o.lines * i + 'deg', left: ~~dx }),
ins(css(vml('roundrect', { arcsize: o.corners }), {
width: r,
height: o.width,
left: o.radius,
top: -o.width >> 1,
filter: filter
}),
vml('fill', { color: getColor(o.color, i), opacity: o.opacity }),
vml('stroke', { opacity: 0 }) // transparent stroke to fix color bleeding upon opacity change
)
)
)
}
if (o.shadow)
for (i = 1; i <= o.lines; i++)
seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)')
for (i = 1; i <= o.lines; i++) seg(i)
return ins(el, g)
}
Spinner.prototype.opacity = function (el, i, val, o) {
var c = el.firstChild
o = o.shadow && o.lines || 0
if (c && i + o < c.childNodes.length) {
c = c.childNodes[i + o]; c = c && c.firstChild; c = c && c.firstChild
if (c) c.opacity = val
}
}
}
var probe = css(createEl('group'), { behavior: 'url(#default#VML)' })
if (!vendor(probe, 'transform') && probe.adj) initVML()
else useCssAnimations = vendor(probe, 'animation')
return Spinner
}));
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
module.exports.translate = function(load){
if (load.source.indexOf('moduleId') != -1) return load;
var url = document.createElement('a');
url.href = load.address;
var basePathParts = url.pathname.split('/');
basePathParts.pop();
var basePath = basePathParts.join('/');
var baseHref = document.createElement('a');
baseHref.href = this.baseURL;
baseHref = baseHref.pathname;
if (!baseHref.startsWith('/base/')) { // it is not karma
basePath = basePath.replace(baseHref, '');
}
load.source = load.source
.replace(templateUrlRegex, function(match, quote, url){
var resolvedUrl = url;
if (url.startsWith('.')) {
resolvedUrl = basePath + url.substr(1);
}
return 'templateUrl: "' + resolvedUrl + '"';
})
.replace(stylesRegex, function(match, relativeUrls) {
var urls = [];
while ((match = stringRegex.exec(relativeUrls)) !== null) {
if (match[2].startsWith('.')) {
urls.push('"' + basePath + match[2].substr(1) + '"');
} else {
urls.push('"' + match[2] + '"');
}
}
return "styleUrls: [" + urls.join(', ') + "]";
});
return load;
};