Renamed prefixes in angular.json
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good

This commit is contained in:
Willem Dantuma
2019-11-04 13:43:46 +01:00
parent c32214f544
commit cec43a636c
183 changed files with 4 additions and 4 deletions

View File

@@ -0,0 +1,2 @@
//$theme-colors: ( "primary": #a7ce39, "secondary": #ffc800 );
//$theme-colors: ( "primary": #a7ce39);

View File

@@ -0,0 +1,234 @@
import { Action } from '@ngrx/store';
import { IItemTypes } from '../models/item.types';
import { IListItem } from '../models/list.item';
import { IUser } from '../models/user';
export const INITUSER = '[AppCommon] InitUser';
export const INITUSERSUCCESS = '[AppCommon] InitUserSuccess';
export const INITROOT = '[Explorer] InitRoot';
export const INITROOTSUCCESS = '[Explorer] InitRootSuccess';
export const OPENMODAL = '[AppCommon] OpenModal';
export const CLOSEMODAL = '[AppCommon] CloseModal';
export const LOGIN = '[AppCommon] Login';
export const INITIALIZED = '[AppCommon] Initialized';
export const ESCAPE = '[AppCommon] Escape';
export const LOADITEMTYPES = '[AppCommon] LoadItemTypes';
export const LOADITEMTYPESSUCCESS = '[AppCommon] LoadItemTypesSuccess';
export const ITEMCHANGEDEVENT = '[AppCommon] ItemChangedEvent';
export const ITEMADDEDEVENT = '[AppCommon] ItemAddedEvent';
export const ITEMDELETEDEVENT = '[AppCommon] ItemDeletedEvent';
export const TASKSTARTEVENT = '[AppCommon] TaskStartEvent';
export const TASKENDEVENT = '[AppCommon] TaskEndEvent';
export const TASKERRORTEVENT = '[AppCommon] TaskErrorEvent';
export const DELETEITEMS = '[AppCommon] DeleteItems';
export const DELETEITEMSSUCCESS = '[AppCommon] DeleteItemsSuccess';
export const STARTROUTELOADING = '[AppCommon] StartRouteLoading';
export const ENDROUTELOADING = '[AppCommon] EndRouteLoading';
export const FULLSCREEN = '[AppCommon] FullScreen';
export const SHOWNAVBAR = '[AppCommon] ShowNavBar';
export const EDITITEM = "[AppCommon] EditItem";
export const VIEWITEM = "[AppCommon] ViewItem";
export const FAIL = '[AppCommon] Fail';
export const UPLOADEDFILECLICK = '[AppCommon] UploadedFileClick';
export class InitUser implements Action {
readonly type = INITUSER;
constructor() { }
}
export class InitUserSuccess implements Action {
readonly type = INITUSERSUCCESS;
constructor(public user:IUser ) { }
}
export class InitRoot implements Action {
readonly type = INITROOT;
constructor() { }
}
export class InitRootSuccess implements Action {
readonly type = INITROOTSUCCESS;
constructor(public items:IListItem[]) { }
}
export class OpenModal implements Action {
readonly type = OPENMODAL;
constructor(public modalName: string) { }
}
export class CloseModal implements Action {
readonly type = CLOSEMODAL;
constructor() { }
}
export class StartRouteLoading implements Action {
readonly type = STARTROUTELOADING;
constructor() { }
}
export class EndRouteLoading implements Action {
readonly type = ENDROUTELOADING;
constructor() { }
}
export class Login implements Action {
readonly type = LOGIN;
constructor(public url: string) { }
}
export class Initialized implements Action {
readonly type = INITIALIZED;
constructor() { }
}
export class Escape implements Action {
readonly type = ESCAPE;
constructor(public escapeKey:boolean, public click:boolean) { }
}
export class LoadItemTypes implements Action {
readonly type = LOADITEMTYPES;
constructor() { }
}
export class LoadItemTypesSuccess implements Action {
readonly type = LOADITEMTYPESSUCCESS;
constructor(public itemTypes: IItemTypes) { }
}
export class Fail implements Action {
readonly type = FAIL;
constructor(public payload: string) { }
}
export class ItemChangedEvent implements Action {
readonly type = ITEMCHANGEDEVENT;
constructor(public itemCode: string, public attributes: any) { }
}
export class ItemAddedEvent implements Action {
readonly type = ITEMADDEDEVENT;
constructor(public itemCode: string, public attributes: any) { }
}
export class ItemDeletedEvent implements Action {
readonly type = ITEMDELETEDEVENT;
constructor(public itemCode: string, public attributes: any) { }
}
export class TaskStartEvent implements Action {
readonly type = TASKSTARTEVENT;
constructor(public itemCode: string, public attributes: any) { }
}
export class TaskEndEvent implements Action {
readonly type = TASKENDEVENT;
constructor(public itemCode: string, public attributes: any) { }
}
export class TaskErrorEvent implements Action {
readonly type = TASKERRORTEVENT;
constructor(public itemCode: string, public attributes: any) { }
}
export class DeleteItems implements Action {
readonly type = DELETEITEMS;
constructor(public itemCodes: string[]) { }
}
export class DeleteItemsSuccess implements Action {
readonly type = DELETEITEMSSUCCESS;
constructor(public deletedItemCodes: string[]) { }
}
export class EditItem implements Action {
readonly type = EDITITEM;
constructor(public item: IListItem) { }
}
export class ViewItem implements Action {
readonly type = VIEWITEM;
constructor(public item: IListItem) { }
}
export class FullScreen implements Action {
readonly type = FULLSCREEN;
constructor() { }
}
export class ShowNavBar implements Action {
readonly type = SHOWNAVBAR;
constructor() { }
}
export class UploadedFileClick implements Action {
readonly type = UPLOADEDFILECLICK;
constructor(public itemCode:string) { }
}
export type Actions = OpenModal
| InitRoot
| InitRootSuccess
| CloseModal
| Login
| Initialized
| ItemChangedEvent
| ItemAddedEvent
| ItemDeletedEvent
| Escape
| LoadItemTypes
| LoadItemTypesSuccess
| DeleteItems
| DeleteItemsSuccess
| Fail
| EditItem
| ViewItem
| FullScreen
| ShowNavBar
| StartRouteLoading
| EndRouteLoading
| InitUser
| InitUserSuccess
| TaskStartEvent
| TaskEndEvent
| TaskErrorEvent;

View File

@@ -0,0 +1,41 @@
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import {AuthCallbackComponent} from './components/auth-callback/auth-callback.component';
import {AuthCallbackGuard} from './components/auth-callback/auth-callback.guard';
import {FullScreenGuard} from './services/full-screen-guard.service';
import {SessionClearedComponent} from './components/session-cleared/session-cleared.component';
import {NotFoundComponent} from './components/not-found/not-found.component';
const routes = [
{
path: 'cb',
component: AuthCallbackComponent,
canActivate: [AuthCallbackGuard],
},
{
path: 'loggedout',
component: SessionClearedComponent,
canActivate: [FullScreenGuard],
},
{
path: '**', component: NotFoundComponent,
data: {
title: '404 - Not found',
meta: [{name: 'description', content: '404 - Error'}],
links: [],
// links: [
// { rel: 'canonical', href: 'http://blogs.example.com/bootstrap/something' },
// { rel: 'alternate', hreflang: 'es', href: 'http://es.example.com/bootstrap-demo' }
//]
},
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class AppCommonRoutingModule {
}

View File

@@ -0,0 +1,167 @@
// angular modules
import { NgModule, APP_INITIALIZER, ModuleWithProviders, Injector } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
// external modules
import { OAuthModule,AuthConfig, OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
import { StoreModule,Store } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import {UploadxModule } from 'ngx-uploadx';
// routing module
import { AppCommonRoutingModule } from './common-routing.module';
import { MODULE_NAME } from './module-name';
//components
import { ItemTypeService } from './services/itemtype.service';
import { FolderService } from './services/folder.service';
import { TimespanService} from './services/timespan.service';
import { ItemService} from './services/item.service';
import { EventService } from './services/event.service';
import { TypeaheadService } from './services/typeahead.service';
import { UserService } from './services/user.service';
import { AppConfig } from './shared/app.config';
import { AccessTokenInterceptor } from "./shared/accesstoken.interceptor";
import { appConfigFactory } from "./shared/app.config.factory";
import { AuthGuard } from './services/auth-guard.service';
import { NavBarGuard } from './services/nav-bar-guard.service';
import { FullScreenGuard } from './services/full-screen-guard.service';
import { SafePipe } from './shared/safe.pipe';
import { AuthCallbackComponent } from './components/auth-callback/auth-callback.component';
import { AuthCallbackGuard } from './components/auth-callback/auth-callback.guard';
import { SessionClearedComponent } from './components/session-cleared/session-cleared.component';
import { ResumableFileUploadService } from './components/resumable-file-upload/resumable-file-upload.service';
import { ResumableFileUploadComponent } from './components/resumable-file-upload/resumable-file-upload.component';
import { NotFoundComponent } from './components/not-found/not-found.component';
import { SidePanelComponent } from './components/side-panel/side-panel.component';
import { TimespanComponent } from './components/timespan/timespan.component';
import { TagInputComponent } from './components/tag-input/tag-input.component';
import {IEventMessage } from './models/event.message';
import { IItem, Item } from './models/item';
import {IItemType} from './models/item.type';
import {IItemTypes} from './models/item.types';
import {IItemTask,ItemTask} from './models/itemTask';
import {IListItem} from './models/list.item';
import {ITypeaheadItem} from './models/typeahead.item';
import {IUser} from './models/user';
import * as commonActions from './actions/app-common.actions';
import * as commonReducers from './reducers/app-common.reducer';
import * as commonEffects from './effects/app-common.effects';
import {NgbDateNativeAdapter} from './services/date-adapter.service'
import { from } from 'rxjs';
export {FolderService,
ItemTypeService,
TimespanService,
ItemService,
EventService,
TypeaheadService,
UserService,
AppConfig,
AccessTokenInterceptor,
AuthGuard,
NavBarGuard,
FullScreenGuard,
SafePipe,
AuthCallbackComponent,
AuthCallbackGuard,
SessionClearedComponent,
ResumableFileUploadService,
ResumableFileUploadComponent,
NotFoundComponent,
SidePanelComponent,
TimespanComponent,
TagInputComponent,
IEventMessage,
IItem,
Item,
IItemType,
IItemTypes,
IItemTask,
ItemTask,
IListItem,
ITypeaheadItem,
IUser,
commonActions,
commonReducers,
NgbDateNativeAdapter
};
@NgModule({
imports: [
CommonModule,
HttpClientModule,
AppCommonRoutingModule,
StoreModule.forFeature(MODULE_NAME, commonReducers.reducer ),
EffectsModule.forFeature([commonEffects.AppCommonEffects]),
OAuthModule.forRoot(),
NgbModule,
FormsModule,
UploadxModule
],
providers: [
DatePipe
],
declarations: [
AuthCallbackComponent,
SidePanelComponent,
SafePipe,
NotFoundComponent,
ResumableFileUploadComponent,
TimespanComponent,
TagInputComponent,
SessionClearedComponent
],
exports: [
NgbModule,
UploadxModule,
CommonModule,
ResumableFileUploadComponent,
AuthCallbackComponent,
SidePanelComponent,
SafePipe,
NotFoundComponent,
ResumableFileUploadComponent,
TimespanComponent,
TagInputComponent,
SessionClearedComponent
]
})
export class AppCommonModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: AppCommonModule,
providers: [
AppConfig,
{
provide: APP_INITIALIZER,
useFactory: appConfigFactory,
deps: [Injector, AppConfig, OAuthService],
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: AccessTokenInterceptor,
multi: true
},
ResumableFileUploadService,
EventService,
FolderService,
UserService,
ItemService,
TypeaheadService,
AuthCallbackGuard,
AuthGuard,
NavBarGuard,
FullScreenGuard,
TimespanService,
ItemTypeService
]
};
}
}

View File

@@ -0,0 +1,12 @@
import { Component } from '@angular/core';
@Component({
selector: 'fm-auth-callback',
template:'<div></div>'
})
export class AuthCallbackComponent {
constructor() {
}
}

View File

@@ -0,0 +1,15 @@
import { Router, CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
import { } from '@angular/router';
@Injectable()
export class AuthCallbackGuard implements CanActivate {
constructor(private router$: Router,private oauthService$:OAuthService) {}
canActivate() {
this.router$.navigateByUrl(this.oauthService$.state);
return false;
}
}

View File

@@ -0,0 +1,5 @@
<div class="wrapper">
<header class="header header--large">
<h1 class="title">This page doesn't exist</h1>
</header>
</div>

View File

@@ -0,0 +1,12 @@
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'fm-not-found',
templateUrl: './not-found.component.html'
// styleUrls: ['./not-found.component.css']
})
export class NotFoundComponent implements OnInit {
constructor() { }
ngOnInit() { }
}

View File

@@ -0,0 +1,23 @@
<div class="resumable-file-upload closed" [ngClass]="{'closed': uploadService.isClosed }">
<div>
<div class="card">
<div class="card-header p-3 bg-primary text-white">
<span *ngIf="uploadService.isUploading">Uploading files (<span>{{uploadService.totalProgress}}</span> %)</span>
<span *ngIf="uploadService.isUploading == false">Uploaded <span>{{uploadService.files.length}}</span> files</span>
<span title="Cancel" class="fa fa-times pull-right" (click)="uploadService.close()"></span><span title="Minimize" class="fa fa-chevron-down pull-right" (click)="uploadService.toggleMinimize()" [ngClass]="{'fa-chevron-down': uploadService.isMinimized == false, 'fa-chevron-up':uploadService.isMinimized}"></span>
</div>
<div [ngClass]="{'minimized': uploadService.isMinimized }">
<div class="card-block p-3">
<ul class="list-unstyled">
<li *ngFor="let file of uploadService.files" class="upload-file busy" [ngClass]="{'done': file.success,'busy':file.success == false,'error': file.error }">
<div *ngIf="file.success == false"><span class="file-name" [attr.title]="file?.fileName">{{file.fileName}}</span><span class="fa fa-times" title="Cancel" (click)="uploadService.cancelFile(file)"></span><span class="fa fa-check"></span></div>
<div *ngIf="file.success"><a href="#" (click)="handleUploadedFileClick($event,file)" class="file-name" [attr.title]="file?.fileName">{{file.fileName}}</a><span class="fa fa-check"></span></div>
<div class="progress-container"><div class="progress-bar" [style.width]="file.progress+'%'"></div></div>
<div class="errormessage">{{file.errorMessage}}</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>

View File

@@ -0,0 +1,113 @@
@import "../../theme.scss";
/* Import Bootstrap & Fonts */
@import "~bootstrap/scss/bootstrap.scss";
div.resumable-file-upload {
position: fixed;
right: 0px;
bottom: 0px;
width: 300px;
max-height: 250px;
/*z-index:2000 !important;*/
}
div.minimized {
height: 0px;
}
div.closed {
height: 0px;
}
div.card {
margin-bottom: 0px;
}
div.card-block {
max-height: calc(250px - 41px);
overflow-y: auto;
}
div.minimized div.card-block {
height: 0px;
}
div.card-header span.fa {
padding-left: 5px;
}
.upload-file {
padding-top: 3px;
}
.upload-file .progress-container {
height: 3px;
width: 100%;
margin-top:4px;
}
.upload-file .progress-container .progress-bar {
display: block;
background-color: color("green");
width: 0%;
height: 100%;
}
.upload-file.done .progress-container .progress-bar {
display: none;
}
.upload-file > div > span.file-name {
display: inline-block;
width: calc(100% - 20px);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.upload-file > div > a.file-name {
display: inline-block;
width: calc(100% - 20px);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.upload-file.busy > div > span.fa-times {
color: theme-color("danger");
width: 20px;
display: inline-block;
vertical-align: middle;
}
.upload-file.done > div > span.fa-times {
display: none;
}
.upload-file.done > div > span.fa-check {
color: color("green");
width: 20px;
display: inline-block;
vertical-align: middle;
}
.upload-file > div.errormessage {
color: theme-color("danger");
display: none;
}
.upload-file.error > div.errormessage {
display: block;
}
.upload-file.busy > div > span.fa-check {
display: none;
}
.resumable-file-upload ul {
padding:0px;
}

View File

@@ -0,0 +1,53 @@
import { Component, Input,Output, HostListener, ChangeDetectorRef, OnDestroy, OnInit,EventEmitter } from '@angular/core';
import { ResumableFileUploadService, File } from './resumable-file-upload.service';
import { Subscription } from 'rxjs';
import { Store } from '@ngrx/store';
import * as commonReducer from '../../reducers/app-common.reducer';
import * as commonActions from '../../actions/app-common.actions';
@Component({
selector: 'fm-resumable-file-upload',
templateUrl: './resumable-file-upload.component.html',
styleUrls: ['./resumable-file-upload.component.scss']
})
export class ResumableFileUploadComponent implements OnInit, OnDestroy {
@Input('parentCode')
set parentCode(parentCode: string) {
if (parentCode && parentCode != "null" && parentCode != "")
this.uploadService.parentCode = parentCode;
else
this.uploadService.parentCode = null;
}
constructor(private cd: ChangeDetectorRef, public uploadService: ResumableFileUploadService,public store: Store<commonReducer.State>) {
}
private refreshSub: Subscription;
ngOnInit() {
this.uploadService.init();
this.refreshSub = this.uploadService.refresh.subscribe((e: any) => {
this.cd.markForCheck();
});
}
ngOnDestroy() {
if(this.refreshSub) this.refreshSub.unsubscribe();
}
handleUploadedFileClick(event:MouseEvent,file:File) {
event.preventDefault();
this.store.dispatch(new commonActions.UploadedFileClick(file.itemCode));
}
//TODO do this with an canunload guard
@HostListener('window:beforeunload')
windowBeforeUnload = function () {
if (this.uploadService.isUploading) {
return false;
}
}
}

View File

@@ -0,0 +1,149 @@
import { Injectable, OnDestroy } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
import { Subject , Subscription } from 'rxjs';
import { HttpClient } from "@angular/common/http";
import { UploadxService, UploadState,UploadxOptions} from 'ngx-uploadx';
import { AppConfig } from '../../shared/app.config';
@Injectable({ providedIn: 'root' })
export class ResumableFileUploadService implements OnDestroy{
public files: Array<File> = new Array<File>();
public isUploading = false;
public totalProgress = 0;
public isClosed = true;
public isMinimized = false;
public parentCode: string;
public refresh: Subject<any> = new Subject<any>();
private _eventSub:Subscription;
private initialized = false;
constructor(private httpClient: HttpClient,private oauthService: OAuthService,private uploadService: UploadxService,public appConfig: AppConfig) {
}
endPoint() {
return `${this.appConfig.getConfig("apiEndPoint")}/api/v1/file`;
}
init() {
if(!this.initialized) {
this._eventSub=this.uploadService.init({
endpoint:this.endPoint(),
token:() => this.oauthService.getAccessToken(),
chunkSize: 2097152}).subscribe((uploadState:UploadState) => {
this.handleState(uploadState);
} );
this.initialized=true;
}
}
updatetotalprogress() {
var totalProgress =0;
var n=0;
for(var i =0;i<this.files.length;i++) {
if(!this.files[i].error) {
totalProgress+=this.files[i].progress;
n++;
}
}
this.totalProgress=totalProgress/this.files.length;
if(this.totalProgress==100) this.isUploading=false;
}
handleState(state:UploadState) {
switch(state.status) {
case "queue": {
this.files.push(new File(state));
this.isClosed=false;
};break;
case "uploading": {
this.isUploading = true;
var file =this.files.find((f) => f.identifier == state.uploadId )
if(file) {
file.progress = (state.progress?state.progress:0);
}
};break;
case "complete": {
var file =this.files.find((f) => f.identifier == state.uploadId )
if(file) {
var parts = state.url.split("/");
file.itemCode = parts[parts.length-1];
file.progress = (state.progress?state.progress:0);
file.success=true;
}
};break;
case "error": {
var file =this.files.find((f) => f.identifier == state.uploadId )
if(file) {
file.error=true;
file.errorMessage = state.response;
}
};break;
}
this.updatetotalprogress();
this.refresh.next({});
}
addFiles = (files: any[], event: any, metadata:any) => {
for (let f of files) {
var options:UploadxOptions = {metadata:metadata};
this.uploadService.handleFile(f,options);
}
}
toggleMinimize = function () {
this.isMinimized = !this.isMinimized;
};
cancelFile = function (file) {
this.uploadService.control({action:'cancel',uploadId:file.identifier});
var index = this.files.indexOf(file, 0);
if (index > -1) {
this.files.splice(index, 1);
}
};
doClose = function () {
this.uploadService.control({action:'cancelAll'});
this.files = new Array<File>();
this.isClosed = true;
}
close = function () {
let close = true;
if (this.isUploading) {
close = false;
}
if (close) {
this.doClose();
}
}
ngOnDestroy() {
if(this._eventSub) this._eventSub.unsubscribe();
}
}
export class File {
private file: any;
public fileName: string;
public progress: number;
public identifier: string;
public itemCode: string;
public success: boolean;
public error: boolean;
public errorMessage: string;
constructor(state: UploadState) {
this.file = state;
this.fileName = state.file.name;
this.progress = state.progress?state.progress:0;
this.identifier = state.uploadId;
this.success = false;
this.error = false;
this.errorMessage = "";
this.itemCode = null;
}
}

View File

@@ -0,0 +1,8 @@
<div class="session-cleared">
<div class="card">
<div class="card-body">
<p class="card-text" i18n>You have been logged out</p>
<button class="btn btn-primary" (click)="handleLoginClick()" i18n>Login again</button>
</div>
</div>
</div>

View File

@@ -0,0 +1,6 @@
.session-cleared {
display: flex;
align-items: center;
justify-content: center;
min-height: 100%;
}

View File

@@ -0,0 +1,24 @@
import { Component, Input } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Store } from '@ngrx/store';
import * as appCommonReducers from '../../reducers/app-common.reducer';
import * as appCommonActions from '../../actions/app-common.actions';
@Component({
selector: 'fm-session-cleared',
templateUrl: 'session-cleared.component.html',
styleUrls: ['session-cleared.component.scss']
})
export class SessionClearedComponent {
constructor(private route: ActivatedRoute, private store: Store<appCommonReducers.State>) {
}
handleLoginClick() {
this.store.dispatch(new appCommonActions.Login(this.route.snapshot.queryParamMap.get('redirectTo')));
}
}

View File

@@ -0,0 +1,14 @@
<div class="side-panel hidden collapsed" [ngClass]="{'hidden':!visible,'collapsed':collapsed,'resizeable':(resizeable && mobile),'resizing':resizing }" [ngStyle]="{'top':top}">
<div *ngIf="collapsable" class="arrow rounded-right p-2" (click)="handleToggleClick($event)">
<i class="fa fa-chevron-left" aria-hidden="true"></i>
</div>
<div draggable="true" class="resizegrip" (dragstart)="handleStartGripDrag($event)" (touchstart)="handleStartGripDrag($event)" (dragend)="handleEndGripDrag()" (touchend)="handleEndGripDrag()" (drag)="handleGripDrag($event)" (touchmove)="handleGripDrag($event)">
<div></div>
<span class="rounded"></span>
</div>
<div class="content">
<ng-content>
</ng-content>
</div>
</div>

View File

@@ -0,0 +1,100 @@
.side-panel {
position: absolute;
bottom: 0px;
width: 100%;
left: 0px;
top:50%;
transition: left 0.3s, top 0.3s;
background-color: white;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}
.side-panel.resizing {
transition: left 0s, top 0s;
}
.side-panel.collapsed {
left:-22rem;
}
.arrow {
position: absolute;
top: 1rem;
left: 100%;
background-color: inherit;
cursor:pointer;
}
.arrow i {
transition: transform 0.3s;
}
.collapsed .arrow i {
-webkit-transform: rotate(180deg);
transform: rotate(180deg);
}
.side-panel.hidden {
top:100%;
}
.content {
height:100% ;
width:100%;
overflow:hidden;
overflow-y:auto;
position: relative;
z-index: 1;
background-color: rgb(255,255,255);
}
.resizegrip {
height:2rem;
line-height: 1rem;
display: none;
text-align: center;
position: relative;
z-index: 2;
}
div.resizegrip > div {
position: absolute;
top:0px;
height: 1rem;
width: 100%;
background-color: rgb(255,255,255);
}
div.resizegrip > span {
position: relative;
display: inline-block;
height:0.3rem;
width:4rem;
background-color:rgba(0, 0, 0, 0.3);
top:-0.3rem;
}
.resizeable .resizegrip {
display:block;
}
.resizeable .content {
height:calc(100% - 1rem);
top:-1rem;
}
@media screen and (min-width:44rem) {
.side-panel {
top:0px;
width: 22rem;
height:100%;
left:0px;
}
.side-panel.hidden {
width: 22rem;
left:-24rem;
height:100%;
}
}

View File

@@ -0,0 +1,85 @@
import { Component, Input,ViewChild,ElementRef,OnChanges,SimpleChanges,HostListener,ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'fm-side-panel',
templateUrl: 'side-panel.component.html',
styleUrls: ['side-panel.component.scss']
})
export class SidePanelComponent implements OnChanges {
@Input() public visible: boolean;
@Input() public collapsed: boolean;
@Input() public collapsable: boolean;
@Input() public resizeable: boolean = false;
@ViewChild("resizeGrip") elementView: ElementRef;
public mobile:boolean = true;
private parentHeight:number = 0;
public top = "100%";
private resizeTop:number=50;
public resizing:boolean=false;
constructor(private element: ElementRef,private ref: ChangeDetectorRef) {
this.collapsable = false;
this.setTop();
}
checkMobile():boolean {
let size = parseFloat(getComputedStyle(document.documentElement).width);
let rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
let threshold = 44 * rem;
return !(size>threshold);
}
setTop() {
this.mobile = this.checkMobile();
this.resizeTop = this.mobile?50:0;
this.top = (this.visible?this.resizeTop: (this.mobile? 100:0)) + "%";
}
ngAfterViewInit() {
this.parentHeight = this.element.nativeElement.offsetParent.clientHeight;
}
handleToggleClick(event) {
if (this.collapsable) {
this.collapsed = !this.collapsed;
}
}
handleStartGripDrag(event:DragEvent|TouchEvent) {
this.resizing=true;
if(event instanceof DragEvent) {
var crt = new Image();
crt.style.display = "none";
document.body.appendChild(crt);
event.dataTransfer.setDragImage(crt,0,0);
}
}
handleEndGripDrag() {
this.resizing = false;
}
handleGripDrag(event:DragEvent|TouchEvent) {
var clientY = 0;
if((event instanceof TouchEvent)) {
clientY = (event as TouchEvent).changedTouches[0].clientY;
} else {
clientY=(event as DragEvent).clientY;
}
this.resizeTop = Math.min(98, Math.max(0, clientY / (this.parentHeight / 100)));
this.top = (this.visible? this.resizeTop:(this.mobile? 100:0)) + "%";
}
ngOnChanges(changes: SimpleChanges) {
if(changes.visible) {
this.top = (changes.visible.currentValue?this.resizeTop:(this.mobile? 100:0)) + "%";
}
}
@HostListener('window:resize', ['$event'])
onResize(event) {
this.setTop();
}
}

View File

@@ -0,0 +1,3 @@
<div class="tags">
<span class="tag rounded bg-primary text-white" *ngFor="let tag of tags;"><span>{{tag}}</span> <i (click)="handleDeleteTag(tag)" class="fa fa-times" aria-hidden="true"></i></span><input type="text" #taginput (blur)="handleAddTag($event)" (keyup)="handleCheckAddTag($event)" [(ngModel)]="tag" [ngbTypeahead]="findTag" (selectItem)="handleSelect($event)" placeholder="New tag"/>
</div>

View File

@@ -0,0 +1,16 @@
.tag {
display:inline-block;
padding:0.5rem;
margin-bottom:0.5rem;
margin-top:0.5rem;
margin-right:1rem;
}
:host(tag-input) {
height: auto ;
}
input {
margin-bottom: 0.5rem;
margin-top: 0.5rem;
}

View File

@@ -0,0 +1,104 @@
import { Component, Input, forwardRef,ElementRef,ViewChild } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR,NgModel } from '@angular/forms';
import { Observable,of } from 'rxjs';
import { tap,catchError,debounceTime,distinctUntilChanged,switchMap } from 'rxjs/operators'
import { TypeaheadService } from '../../services/typeahead.service';
@Component({
selector: 'fm-tag-input',
templateUrl: 'tag-input.component.html',
styleUrls: ['tag-input.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TagInputComponent),
multi: true
}
]
})
export class TagInputComponent implements ControlValueAccessor {
@Input() tags: string[]
@ViewChild('taginput') tagInputElement: ElementRef;
public tag: string;
searching = false;
searchFailed = false;
constructor(private typeaheadService: TypeaheadService) {
}
tagExists(tag) {
if (tag.length == 0) return true;
for (let t of this.tags) {
if (t.toLowerCase() == tag.toLowerCase()) return true;
}
return false;
}
handleDeleteTag(tag) {
let tags = [];
for (let t of this.tags) {
if (t != tag) tags.push(t);
}
this.tags = tags;
this.propagateChange(tags);
}
handleAddTag(event) {
if (!this.tagExists(this.tag)) {
this.tags.push(this.tag);
this.propagateChange(this.tags);
}
this.tag = "";
this.tagInputElement.nativeElement.focus();
}
handleCheckAddTag(event: KeyboardEvent) {
if (event.keyCode == 188) {
let tag = this.tag.substr(0, this.tag.length - 1); // strip ,
if (!this.tagExists(tag)) {
this.tags.push(tag);
this.propagateChange(this.tags);
}
this.tag = "";
}
}
handleSelect(event) {
if (!this.tagExists(event.item)) {
this.tags.push(event.item);
this.propagateChange(this.tags);
}
event.preventDefault();
this.tag = "";
}
propagateChange = (_: any) => { };
registerOnChange(fn) {
this.propagateChange = fn;
}
findTag = (text$: Observable<string>) =>
text$.pipe(
debounceTime(200),
distinctUntilChanged(),
tap(() => this.searching = true),
switchMap(term => term.length < 1 ? of([]) :
this.typeaheadService.getTagTypeaheadItems(term).pipe(
tap(() => this.searchFailed = false),
catchError(() => {
this.searchFailed = true;
return of([]);
}))
),
tap(() => this.searching = false)
);
writeValue(value: any) {
this.tags = value;
this.tag = "";
}
registerOnTouched() { }
}

View File

@@ -0,0 +1,77 @@
.timespan {
width:100%;
position: relative;
user-select: none;
}
.collapsed {
height:0;
overflow: hidden;
}
.timeline {
position: relative;
height: 6rem;
width: 100%;
margin-top: 0.5rem;
overflow: hidden;
}
.timeline canvas {
top:0;
left:0;
width:100%;
height:100%;
}
.control-container {
position: absolute;
top:0px;
width:100%;
overflow: hidden;
font-size: 0;
white-space: nowrap;
pointer-events: none;
}
.leftGrip,.rightGrip,.range {
pointer-events: all;
display: inline-block;
height:100%;
/* float: left; */
font-size: 9pt;
text-align: center;
vertical-align: top;
overflow: hidden;
}
.range {
/* height:100%; */
}
.leftGrip,.rightGrip {
width:15px;
background-color: rgb(204, 200, 200);
border:1px solid black;
}
.rightGrip {
cursor: e-resize;
}
.leftGrip {
left: -100px;
cursor:w-resize;
}
.range {
/* background: linear-gradient( rgba(0, 140, 255, 0.856),transparent); */
background-color:rgba(0, 140, 255, 0.856);
cursor: move;
}
.popover-anchor {
position:absolute;
top:2rem;
font-size: 0.8rem;
}

View File

@@ -0,0 +1,34 @@
<div class="timespan p-1" (window:resize)="handleResize($event)">
<div (click)="handleClick()">{{caption}}</div>
<ng-template #popoverContent let-caption="popoverCaption">{{caption}}</ng-template>
<div class="popover-anchor" [style.left.px] = "startPopoverLeft" [ngbPopover]="popoverContent" #popoverStart="ngbPopover">&nbsp;</div>
<div class="popover-anchor" [style.left.px] = "endPopoverLeft" [ngbPopover]="popoverContent" #popoverEnd="ngbPopover">&nbsp;</div>
<div class="collapsed clearfix" [ngClass]="{'collapsed':collapsed}">
<!-- <div class="clearfix">
<select class="form-control float-right" [value]="unitScale">
<option value="0">Millisecond</option>
<option value="1">Second</option>
<option value="2">Minute</option>
<option value="3">Hour</option>
<option value="4">Day</option>
<option value="5">Week</option>
<option value="6">Month</option>
<option value="6">Quarter</option>
<option value="8">Year</option>
</select>
</div> -->
<div class="timeline" (window:mousemove)="handleMouseMove($event)" (window:touchmove)="handleMouseMove($event)" (window:mouseup)="handleMouseUp($event)" (window:touchend)="handleMouseUp($event)" (wheel)="handleMouseWheel($event)" [style.height.px]="height">
<canvas #timeLine (mousedown)="handleViewPanMouseDown($event)" (touchstart)="handleViewPanMouseDown($event)" (mousemove)="handleCanvasMouseMove($event)" (mouseleave)="handleCanvasMouseLeave($event)">
</canvas>
<div class="control-container" [style.margin-left.px]="marginLeft" [style.height.px]="lineHeight" >
<div class="leftGrip rounded-left" (mousedown)="handleLeftGripMouseDown($event)" (touchstart)="handleLeftGripMouseDown($event)" (mouseenter)="handleLeftGripMouseEnter($event)" (mouseleave)="handleLeftGripMouseLeave($event)"><i class="fa fa-ellipsis-v" aria-hidden="true"></i></div>
<div class="range" [style.width.px]="rangeWidth" (mousedown)="handleRangeGripMouseDown($event)" (touchstart)="handleRangeGripMouseDown($event)" (mouseenter)="handleRangeGripMouseEnter($event)"></div>
<div class="rightGrip rounded-right" (mousedown)="handleRightGripMouseDown($event)" (touchstart)="handleRightGripMouseDown($event)" (mouseenter)="handleRightGripMouseEnter($event)" (mouseleave)="handleRightGripMouseLeave($event)"><i class="fa fa-ellipsis-v" aria-hidden="true"></i></div>
</div>
</div>
<!-- <div>
<div class="btn btn-primary" (click)="handleZoomIn()">+</div>
<div class="btn btn-primary" (click)="handleZoomOut()">-</div>
</div> -->
</div>
</div>

View File

@@ -0,0 +1,583 @@
import { Component, OnInit,Input,ViewChild,OnChanges,ChangeDetectorRef,Output, EventEmitter,SimpleChanges } from '@angular/core';
import { DatePipe } from '@angular/common';
import {NgbPopover} from '@ng-bootstrap/ng-bootstrap';
export interface TimeSpan {
startDate:Date;
endDate:Date;
}
@Component({
selector: 'fm-timespan',
templateUrl: './timespan.component.html',
styleUrls: ['./timespan.component.css']
})
export class TimespanComponent implements OnInit, OnChanges {
scale:number = 1000 * 60 * 60 ; // milliseconds / pixel ( 1 hour )
unitScales:number[] = [1,1000,1000*60,1000*60*60,1000*60*60*24,1000*60*60*24*7,1000*60*60*24*31,1000*60*60*24*31*3,1000*60*60*24*365.25];
units:string[] = [ 'millisecond','second','minute','hour','day','week','month','quarter','year'];
quarters:string[] = ['KW1','KW2','KW3','KW4'];
unitScale:number = 3;
viewMinDate:Date;
viewMaxDate:Date;
extentMinDate:Date;
extentMaxDate:Date;
cursorDate:Date;
leftGripMove:boolean = false;
rightGripMove:boolean = false;
rangeGripMove:boolean = false;
viewPan:boolean = false;
downX:number = -1;
mouseX: number = -1;
mouseY: number = -1;
elementWidth:number;
elementHeight:number;
lastOffsetInPixels:number=0;
@ViewChild('timeLine') canvasRef;
@ViewChild('popoverStart') public popoverStart:NgbPopover;
@ViewChild('popoverEnd') public popoverEnd:NgbPopover;
@Input() collapsed: boolean = true;
@Input() startDate: Date = new Date(2018,1,3);
@Input() endDate: Date = new Date(2018,1,5);
@Input() unit:string;
@Input() color:string = '#000000';
@Input() background:string = '#ffffff';
@Input() hoverColor:string ='#ffffff';
@Input() hoverBackground:string ='#0000ff';
@Input() lineColor:string='#000000';
@Input() lineWidth:number=1;
@Input() padding:number = 4;
@Output() change:EventEmitter<TimeSpan> = new EventEmitter();
public caption:string = "2016/2017";
public marginLeft:number = 100;
public startPopoverLeft:number=110;
public endPopoverLeft:number=120;
public rangeWidth:number =75;
public startCaption={};
public endCaption={};
private ratio:number=1;
private initialized:boolean=false;
private ctx:CanvasRenderingContext2D;
public posibleUnits:number[] = [];
public height:number = 0;
public lineHeight:number = 0;
constructor(private changeDetectorRef: ChangeDetectorRef,private datePipe: DatePipe) { }
setCanvasSize() {
let canvas = this.canvasRef.nativeElement;
this.elementWidth = canvas.offsetWidth;
this.elementHeight = canvas.offsetHeight;
canvas.height = this.elementHeight * this.ratio;
canvas.width = this.elementWidth * this.ratio;
}
getPosibleUnits(scale:number):number[] {
let posibleUnits = [];
for(let u of [3,4,6,8]) {
if((this.unitScale <=u) )
posibleUnits.push(u);
}
return posibleUnits;
}
getLineHeight():number {
return (parseInt(this.ctx.font.match(/\d+/)[0], 10)/ this.ratio) + (2*this.padding) ;
}
getHeight():number {
return (this.posibleUnits.length * this.getLineHeight());
}
ngOnInit() {
this.ratio = 2;
this.unitScale = this.getUnitScale(this.unit);
let canvas:HTMLCanvasElement = this.canvasRef.nativeElement;
this.ctx = canvas.getContext('2d');
this.elementWidth = canvas.offsetWidth;
this.elementHeight = canvas.offsetHeight;
this.ctx.font=`normal ${this.ratio*10}pt Sans-serif`;
this.startDate = new Date(this.startDate.getTime() + this.getUnitDateOffset(this.startDate,this.unitScale,0));
this.endDate = new Date(this.endDate.getTime() + this.getUnitDateOffset(this.endDate,this.unitScale,1));
this.change.emit({startDate:this.startDate,endDate:this.endDate});
let rangeInMilliseconds = this.endDate.getTime() - this.startDate.getTime();
this.scale = this.getFitScale(rangeInMilliseconds,this.elementWidth);
this.posibleUnits=this.getPosibleUnits(this.scale);
this.height=this.getHeight();
this.lineHeight= this.getLineHeight();
this.setCanvasSize();
let center = (this.startDate.getTime()+this.endDate.getTime())/2;
this.viewMinDate = new Date(center - (this.elementWidth/2* this.scale));
this.viewMaxDate = new Date(center + (this.elementWidth/2* this.scale));
this.updateStyle(this.startDate,this.endDate);
this.startCaption={popoverCaption:this.getStartCaption(this.startDate,this.unitScale,true)};
this.endCaption={popoverCaption:this.getEndCaption(this.endDate,this.unitScale,true)};
this.redraw();
this.initialized=true;
}
getStartEndCaption(date:Date,otherDate:Date,unitScale:number,suffix:boolean = false,extended:boolean=true):string {
let showSuffix = false;
otherDate=new Date(otherDate.getTime()-1); // fix year edge case
if(unitScale == 3) {
let format="HH:00";
if(extended) {
if(suffix || date.getFullYear() != otherDate.getFullYear())
format="d MMM yyyy:HH:00";
else if(date.getMonth() !== otherDate.getMonth())
format="d MMM HH:00";
}
return this.datePipe.transform(date,format);
}
if(unitScale == 4) {
let format="d";
if(extended) {
if(suffix || date.getFullYear() != otherDate.getFullYear())
format="d MMM yyyy";
else if(date.getMonth() !== otherDate.getMonth())
format="d MMM"
}
return this.datePipe.transform(date,format);
}
if(unitScale == 6) {
let format = "MMM";
if(extended) {
if(suffix || date.getFullYear() != otherDate.getFullYear())
format="MMM yyyy";
}
return this.datePipe.transform(date,format);
}
if(unitScale == 7) {
let q = Math.trunc(date.getMonth() /3 );
return this.quarters[q];
}
if(unitScale == 8) {
return this.datePipe.transform(date,"yyyy");
}
return "";
}
getStartCaption(startDate:Date,unitScale:number,suffix:boolean=false,extended:boolean=true):string {
return this.getStartEndCaption(new Date(startDate.getTime() + (this.unitScales[unitScale]/2)), this.endDate,unitScale,suffix,extended);
}
getEndCaption(endDate:Date,unitScale:number,suffix:boolean=true):string {
return this.getStartEndCaption(new Date(endDate.getTime() - (this.unitScales[unitScale]/2)),this.startDate, unitScale,suffix);
}
getCaption(startDate:Date,endDate:Date,unitScale:number):string {
let startCaption=this.getStartCaption(startDate,unitScale);
let endCaption=this.getEndCaption(endDate,unitScale);
if((endDate.getTime() - startDate.getTime()) < (1.5*this.unitScales[this.unitScale]))
return endCaption;
return `${startCaption}-${endCaption}`;
}
public updatePopoverText(popover:NgbPopover, text:string): void {
const isOpen = popover.isOpen();
if (isOpen) {
popover.close();
popover.open({popoverCaption:text});
}
}
getFitScale(rangeInMilliSeconds:number,elementWidth:number):number {
let width = elementWidth*0.33;
return rangeInMilliSeconds/width;
}
getUnitScale(unit:string):number {
if(!unit) return 3; // hour
for(var _i=0;_i<this.units.length;_i++) {
if(this.units[_i]==unit.toLowerCase()) return _i;
}
throw new Error(`Invalid unit : {{unit}} `);
}
getUnitDateOffset(date:Date, unitScale:number,tick:number):number {
var offsetDate:Date;
if(unitScale==0)
offsetDate = new Date(date.getFullYear(),date.getMonth(),date.getDate() ,date.getHours() ,date.getMinutes(),date.getSeconds(),date.getMilliseconds()+ tick);
if(unitScale==1)
offsetDate = new Date(date.getFullYear(),date.getMonth(),date.getDate() ,date.getHours() ,date.getMinutes(),date.getSeconds() + tick,0);
if(unitScale==2)
offsetDate = new Date(date.getFullYear(),date.getMonth(),date.getDate() ,date.getHours() ,date.getMinutes() + tick,0,0);
if(unitScale==3)
offsetDate = new Date(date.getFullYear(),date.getMonth(),date.getDate() ,date.getHours()+ tick ,0,0,0);
if(unitScale==4)
offsetDate = new Date(date.getFullYear(),date.getMonth(),date.getDate() + tick ,0,0,0,0);
if(unitScale==6)
offsetDate = new Date(date.getFullYear(),date.getMonth()+tick,1,0,0,0,0);
if(unitScale==7) {
var month = (tick * 3);
offsetDate = new Date(date.getFullYear(),month,1,0,0,0,0);
}
if(unitScale==8)
offsetDate = new Date(date.getFullYear()+tick,0,1,0,0,0,0);
return offsetDate.getTime()-date.getTime();
}
getUnitTextWidth(unitScale:number):number {
switch(unitScale) {
case 3:return this.ctx.measureText("88:88").width/this.ratio;
case 4:return this.ctx.measureText("88").width/this.ratio;
case 5:return this.ctx.measureText("WWW").width/this.ratio;
case 6:return this.ctx.measureText("WW").width/this.ratio;
case 7:return this.ctx.measureText("WW").width/this.ratio;
case 8:return this.ctx.measureText("8888").width/this.ratio;
default: return this.ctx.measureText("WW").width/this.ratio;
}
}
getNextTick(viewStartDate:Date, tick:number,step:number,unitScale:number):number {
let unitTextWidth = this.getUnitTextWidth(unitScale);
let dateOffset =this.getUnitDateOffset(viewStartDate,unitScale,tick);
let date = new Date(viewStartDate.getTime() + dateOffset);
let nextTick=tick+step+Math.trunc(step/2);
let nextDateOffset =this.getUnitDateOffset(viewStartDate,unitScale,nextTick);
let nextDate = new Date(viewStartDate.getTime() + nextDateOffset);
let n=1;
switch(unitScale) {
case 4:n=nextDate.getDate()-1;break;
case 6:n=nextDate.getMonth();break;
case 8:n=nextDate.getFullYear();break;
default: n = 1;break;
}
let a = Math.trunc(n / step)*step;
nextTick=nextTick-n+a;
if(nextTick<=tick) return tick+step;
return nextTick;
}
getSteps(unitScale:number):number[] {
if(unitScale==4)
return [1,14];
if(unitScale==6)
return [1,3,6];
return [1,2,3,4,5];
}
drawUnits(yOffset:number,width:number,viewStartDate:Date,unitScale:number):number {
let oneUnit = (this.getUnitDateOffset(viewStartDate,unitScale,1)- this.getUnitDateOffset(viewStartDate,unitScale,0)) / this.scale;
this.ctx.font=`normal ${this.ratio*10}pt Sans-serif`;
let lineHeight = this.getLineHeight();
let dateOffset = this.getUnitDateOffset(viewStartDate,unitScale,0);
let pixelOffset = (dateOffset / this.scale);
let caption = this.getStartCaption(new Date(viewStartDate.getTime()+dateOffset),unitScale,false,false);
let unitTextWidth=this.getUnitTextWidth(unitScale);
this.ctx.beginPath();
this.ctx.strokeStyle=this.lineColor;
let steps=this.getSteps(unitScale);
let s=0;
let step=steps[s];
let steppedOneUnit=oneUnit*step;
while(unitTextWidth > (steppedOneUnit-(2*this.padding)) && s < steps.length -1) {
step=steps[++s];
steppedOneUnit=oneUnit*step;
}
if(steppedOneUnit - (2*this.padding) < unitTextWidth) return yOffset;
this.ctx.moveTo(0,yOffset*this.ratio);
this.ctx.lineTo(width*this.ratio,yOffset*this.ratio);
this.ctx.stroke();
var x:number = pixelOffset;
var nextDateOffset = this.getUnitDateOffset(viewStartDate,unitScale,1);
var nextX:number = (nextDateOffset / this.scale);
var n=0;
while(x < width) {
this.ctx.fillStyle=this.color;
//mouseover
if(this.mouseX> x && this.mouseX <nextX && this.mouseY > yOffset && this.mouseY <( yOffset + lineHeight) && !this.leftGripMove && !this.rightGripMove && !this.rangeGripMove&& !this.viewPan) {
this.ctx.fillStyle=this.hoverBackground;
this.ctx.fillRect((x+0.5)*this.ratio,(yOffset+0.5)*this.ratio,(nextX-x)*this.ratio,lineHeight*this.ratio);
this.ctx.fillStyle=this.hoverColor;
}
this.ctx.moveTo((x+0.5)*this.ratio,(yOffset+0.5)*this.ratio);
this.ctx.lineTo((x+0.5)*this.ratio,(yOffset+lineHeight+0.5)*this.ratio);
this.ctx.stroke();
if(unitTextWidth < steppedOneUnit - (2*this.padding) && x > 0) {
this.ctx.fillText(caption,(x+this.padding)*this.ratio,(yOffset+lineHeight-this.padding)*this.ratio);
} else if((unitTextWidth < (steppedOneUnit - (2*this.padding) +pixelOffset)) && (unitTextWidth < (steppedOneUnit-(2*this.padding)))) {
this.ctx.fillText(caption, (this.padding*this.ratio),(yOffset+lineHeight-this.padding)*this.ratio);
} else if(x < 0 && (unitTextWidth <steppedOneUnit - (2*this.padding))) {
this.ctx.fillText(caption, ((x+steppedOneUnit-this.padding-unitTextWidth) *this.ratio),(yOffset+ lineHeight-this.padding)*this.ratio);
}
n=this.getNextTick(viewStartDate,n,step,unitScale);
dateOffset = this.getUnitDateOffset(viewStartDate,unitScale,n);
nextDateOffset = this.getUnitDateOffset(viewStartDate,unitScale,this.getNextTick(viewStartDate,n,step,unitScale));
nextX = (nextDateOffset / this.scale);
pixelOffset = (dateOffset / this.scale);
caption= this.getStartCaption(new Date(viewStartDate.getTime()+dateOffset),unitScale,false,false);
x=pixelOffset;
}
return lineHeight;
}
redraw() {
let yOffset=0;
let canvas = this.canvasRef.nativeElement;
let height = canvas.offsetHeight;
let width = canvas.offsetWidth;
this.ctx.lineWidth = this.lineWidth;// *this.ratio;
this.ctx.clearRect(0,0,width *this.ratio,height*this.ratio);
for(let unit of this.posibleUnits) {
if(this.unitScale <=unit) yOffset+=this.drawUnits(yOffset,width,this.viewMinDate,unit);
}
}
handleClick() {
this.collapsed = !this.collapsed;
}
updateStyle(startDate:Date,endDate:Date) {
let rangeInMilliseconds = endDate.getTime() - startDate.getTime();
let range = rangeInMilliseconds / this.scale;
let left = (startDate.getTime() - this.viewMinDate.getTime()) / this.scale;
this.startPopoverLeft=(left-10);
this.endPopoverLeft=(left+range+10);
this.marginLeft = (left - 15);
this.rangeWidth = range;
this.updatePopoverText(this.popoverStart,this.getStartCaption(startDate,this.unitScale,true));
this.updatePopoverText(this.popoverEnd,this.getEndCaption(endDate,this.unitScale,true));
this.caption=this.getCaption(startDate,endDate,this.unitScale);
}
snapToUnit(date:Date,unitScale:number):Date {
var d = new Date(date.getTime() + (this.unitScales[this.unitScale]/2));
var offsetInMilliseconds =this.getUnitDateOffset(d,this.unitScale,0)
return new Date(d.getTime()+offsetInMilliseconds);
}
getEndDate(offsetInPixels:number):Date {
let oneUnit = this.unitScales[this.unitScale];
let offsetInMilliseconds = offsetInPixels * this.scale;
if(this.leftGripMove) {
if(this.startDate.getTime() + offsetInMilliseconds > this.endDate.getTime() - oneUnit) {
return this.snapToUnit(new Date(this.startDate.getTime() + offsetInMilliseconds + oneUnit),this.unitScale);
}
} else if(this.rightGripMove || this.rangeGripMove) {
return this.snapToUnit(new Date(this.endDate.getTime() + offsetInMilliseconds),this.unitScale);
}
return this.endDate;
}
getStartDate(offsetInPixels:number):Date {
let oneUnit = this.unitScales[this.unitScale];
let offsetInMilliseconds = offsetInPixels * this.scale;
if(this.leftGripMove || this.rangeGripMove) {
return this.snapToUnit(new Date(this.startDate.getTime() + offsetInMilliseconds),this.unitScale);
} else if(this.rightGripMove) {
if(this.endDate.getTime() + offsetInMilliseconds < this.startDate.getTime() + oneUnit) {
return this.snapToUnit(new Date(this.endDate.getTime() + offsetInMilliseconds - oneUnit),this.unitScale);
}
}
return this.startDate;
}
updateControl(event:MouseEvent|TouchEvent) {
let offsetInPixels = this.getClientX(event) - this.downX;
if(this.leftGripMove || this.rightGripMove || this.rangeGripMove) {
let startDate = this.getStartDate(offsetInPixels);
let endDate = this.getEndDate(offsetInPixels);
this.updateStyle(startDate,endDate)
this.changeDetectorRef.detectChanges();
} else if(this.viewPan) {
let offsetInMilliseconds = offsetInPixels*this.scale;
this.viewMinDate = new Date(this.viewMinDate.getTime()-offsetInMilliseconds);
this.viewMaxDate = new Date(this.viewMaxDate.getTime()-offsetInMilliseconds);
this.updateStyle(this.startDate,this.endDate);
this.redraw();
this.changeDetectorRef.detectChanges();
this.downX=this.getClientX(event);
}
this.lastOffsetInPixels=offsetInPixels
}
isMouseEvent(arg: any): arg is MouseEvent {
return arg.clientX !== undefined;
}
getClientX(event:MouseEvent|TouchEvent) {
if(this.isMouseEvent(event)) {
return (event as MouseEvent).clientX;
} else {
return (event as TouchEvent).touches[0].clientX;
}
}
handleRightGripMouseDown(event:MouseEvent) {
this.rightGripMove=true;
this.downX = this.getClientX(event);
this.popoverEnd.open(this.endCaption);
event.preventDefault();
}
handleRightGripMouseEnter(event:MouseEvent) {
this.mouseX=-1;
this.mouseY=-1;
this.redraw();
if(!this.rangeGripMove && !this.leftGripMove && !this.rightGripMove) this.popoverEnd.open(this.endCaption);
}
handleRightGripMouseLeave(event:MouseEvent) {
if(!this.rightGripMove) this.popoverEnd.close();
}
handleLeftGripMouseDown(event:MouseEvent|TouchEvent) {
this.leftGripMove=true;
this.downX = this.getClientX(event);
this.popoverStart.open(this.startCaption);
event.preventDefault();
}
handleLeftGripMouseEnter(event:MouseEvent|TouchEvent) {
this.mouseX=-1;
this.mouseY=-1;
this.redraw();
if(!this.rangeGripMove && !this.leftGripMove && !this.rightGripMove) this.popoverStart.open(this.startCaption);
}
handleLeftGripMouseLeave(event:MouseEvent) {
if(!this.leftGripMove) this.popoverStart.close();
}
handleRangeGripMouseEnter(event:MouseEvent) {
this.mouseX=-1;
this.mouseY=-1;
this.redraw();
}
handleRangeGripMouseDown(event:MouseEvent|TouchEvent) {
this.rangeGripMove=true;
this.downX = this.getClientX(event);
event.preventDefault();
}
handleViewPanMouseDown(event:MouseEvent|TouchEvent) {
this.viewPan=true;
this.downX =this.getClientX(event);
event.preventDefault();
}
handleMouseUp(event:MouseEvent|TouchEvent) {
//this.updateControl(event);
this.startDate = this.getStartDate(this.lastOffsetInPixels);
this.endDate = this.getEndDate(this.lastOffsetInPixels);
this.popoverStart.close();
this.popoverEnd.close();
this.startCaption={popoverCaption:this.getStartCaption(this.startDate,this.unitScale,true)};
this.endCaption={popoverCaption:this.getEndCaption(this.endDate,this.unitScale,true)};
if(this.leftGripMove || this.rightGripMove || this.rangeGripMove) {
this.change.emit({ startDate:this.startDate,endDate:this.endDate});
}
this.rightGripMove=false;
this.leftGripMove=false;
this.rangeGripMove=false;
this.viewPan = false;
this.lastOffsetInPixels=0;
}
handleMouseMove(event:MouseEvent) {
this.mouseX = -1;
this.mouseY = -1;
if(!this.leftGripMove && ! this.rightGripMove && !this.rangeGripMove && !this.viewPan) {
return;
} else {
this.updateControl(event);
}
}
handleCanvasMouseMove(event:MouseEvent) {
this.mouseX = event.offsetX;
this.mouseY = event.offsetY;
this.redraw();
}
handleCanvasMouseLeave(event:MouseEvent) {
this.mouseX = -1;
this.mouseY = -1;
this.redraw();
}
canZoom(currentScale:number, direction:number):boolean {
let nextScale=currentScale;
if(direction<0 ) {
return true;
} else {
nextScale*=1.1;
let canZoom=false;
let oneUnit = (this.getUnitDateOffset(this.viewMinDate,8,1)- this.getUnitDateOffset(this.viewMinDate,8,0)) / nextScale;
let unitTextWidth=this.getUnitTextWidth(8);
let steps=this.getSteps(8);
let s=0;
let step=steps[s];
let steppedOneUnit=oneUnit*step;
while(unitTextWidth > (steppedOneUnit-(2*this.padding)) && s < steps.length -1) {
step=steps[++s];
steppedOneUnit=oneUnit*step;
}
return unitTextWidth < (steppedOneUnit-(2*this.padding)) && s < steps.length;
}
}
handleMouseWheel(event:WheelEvent) {
if(!this.canZoom(this.scale,event.deltaY)) return;
let oldOffsetInMilliseconds = event.clientX * this.scale;
if(event.deltaY>=0)
this.scale*=1.1;
else
this.scale/=1.1;
this.posibleUnits=this.getPosibleUnits(this.scale);
this.height=this.getHeight();
this.changeDetectorRef.detectChanges();
this.setCanvasSize();
let newOffsetInMilliseconds = event.clientX * this.scale;
let offsetInMilliseconds = newOffsetInMilliseconds-oldOffsetInMilliseconds;
this.viewMinDate = new Date(this.viewMinDate.getTime()-offsetInMilliseconds);
this.viewMaxDate = new Date(this.viewMaxDate.getTime()-offsetInMilliseconds);
this.updateStyle(this.startDate,this.endDate);
this.redraw();
this.changeDetectorRef.detectChanges();
}
handleZoomOut() {
if(!this.canZoom(this.scale,1)) return;
this.scale*=1.1;
this.posibleUnits=this.getPosibleUnits(this.scale);
this.height=this.getHeight();
this.setCanvasSize();
this.redraw();
this.updateStyle(this.startDate,this.endDate);
}
handleZoomIn() {
if(!this.canZoom(this.scale,-1)) return;
this.scale/=1.1;
this.posibleUnits=this.getPosibleUnits(this.scale);
this.height=this.getHeight();
this.setCanvasSize();
this.redraw();
this.updateStyle(this.startDate,this.endDate);
}
handleResize(event:any) {
if(this.initialized) {
this.setCanvasSize();
this.updateStyle(this.startDate,this.endDate);
this.redraw();
}
}
ngOnChanges (changes: SimpleChanges) {
if(this.initialized) {
this.setCanvasSize();
this.updateStyle(this.startDate,this.endDate);
this.redraw();
}
}
}

View File

@@ -0,0 +1,116 @@
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';
import { Store, Action } from '@ngrx/store';
import { Effect, Actions,ofType } from '@ngrx/effects';
import { Observable , defer , of } from 'rxjs';
import { withLatestFrom,mergeMap,switchMap,map,catchError} from 'rxjs/operators';
import * as appCommonActions from '../actions/app-common.actions';
import * as appCommonReducers from '../reducers/app-common.reducer';
import { ItemService } from '../services/item.service';
import { FolderService } from '../services/folder.service';
import { UserService } from '../services/user.service';
import { IItemTypes } from '../models/item.types';
import { IListItem } from '../models/list.item';
import { IUser } from '../models/user';
@Injectable()
export class AppCommonEffects {
@Effect({ dispatch: false })
login$: Observable<Action> = this.actions$.pipe(
ofType(appCommonActions.LOGIN),
withLatestFrom(this.store$.select(appCommonReducers.selectGetInitialized)),
mergeMap(([action, initialized]) => {
var a = (action as appCommonActions.Login);
this.oauthService$.initImplicitFlow(a.url);
return [];
}));
@Effect()
loadItemTypes$: Observable<Action> = this.actions$.pipe(
ofType(appCommonActions.LOADITEMTYPES),
switchMap((action) => {
return this.itemService$.getItemTypes().pipe(
map((itemTypes: IItemTypes) => new appCommonActions.LoadItemTypesSuccess(itemTypes)),
catchError(error => of(new appCommonActions.Fail(error))))
}
));
@Effect()
initUser$: Observable<Action> = this.actions$.pipe(
ofType(appCommonActions.INITUSER),
switchMap(() => {
return this.userService$.getCurrentUser().pipe(
map((user: IUser) => new appCommonActions.InitUserSuccess(user)),
catchError(error => of(new appCommonActions.Fail(error))))
}
));
@Effect()
initUserSuccess$: Observable<Action> = this.actions$.pipe(
ofType(appCommonActions.INITUSERSUCCESS),
switchMap(() => {
return of(new appCommonActions.InitRoot());
}
));
@Effect()
initRoot$: Observable<Action> = this.actions$.pipe(
ofType(appCommonActions.INITROOT),
switchMap(() => {
return this.folderService$.getMyRoots().pipe(
map((folders: IListItem[]) => new appCommonActions.InitRootSuccess(folders)),
catchError(error => of(new appCommonActions.Fail(error))))
}
));
@Effect()
deleteItems$: Observable<Action> = this.actions$.pipe(
ofType(appCommonActions.DELETEITEMS),
switchMap((action:appCommonActions.DeleteItems) => {
return this.itemService$.deleteItems(action.itemCodes).pipe(
map((deletedItemCodes: string[]) => new appCommonActions.DeleteItemsSuccess(deletedItemCodes)),
catchError(error => of(new appCommonActions.Fail(error))))
}
));
@Effect()
editItem$: Observable<Action> = this.actions$.pipe(
ofType(appCommonActions.EDITITEM),
withLatestFrom(this.store$.select(appCommonReducers.selectGetItemTypes)),
switchMap(([action, itemtypes]) => {
var a = action as appCommonActions.EditItem;
var itemType = itemtypes[a.item.itemType];
var editor = itemType.editor ? itemType.editor : "property";
this.router$.navigate(['/editor',editor,'item', a.item.code])
return [];
}
));
@Effect()
viewItem$: Observable<Action> = this.actions$.pipe(
ofType(appCommonActions.VIEWITEM),
withLatestFrom(this.store$.select(appCommonReducers.selectGetItemTypes)),
switchMap(([action, itemtypes]) => {
var a = action as appCommonActions.EditItem;
var itemType = itemtypes[a.item.itemType];
var viewer = itemType.viewer;
this.router$.navigate(['/viewer', viewer, 'item', a.item.code])
return [];
}
));
@Effect({ dispatch: false })
fail$: Observable<Action> = this.actions$.pipe(
ofType(appCommonActions.FAIL),
map((action) => {
let failAction = action as appCommonActions.Fail;
console.log(failAction.payload)
return null;
}));
constructor(private actions$: Actions, private store$: Store<appCommonReducers.State>, private oauthService$: OAuthService, private itemService$: ItemService, private folderService$:FolderService, private userService$: UserService, private router$: Router) {
store$.dispatch(new appCommonActions.LoadItemTypes());
}
}

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,6 @@
export interface IEventMessage {
eventType: string;
parentCode: string;
itemCode: string;
attributes: any;
}

View File

@@ -0,0 +1,28 @@
import { IListItem } from './list.item';
export interface IItem extends IListItem {
parentCode?: string;
geometry?: any;
tags:string[],
data?:any
}
export class Item implements IItem {
public code?:string;
public parentCode?:string;
public tags:string[];
public geometry?:any;
public url?: string;
public name?: string;
public created?: Date;
public updated?: Date;
public dataDate?: Date;
public itemType?: string;
public sourceTask?: string;
public size?: number;
public state?: number;
public data?:any;
constructor() {
}
}

View File

@@ -0,0 +1,7 @@
export interface IItemType {
icon?: string;
viewer?: string;
editor?: string;
isFolder?: boolean;
iconColor?: string;
}

View File

@@ -0,0 +1,5 @@
import { IItemType } from './item.type';
export interface IItemTypes{
[id: string]: IItemType;
};

View File

@@ -0,0 +1,15 @@
export interface IItemTask {
code?: string;
taskType?: string;
attributes?:any
}
export class ItemTask implements IItemTask {
public code?:string;
public taskType?: string;
public attributes?: any;
constructor() {
}
}

View File

@@ -0,0 +1,13 @@
export interface IListItem {
url?: string;
code?: string;
name?: string;
created?: Date;
updated?: Date;
dataDate?: Date;
itemType?: string;
sourceTask?: string;
size?: number;
state?: number;
thumbnail?: boolean;
}

View File

@@ -0,0 +1,4 @@
export interface ITypeaheadItem {
name: string;
type: string;
}

View File

@@ -0,0 +1,5 @@
export interface IUser {
code?: string;
name?: string;
email?: string;
}

View File

@@ -0,0 +1 @@
export const MODULE_NAME = "FarmMapsCommon";

View File

@@ -0,0 +1,65 @@
import { tassign } from 'tassign';
import { IItemTypes} from '../models/item.types';
import { IListItem } from '../models/list.item';
import { IUser } from '../models/user';
import * as appCommonActions from '../actions/app-common.actions';
import { createSelector, createFeatureSelector, ActionReducerMap } from '@ngrx/store';
import { MODULE_NAME } from '../module-name';
export interface State {
openedModalName: string,
initialized: boolean,
rootItems: IListItem[],
itemTypes: IItemTypes,
user:IUser
}
export const initialState: State = {
openedModalName: null,
initialized: false,
rootItems: [],
itemTypes: {},
user:null
}
export function reducer(state = initialState, action: appCommonActions.Actions ): State {
switch (action.type) {
case appCommonActions.INITUSERSUCCESS: {
let a = action as appCommonActions.InitUserSuccess;
return tassign(state, { user: a.user });
}
case appCommonActions.INITROOTSUCCESS: {
let a = action as appCommonActions.InitRootSuccess;
return tassign(state, { rootItems:a.items});
}
case appCommonActions.OPENMODAL: {
return tassign(state, { openedModalName: action.modalName });
}
case appCommonActions.CLOSEMODAL: {
return tassign(state, { openedModalName: null });
}
case appCommonActions.INITIALIZED: {
return tassign(state, { initialized: true });
}
case appCommonActions.LOADITEMTYPESSUCCESS: {
let a = action as appCommonActions.LoadItemTypesSuccess;
return tassign(state, { itemTypes: a.itemTypes });
}
default: {
return state;
}
}
}
export const getOpenedModalName = (state: State) => state.openedModalName;
export const getInitialized = (state: State) => state.initialized;
export const getItemTypes = (state: State) => state.itemTypes;
export const getRootItems = (state: State) => state.rootItems;
export const selectAppCommonState = createFeatureSelector<State>(MODULE_NAME);
export const selectOpenedModalName = createSelector(selectAppCommonState, getOpenedModalName);
export const selectGetInitialized = createSelector(selectAppCommonState, getInitialized);
export const selectGetItemTypes = createSelector(selectAppCommonState, getItemTypes);
export const selectGetRootItems = createSelector(selectAppCommonState, getRootItems);

View File

@@ -0,0 +1,58 @@
import { Injectable } from '@angular/core';
import {
CanActivate, Router, CanLoad, Route, CanActivateChild ,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import { Store } from '@ngrx/store';
import { OAuthService } from 'angular-oauth2-oidc';
import * as appCommonReducer from '../reducers/app-common.reducer'
import * as appCommonActions from '../actions/app-common.actions';
@Injectable()
export class AuthGuard implements CanActivate, CanLoad, CanActivateChild {
private loginDispatched = false;
private initialized = false;
constructor(private oauthService: OAuthService, private router: Router, private store: Store<appCommonReducer.State> ) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
canLoad(route: Route): boolean {
return this.checkLogin(route.path);
}
checkLogin(url: string): boolean {
if (!this.oauthService.hasValidAccessToken()) {
if (!this.loginDispatched) {
this.oauthService.silentRefresh().then(info => {
this.router.navigateByUrl(url);
}).catch(error => {
this.loginDispatched = true;
this.store.dispatch(new appCommonActions.Login(url));
})
}
return false;
} else {
if (!this.initialized) {
this.initialized = true;
this.store.dispatch(new appCommonActions.InitUser());
}
return true;
}
}
}

View File

@@ -0,0 +1,14 @@
import { Component, Injectable } from '@angular/core';
import { NgbDateAdapter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
@Injectable()
export class NgbDateNativeAdapter extends NgbDateAdapter<Date> {
fromModel(date: Date): NgbDateStruct {
return (date && date.getFullYear) ? {year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate()} : null;
}
toModel(date: NgbDateStruct): Date {
return date ? new Date(Date.UTC(date.year, date.month - 1, date.day)) : null;
}
}

View File

@@ -0,0 +1,29 @@
import { Injectable } from '@angular/core';
import { IEventMessage } from '../models/event.message';
import { Subject } from 'rxjs';
import { OAuthService } from 'angular-oauth2-oidc';
import { HubConnection, HubConnectionBuilder, LogLevel } from '@aspnet/signalr';
import { AppConfig } from "../shared/app.config";
@Injectable()
export class EventService {
public event:Subject <IEventMessage> = new Subject<IEventMessage>();
private _connection: HubConnection = null;
private _apiEndPoint: string;
constructor(private oauthService: OAuthService, private appConfig: AppConfig) {
this._apiEndPoint = appConfig.getConfig("apiEndPoint");
this._connection = new HubConnectionBuilder().withUrl(`${ this._apiEndPoint}/eventHub`).configureLogging(LogLevel.Information).build();
this._connection.start().then(() => {
var accessToken = oauthService.getAccessToken();
if (accessToken) {
this._connection.send('authenticate', oauthService.getAccessToken());
}
});
this._connection.on('event', eventMessage => {
this.event.next(eventMessage);
});
}
}

View File

@@ -0,0 +1,54 @@
import { Injectable } from '@angular/core';
import { Observable , Observer } from 'rxjs';
import {map} from 'rxjs/operators';
import { IListItem } from '../models/list.item';
import { IItem } from '../models/item';
import { HttpClient } from "@angular/common/http";
import { AppConfig } from "../shared/app.config";
@Injectable()
export class FolderService {
constructor(public httpClient: HttpClient, public appConfig: AppConfig) {
}
ApiEndpoint() {
return this.appConfig.getConfig("apiEndPoint");
}
parseDates(item: any): IListItem {
item.created = new Date(Date.parse(item.created));
item.updated = new Date(Date.parse(item.updated));
item.dataDate = new Date(Date.parse(item.dataDate));
return item;
}
getFolder(code: string): Observable<IListItem> {
return this.httpClient.get<IListItem>(`${this.ApiEndpoint()}/api/v1/folders/${code}`).pipe(map(i => this.parseDates(i)));
}
getMyRoots(): Observable<IListItem[]> {
return this.httpClient.get<IListItem[]>(`${this.ApiEndpoint()}/api/v1/folders/my_roots`).pipe(map(ia => ia.map(i => this.parseDates(i))));
}
getFolderParents(code: string): Observable<IListItem[]> {
return this.httpClient.get<IListItem[]>(`${this.ApiEndpoint()}/api/v1/folders/${code}/parents`).pipe(map(ia => ia.map(i => this.parseDates(i))));
}
getChildFolders(code: string): Observable<IListItem[]> {
return this.httpClient.get<IListItem[]>(`${this.ApiEndpoint()}/api/v1/folders/${code}/listfolders`).pipe(map(ia => ia.map(i => this.parseDates(i))));
}
getItems(code: string,skip:number, take:number): Observable<IListItem[]> {
return this.httpClient.get<IListItem[]>(`${this.ApiEndpoint()}/api/v1/folders/${code}/list?skip=${skip}&take=${take}`).pipe(map(ia => ia.map(i => this.parseDates(i))));
}
moveItem(itemCode: string, newParentCode: string): Observable<IListItem> {
const body = { itemCode: itemCode,newParentCode: newParentCode };
return this.httpClient.post<IListItem>(`${this.ApiEndpoint()}/api/v1/items/move`, body).pipe(map(i => this.parseDates(i)));
}
createFolder(folder: IItem): Observable<IListItem> {
return this.httpClient.post<IListItem>(`${this.ApiEndpoint()}/api/v1/folders/`, folder).pipe(map(i => this.parseDates(i)));
}
}

View File

@@ -0,0 +1,20 @@
import { Injectable } from '@angular/core';
import { CanLoad, Route, CanActivate, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import { Store } from '@ngrx/store';
import * as appCommonReducer from '../reducers/app-common.reducer'
import * as appCommonActions from '../actions/app-common.actions';
@Injectable()
export class FullScreenGuard implements CanActivate {
private loginDispatched = false;
constructor(private store: Store<appCommonReducer.State> ) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
this.store.dispatch(new appCommonActions.FullScreen());
return true;
}
}

View File

@@ -0,0 +1,124 @@
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { IItemType } from '../models/item.type';
import { IItem } from '../models/item';
import { IItemTask } from '../models/itemTask';
import { HttpClient, HttpParams } from "@angular/common/http";
import { AppConfig } from "../shared/app.config";
@Injectable()
export class ItemService {
constructor(public httpClient: HttpClient, public appConfig: AppConfig) {
}
ApiEndpoint() {
return this.appConfig.getConfig("apiEndPoint");
}
parseDates(item: any): IItem {
item.created = new Date(Date.parse(item.created));
item.updated = new Date(Date.parse(item.updated));
item.dataDate = new Date(Date.parse(item.dataDate));
return item;
}
getItemTypes(): Observable<{ [id: string]: IItemType }> {
return this.httpClient.get<{ [id: string]: IItemType }>(`${this.ApiEndpoint()}/api/v1/itemtypes/`);
}
getFeatures(extent: number[], crs: string, searchText?: string, searchTags?:string,startDate?:Date,endDate?:Date,itemType?:string,parentCode?:string,dataFilter?:string,level?:number): Observable<any> {
var params = new HttpParams();
params = params.append("bbox", extent.join(","));
params = params.append("crs", crs);
if (searchText) params = params.append("q", searchText);
if (searchTags) params = params.append("t", searchTags);
if (startDate) params = params.append("sd", startDate.toISOString());
if (endDate) params = params.append("ed", endDate.toISOString());
if (itemType) params = params.append("it", itemType);
if (parentCode) params = params.append("pc", parentCode);
if (dataFilter) params = params.append("df", dataFilter);
if (level) params = params.append("lvl", dataFilter);
return this.httpClient.get<any>(`${this.ApiEndpoint()}/api/v1/items/features/`, {params:params});
}
getFeature(code:string, crs: string): Observable<any> {
var params = new HttpParams();
params = params.append("crs", crs);
return this.httpClient.get<any>(`${this.ApiEndpoint()}/api/v1/items/${code}/feature/`, { params: params });
}
getItem(code: string): Observable<IItem> {
return this.httpClient.get<IItem>(`${this.ApiEndpoint()}/api/v1/items/${code}`).pipe(map(i => this.parseDates(i)));
}
getItemByCodeAndType(code: string, itemType: string): Observable<IItem> {
return this.httpClient.get<IItem>(`${this.ApiEndpoint()}/api/v1/items/${code}/${itemType}`);
}
getItemList(itemType: string, dataFilter?: any, level: number = 1): Observable<IItem[]> {
var params = new HttpParams();
params = params.append("it", itemType);
if(dataFilter != null){
params = params.append("df", JSON.stringify(dataFilter));
}
params = params.append("lvl", itemType);
return this.httpClient.get<IItem[]>(`${this.ApiEndpoint()}/api/v1/items/`, { params: params }).pipe(map(ia => ia.map(i => this.parseDates(i))));
}
getChildItemList(parentcode: string, itemType: string, dataFilter?: any, level: number = 1): Observable<IItem[]> {
var params = new HttpParams();
params = params.append("it", itemType);
if (dataFilter != null) {
params = params.append("df", JSON.stringify(dataFilter));
}
params = params.append("lvl", level.toString());
return this.httpClient.get<IItem[]>(`${this.ApiEndpoint()}/api/v1/items/${parentcode}/children`, { params: params });
}
getChildItemListByExtent(parentcode: string, itemType: string, extent: number[], crs: string, dataFilter?: any, level: number = 1): Observable<IItem[]> {
var params = new HttpParams();
params = params.append("it", itemType);
params = params.append("bbox", extent.join(","));
params = params.append("crs", crs);
if (dataFilter != null) {
params = params.append("df", JSON.stringify(dataFilter));
}
params = params.append("lvl", level.toString());
return this.httpClient.get<IItem[]>(`${this.ApiEndpoint()}/api/v1/items/${parentcode}/children`, { params: params });
}
getItemFeatures(code: string, extent: number[], crs: string, layerIndex?:number): Observable<any> {
var params = new HttpParams();
params = params.append("bbox", extent.join(","));
params = params.append("crs", crs);
if(layerIndex!=null)
return this.httpClient.get<any>(`${this.ApiEndpoint()}/api/v1/items/${code}/features/layer/${layerIndex}`, { params: params });
else
return this.httpClient.get<any>(`${this.ApiEndpoint()}/api/v1/items/${code}/features`, { params: params });
}
putItem(item:IItem): Observable<IItem> {
return this.httpClient.put<IItem>(`${this.ApiEndpoint()}/api/v1/items/${item.code}`,item);
}
deleteItems(itemCodes:string[]): Observable<any> {
return this.httpClient.post<any>(`${this.ApiEndpoint()}/api/v1/items/delete`, itemCodes);
}
getTemporalLast(code: string): Observable<any> {
return this.httpClient.get<any>(`${this.ApiEndpoint()}/api/v1/items/${code}/temporal/last`);
}
getTemporal(code: string, startDate?: Date, endDate?: Date): Observable<any> {
var params = new HttpParams();
if (startDate) params = params.append("sd", startDate.toISOString());
if (endDate) params = params.append("ed", endDate.toISOString());
return this.httpClient.get<any>(`${this.ApiEndpoint()}/api/v1/items/${code}/temporal/`, { params: params });
}
postItemTask(item: IItem, task: IItemTask): Observable<IItemTask> {
return this.httpClient.post<IItemTask>(`${this.ApiEndpoint()}/api/v1/items/${item.code}/tasks`, task);
}
}

View File

@@ -0,0 +1,39 @@
import { Component, Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import * as appCommonReducer from '../reducers/app-common.reducer'
import {IItemTypes} from '../models/item.types'
import {IItem} from '../models/item'
@Injectable()
export class ItemTypeService {
public itemTypes: IItemTypes;
constructor(private store: Store<appCommonReducer.State> ) {
this.store.select(appCommonReducer.selectGetItemTypes).subscribe((itemTypes) => {
this.itemTypes = itemTypes;
});
}
getIcon(itemType: string) {
var icon = "fa fa-file-o";
if (this.itemTypes[itemType]) icon = this.itemTypes[itemType].icon;
return icon;
}
getColor(itemType: string) {
var color = "#000000";
if (this.itemTypes[itemType]) color = this.itemTypes[itemType].iconColor;
return color;
}
hasViewer(item: IItem) {
let itemType: string = item.itemType;
if (this.itemTypes[itemType]) return this.itemTypes[itemType].viewer !== undefined;
return false;
}
isLayer(item: IItem) {
let itemType: string = item.itemType;
return itemType == "vnd.farmmaps.itemtype.geotiff.processed" || itemType == "vnd.farmmaps.itemtype.layer" || itemType == "vnd.farmmaps.itemtype.shape.processed";
}
}

View File

@@ -0,0 +1,20 @@
import { Injectable } from '@angular/core';
import { CanLoad, Route, CanActivate, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Store } from '@ngrx/store';
import * as appCommonReducer from '../reducers/app-common.reducer'
import * as appCommonActions from '../actions/app-common.actions';
@Injectable()
export class NavBarGuard implements CanActivate {
private loginDispatched = false;
constructor(private store: Store<appCommonReducer.State>) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
this.store.dispatch(new appCommonActions.ShowNavBar());
return true;
}
}

View File

@@ -0,0 +1,73 @@
import { Injectable } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Observable , Observer } from 'rxjs';
import { ITypeaheadItem } from '../models/typeahead.item';
@Injectable()
export class TimespanService {
constructor(private datePipe: DatePipe) {
}
unitScales: number[] = [1, 1000, 1000 * 60, 1000 * 60 * 60, 1000 * 60 * 60 * 24, 1000 * 60 * 60 * 24 * 7, 1000 * 60 * 60 * 24 * 31, 1000 * 60 * 60 * 24 * 31 * 3, 1000 * 60 * 60 * 24 * 365.25];
units: string[] = ['millisecond', 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'];
quarters: string[] = ['KW1', 'KW2', 'KW3', 'KW4'];
getStartEndCaption(date: Date, otherDate: Date, unitScale: number, suffix: boolean = false, extended: boolean = true): string {
let showSuffix = false;
otherDate = new Date(otherDate.getTime() - 1); // fix year edge case
if (unitScale == 3) {
let format = "HH:00";
if (extended) {
if (suffix || date.getFullYear() != otherDate.getFullYear())
format = "d MMM yyyy:HH:00";
else if (date.getMonth() !== otherDate.getMonth())
format = "d MMM HH:00";
}
return this.datePipe.transform(date, format);
}
if (unitScale == 4) {
let format = "d";
if (extended) {
if (suffix || date.getFullYear() != otherDate.getFullYear())
format = "d MMM yyyy";
else if (date.getMonth() !== otherDate.getMonth())
format = "d MMM"
}
return this.datePipe.transform(date, format);
}
if (unitScale == 6) {
let format = "MMM";
if (extended) {
if (suffix || date.getFullYear() != otherDate.getFullYear())
format = "MMM yyyy";
}
return this.datePipe.transform(date, format);
}
if (unitScale == 7) {
let q = Math.trunc(date.getMonth() / 3);
return this.quarters[q];
}
if (unitScale == 8) {
return this.datePipe.transform(date, "yyyy");
}
return "";
}
getStartCaption(startDate: Date, endDate: Date, unitScale: number, suffix: boolean = false, extended: boolean = true): string {
return this.getStartEndCaption(new Date(startDate.getTime() + (this.unitScales[unitScale] / 2)), endDate, unitScale, suffix, extended);
}
getEndCaption(startDate: Date,endDate: Date, unitScale: number, suffix: boolean = true): string {
return this.getStartEndCaption(new Date(endDate.getTime() - (this.unitScales[unitScale] / 2)), startDate, unitScale, suffix);
}
getCaption(startDate: Date, endDate: Date, unitScale: number): string {
let startCaption = this.getStartCaption(startDate, endDate, unitScale);
let endCaption = this.getEndCaption(startDate,endDate, unitScale);
if ((endDate.getTime() - startDate.getTime()) < (1.5 * this.unitScales[unitScale]))
return endCaption;
return `${startCaption}-${endCaption}`;
}
}

View File

@@ -0,0 +1,23 @@
import { Injectable } from '@angular/core';
import { Observable , Observer } from 'rxjs';
import { ITypeaheadItem } from '../models/typeahead.item';
import { HttpClient, HttpParams } from "@angular/common/http";
import { AppConfig } from "../shared/app.config";
@Injectable()
export class TypeaheadService {
constructor(public httpClient: HttpClient, public appConfig: AppConfig) {
}
ApiEndpoint() {
return this.appConfig.getConfig("apiEndPoint");
}
getSearchTypeaheadItems(searchText:string,skip:number = 0,take:number = 10): Observable<ITypeaheadItem[]> {
return this.httpClient.get<ITypeaheadItem[]>(`${this.ApiEndpoint()}/api/v1/typeahead/search/?q=${searchText}&skip=${skip}&take=${take}`);
}
getTagTypeaheadItems(searchText: string, skip: number = 0, take: number = 10): Observable<ITypeaheadItem[]> {
return this.httpClient.get<ITypeaheadItem[]>(`${this.ApiEndpoint()}/api/v1/typeahead/tag/?q=${searchText}&skip=${skip}&take=${take}`);
}
}

View File

@@ -0,0 +1,19 @@
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { IUser } from '../models/user';
import { HttpClient } from "@angular/common/http";
import { AppConfig } from "../shared/app.config";
@Injectable()
export class UserService {
constructor(public httpClient: HttpClient, public appConfig: AppConfig) {
}
ApiEndpoint() {
return this.appConfig.getConfig("apiEndPoint");
}
getCurrentUser(): Observable<IUser> {
return this.httpClient.get<IUser>(`${this.ApiEndpoint()}/api/v1/currentuser`);
}
}

View File

@@ -0,0 +1,47 @@
import { Injectable, Injector, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common'
import { AppConfig } from "./app.config";
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { OAuthService } from 'angular-oauth2-oidc';
import { Observable } from 'rxjs';
@Injectable()
export class AccessTokenInterceptor implements HttpInterceptor {
private oauthService: OAuthService = null;
private audience: string[] = [];
private base: string;
constructor(private injector: Injector, private appConfig: AppConfig, @Inject(DOCUMENT) private document: any) {
this.base = document.location.href;
}
hasAudience(url: string): boolean {
let u = new URL(url,this.base);
for (let audience of this.audience) {
if (u.href.startsWith(audience)) return true;
}
return false;
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.oauthService && this.hasAudience(request.url)) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.oauthService.getAccessToken()}`
}
// Please uncomment the next line if you need to connect to the backend running in Docker.
//, url: `http://localhost:8082${request.url}`
});
} else {
this.oauthService = this.injector.get(OAuthService, null);
if(this.oauthService && this.oauthService.issuer) this.audience = (this.appConfig.getConfig("audience") as string).split(",");
}
return next.handle(request);
}
}

View File

@@ -0,0 +1,61 @@
import { Injector } from '@angular/core';
import { Router,UrlSerializer } from '@angular/router';
import { AuthConfig, OAuthService, JwksValidationHandler, OAuthErrorEvent } from 'angular-oauth2-oidc';
import { AppConfig } from "./app.config";
function getAuthConfig(appConfig: AppConfig): AuthConfig {
let authConfig: AuthConfig = new AuthConfig();
authConfig.issuer = appConfig.getConfig("issuer");
authConfig.redirectUri = window.location.origin + "/cb";
authConfig.silentRefreshRedirectUri = window.location.origin + "/silent-refresh.html";
authConfig.clientId = appConfig.getConfig("clientId");
authConfig.customQueryParams = { audience: appConfig.getConfig("audience") };
authConfig.scope = "openid profile email";
authConfig.oidc = true;
authConfig.disableAtHashCheck = true;
authConfig.requireHttps = appConfig.getConfig("requireHttps");
return authConfig;
}
export function appConfigFactory(injector:Injector, appConfig: AppConfig, oauthService: OAuthService): () => Promise<any> {
return (): Promise<any> => {
return appConfig.load().then(() => {
oauthService.events.subscribe((event) => {
console.log(event.type);
if (event.type == 'token_error' || event.type == 'silent_refresh_timeout') {
let e = event as OAuthErrorEvent;
let p = e.params as any;
if (event.type == 'silent_refresh_timeout' || (p.error && p.error == 'login_required')) {
let router = injector.get(Router);
console.log("Session expired");
router.navigate(['loggedout'], { queryParams: { redirectTo: router.url } });
}
}
});
oauthService.configure(getAuthConfig(appConfig));
oauthService.tokenValidationHandler = new JwksValidationHandler();
oauthService.tokenValidationHandler.validateAtHash = function () {
return new Promise<boolean>((res) => { res(true); })
};
oauthService.setupAutomaticSilentRefresh();
let router = injector.get(Router);
var urlTree = router.parseUrl(window.location.href);
var urlPath = window.location.pathname;
oauthService.loadDiscoveryDocument().then(() => {
oauthService.tryLogin({
onTokenReceived: (info) => {
urlPath = info.state;
}
}).then(() => {
let router = injector.get(Router);
if (!oauthService.hasValidAccessToken()) {
oauthService.initImplicitFlow(urlPath);
} else {
router.navigateByUrl(urlPath);
}
});
})
});
}
}

View File

@@ -0,0 +1,33 @@
import {Inject, Injectable} from '@angular/core';
import {HttpClient, HttpXhrBackend} from '@angular/common/http';
import {Observable} from 'rxjs';
@Injectable()
export class AppConfig {
private config: Object = null;
private httpClient: HttpClient;
constructor(xhrBackend: HttpXhrBackend) {
this.httpClient = new HttpClient(xhrBackend);
this.config = null;
}
public getConfig(key: any) {
if (!this.config.hasOwnProperty(key)) {
console.log(`Config key ${key} not set`);
}
return this.config[key];
}
public load(): Promise<any> {
return this.httpClient.get('/configuration.json')
.toPromise()
.then(data => {
this.config = data;
//return data;
})
.catch(error => this.config = null);
};
}

View File

@@ -0,0 +1,13 @@
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}