38 Commits

Author SHA1 Message Date
719c699981 Merge branch 'feature/AW784_MergeFarmMapsMap_FarmMapsLibMap' into develop
Some checks failed
FarmMaps.Develop/FarmMapsLib/develop There was a failure building this commit
2019-12-20 09:59:04 +01:00
456628d014 AW-784 Reapply from Farmmaps commits
- cd035366: AW-718 Layout as requested by Thomas.
2019-12-20 09:53:22 +01:00
76a44a8f95 AW-784 Reapply from Farmmaps commits
- cd035366: AW-718 Layout as requested by Thomas.
2019-12-20 09:50:21 +01:00
f66428d04c AW-784 Reapply from Farmmaps commits
- cd035366: AW-718 Layout as requested by Thomas.
2019-12-20 09:47:33 +01:00
ee925d07b4 AW-784 Reapply from Farmmaps commits
- 47deb5f6: AW-772 Panels
2019-12-20 09:41:06 +01:00
9b03b49028 AW-784 Reapply from Farmmaps commits
- 47deb5f6: AW-772 Panels
2019-12-20 09:39:29 +01:00
15c224ff5d AW-784 Reapply from Farmmaps commits
- 5d11bfe8: Enable histogram for shape
2019-12-20 09:36:55 +01:00
7cb129dbc4 AW-784 Reapply from Farmmaps commits
- cd035366: AW-718 Layout as requested by Thomas.
2019-12-20 09:25:09 +01:00
2059b48abb AW-784 Reapply from Farmmaps commits
- a4bb051a: AW-738 fixed bug
2019-12-20 09:19:53 +01:00
e1ff44ed3c AW-784 Reapply from Farmmaps commits
- 6f79b625: AW-738 changed selected-item-container to allow forSourceTask annotation.
2019-12-20 09:18:00 +01:00
Willem Dantuma
709c76a851 Hack for cordova
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-12-19 18:29:44 +01:00
Willem Dantuma
677608c14d Fix configuration loading
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-12-19 17:03:10 +01:00
Willem Dantuma
fd8025c674 Update sample app
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-12-19 13:41:59 +01:00
Willem Dantuma
560c426bc0 Refactor authconfig
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-12-19 13:32:51 +01:00
Willem Dantuma
e1fef2d7f3 Show histogram
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-12-18 10:21:25 +01:00
Willem Dantuma
f44b079cde Fix thumbnail source
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-12-11 18:03:37 +01:00
Willem Dantuma
8e5383b0f2 Update deps
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-12-11 10:47:32 +01:00
Willem Dantuma
615872992f Implement device update event
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-12-11 10:29:47 +01:00
Willem Dantuma
2e0b090fb7 Added deviceUpdateEvent
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-12-10 18:14:48 +01:00
Willem Dantuma
5d7fd63adc Oops remember to test it next time..
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-29 12:52:18 +01:00
Willem Dantuma
0948bacaaf Merge latest changes
Some checks failed
FarmMaps.Develop/FarmMapsLib/develop There was a failure building this commit
2019-11-29 12:24:34 +01:00
8fd653afbc AW-698 Round percentage "Uploading files".
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-29 09:18:35 +01:00
b058cb80b1 AW-716 Spacing
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-29 09:17:45 +01:00
Willem Dantuma
490ae1868b Update README
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-25 16:22:55 +01:00
Willem Dantuma
4384fd1387 Update example to angular 8.2 and ol 6
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-25 15:52:02 +01:00
Willem Dantuma
529b1c9bd7 Upgrade @farmmaps/common-map to angular 8.2
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-25 15:31:42 +01:00
Willem Dantuma
fc84548d8a Oops forgot ng build
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-25 14:49:46 +01:00
Willem Dantuma
e57b8297c0 Disable common-map temporarily
Some checks failed
FarmMaps.Develop/FarmMapsLib/develop There was a failure building this commit
2019-11-25 14:47:20 +01:00
Willem Dantuma
efe38aba62 Update @farmmaps/common to angular 8.2
Some checks failed
FarmMaps.Develop/FarmMapsLib/develop There was a failure building this commit
2019-11-25 14:43:26 +01:00
Willem Dantuma
7bd5dada2b Update to angular 8.2 2019-11-25 14:34:51 +01:00
Willem Dantuma
16db063339 Make bbox optional
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-18 09:42:05 +01:00
Willem Dantuma
5d79dcc7b6 Update library versions
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-13 11:46:23 +01:00
Willem Dantuma
deda769e8b Add service module
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-12 22:50:57 +01:00
Willem Dantuma
f31e4154b2 Fix date parsing for lists
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-12 16:27:08 +01:00
Willem Dantuma
7476e4c928 Set configuration correctly
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-11 17:38:49 +01:00
Willem Dantuma
d5258b7c79 Update versions
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-11 15:42:50 +01:00
Willem Dantuma
04929a1ca3 Removed index.ts files
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
2019-11-11 15:39:19 +01:00
Willem Dantuma
67e0e5ed5d Use label instead of value if it is available 2019-11-11 11:08:23 +01:00
67 changed files with 9957 additions and 7221 deletions

View File

@@ -1,47 +1,47 @@
pipeline { pipeline {
agent any agent any
environment { environment {
PACKAGE_VERSION_PREFIX=sh(script: 'jq .version package.json |sed "s/\\"//g"', returnStdout: true).trim() PACKAGE_VERSION_PREFIX=sh(script: 'jq .version package.json |sed "s/\\"//g"', returnStdout: true).trim()
PACKAGE_VERSION="${PACKAGE_VERSION_PREFIX + '-prerelease.' + env.BUILD_NUMBER}" PACKAGE_VERSION="${PACKAGE_VERSION_PREFIX + '-prerelease.' + env.BUILD_NUMBER}"
} }
stages { stages {
stage('npm install'){ stage('npm install'){
steps { steps {
sh '''npm install sh '''npm install
cd projects/common cd projects/common
npm install npm install
cd ../common-map cd ../common-map
npm install npm install
''' '''
} }
} }
stage('build'){ stage('build'){
steps { steps {
sh '''ng build common sh '''ng build common
ng build common-map''' ng build common-map'''
} }
} }
stage('npm publish'){ stage('npm publish'){
steps { steps {
sh '''cd dist/common sh '''cd dist/common
npm version ${PACKAGE_VERSION} npm version ${PACKAGE_VERSION}
npm publish npm publish
cd ../common-map cd ../common-map
npm version ${PACKAGE_VERSION} npm version ${PACKAGE_VERSION}
npm publish''' npm publish'''
} }
} }
} }
post { post {
always { always {
emailext ( emailext (
body: '${DEFAULT_CONTENT}', body: '${DEFAULT_CONTENT}',
mimeType: 'text/html', mimeType: 'text/html',
replyTo: '${DEFAULT_REPLYTO}', replyTo: '${DEFAULT_REPLYTO}',
subject: '${DEFAULT_SUBJECT}', subject: '${DEFAULT_SUBJECT}',
to: emailextrecipients([[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider']]) to: emailextrecipients([[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider']])
) )
} }
} }
} }

118
README.md
View File

@@ -1,59 +1,59 @@
# Farmmaps viewer # Farmmaps viewer
This is a sample FarmMaps client in Angular 7.x. This is a sample FarmMaps client in Angular 7.x.
## Quick start ## Quick start
Use one of the two options below to get started. Use one of the two options below to get started.
## Option 1, Using docker ## Option 1, Using docker
*Dependencies* *Dependencies*
* docker desktop * docker desktop
*Setup* *Setup*
``` ```
docker pull node:10.16.0 docker pull node:12.13.1
docker run -t -i --entrypoint /bin/bash -p 4200:4200 node:10.16.0 docker run -t -i --entrypoint /bin/bash -p 4200:4200 node:12.13.1
``` ```
Inside the running container Inside the running container
``` ```
git clone https://git.akkerweb.nl/FarmMaps/FarmMapsLib.git git clone https://git.akkerweb.nl/FarmMaps/FarmMapsLib.git
cd FarmMapsLib cd FarmMapsLib
npm config set @farmmaps:registry https://repository.akkerweb.nl/repository/npm-group/ npm config set @farmmaps:registry https://repository.akkerweb.nl/repository/npm-group/
npm install -g @angular/cli npm install -g @angular/cli
npm install npm install
ng serve --host 0.0.0.0 ng serve --host 0.0.0.0
``` ```
*Go* *Go*
Point your browser to http://localhost:4200 Point your browser to http://localhost:4200
## Option 2, Using local machine ## Option 2, Using local machine
*Dependencies* *Dependencies*
* npm 6.9.0 * npm 6.9.0
* nodejs 10.16.0 * nodejs 10.16.0
* git * git
*Setup* *Setup*
``` ```
git clone https://git.akkerweb.nl/FarmMaps/FarmMapsLib.git git clone https://git.akkerweb.nl/FarmMaps/FarmMapsLib.git
cd FarmMapsLib cd FarmMapsLib
npm config set @farmmaps:registry https://repository.akkerweb.nl/repository/npm-group/ npm config set @farmmaps:registry https://repository.akkerweb.nl/repository/npm-group/
npm install -g @angular/cli npm install -g @angular/cli
npm install npm install
ng serve ng serve
``` ```
*Go* *Go*
Point your browser to http://localhost:4200 Point your browser to http://localhost:4200

View File

@@ -66,7 +66,7 @@
{ {
"type": "initial", "type": "initial",
"maximumWarning": "2mb", "maximumWarning": "2mb",
"maximumError": "5mb" "maximumError": "7mb"
} }
] ]
} }

View File

@@ -1,11 +1,11 @@
# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
# For additional information regarding the format and rule options, please see: # For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries # https://github.com/browserslist/browserslist#queries
# #
# For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed # For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed
> 0.5% > 0.5%
last 2 versions last 2 versions
Firefox ESR Firefox ESR
not dead not dead
not IE 9-11 not IE 9-11

9460
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,40 +11,40 @@
}, },
"private": true, "private": true,
"dependencies": { "dependencies": {
"@angular/animations": "~7.2.0", "@angular/animations": "~8.2.14",
"@angular/common": "~7.2.0", "@angular/common": "~8.2.14",
"@angular/compiler": "~7.2.0", "@angular/compiler": "~8.2.14",
"@angular/core": "~7.2.0", "@angular/core": "~8.2.14",
"@angular/forms": "~7.2.0", "@angular/forms": "~8.2.14",
"@angular/platform-browser": "~7.2.0", "@angular/platform-browser": "~8.2.14",
"@angular/platform-browser-dynamic": "~7.2.0", "@angular/platform-browser-dynamic": "~8.2.14",
"@angular/router": "~7.2.0", "@angular/router": "~8.2.14",
"@aspnet/signalr": "^1.1.4", "@aspnet/signalr": "^1.1.4",
"@farmmaps/common": ">=0.0.1-prerelease.69 <0.0.1", "@farmmaps/common": ">=0.0.1-prerelease.95 <0.0.1",
"@farmmaps/common-map": ">=0.0.1-prerelease.69 <0.0.1", "@farmmaps/common-map": ">=0.0.1-prerelease.95 <0.0.1",
"@ng-bootstrap/ng-bootstrap": "^4.2.1", "@ng-bootstrap/ng-bootstrap": "^4.2.1",
"@ngrx/effects": "^7.2.0", "@ngrx/effects": "^8.2.0",
"@ngrx/router-store": "^7.2.0", "@ngrx/router-store": "^8.2.0",
"@ngrx/store": "^7.2.0", "@ngrx/store": "^8.2.0",
"bootstrap": "^4.3.1", "bootstrap": "^4.3.1",
"font-awesome": "^4.7.0", "font-awesome": "^4.7.0",
"core-js": "^2.5.4", "core-js": "^2.5.4",
"ngrx-store-localstorage": "^8.0.0", "ngrx-store-localstorage": "^8.0.0",
"resumablejs": "^1.1.0", "resumablejs": "^1.1.0",
"rxjs": "~6.3.3", "rxjs": "~6.5.3",
"tassign": "^1.0.0", "tassign": "^1.0.0",
"zone.js": "~0.8.26" "zone.js": "~0.9.1"
}, },
"devDependencies": { "devDependencies": {
"@angular-devkit/build-angular": "~0.13.0", "@angular-devkit/build-angular": "~0.803.19",
"@angular-devkit/build-ng-packagr": "~0.13.0", "@angular-devkit/build-ng-packagr": "~0.803.19",
"@angular/cli": "~7.3.8", "@angular/cli": "~8.3.19",
"@angular/compiler-cli": "~7.2.0", "@angular/compiler-cli": "~8.2.14",
"@angular/language-service": "~7.2.0", "@angular/language-service": "~8.2.14",
"@types/node": "~8.9.4", "@types/node": "~8.9.4",
"@types/jasmine": "~2.8.8", "@types/jasmine": "~2.8.8",
"@types/jasminewd2": "~2.0.3", "@types/jasminewd2": "~2.0.3",
"codelyzer": "~4.5.0", "codelyzer": "^5.0.1",
"jasmine-core": "~2.99.1", "jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1", "jasmine-spec-reporter": "~4.2.1",
"karma": "~4.0.0", "karma": "~4.0.0",
@@ -52,12 +52,12 @@
"karma-coverage-istanbul-reporter": "~2.0.1", "karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~1.1.2", "karma-jasmine": "~1.1.2",
"karma-jasmine-html-reporter": "^0.2.2", "karma-jasmine-html-reporter": "^0.2.2",
"ng-packagr": "^4.2.0", "ng-packagr": "^5.4.0",
"protractor": "~5.4.0", "protractor": "~5.4.0",
"ts-node": "~7.0.0", "ts-node": "~7.0.0",
"tsickle": ">=0.34.0", "tsickle": "^0.37.0",
"tslib": "^1.9.0", "tslib": "^1.9.0",
"tslint": "~5.11.0", "tslint": "~5.11.0",
"typescript": "~3.2.2" "typescript": "~3.5.3"
} }
} }

View File

@@ -4,68 +4,42 @@
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {
"@farmmaps/common": { "@openlayers/pepjs": {
"version": "0.0.1-prerelease.56", "version": "0.5.3",
"resolved": "https://repository.akkerweb.nl/repository/npm-group/@farmmaps/common/-/common-0.0.1-prerelease.56.tgz", "resolved": "https://registry.npmjs.org/@openlayers/pepjs/-/pepjs-0.5.3.tgz",
"integrity": "sha512-m9KxWsLkTSz2JI074gIJH1kDR0PCLsFAug8oBjtlU/QxgBySrvqHCRiODpNmNWnFyNTZHqKHJQefn3Q9iAil4g==", "integrity": "sha512-Bgvi5c14BS0FJWyYWWFstNEnXsB30nK8Jt8hkAAdqr7E0gDdBBWVDglF3Ub19wTxvgJ/CVHyTY6VuCtnyRzglg=="
"requires": {
"angular-oauth2-oidc": "^5.0.2",
"ngx-uploadx": "^3.1.3",
"tslib": "^1.9.0"
}
},
"angular-oauth2-oidc": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/angular-oauth2-oidc/-/angular-oauth2-oidc-5.0.2.tgz",
"integrity": "sha512-jtOv4IWEjSFfBHVE4seWGWT/ZfWJ95QJ1JaFhVVGJEF64ibGuPwV3ztwTOUl98QHi/Yg4PXXDAisb31JnIbxBw==",
"requires": {
"jsrsasign": "^8.0.12",
"tslib": "^1.9.0"
}
}, },
"ieee754": { "ieee754": {
"version": "1.1.13", "version": "1.1.13",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz",
"integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg==" "integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg=="
}, },
"jsrsasign": {
"version": "8.0.12",
"resolved": "https://registry.npmjs.org/jsrsasign/-/jsrsasign-8.0.12.tgz",
"integrity": "sha1-Iqu5ZW00owuVMENnIINeicLlwxY="
},
"ngx-openlayers": { "ngx-openlayers": {
"version": "1.0.0-next.9", "version": "1.0.0-next.13",
"resolved": "https://registry.npmjs.org/ngx-openlayers/-/ngx-openlayers-1.0.0-next.9.tgz", "resolved": "https://registry.npmjs.org/ngx-openlayers/-/ngx-openlayers-1.0.0-next.13.tgz",
"integrity": "sha512-14UFxJX9oeOXtq+HJCJyXn0sBmYmCqj2AnFtetKk1FsDe8EUMFGIRju8UOFegCr2oEu5JsuRjALcfW7lCe+teg==", "integrity": "sha512-6y724s5JV6n1oxEhryxP3wcbwzpierj9RLiMLXInfKOG3l5IO1AtPNkeK9+mKctVDUVm5URIfzzZH02Ld+bvSQ==",
"requires": {
"tslib": "^1.9.0"
}
},
"ngx-uploadx": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/ngx-uploadx/-/ngx-uploadx-3.3.2.tgz",
"integrity": "sha512-gRdXXq2cRU9HE6dj65qay9GV8NRC7n8y5LtMzJWqsfu2k3CHMQxo2TqZwA9/l/PqJ76RoO7sTPy1OenFQ+krkQ==",
"requires": { "requires": {
"tslib": "^1.9.0" "tslib": "^1.9.0"
} }
}, },
"ol": { "ol": {
"version": "5.3.3", "version": "6.1.1",
"resolved": "https://registry.npmjs.org/ol/-/ol-5.3.3.tgz", "resolved": "https://registry.npmjs.org/ol/-/ol-6.1.1.tgz",
"integrity": "sha512-7eU4x8YMduNcED1D5wI+AMWDRe7/1HmGfsbV+kFFROI9RNABU/6n4osj6Q3trZbxxKnK2DSRIjIRGwRHT/Z+Ww==", "integrity": "sha512-0dL3i3eJqgOpqIjDKEY3grkeQnjAYfV5L/JCxhOu4SxiaizRwFrFgeas6LILRoxKa03jhQFbut2r2bbgcLGQeA==",
"requires": { "requires": {
"pbf": "3.1.0", "@openlayers/pepjs": "^0.5.3",
"pbf": "3.2.1",
"pixelworks": "1.1.0", "pixelworks": "1.1.0",
"rbush": "2.0.2" "rbush": "^3.0.1"
} }
}, },
"pbf": { "pbf": {
"version": "3.1.0", "version": "3.2.1",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-3.1.0.tgz", "resolved": "https://registry.npmjs.org/pbf/-/pbf-3.2.1.tgz",
"integrity": "sha512-/hYJmIsTmh7fMkHAWWXJ5b8IKLWdjdlAFb3IHkRBn1XUhIYBChVGfVwmHEAV3UfXTxsP/AKfYTXTS/dCPxJd5w==", "integrity": "sha512-ClrV7pNOn7rtmoQVF4TS1vyU0WhYRnP92fzbfF75jAIwpnzdJXf8iTd4CMEqO4yUenH6NDqLiwjqlh6QgZzgLQ==",
"requires": { "requires": {
"ieee754": "^1.1.6", "ieee754": "^1.1.12",
"resolve-protobuf-schema": "^2.0.0" "resolve-protobuf-schema": "^2.1.0"
} }
}, },
"pixelworks": { "pixelworks": {
@@ -79,16 +53,16 @@
"integrity": "sha512-Xdayp8sB/mU+sUV4G7ws8xtYMGdQnxbeIfLjyO9TZZRJdztBGhlmbI5x1qcY4TG5hBkIKGnc28i7nXxaugu88w==" "integrity": "sha512-Xdayp8sB/mU+sUV4G7ws8xtYMGdQnxbeIfLjyO9TZZRJdztBGhlmbI5x1qcY4TG5hBkIKGnc28i7nXxaugu88w=="
}, },
"quickselect": { "quickselect": {
"version": "1.1.1", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/quickselect/-/quickselect-1.1.1.tgz", "resolved": "https://registry.npmjs.org/quickselect/-/quickselect-2.0.0.tgz",
"integrity": "sha512-qN0Gqdw4c4KGPsBOQafj6yj/PA6c/L63f6CaZ/DCF/xF4Esu3jVmKLUDYxghFx8Kb/O7y9tI7x2RjTSXwdK1iQ==" "integrity": "sha512-RKJ22hX8mHe3Y6wH/N3wCM6BWtjaxIyyUIkpHOvfFnxdI4yD4tBXEBKSbriGujF6jnSVkJrffuo6vxACiSSxIw=="
}, },
"rbush": { "rbush": {
"version": "2.0.2", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/rbush/-/rbush-2.0.2.tgz", "resolved": "https://registry.npmjs.org/rbush/-/rbush-3.0.1.tgz",
"integrity": "sha512-XBOuALcTm+O/H8G90b6pzu6nX6v2zCKiFG4BJho8a+bY6AER6t8uQUZdi5bomQc0AprCWhEGa7ncAbbRap0bRA==", "integrity": "sha512-XRaVO0YecOpEuIvbhbpTrZgoiI6xBlz6hnlr6EHhd+0x9ase6EmeN+hdwwUaJvLcsFFQ8iWVF1GAK1yB0BWi0w==",
"requires": { "requires": {
"quickselect": "^1.0.1" "quickselect": "^2.0.0"
} }
}, },
"resolve-protobuf-schema": { "resolve-protobuf-schema": {

View File

@@ -5,16 +5,16 @@
"registry": "https://repository.akkerweb.nl/repository/npm-hosted/" "registry": "https://repository.akkerweb.nl/repository/npm-hosted/"
}, },
"dependencies": { "dependencies": {
"ngx-openlayers": "1.0.0-next.9", "ngx-openlayers": "1.0.0-next.13",
"ol": "^5.3.3" "ol": "^6.0.0"
}, },
"peerDependencies": { "peerDependencies": {
"@angular/core": "^7.2.0", "@angular/core": "^8.2.0",
"ngrx-store-localstorage": "^8.0.0", "ngrx-store-localstorage": "^8.0.0",
"@ngrx/effects": "^7.2", "@ngrx/effects": "^8.2",
"@ngrx/router-store": "^7.2", "@ngrx/router-store": "^8.2",
"@ngrx/store": "^7.2", "@ngrx/store": "^8.2",
"tassign": "^1.0.0", "tassign": "^1.0.0",
"@farmmaps/common": ">=0.0.1-prerelease.56 <0.0.1" "@farmmaps/common": ">=0.0.1-prerelease.90 <0.0.1"
} }
} }

View File

@@ -1,6 +1,8 @@
import { Action } from '@ngrx/store'; import { Action } from '@ngrx/store';
import { IMapState,IItemLayer,IQueryState } from '../models'; import { IMapState } from '../models/map.state';
import { IItemLayer } from '../models/item.layer';
import { IQueryState } from '../models/query.state';
import { IItem } from '@farmmaps/common'; import { IItem } from '@farmmaps/common';
import { Feature } from 'ol'; import { Feature } from 'ol';
import { Extent } from 'ol/extent'; import { Extent } from 'ol/extent';

View File

@@ -16,12 +16,12 @@ import * as mapReducers from './reducers/map.reducer';
import * as mapActions from './actions/map.actions'; import * as mapActions from './actions/map.actions';
import * as mapEffects from './effects/map.effects'; import * as mapEffects from './effects/map.effects';
import { IMapState} from './models'; import { IMapState} from './models/map.state';
import { ISelectedFeatures } from './models'; import { ISelectedFeatures } from './models/selected.features';
import { IItemLayer } from './models'; import { IItemLayer } from './models/item.layer';
import { ItemLayer} from './models'; import { ItemLayer} from './models/item.layer';
import { IQueryState } from './models'; import { IQueryState } from './models/query.state';
import { IPeriodState } from './models'; import { IPeriodState } from './models/period.state';
// components // components
import { GpsLocation} from './components/aol/gps-location/gps-location.component'; import { GpsLocation} from './components/aol/gps-location/gps-location.component';
@@ -54,7 +54,7 @@ import { LayerListComponent } from './components/aol/layer-list/layer-list.compo
import { MetaDataModalComponent } from './components/meta-data-modal/meta-data-modal.component'; import { MetaDataModalComponent } from './components/meta-data-modal/meta-data-modal.component';
import { SelectPeriodModalComponent } from './components/select-period-modal/select-period-modal.component'; import { SelectPeriodModalComponent } from './components/select-period-modal/select-period-modal.component';
import { MapComponent } from './components/map/map.component'; import { MapComponent } from './components/map/map.component';
import { MapSearchComponent } from './components/map-search'; import { MapSearchComponent } from './components/map-search/map-search.component';
import { MapRoutingModule } from './common-map-routing.module'; import { MapRoutingModule } from './common-map-routing.module';
import { LegendComponent } from './components/legend/legend.component'; import { LegendComponent } from './components/legend/legend.component';
import { LayerVectorImageComponent } from './components/aol/layer-vector-image/layer-vector-image.component'; import { LayerVectorImageComponent } from './components/aol/layer-vector-image/layer-vector-image.component';

View File

@@ -1,68 +1,68 @@
import { Component, OnInit, Input, ViewChild, ElementRef, OnChanges, SimpleChanges } from '@angular/core'; import { Component, OnInit, Input, ViewChild, ElementRef, OnChanges, SimpleChanges } from '@angular/core';
import { MapComponent } from 'ngx-openlayers'; import { MapComponent } from 'ngx-openlayers';
import Overlay from 'ol/Overlay'; import Overlay from 'ol/Overlay';
import { fromLonLat, toLonLat } from 'ol/proj'; import { fromLonLat, toLonLat } from 'ol/proj';
@Component({ @Component({
selector: 'fm-map-gps-location', selector: 'fm-map-gps-location',
templateUrl: './gps-location.component.html', templateUrl: './gps-location.component.html',
styleUrls: ['./gps-location.component.scss'] styleUrls: ['./gps-location.component.scss']
}) })
export class GpsLocation implements OnInit,OnChanges{ export class GpsLocation implements OnInit,OnChanges{
@Input() enable:boolean; @Input() enable:boolean;
public instance: Overlay; public instance: Overlay;
@Input() position: Position; @Input() position: Position;
@Input() location: number[]=[0,0]; @Input() location: number[]=[0,0];
@Input() locationTolerance: number = 0; @Input() locationTolerance: number = 0;
@Input() showHeading: boolean = false; @Input() showHeading: boolean = false;
@Input() heading: number = 0; @Input() heading: number = 0;
@Input() headingTolerance: number = 0; @Input() headingTolerance: number = 0;
public locTolerancePixels: number = 0; public locTolerancePixels: number = 0;
public path: string = ""; public path: string = "";
public rotate: string = ""; public rotate: string = "";
private resolution: number = 0; private resolution: number = 0;
@ViewChild('location') locationElement: ElementRef; @ViewChild('location', { static: true }) locationElement: ElementRef;
constructor(private map: MapComponent) { constructor(private map: MapComponent) {
} }
recalcLocationTolerance() { recalcLocationTolerance() {
this.locTolerancePixels = this.resolution >0? this.locationTolerance / this.resolution:0; this.locTolerancePixels = this.resolution >0? this.locationTolerance / this.resolution:0;
} }
ngOnInit() { ngOnInit() {
this.instance = new Overlay({ this.instance = new Overlay({
stopEvent:false, stopEvent:false,
positioning: 'center-center', positioning: 'center-center',
position: fromLonLat( this.location), position: fromLonLat( this.location),
element: this.locationElement.nativeElement element: this.locationElement.nativeElement
}); });
var x = Math.tan(this.headingTolerance * Math.PI / 180)*40; var x = Math.tan(this.headingTolerance * Math.PI / 180)*40;
var y = Math.cos(this.headingTolerance * Math.PI / 180) * 40; var y = Math.cos(this.headingTolerance * Math.PI / 180) * 40;
var y1 = Math.round(500 - y); var y1 = Math.round(500 - y);
var x1 = Math.round(500 - x); var x1 = Math.round(500 - x);
var y2 = Math.round(y1); var y2 = Math.round(y1);
var x2 = Math.round(500 + x); var x2 = Math.round(500 + x);
this.path = "M " + x2 + " " + y2 + " A 45 45,0,0,0, " + x1 + " " + y1 + " L 493 500 L 507 500 Z"; this.path = "M " + x2 + " " + y2 + " A 45 45,0,0,0, " + x1 + " " + y1 + " L 493 500 L 507 500 Z";
this.rotate = "rotate(" + Math.round(this.heading) + " 500 500)"; this.rotate = "rotate(" + Math.round(this.heading) + " 500 500)";
this.locTolerancePixels = this.locationTolerance; this.locTolerancePixels = this.locationTolerance;
this.map.instance.addOverlay(this.instance); this.map.instance.addOverlay(this.instance);
this.map.instance.getView().on('change:resolution', (evt) => { this.map.instance.getView().on('change:resolution', (evt) => {
this.resolution = evt.target.get('resolution'); this.resolution = evt.target.get('resolution');
this.recalcLocationTolerance(); this.recalcLocationTolerance();
}); });
} }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
if (changes.position && this.instance) { if (changes.position && this.instance) {
var p = changes.position.currentValue as Position; var p = changes.position.currentValue as Position;
this.instance.setPosition(fromLonLat([p.coords.longitude, p.coords.latitude])); this.instance.setPosition(fromLonLat([p.coords.longitude, p.coords.latitude]));
this.locationTolerance = p.coords.accuracy; this.locationTolerance = p.coords.accuracy;
this.recalcLocationTolerance(); this.recalcLocationTolerance();
this.heading = p.coords.heading; this.heading = p.coords.heading;
} }
} }
} }

View File

@@ -4,7 +4,7 @@ import { LayerVectorComponent, SourceVectorComponent, MapComponent, LayerImageCo
import { LayerVectorImageComponent } from '../layer-vector-image/layer-vector-image.component'; import { LayerVectorImageComponent } from '../layer-vector-image/layer-vector-image.component';
import { ItemService } from '@farmmaps/common'; import { ItemService } from '@farmmaps/common';
import { IItem } from '@farmmaps/common'; import { IItem } from '@farmmaps/common';
import { ISelectedFeatures } from '../../../models'; import { ISelectedFeatures } from '../../../models/selected.features';
import {Vector} from 'ol/source'; import {Vector} from 'ol/source';
import {Feature,Collection} from 'ol'; import {Feature,Collection} from 'ol';

View File

@@ -3,8 +3,9 @@ import { HttpClient } from "@angular/common/http";
import { LayerVectorComponent, LayerTileComponent, LayerGroupComponent, MapComponent } from 'ngx-openlayers'; import { LayerVectorComponent, LayerTileComponent, LayerGroupComponent, MapComponent } from 'ngx-openlayers';
import { ItemService } from '@farmmaps/common'; import { ItemService } from '@farmmaps/common';
import { AppConfig } from '@farmmaps/common'; import { AppConfig } from '@farmmaps/common';
import { IItemLayer, ILayerData, IRenderoutputTiles, IRenderoutputImage, IGradientstop, ILayer, IHistogram } from '../../../models'; import { IItemLayer} from '../../../models/item.layer';
import { ILayerData} from '../../../models/layer.data';
import { IRenderoutputTiles,IRenderoutputImage,IGradientstop,ILayer,IHistogram} from '../../../models/color.map';
import {Extent} from 'ol/extent'; import {Extent} from 'ol/extent';
import Projection from 'ol/proj/Projection'; import Projection from 'ol/proj/Projection';
import * as proj from 'ol/proj'; import * as proj from 'ol/proj';

View File

@@ -1,5 +1,5 @@
import { Component,Input,Output,EventEmitter } from '@angular/core'; import { Component,Input,Output,EventEmitter } from '@angular/core';
import { IItemLayer } from '../../../models'; import { IItemLayer } from '../../../models/item.layer';
@Component({ @Component({
selector: 'fm-map-layer-list', selector: 'fm-map-layer-list',

View File

@@ -1,59 +1,59 @@
import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject, Type} from '@angular/core'; import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject, Type} from '@angular/core';
import { Feature } from 'ol'; import { Feature } from 'ol';
import { FeatureListComponent,AbstractFeatureListComponent } from '../feature-list/feature-list.component'; import { FeatureListComponent,AbstractFeatureListComponent } from '../feature-list/feature-list.component';
import { WidgetHostDirective } from '../widget-host/widget-host.directive'; import { WidgetHostDirective } from '../widget-host/widget-host.directive';
import {IQueryState } from '../../models/query.state'; import {IQueryState } from '../../models/query.state';
import * as mapReducers from '../../reducers/map.reducer'; import * as mapReducers from '../../reducers/map.reducer';
import * as mapActions from '../../actions/map.actions'; import * as mapActions from '../../actions/map.actions';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
@Component({ @Component({
selector: 'fm-map-feature-list-container', selector: 'fm-map-feature-list-container',
templateUrl: './feature-list-container.component.html', templateUrl: './feature-list-container.component.html',
styleUrls: ['./feature-list-container.component.scss'] styleUrls: ['./feature-list-container.component.scss']
}) })
export class FeatureListContainerComponent { export class FeatureListContainerComponent {
constructor(private store: Store<mapReducers.State>,private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractFeatureListComponent) public featureLists: AbstractFeatureListComponent[] ) { constructor(private store: Store<mapReducers.State>,private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractFeatureListComponent) public featureLists: AbstractFeatureListComponent[] ) {
} }
@Input() features: Array<Feature> @Input() features: Array<Feature>
@Input() queryState: IQueryState; @Input() queryState: IQueryState;
@ViewChild(WidgetHostDirective) widgetHost: WidgetHostDirective; @ViewChild(WidgetHostDirective, { static: true }) widgetHost: WidgetHostDirective;
loadComponent(queryState:IQueryState) { loadComponent(queryState:IQueryState) {
var componentFactory: ComponentFactory<AbstractFeatureListComponent> = this.componentFactoryResolver.resolveComponentFactory(FeatureListComponent); // default var componentFactory: ComponentFactory<AbstractFeatureListComponent> = this.componentFactoryResolver.resolveComponentFactory(FeatureListComponent); // default
var selected = -1; var selected = -1;
for (var i = 0; i < this.featureLists.length; i++) { for (var i = 0; i < this.featureLists.length; i++) {
if (this.featureLists[i]['forItemType'] == queryState.itemType && this.featureLists[i]['forChild'] && queryState.parentCode && queryState.parentCode != "") { if (this.featureLists[i]['forItemType'] == queryState.itemType && this.featureLists[i]['forChild'] && queryState.parentCode && queryState.parentCode != "") {
selected = i; selected = i;
break; break;
} else if (this.featureLists[i]['forItemType'] == queryState.itemType) { } else if (this.featureLists[i]['forItemType'] == queryState.itemType) {
selected = i; selected = i;
break; break;
} }
} }
if (selected >= 0) { if (selected >= 0) {
componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.featureLists[i]['constructor'] as any); componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.featureLists[i]['constructor'] as any);
if (this.featureLists[selected]['collapseSearch'] === true) { if (this.featureLists[selected]['collapseSearch'] === true) {
this.store.dispatch(new mapActions.CollapseSearch()); this.store.dispatch(new mapActions.CollapseSearch());
} }
} }
const viewContainerRef = this.widgetHost.viewContainerRef; const viewContainerRef = this.widgetHost.viewContainerRef;
viewContainerRef.clear(); viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory); const componentRef = viewContainerRef.createComponent(componentFactory);
(<AbstractFeatureListComponent>componentRef.instance).features = this.features; (<AbstractFeatureListComponent>componentRef.instance).features = this.features;
(<AbstractFeatureListComponent>componentRef.instance).queryState = this.queryState; (<AbstractFeatureListComponent>componentRef.instance).queryState = this.queryState;
} }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
if (changes["features"] && changes["features"].currentValue) { if (changes["features"] && changes["features"].currentValue) {
if (this.queryState) { if (this.queryState) {
this.loadComponent(this.queryState); this.loadComponent(this.queryState);
} }
} }
} }
} }

View File

@@ -1,43 +1,43 @@
import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject, Type} from '@angular/core'; import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject, Type} from '@angular/core';
import { Feature } from 'ol'; import { Feature } from 'ol';
import { AbstractFeatureListFeatureComponent,FeatureListFeatureComponent } from '../feature-list-feature/feature-list-feature.component'; import { AbstractFeatureListFeatureComponent,FeatureListFeatureComponent } from '../feature-list-feature/feature-list-feature.component';
import { WidgetHostDirective } from '../widget-host/widget-host.directive'; import { WidgetHostDirective } from '../widget-host/widget-host.directive';
@Component({ @Component({
selector: 'fm-map-feature-list-feature-container', selector: 'fm-map-feature-list-feature-container',
template: ` template: `
<div> <div>
<ng-template fm-map-widget-host></ng-template> <ng-template fm-map-widget-host></ng-template>
</div> </div>
` `
}) })
export class FeatureListFeatureContainerComponent { export class FeatureListFeatureContainerComponent {
constructor(private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractFeatureListFeatureComponent) public featureLists: AbstractFeatureListFeatureComponent[] ) { constructor(private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractFeatureListFeatureComponent) public featureLists: AbstractFeatureListFeatureComponent[] ) {
} }
@Input() feature: Feature; @Input() feature: Feature;
@ViewChild(WidgetHostDirective) widgetHost: WidgetHostDirective; @ViewChild(WidgetHostDirective, { static: true }) widgetHost: WidgetHostDirective;
loadComponent() { loadComponent() {
var componentFactory: ComponentFactory<AbstractFeatureListFeatureComponent> = this.componentFactoryResolver.resolveComponentFactory(FeatureListFeatureComponent); // default var componentFactory: ComponentFactory<AbstractFeatureListFeatureComponent> = this.componentFactoryResolver.resolveComponentFactory(FeatureListFeatureComponent); // default
for (var i = 0; i < this.featureLists.length; i++) { for (var i = 0; i < this.featureLists.length; i++) {
if (this.featureLists[i]['forItemType'] == this.feature.get("itemType")) { if (this.featureLists[i]['forItemType'] == this.feature.get("itemType")) {
componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.featureLists[i]['constructor'] as any); componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.featureLists[i]['constructor'] as any);
} }
} }
const viewContainerRef = this.widgetHost.viewContainerRef; const viewContainerRef = this.widgetHost.viewContainerRef;
viewContainerRef.clear(); viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory); const componentRef = viewContainerRef.createComponent(componentFactory);
(<AbstractFeatureListFeatureComponent>componentRef.instance).feature = this.feature; (<AbstractFeatureListFeatureComponent>componentRef.instance).feature = this.feature;
} }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
if (changes["feature"] && changes["feature"].currentValue) { if (changes["feature"] && changes["feature"].currentValue) {
this.loadComponent(); this.loadComponent();
} }
} }
} }

View File

@@ -8,7 +8,7 @@ import * as mapActions from '../../actions/map.actions';
import { Observable, from } from 'rxjs'; import { Observable, from } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators'; import { withLatestFrom } from 'rxjs/operators';
import { tassign } from 'tassign'; import { tassign } from 'tassign';
import { IQueryState } from '../../models'; import { IQueryState } from '../../models/query.state';
@Injectable() @Injectable()

View File

@@ -1,47 +1,47 @@
import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject, Type} from '@angular/core'; import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject, Type} from '@angular/core';
import { AbstractItemListItemComponent,ItemListItemComponent } from '../item-list-item/item-list-item.component'; import { AbstractItemListItemComponent,ItemListItemComponent } from '../item-list-item/item-list-item.component';
import { WidgetHostDirective } from '../widget-host/widget-host.directive'; import { WidgetHostDirective } from '../widget-host/widget-host.directive';
import { IItem, IListItem } from '@farmmaps/common'; import { IItem, IListItem } from '@farmmaps/common';
@Component({ @Component({
selector: 'fm-map-item-list-item-container', selector: 'fm-map-item-list-item-container',
template: ` template: `
<div style="height:100%"> <div style="height:100%">
<ng-template fm-map-widget-host></ng-template> <ng-template fm-map-widget-host></ng-template>
</div> </div>
` `
}) })
export class ItemListItemContainerComponent { export class ItemListItemContainerComponent {
constructor(private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractItemListItemComponent) public itemComponentList: AbstractItemListItemComponent[] ) { constructor(private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractItemListItemComponent) public itemComponentList: AbstractItemListItemComponent[] ) {
} }
@Input() item: IListItem; @Input() item: IListItem;
@ViewChild(WidgetHostDirective) widgetHost: WidgetHostDirective; @ViewChild(WidgetHostDirective, { static: true }) widgetHost: WidgetHostDirective;
loadComponent() { loadComponent() {
var componentFactory: ComponentFactory<AbstractItemListItemComponent> = this.componentFactoryResolver.resolveComponentFactory(ItemListItemComponent); // default var componentFactory: ComponentFactory<AbstractItemListItemComponent> = this.componentFactoryResolver.resolveComponentFactory(ItemListItemComponent); // default
for (var i = 0; i < this.itemComponentList.length; i++) { for (var i = 0; i < this.itemComponentList.length; i++) {
if (this.itemComponentList[i]['forItemType'] && if (this.itemComponentList[i]['forItemType'] &&
this.itemComponentList[i]['forItemType'].indexOf(this.item.itemType) >= 0 && this.itemComponentList[i]['forItemType'].indexOf(this.item.itemType) >= 0 &&
this.itemComponentList[i]['forSourceTask'] && this.itemComponentList[i]['forSourceTask'] &&
this.itemComponentList[i]['forSourceTask'].indexOf(this.item.sourceTask) >= 0 ) this.itemComponentList[i]['forSourceTask'].indexOf(this.item.sourceTask) >= 0 )
{ {
componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.itemComponentList[i]['constructor'] as any); componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.itemComponentList[i]['constructor'] as any);
} }
} }
const viewContainerRef = this.widgetHost.viewContainerRef; const viewContainerRef = this.widgetHost.viewContainerRef;
viewContainerRef.clear(); viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory); const componentRef = viewContainerRef.createComponent(componentFactory);
(<AbstractItemListItemComponent>componentRef.instance).item = this.item; (<AbstractItemListItemComponent>componentRef.instance).item = this.item;
} }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
if (changes["item"] && changes["item"].currentValue) { if (changes["item"] && changes["item"].currentValue) {
this.loadComponent(); this.loadComponent();
} }
} }
} }

View File

@@ -1,4 +1,4 @@
<div *ngIf="items;let items" class="widget-container"> <div *ngIf="items;let items" class="widget-container pt-0">
<div class="widget" *ngFor="let item of items" (click)="handleItemClick(item)"> <div class="widget" *ngFor="let item of items" (click)="handleItemClick(item)">
<div class="content"> <div class="content">
<fm-map-item-list-item-container [item]="item" class="item-container"></fm-map-item-list-item-container> <fm-map-item-list-item-container [item]="item" class="item-container"></fm-map-item-list-item-container>

View File

@@ -1,14 +1,10 @@
import { Component, Input, Injectable } from '@angular/core'; import { Component, Input, Injectable } from '@angular/core';
import { Location } from '@angular/common'; import { Location } from '@angular/common';
import { Feature } from 'ol';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import * as mapReducers from '../../reducers/map.reducer'; import * as mapReducers from '../../reducers/map.reducer';
import { commonReducers,ItemTypeService, IItem, Item,IListItem } from '@farmmaps/common'; import { commonReducers,ItemTypeService,IListItem } from '@farmmaps/common';
import * as mapActions from '../../actions/map.actions'; import * as mapActions from '../../actions/map.actions';
import { Observable, from } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { tassign } from 'tassign'; import { tassign } from 'tassign';
import { IQueryState } from '../../models';
@Injectable() @Injectable()

View File

@@ -1,4 +1,4 @@
<div *ngIf="widgets;let widgets" class="widget-container"> <div *ngIf="widgets;let widgets" class="widget-container pt-0">
<div class="widget" *ngFor="let widget of widgets"> <div class="widget" *ngFor="let widget of widgets">
<div class="content"> <div class="content">
<ng-template #widgetTemplate></ng-template> <ng-template #widgetTemplate></ng-template>

View File

@@ -1,39 +1,41 @@
<table class="container" *ngIf="layer"> <table class="container" *ngIf="showLegend()">
<tr> <tr>
<td colspan="2"> <td colspan="2">
<div class="title"> <div class="title">
<h4 *ngIf="showTitle">{{layer.name}}</h4> <h4 *ngIf="showTitle">{{layer.name}}</h4>
<b *ngIf="layer.unit">({{layer.unit}})</b> <b *ngIf="layer.unit">({{layer.unit}})</b>
</div> </div>
</td> </td>
<td colspan="2"> <td colspan="2">
<div class="title" *ngIf="histogramenabled"> <div class="title" *ngIf="histogramenabled">
<h4>{{histogram}}</h4> <h4>{{histogram}}</h4>
<b *ngIf="histogramunit">({{histogramunit}})</b> <b *ngIf="histogramunit">({{histogramunit}})</b>
</div> </div>
</td> </td>
</tr> </tr>
<tr *ngFor="let entry of layer.renderer.colorMap.entries; let i = index "> <tr *ngFor="let entry of layer.renderer.colorMap.entries; let i = index ">
<td class="legend-items"><div [style.background-color]="getHex(entry.color)"></div></td> <td class="legend-items"><span [style.background-color]="getHex(entry.color)" class="color"></span></td>
<td class="legend-items-text">{{entry.value | number:'1.0-2'}} {{legendunit}}</td> <td class="legend-items-text"><span *ngIf="!entry.label">{{entry.value | number:'1.0-2'}} {{legendunit}}</span><span *ngIf="entry.label">{{entry.label}}</span></td>
<!--<td class="histogram-items-text"><span *ngIf="histogramenabled">{{entry.value}} {{histogramunit}}</span></td> <td class="histogram-items">
<td class="histogram-items"> <div *ngIf="showHistogram()">
<div *ngIf="histogramenabled" [style.background-color]="getHex(selectedColorMap.noValue)" [style.width]="getPart(selectedColorMap, entry)"> <span class="bar" [style.background-color]="getHex(entry.color)" [style.width]="getPart(layer.renderer, i)">
</div> </span>
</td>--> <span class="bar-label">{{getLabel(layer.renderer,i)}}</span>
</tr> </div>
<tr> </td>
<td colspan="4"></td> </tr>
</tr> <tr>
<!--<tr> <td colspan="4"></td>
<td> </tr>
<i class="fas fa-chart-bar" (click)="onClickHistoGram()"></i> <!--<tr *ngIf="layer.renderer.colorMap.entries.length > 0">
</td> <td>
<td colspan="3"></td> <i title="Show histogram" class="fa fa-bar-chart fa-rotate-90" (click)="onClickHistoGram()"></i>
</tr>--> </td>
</table> <td colspan="3"></td>
</tr>-->
</table>

View File

@@ -1,58 +1,67 @@
.container { .container {
max-width: 40em; max-width: 40em;
border-spacing: 0.5em; border-spacing: 0.5em;
font-family: inherit; font-family: inherit;
} }
.title { .title {
padding: 7px; padding: 7px;
text-align: center; text-align: center;
font-size: 14px; font-size: 14px;
line-height: 28px; line-height: 28px;
} }
.title > h4 { .title > h4 {
margin-bottom: 0; margin-bottom: 0;
} }
.legend-items { span.color {
width: 1.5em; display:inline-block;
height: 1.5em; width: 1.5em;
padding: 0.1em; height: 1.5em;
border-style: none; }
border-width: 0.05em;
} .legend-items {
padding: 0.1em;
.legend-items div { border-style: none;
width:100%; border-width: 0.05em;
height:100%; }
}
.legend-items div {
.legend-items-text { width:100%;
max-width: 20em; height:100%;
padding-left: 0.5em; }
text-align: left;
} .legend-items-text {
max-width: 20em;
.histogram-items { padding-left: 0.5em;
width: 5em; text-align: left;
padding-left: 1em; }
}
.histogram-items {
.histogram-items > div { width: 100%;
height: 1em; padding-left: 1em;
border-style: solid; }
border-width: 0.05em;
vertical-align: middle;
} .histogram-items-text {
max-width: 20em;
.histogram-items-text { font-size: 14pt;
max-width: 20em; padding-left: 1em;
font-size: 14pt; text-align: left;
padding-left: 1em; }
text-align: left;
} .bar {
display:inline-block;
height: 1em;
vertical-align: middle;
}
.bar-label {
margin-left:0.3em;
font-size:0.7em;
}

View File

@@ -1,66 +1,83 @@
import { Component, OnInit, Input,AfterViewInit } from '@angular/core'; import { Component, OnInit, Input,AfterViewInit } from '@angular/core';
import { IColorMap, IColor, IColorEntry,ILayer } from '../../models'; import { IColorMap, IColor, IColorEntry,ILayer, IRenderer } from '../../models/color.map';
@Component({ @Component({
selector: 'fm-map-layer-legend', selector: 'fm-map-layer-legend',
templateUrl: './legend.component.html', templateUrl: './legend.component.html',
styleUrls: ['./legend.component.scss'] styleUrls: ['./legend.component.scss']
}) })
export class LegendComponent implements OnInit,AfterViewInit { export class LegendComponent implements OnInit,AfterViewInit {
constructor() { constructor() {
} }
ngOnInit() { ngOnInit() {
} }
ngAfterViewInit() { ngAfterViewInit() {
} }
@Input() @Input()
layer: ILayer; layer: ILayer;
@Input() @Input()
legend: string; legend: string;
@Input() @Input()
histogram: string; histogram: string;
@Input() @Input()
showTitle: boolean = true; showTitle: boolean = true;
@Input() @Input()
histogramenabled: boolean; histogramenabled: boolean;
@Input() @Input()
legendunit: string; legendunit: string;
@Input() @Input()
histogramunit: string; histogramunit: string;
onClickHistoGram(): void { onClickHistoGram(): void {
this.histogramenabled = !this.histogramenabled; this.histogramenabled = !this.histogramenabled;
} }
public getHex(color: IColor): string {
return '#' + this.componentToHex(color.red) + this.componentToHex(color.green) + this.componentToHex(color.blue);
}
public getHex(color: IColor): string {
public componentToHex(c: number): string { return '#' + this.componentToHex(color.red) + this.componentToHex(color.green) + this.componentToHex(color.blue);
const hex = c.toString(16); }
return hex.length === 1 ? `0${hex}` : hex;
} private componentToHex(c: number): string {
const hex = c.toString(16);
private getPart(colorMap: IColorMap, colorEntry: IColorEntry): string { return hex.length === 1 ? `0${hex}` : hex;
let sumOfValue = colorMap.entries.reduce((sum, item) => sum + item.value, 0); }
let part = ((colorEntry.value / sumOfValue) * 100) + "%";
public getPart(renderer: IRenderer, index: number): string {
return part; let max = renderer.band.histogram.entries.reduce((max, entry) => entry.freqency > max ? entry.freqency : max, 0);
} let scale = 75 / max;
let part = (renderer.band.histogram.entries[index].freqency * scale) + "%";
}
return part;
}
public getLabel(renderer: IRenderer, index: number): string {
let scale = 100 / renderer.band.histogram.entries.reduce((sum, entry) => sum + entry.freqency, 0);
let percent = renderer.band.histogram.entries[index].freqency * scale;
return percent < 0.1 ? "" : percent.toFixed(1) + " %";
}
showLegend(): boolean {
return this.layer && this.layer.renderer && this.layer.renderer.renderType != "MULTIBAND_COLOR";
}
showHistogram(): boolean {
return this.histogramenabled && this.layer.renderer.band.histogram.entries && this.layer.renderer.band.histogram.entries.length > 0 && this.layer.renderer.colorMap.colormapType == "minmax";
}
}

View File

@@ -1 +0,0 @@
export * from './map-search.component';

View File

@@ -1,178 +1,178 @@
import { Component, Input, Output, OnInit, EventEmitter, SimpleChanges, OnChanges, ViewChild } from '@angular/core'; import { Component, Input, Output, OnInit, EventEmitter, SimpleChanges, OnChanges, ViewChild } from '@angular/core';
import { Observable , of } from 'rxjs'; import { Observable , of } from 'rxjs';
import { debounceTime,distinctUntilChanged,tap,switchMap,merge,catchError} from 'rxjs/operators'; import { debounceTime,distinctUntilChanged,tap,switchMap,merge,catchError} from 'rxjs/operators';
import { TypeaheadService, TimespanService } from '@farmmaps/common'; import { TypeaheadService, TimespanService } from '@farmmaps/common';
import { IQueryState,IPeriodState } from '../../models'; import { IQueryState } from '../../models/query.state';
import { fillProperties } from '@angular/core/src/util/property'; import { IPeriodState } from '../../models/period.state';
import { tassign } from 'tassign'; import { tassign } from 'tassign';
@Component({ @Component({
selector: 'fm-map-map-search', selector: 'fm-map-map-search',
templateUrl: './map-search.component.html', templateUrl: './map-search.component.html',
styleUrls: ['./map-search.component.scss'] styleUrls: ['./map-search.component.scss']
}) })
export class MapSearchComponent { export class MapSearchComponent {
@ViewChild('searchText') searchText; @ViewChild('searchText', { static: true }) searchText;
@Input() clearEnabled: boolean @Input() clearEnabled: boolean
@Input() set collapsed(collapsed: boolean) { @Input() set collapsed(collapsed: boolean) {
this.collapsedLocal = collapsed; this.collapsedLocal = collapsed;
if (collapsed) this.searchText.nativeElement.blur(); if (collapsed) this.searchText.nativeElement.blur();
} }
@Input() set searchMinified(minified: boolean) { @Input() set searchMinified(minified: boolean) {
this.searchMinifiedLocal = minified; this.searchMinifiedLocal = minified;
} }
@Input() period: IPeriodState @Input() period: IPeriodState
@Output() onSearch = new EventEmitter<IQueryState>(); @Output() onSearch = new EventEmitter<IQueryState>();
@Output() onClear = new EventEmitter<any>(); @Output() onClear = new EventEmitter<any>();
@Output() onSearchCollapse = new EventEmitter<any>(); @Output() onSearchCollapse = new EventEmitter<any>();
@Output() onSearchExpand = new EventEmitter<any>(); @Output() onSearchExpand = new EventEmitter<any>();
@Output() onToggleMenu = new EventEmitter<any>(); @Output() onToggleMenu = new EventEmitter<any>();
@Output() onOpenModal = new EventEmitter<string>(); @Output() onOpenModal = new EventEmitter<string>();
@Output() onCloseModal = new EventEmitter<any>(); @Output() onCloseModal = new EventEmitter<any>();
@Input() openedModalName: string; @Input() openedModalName: string;
@Input() set filterOptions(filterOptions: IQueryState) { @Input() set filterOptions(filterOptions: IQueryState) {
if (filterOptions && filterOptions.query && filterOptions.query.length > 0) { if (filterOptions && filterOptions.query && filterOptions.query.length > 0) {
this.disabled = false; this.disabled = false;
} else { } else {
this.disabled = true; this.disabled = true;
} }
this.filterOptionsLocal = tassign(this.filterOptionsLocal, { tags: filterOptions.tags, query: filterOptions.query,bbox:filterOptions.bbox }); this.filterOptionsLocal = tassign(this.filterOptionsLocal, { tags: filterOptions.tags, query: filterOptions.query,bbox:filterOptions.bbox });
if (filterOptions.tags) { if (filterOptions.tags) {
this.searchTextLocal = { name: filterOptions.tags }; this.searchTextLocal = { name: filterOptions.tags };
} else { } else {
this.searchTextLocal = { name: filterOptions.query }; this.searchTextLocal = { name: filterOptions.query };
} }
if (this.dateFilter) { if (this.dateFilter) {
this.filterOptionsLocal.startDate = this.startDate; this.filterOptionsLocal.startDate = this.startDate;
this.filterOptionsLocal.endDate = this.endDate; this.filterOptionsLocal.endDate = this.endDate;
} }
} }
public collapsedLocal: boolean = true; public collapsedLocal: boolean = true;
public searchMinifiedLocal: boolean = false; public searchMinifiedLocal: boolean = false;
public filterOptionsLocal: IQueryState; public filterOptionsLocal: IQueryState;
private extent: number[]; private extent: number[];
public searchTextLocal: any; public searchTextLocal: any;
public searchTextLocalOutput: string; public searchTextLocalOutput: string;
public dateFilter: boolean = true; public dateFilter: boolean = true;
public startDate: Date = new Date(new Date(Date.now()).getFullYear(), new Date(Date.now()).getMonth() - 3, 1); public startDate: Date = new Date(new Date(Date.now()).getFullYear(), new Date(Date.now()).getMonth() - 3, 1);
public endDate: Date = new Date(Date.now()); public endDate: Date = new Date(Date.now());
public startEndCaption: string = this.timespanService.getCaption(this.startDate, this.endDate, 4); public startEndCaption: string = this.timespanService.getCaption(this.startDate, this.endDate, 4);
searching = false; searching = false;
searchFailed = false; searchFailed = false;
hideSearchingWhenUnsubscribed = new Observable(() => () => this.searching = false); hideSearchingWhenUnsubscribed = new Observable(() => () => this.searching = false);
public disabled: boolean = true; public disabled: boolean = true;
constructor(private typeaheadService: TypeaheadService, private timespanService: TimespanService) { constructor(private typeaheadService: TypeaheadService, private timespanService: TimespanService) {
this.filterOptionsLocal = { query: "", tags: "", startDate: null, endDate: null, bboxFilter: true, itemType: null, itemCode:null,level:0,parentCode:null,bbox:[] }; this.filterOptionsLocal = { query: "", tags: "", startDate: null, endDate: null, bboxFilter: true, itemType: null, itemCode:null,level:0,parentCode:null,bbox:[] };
} }
search = (text$: Observable<string>) => search = (text$: Observable<string>) =>
text$.pipe( text$.pipe(
debounceTime(300), debounceTime(300),
distinctUntilChanged(), distinctUntilChanged(),
tap(() => this.searching = true), tap(() => this.searching = true),
switchMap(term => term.length < 1 ? of([]) : switchMap(term => term.length < 1 ? of([]) :
this.typeaheadService.getSearchTypeaheadItems(term).pipe( this.typeaheadService.getSearchTypeaheadItems(term).pipe(
tap(() => this.searchFailed = false), tap(() => this.searchFailed = false),
catchError(() => { catchError(() => {
this.searchFailed = true; this.searchFailed = true;
return of([]); return of([]);
})) ), })) ),
tap(() => this.searching = false), tap(() => this.searching = false),
merge(this.hideSearchingWhenUnsubscribed)); merge(this.hideSearchingWhenUnsubscribed));
formatter = (x: { name: string }) => x.name; formatter = (x: { name: string }) => x.name;
handleSearch(event) { handleSearch(event) {
this.filterOptionsLocal.tags = null; this.filterOptionsLocal.tags = null;
this.filterOptionsLocal.itemType = null; this.filterOptionsLocal.itemType = null;
this.filterOptionsLocal.itemCode = null; this.filterOptionsLocal.itemCode = null;
this.filterOptionsLocal.parentCode = null; this.filterOptionsLocal.parentCode = null;
this.filterOptionsLocal.query = this.searchTextLocalOutput; this.filterOptionsLocal.query = this.searchTextLocalOutput;
if (this.dateFilter) { if (this.dateFilter) {
this.filterOptionsLocal.startDate = this.startDate; this.filterOptionsLocal.startDate = this.startDate;
this.filterOptionsLocal.endDate = this.endDate; this.filterOptionsLocal.endDate = this.endDate;
} }
this.onSearch.emit(this.filterOptionsLocal); this.onSearch.emit(this.filterOptionsLocal);
} }
handleOpenSelectPeriodModal(event: MouseEvent) { handleOpenSelectPeriodModal(event: MouseEvent) {
event.preventDefault(); event.preventDefault();
this.onOpenModal.emit('selectPeriodModal'); this.onOpenModal.emit('selectPeriodModal');
} }
handleCloseModal() { handleCloseModal() {
this.onCloseModal.emit({}); this.onCloseModal.emit({});
} }
handleSelect(event) { handleSelect(event) {
event.preventDefault(); event.preventDefault();
this.filterOptionsLocal.query = null; this.filterOptionsLocal.query = null;
this.filterOptionsLocal.itemType = null; this.filterOptionsLocal.itemType = null;
this.filterOptionsLocal.itemCode = null; this.filterOptionsLocal.itemCode = null;
this.filterOptionsLocal.parentCode = null; this.filterOptionsLocal.parentCode = null;
this.filterOptionsLocal.tags = event.item.name; this.filterOptionsLocal.tags = event.item.name;
if (this.dateFilter) { if (this.dateFilter) {
this.filterOptionsLocal.startDate = this.startDate; this.filterOptionsLocal.startDate = this.startDate;
this.filterOptionsLocal.endDate = this.endDate; this.filterOptionsLocal.endDate = this.endDate;
} }
this.onSearch.emit(this.filterOptionsLocal); this.onSearch.emit(this.filterOptionsLocal);
this.searchTextLocal = { name: this.filterOptionsLocal.tags }; this.searchTextLocal = { name: this.filterOptionsLocal.tags };
} }
handleSelectPeriod(event: { startDate: Date, endDate: Date }) { handleSelectPeriod(event: { startDate: Date, endDate: Date }) {
this.startDate = event.startDate; this.startDate = event.startDate;
this.endDate = event.endDate; this.endDate = event.endDate;
this.handleCloseModal(); this.handleCloseModal();
this.startEndCaption = this.timespanService.getCaption(event.startDate, event.endDate, 4); this.startEndCaption = this.timespanService.getCaption(event.startDate, event.endDate, 4);
this.onSearch.emit(this.filterOptionsLocal); this.onSearch.emit(this.filterOptionsLocal);
} }
handleChangeEnableDateFilter(enabled) { handleChangeEnableDateFilter(enabled) {
this.dateFilter = enabled; this.dateFilter = enabled;
if (enabled) { if (enabled) {
this.filterOptionsLocal.startDate = this.startDate; this.filterOptionsLocal.startDate = this.startDate;
this.filterOptionsLocal.endDate = this.endDate; this.filterOptionsLocal.endDate = this.endDate;
} else { } else {
this.filterOptionsLocal.startDate = null; this.filterOptionsLocal.startDate = null;
this.filterOptionsLocal.endDate = null; this.filterOptionsLocal.endDate = null;
} }
if(this.filterOptionsLocal.query || this.filterOptionsLocal.tags) if(this.filterOptionsLocal.query || this.filterOptionsLocal.tags)
this.onSearch.emit(this.filterOptionsLocal); this.onSearch.emit(this.filterOptionsLocal);
} }
handleChangeEnableBBOXFilter(enabled) { handleChangeEnableBBOXFilter(enabled) {
this.filterOptionsLocal.bboxFilter = enabled; this.filterOptionsLocal.bboxFilter = enabled;
if (this.filterOptionsLocal.query || this.filterOptionsLocal.tags) if (this.filterOptionsLocal.query || this.filterOptionsLocal.tags)
this.onSearch.emit(this.filterOptionsLocal); this.onSearch.emit(this.filterOptionsLocal);
} }
handleToggleMenu(event) { handleToggleMenu(event) {
this.onToggleMenu.emit({}); this.onToggleMenu.emit({});
} }
handleFocus(event) { handleFocus(event) {
this.onSearchExpand.emit({}); this.onSearchExpand.emit({});
} }
handleChange(event: string) { handleChange(event: string) {
this.searchTextLocalOutput = event; this.searchTextLocalOutput = event;
if (event && event.length == 1) { if (event && event.length == 1) {
this.onSearchExpand.emit({}); this.onSearchExpand.emit({});
} }
if (event && event.length > 0) if (event && event.length > 0)
this.disabled = false; this.disabled = false;
else else
this.disabled = true; this.disabled = true;
} }
handleClearClick(event) { handleClearClick(event) {
this.onClear.emit({}); this.onClear.emit({});
} }
} }

View File

@@ -1,303 +1,307 @@
import { Component, OnInit, OnDestroy, HostListener, Inject, ViewChild, AfterViewInit } from '@angular/core'; import { Component, OnInit, OnDestroy, HostListener, Inject, ViewChild, AfterViewInit } from '@angular/core';
import { Location } from '@angular/common'; import { Location } from '@angular/common';
import { Observable, Subject, Subscription,combineLatest, from } from 'rxjs'; import { Observable, Subject, Subscription,combineLatest, from } from 'rxjs';
import { debounce, withLatestFrom, first, combineAll } from 'rxjs/operators'; import { debounce, withLatestFrom, first, combineAll } from 'rxjs/operators';
import { Router, ActivatedRoute, ParamMap, Event } from '@angular/router'; import { Router, ActivatedRoute, ParamMap, Event } from '@angular/router';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
//import { proj,Map } from 'openlayers'; //import { proj,Map } from 'openlayers';
// Map // Map
import * as mapReducers from '../../reducers/map.reducer'; import * as mapReducers from '../../reducers/map.reducer';
import * as mapActions from '../../actions/map.actions'; import * as mapActions from '../../actions/map.actions';
import { IMapState,ISelectedFeatures,IItemLayer, ItemLayer,IQueryState,IPeriodState } from '../../models'; import { IMapState} from '../../models/map.state';
import { IDroppedFile } from '../aol/file-drop-target/file-drop-target.component'; import { ISelectedFeatures } from '../../models/selected.features';
import { IMetaData } from '../meta-data-modal/meta-data-modal.component'; import { IItemLayer } from '../../models/item.layer';
import { StateSerializerService } from '../../services/state-serializer.service'; import { IQueryState } from '../../models/query.state';
import { GeolocationService} from '../../services/geolocation.service'; import { IPeriodState } from '../../models/period.state';
import { IDroppedFile } from '../aol/file-drop-target/file-drop-target.component';
// AppCommon import { IMetaData } from '../meta-data-modal/meta-data-modal.component';
import { ResumableFileUploadService, ItemTypeService } from '@farmmaps/common'; import { StateSerializerService } from '../../services/state-serializer.service';
import { IItemType, IItem } from '@farmmaps/common'; import { GeolocationService} from '../../services/geolocation.service';
import {commonReducers} from '@farmmaps/common';
import {commonActions} from '@farmmaps/common'; // AppCommon
import { ResumableFileUploadService, ItemTypeService } from '@farmmaps/common';
import {Feature} from 'ol'; import { IItemType, IItem } from '@farmmaps/common';
import {Extent,createEmpty,extend } from 'ol/extent'; import {commonReducers} from '@farmmaps/common';
import {transform} from 'ol/proj'; import {commonActions} from '@farmmaps/common';
import { query } from '@angular/animations';
import { tassign } from 'tassign'; import {Feature} from 'ol';
import {Extent,createEmpty,extend } from 'ol/extent';
import {transform} from 'ol/proj';
@Component({ import { query } from '@angular/animations';
selector: 'fm-map-map', import { tassign } from 'tassign';
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss']
}) @Component({
selector: 'fm-map-map',
export class MapComponent implements OnInit, OnDestroy,AfterViewInit { templateUrl: './map.component.html',
title: string = 'Map'; styleUrls: ['./map.component.scss']
public openedModalName: Observable<string>; })
public itemTypes: Observable<{ [id: string]: IItemType }>;
public mapState: Observable<IMapState>; export class MapComponent implements OnInit, OnDestroy,AfterViewInit {
public features: Observable<Array<Feature>>; title: string = 'Map';
public overlayLayers: Observable<Array<IItemLayer>>; public openedModalName: Observable<string>;
public selectedOverlayLayer: Observable<IItemLayer>; public itemTypes: Observable<{ [id: string]: IItemType }>;
public selectedItemLayer: Observable<IItemLayer>; public mapState: Observable<IMapState>;
public baseLayers: Observable<Array<IItemLayer>>; public features: Observable<Array<Feature>>;
public selectedBaseLayer: Observable<IItemLayer>; public overlayLayers: Observable<Array<IItemLayer>>;
public projection: Observable<string>; public selectedOverlayLayer: Observable<IItemLayer>;
public selectedFeatures: Subject<ISelectedFeatures> = new Subject<ISelectedFeatures>(); public selectedItemLayer: Observable<IItemLayer>;
public droppedFile: Subject<IDroppedFile> = new Subject<IDroppedFile>(); public baseLayers: Observable<Array<IItemLayer>>;
private paramSub: Subscription; public selectedBaseLayer: Observable<IItemLayer>;
private itemTypeSub: Subscription; public projection: Observable<string>;
private mapStateSub: Subscription; public selectedFeatures: Subject<ISelectedFeatures> = new Subject<ISelectedFeatures>();
private queryStateSub: Subscription; public droppedFile: Subject<IDroppedFile> = new Subject<IDroppedFile>();
public parentCode: Observable<string>; private paramSub: Subscription;
public panelVisible: Observable<boolean>; private itemTypeSub: Subscription;
public panelCollapsed: Observable<boolean>; private mapStateSub: Subscription;
public selectedFeature: Observable<Feature>; private queryStateSub: Subscription;
public selectedItem: Observable<IItem>; public parentCode: Observable<string>;
public queryState: Observable<IQueryState>; public panelVisible: Observable<boolean>;
public period: Observable<IPeriodState>; public panelCollapsed: Observable<boolean>;
public clearEnabled: Observable<boolean>; public selectedFeature: Observable<Feature>;
public searchCollapsed: Observable<boolean>; public selectedItem: Observable<IItem>;
public searchMinified: Observable<boolean>; public queryState: Observable<IQueryState>;
public menuVisible: Observable<boolean>; public period: Observable<IPeriodState>;
public query: Observable<IQueryState>; public clearEnabled: Observable<boolean>;
public position: Observable<Position>; public searchCollapsed: Observable<boolean>;
public baseLayersCollapsed:boolean = true; public searchMinified: Observable<boolean>;
public overlayLayersCollapsed: boolean = true; public menuVisible: Observable<boolean>;
public extent: Observable<Extent>; public query: Observable<IQueryState>;
@ViewChild('map') map; public position: Observable<Position>;
public baseLayersCollapsed:boolean = true;
constructor(private store: Store<mapReducers.State | commonReducers.State>, private route: ActivatedRoute, private router: Router, private uploadService: ResumableFileUploadService, private serializeService: StateSerializerService, public itemTypeService: ItemTypeService, private location: Location, private geolocationService: GeolocationService ) { public overlayLayersCollapsed: boolean = true;
} public extent: Observable<Extent>;
@ViewChild('map', { static: true }) map;
@HostListener('document:keyup', ['$event'])
escapeClose(event: KeyboardEvent) { constructor(private store: Store<mapReducers.State | commonReducers.State>, private route: ActivatedRoute, private router: Router, private uploadService: ResumableFileUploadService, private serializeService: StateSerializerService, public itemTypeService: ItemTypeService, private location: Location, private geolocationService: GeolocationService ) {
let x = event.keyCode; }
if (x === 27) {
this.handleCloseModal() @HostListener('document:keyup', ['$event'])
} escapeClose(event: KeyboardEvent) {
} let x = event.keyCode;
if (x === 27) {
handleOpenModal(modalName: string) { this.handleCloseModal()
this.store.dispatch(new commonActions.OpenModal(modalName)); }
} }
handleCloseModal() { handleOpenModal(modalName: string) {
this.store.dispatch(new commonActions.CloseModal()); this.store.dispatch(new commonActions.OpenModal(modalName));
} }
handleFileDropped(droppedFile: IDroppedFile) { handleCloseModal() {
this.uploadService.addFiles(droppedFile.files, droppedFile.event, { parentCode:droppedFile.parentCode, geometry:droppedFile.geometry }); this.store.dispatch(new commonActions.CloseModal());
} }
handleFeaturesSelected(feature: Feature) { handleFileDropped(droppedFile: IDroppedFile) {
if (feature) { this.uploadService.addFiles(droppedFile.files, droppedFile.event, { parentCode:droppedFile.parentCode, geometry:droppedFile.geometry });
let newQuery = tassign(mapReducers.initialQueryState, { itemCode: feature.get('code') }); }
this.store.dispatch(new mapActions.DoQuery(newQuery));
} handleFeaturesSelected(feature: Feature) {
} if (feature) {
let newQuery = tassign(mapReducers.initialQueryState, { itemCode: feature.get('code') });
handleSearch(queryState: IQueryState) { this.store.dispatch(new mapActions.DoQuery(newQuery));
this.store.dispatch(new mapActions.DoQuery(queryState)); }
} }
ngOnInit() { handleSearch(queryState: IQueryState) {
this.store.dispatch(new mapActions.Init()); this.store.dispatch(new mapActions.DoQuery(queryState));
this.selectedFeatures.next({x:0,y:0,features:[]}); }
this.mapState = this.store.select(mapReducers.selectGetMapState);
this.parentCode = this.store.select(mapReducers.selectGetParentCode); ngOnInit() {
this.features = this.store.select(mapReducers.selectGetFeatures); this.store.dispatch(new mapActions.Init());
this.overlayLayers = this.store.select(mapReducers.selectGetOverlayLayers); this.selectedFeatures.next({x:0,y:0,features:[]});
this.selectedOverlayLayer = this.store.select(mapReducers.selectGetSelectedOverlayLayer); this.mapState = this.store.select(mapReducers.selectGetMapState);
this.baseLayers = this.store.select(mapReducers.selectGetBaseLayers); this.parentCode = this.store.select(mapReducers.selectGetParentCode);
this.projection = this.store.select(mapReducers.selectGetProjection); this.features = this.store.select(mapReducers.selectGetFeatures);
this.selectedBaseLayer = this.store.select(mapReducers.selectGetSelectedBaseLayer); this.overlayLayers = this.store.select(mapReducers.selectGetOverlayLayers);
this.panelVisible = this.store.select(mapReducers.selectGetPanelVisible); this.selectedOverlayLayer = this.store.select(mapReducers.selectGetSelectedOverlayLayer);
this.panelCollapsed = this.store.select(mapReducers.selectGetPanelCollapsed); this.baseLayers = this.store.select(mapReducers.selectGetBaseLayers);
this.selectedFeature = this.store.select(mapReducers.selectGetSelectedFeature); this.projection = this.store.select(mapReducers.selectGetProjection);
this.selectedItem = this.store.select(mapReducers.selectGetSelectedItem); this.selectedBaseLayer = this.store.select(mapReducers.selectGetSelectedBaseLayer);
this.queryState = this.store.select(mapReducers.selectGetQueryState); this.panelVisible = this.store.select(mapReducers.selectGetPanelVisible);
this.clearEnabled = this.store.select(mapReducers.selectGetClearEnabled); this.panelCollapsed = this.store.select(mapReducers.selectGetPanelCollapsed);
this.searchCollapsed = this.store.select(mapReducers.selectGetSearchCollapsed); this.selectedFeature = this.store.select(mapReducers.selectGetSelectedFeature);
this.searchMinified = this.store.select(mapReducers.selectGetSearchMinified); this.selectedItem = this.store.select(mapReducers.selectGetSelectedItem);
this.menuVisible = this.store.select(mapReducers.selectGetMenuVisible); this.queryState = this.store.select(mapReducers.selectGetQueryState);
this.openedModalName = this.store.select(commonReducers.selectOpenedModalName); this.clearEnabled = this.store.select(mapReducers.selectGetClearEnabled);
this.query = this.store.select(mapReducers.selectGetQuery); this.searchCollapsed = this.store.select(mapReducers.selectGetSearchCollapsed);
this.extent = this.store.select(mapReducers.selectGetExtent); this.searchMinified = this.store.select(mapReducers.selectGetSearchMinified);
this.selectedFeatures.next(null); this.menuVisible = this.store.select(mapReducers.selectGetMenuVisible);
this.selectedItemLayer = this.store.select(mapReducers.selectGetSelectedItemLayer); this.openedModalName = this.store.select(commonReducers.selectOpenedModalName);
this.period = this.store.select(mapReducers.selectGetPeriod); this.query = this.store.select(mapReducers.selectGetQuery);
this.position = this.geolocationService.getCurrentPosition(); this.extent = this.store.select(mapReducers.selectGetExtent);
this.selectedFeatures.next(null);
this.mapState.pipe(withLatestFrom(this.queryState)).subscribe((state) => { this.selectedItemLayer = this.store.select(mapReducers.selectGetSelectedItemLayer);
this.replaceUrl(state[0], state[1], true); this.period = this.store.select(mapReducers.selectGetPeriod);
}); this.position = this.geolocationService.getCurrentPosition();
this.query.pipe(withLatestFrom(this.mapState)).subscribe((state) => {
this.replaceUrl(state[1], state[0],false); this.mapState.pipe(withLatestFrom(this.queryState)).subscribe((state) => {
}); this.replaceUrl(state[0], state[1], true);
} });
this.query.pipe(withLatestFrom(this.mapState)).subscribe((state) => {
private stateSetCount: number = 0; this.replaceUrl(state[1], state[0],false);
private lastQueryState: string = this.serializeService.serialize(mapReducers.initialQueryState); });
private lastMapState: string = ""; }
ngAfterViewInit() {
this.paramSub = this.route.paramMap.subscribe((params: ParamMap) => { private stateSetCount: number = 0;
//console.log("Param sub"); private lastQueryState: string = this.serializeService.serialize(mapReducers.initialQueryState);
var newMapState: IMapState = null; private lastMapState: string = "";
var newQueryState: IQueryState = null; ngAfterViewInit() {
var mapStateChanged = false; this.paramSub = this.route.paramMap.subscribe((params: ParamMap) => {
var queryStateChanged = false; //console.log("Param sub");
if (params.has("xCenter") && params.has("yCenter")) { var newMapState: IMapState = null;
let xCenter = parseFloat(params.get("xCenter")); var newQueryState: IQueryState = null;
let yCenter = parseFloat(params.get("yCenter")); var mapStateChanged = false;
let zoom = parseFloat(params.get("zoom")); var queryStateChanged = false;
let rotation = parseFloat(params.get("rotation")); if (params.has("xCenter") && params.has("yCenter")) {
let baseLayer = params.get("baseLayer")?params.get("baseLayer"):""; let xCenter = parseFloat(params.get("xCenter"));
newMapState = { xCenter: xCenter, yCenter: yCenter, zoom: zoom, rotation: rotation, baseLayerCode: baseLayer } let yCenter = parseFloat(params.get("yCenter"));
mapStateChanged = this.lastMapState != JSON.stringify(newMapState) && this.stateSetCount == 0; let zoom = parseFloat(params.get("zoom"));
this.lastMapState = JSON.stringify(newMapState); let rotation = parseFloat(params.get("rotation"));
} let baseLayer = params.get("baseLayer")?params.get("baseLayer"):"";
if (params.has("queryState")) { newMapState = { xCenter: xCenter, yCenter: yCenter, zoom: zoom, rotation: rotation, baseLayerCode: baseLayer }
let queryState = params.get("queryState"); mapStateChanged = this.lastMapState != JSON.stringify(newMapState) && this.stateSetCount == 0;
newQueryState = tassign(mapReducers.initialQueryState); this.lastMapState = JSON.stringify(newMapState);
if (queryState != "") { }
newQueryState = this.serializeService.deserialize(queryState); if (params.has("queryState")) {
} let queryState = params.get("queryState");
queryStateChanged = this.lastQueryState != queryState; newQueryState = tassign(mapReducers.initialQueryState);
this.lastQueryState = queryState; if (queryState != "") {
} newQueryState = this.serializeService.deserialize(queryState);
}
if (mapStateChanged && queryStateChanged) { queryStateChanged = this.lastQueryState != queryState;
//console.log("Both states"); this.lastQueryState = queryState;
this.store.dispatch(new mapActions.SetState(newMapState, newQueryState)); }
} else if (mapStateChanged) {
//console.log("Map state"); if (mapStateChanged && queryStateChanged) {
this.store.dispatch(new mapActions.SetMapState(newMapState)); //console.log("Both states");
} else if (queryStateChanged) { this.store.dispatch(new mapActions.SetState(newMapState, newQueryState));
//console.log("Query state"); } else if (mapStateChanged) {
this.store.dispatch(new mapActions.SetQueryState(newQueryState)); //console.log("Map state");
} this.store.dispatch(new mapActions.SetMapState(newMapState));
this.stateSetCount += 1; } else if (queryStateChanged) {
}); //console.log("Query state");
setTimeout(() => { this.store.dispatch(new mapActions.SetQueryState(newQueryState));
this.map.instance.updateSize(); }
}, 500); this.stateSetCount += 1;
} });
setTimeout(() => {
handleSearchCollapse(event) { this.map.instance.updateSize();
this.store.dispatch(new mapActions.CollapseSearch()); }, 500);
} }
handleSearchExpand(event) { handleSearchCollapse(event) {
this.store.dispatch(new mapActions.ExpandSearch()); this.store.dispatch(new mapActions.CollapseSearch());
} }
handleToggleMenu(event) { handleSearchExpand(event) {
this.store.dispatch(new mapActions.ToggleMenu()); this.store.dispatch(new mapActions.ExpandSearch());
} }
handleToggleBaseLayers(event:MouseEvent) { handleToggleMenu(event) {
this.baseLayersCollapsed = !this.baseLayersCollapsed; this.store.dispatch(new mapActions.ToggleMenu());
event.preventDefault(); }
}
handleToggleBaseLayers(event:MouseEvent) {
handleToggleOverlayLayers(event: MouseEvent) { this.baseLayersCollapsed = !this.baseLayersCollapsed;
this.overlayLayersCollapsed = !this.overlayLayersCollapsed; event.preventDefault();
event.preventDefault(); }
}
handleToggleOverlayLayers(event: MouseEvent) {
handlePredefinedQuery(event: MouseEvent, query: any) { this.overlayLayersCollapsed = !this.overlayLayersCollapsed;
event.preventDefault(); event.preventDefault();
var queryState = tassign(mapReducers.initialQueryState, query); }
this.store.dispatch(new mapActions.DoQuery(queryState));
} handlePredefinedQuery(event: MouseEvent, query: any) {
event.preventDefault();
handleTrijntjeClick(event: MouseEvent, query: any) { var queryState = tassign(mapReducers.initialQueryState, query);
event.preventDefault(); this.store.dispatch(new mapActions.DoQuery(queryState));
var queryState = tassign(mapReducers.initialQueryState, query); }
var mapState = JSON.parse(this.lastMapState);
this.router.navigate(["app","trijntje" , mapState.xCenter.toFixed(5), mapState.yCenter.toFixed(5), mapState.zoom, mapState.rotation.toFixed(2), mapState.baseLayerCode, this.serializeService.serialize(queryState)], { replaceUrl: false }); handleTrijntjeClick(event: MouseEvent, query: any) {
} event.preventDefault();
var queryState = tassign(mapReducers.initialQueryState, query);
replaceUrl(mapState: IMapState, queryState: IQueryState, replace: boolean = true) { var mapState = JSON.parse(this.lastMapState);
console.debug(`Replace url : Baselayer(${mapState.baseLayerCode}) Querystate(${this.serializeService.serialize(queryState)})`); this.router.navigate(["app","trijntje" , mapState.xCenter.toFixed(5), mapState.yCenter.toFixed(5), mapState.zoom, mapState.rotation.toFixed(2), mapState.baseLayerCode, this.serializeService.serialize(queryState)], { replaceUrl: false });
let parts =["."]; }
parts.push(mapState.xCenter.toFixed(5));
parts.push(mapState.yCenter.toFixed(5)); replaceUrl(mapState: IMapState, queryState: IQueryState, replace: boolean = true) {
parts.push( mapState.zoom.toFixed(0)); console.debug(`Replace url : Baselayer(${mapState.baseLayerCode}) Querystate(${this.serializeService.serialize(queryState)})`);
parts.push( mapState.rotation.toFixed(2)); let parts =["."];
if(mapState.baseLayerCode!="") { parts.push(mapState.xCenter.toFixed(5));
parts.push(mapState.baseLayerCode); parts.push(mapState.yCenter.toFixed(5));
parts.push( this.serializeService.serialize(queryState)); parts.push( mapState.zoom.toFixed(0));
this.router.navigate(parts, { replaceUrl: replace,relativeTo:this.route.parent }); parts.push( mapState.rotation.toFixed(2));
} if(mapState.baseLayerCode!="") {
} parts.push(mapState.baseLayerCode);
parts.push( this.serializeService.serialize(queryState));
handleOnMoveEnd(event) { this.router.navigate(parts, { replaceUrl: replace,relativeTo:this.route.parent });
var map = event.map; }
var view = map.getView(); }
var rotation = view.getRotation();
var zoom = view.getZoom(); handleOnMoveEnd(event) {
var center = transform(view.getCenter(), view.getProjection(), "EPSG:4326"); var map = event.map;
var extent = view.calculateExtent(this.map.instance.getSize()); var view = map.getView();
let mapState: IMapState = { xCenter: center[0], yCenter: center[1], zoom: zoom, rotation: rotation, baseLayerCode: null }; var rotation = view.getRotation();
let state = { mapState: mapState, extent: extent }; var zoom = view.getZoom();
let source = from([state]); var center = transform(view.getCenter(), view.getProjection(), "EPSG:4326");
source.pipe(withLatestFrom(this.selectedBaseLayer), withLatestFrom(this.queryState)).subscribe(([[state, baselayer], queryState]) => { var extent = view.calculateExtent(this.map.instance.getSize());
if (mapState && baselayer && queryState) { let mapState: IMapState = { xCenter: center[0], yCenter: center[1], zoom: zoom, rotation: rotation, baseLayerCode: null };
let newMapState = tassign(state.mapState, { baseLayerCode: baselayer.item.code }); let state = { mapState: mapState, extent: extent };
this.replaceUrl(newMapState, tassign(queryState, { bbox: queryState.bboxFilter ? state.extent : queryState.bbox })); let source = from([state]);
this.store.dispatch(new mapActions.SetViewExtent(state.extent)); source.pipe(withLatestFrom(this.selectedBaseLayer), withLatestFrom(this.queryState)).subscribe(([[state, baselayer], queryState]) => {
} if (mapState && baselayer && queryState) {
}); let newMapState = tassign(state.mapState, { baseLayerCode: baselayer.item.code });
} this.replaceUrl(newMapState, tassign(queryState, { bbox: queryState.bboxFilter ? state.extent : queryState.bbox }));
this.store.dispatch(new mapActions.SetViewExtent(state.extent));
handleOnMouseDown(event: MouseEvent) { }
this.store.dispatch(new mapActions.CollapseSearch()); });
} }
handleOnDownload(event) { handleOnMouseDown(event: MouseEvent) {
this.store.dispatch(new mapActions.CollapseSearch());
} }
handleClearSearch(event) { handleOnDownload(event) {
this.store.dispatch(new commonActions.Escape(true, false));
} }
handleOnDelete(itemLayer: IItemLayer) { handleClearSearch(event) {
this.store.dispatch(new mapActions.RemoveLayer(itemLayer)); this.store.dispatch(new commonActions.Escape(true, false));
} }
handleOnToggleVisibility(itemLayer: IItemLayer) { handleOnDelete(itemLayer: IItemLayer) {
this.store.dispatch(new mapActions.SetVisibility(itemLayer,!itemLayer.visible)); this.store.dispatch(new mapActions.RemoveLayer(itemLayer));
} }
handleOnSetOpacity(event:{ layer: IItemLayer,opacity:number }) { handleOnToggleVisibility(itemLayer: IItemLayer) {
this.store.dispatch(new mapActions.SetOpacity(event.layer, event.opacity)); this.store.dispatch(new mapActions.SetVisibility(itemLayer,!itemLayer.visible));
} }
handleZoomToExtent(itemLayer: IItemLayer) { handleOnSetOpacity(event:{ layer: IItemLayer,opacity:number }) {
var extent = createEmpty(); this.store.dispatch(new mapActions.SetOpacity(event.layer, event.opacity));
extend(extent, itemLayer.layer.getExtent()); }
if (extent) {
this.store.dispatch(new mapActions.SetExtent(extent)); handleZoomToExtent(itemLayer: IItemLayer) {
} var extent = createEmpty();
} extend(extent, itemLayer.layer.getExtent());
if (extent) {
handleSelectBaseLayer(itemLayer: IItemLayer) { this.store.dispatch(new mapActions.SetExtent(extent));
this.store.dispatch(new mapActions.SelectBaseLayer(itemLayer)); }
} }
handleSelectOverlayLayer(itemLayer: IItemLayer) { handleSelectBaseLayer(itemLayer: IItemLayer) {
this.store.dispatch(new mapActions.SelectOverlayLayer(itemLayer)); this.store.dispatch(new mapActions.SelectBaseLayer(itemLayer));
} }
ngOnDestroy() { handleSelectOverlayLayer(itemLayer: IItemLayer) {
this.paramSub.unsubscribe(); this.store.dispatch(new mapActions.SelectOverlayLayer(itemLayer));
if (this.itemTypeSub) this.itemTypeSub.unsubscribe(); }
if (this.mapStateSub) this.mapStateSub.unsubscribe();
if (this.queryStateSub) this.queryStateSub.unsubscribe(); } ngOnDestroy() {
} this.paramSub.unsubscribe();
if (this.itemTypeSub) this.itemTypeSub.unsubscribe();
if (this.mapStateSub) this.mapStateSub.unsubscribe();
if (this.queryStateSub) this.queryStateSub.unsubscribe(); }
}

View File

@@ -1,61 +1,61 @@
import { Component, Output, ViewChild, EventEmitter, Input, ElementRef, HostListener } from '@angular/core'; import { Component, Output, ViewChild, EventEmitter, Input, ElementRef, HostListener } from '@angular/core';
import { FormGroup,FormBuilder, Validators } from '@angular/forms'; import { FormGroup,FormBuilder, Validators } from '@angular/forms';
import { IListItem } from '@farmmaps/common'; import { IListItem } from '@farmmaps/common';
import { IDroppedFile } from '../aol/file-drop-target/file-drop-target.component'; import { IDroppedFile } from '../aol/file-drop-target/file-drop-target.component';
import {NgbModal, NgbModalRef} from "@ng-bootstrap/ng-bootstrap"; import {NgbModal, NgbModalRef} from "@ng-bootstrap/ng-bootstrap";
export interface IMetaData { export interface IMetaData {
droppedFile: IDroppedFile, droppedFile: IDroppedFile,
attributes: any attributes: any
} }
@Component({ @Component({
selector: 'fm-map-meta-data-modal', selector: 'fm-map-meta-data-modal',
templateUrl: 'meta-data-modal.component.html' templateUrl: 'meta-data-modal.component.html'
}) })
export class MetaDataModalComponent { export class MetaDataModalComponent {
private modalName: string = 'metaDataModal'; private modalName: string = 'metaDataModal';
private modalRef: NgbModalRef; private modalRef: NgbModalRef;
@ViewChild('content') _templateModal:ElementRef; @ViewChild('content', { static: true }) _templateModal:ElementRef;
@Input() droppedFile: IDroppedFile; @Input() droppedFile: IDroppedFile;
@Input() set modalState(_modalState:any) {; @Input() set modalState(_modalState:any) {;
if(_modalState == this.modalName) { if(_modalState == this.modalName) {
this.openModal() this.openModal()
} else if(this.modalRef) { } else if(this.modalRef) {
this.closeModal(); this.closeModal();
} }
} }
@Input() event: IListItem; @Input() event: IListItem;
@Output() onCloseModal = new EventEmitter<any>(); @Output() onCloseModal = new EventEmitter<any>();
@Output() onAddFilesWithMetaData = new EventEmitter<IMetaData>(); @Output() onAddFilesWithMetaData = new EventEmitter<IMetaData>();
constructor(private modalService: NgbModal, public fb: FormBuilder) { } constructor(private modalService: NgbModal, public fb: FormBuilder) { }
public metaDataForm: FormGroup; public metaDataForm: FormGroup;
handleMetaDataEntered(event) { handleMetaDataEntered(event) {
if (this.metaDataForm.valid) { if (this.metaDataForm.valid) {
this.onAddFilesWithMetaData.emit({ droppedFile: this.droppedFile, attributes: { name: this.metaDataForm.value.name } }); this.onAddFilesWithMetaData.emit({ droppedFile: this.droppedFile, attributes: { name: this.metaDataForm.value.name } });
} }
} }
openModal() { openModal() {
//Timeout trick to avoid ExpressionChangedAfterItHasBeenCheckedError //Timeout trick to avoid ExpressionChangedAfterItHasBeenCheckedError
setTimeout(() => this.modalRef = this.modalService.open(this._templateModal, { backdrop: 'static', keyboard: false })); setTimeout(() => this.modalRef = this.modalService.open(this._templateModal, { backdrop: 'static', keyboard: false }));
} }
closeModal() { closeModal() {
this.modalRef.close(); this.modalRef.close();
this.metaDataForm.patchValue({ name: "" }); this.metaDataForm.patchValue({ name: "" });
} }
ngOnInit(): void { ngOnInit(): void {
this.metaDataForm = this.fb.group({ this.metaDataForm = this.fb.group({
name: ["", Validators.compose([Validators.required, Validators.pattern("[a-zA-Z0-9_].*")])] name: ["", Validators.compose([Validators.required, Validators.pattern("[a-zA-Z0-9_].*")])]
}); });
} }
} }

View File

@@ -1,93 +1,93 @@
import { Component, Output, ViewChild, EventEmitter, Input, ElementRef, HostListener } from '@angular/core'; import { Component, Output, ViewChild, EventEmitter, Input, ElementRef, HostListener } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModal, NgbModalRef, NgbDateStruct, NgbCalendar, NgbDateAdapter } from "@ng-bootstrap/ng-bootstrap"; import { NgbModal, NgbModalRef, NgbDateStruct, NgbCalendar, NgbDateAdapter } from "@ng-bootstrap/ng-bootstrap";
import { NgbDateNativeAdapter } from '@farmmaps/common'; import { NgbDateNativeAdapter } from '@farmmaps/common';
const equals = (one: NgbDateStruct, two: NgbDateStruct) => const equals = (one: NgbDateStruct, two: NgbDateStruct) =>
one && two && two.year === one.year && two.month === one.month && two.day === one.day; one && two && two.year === one.year && two.month === one.month && two.day === one.day;
const before = (one: NgbDateStruct, two: NgbDateStruct) => const before = (one: NgbDateStruct, two: NgbDateStruct) =>
!one || !two ? false : one.year === two.year ? one.month === two.month ? one.day === two.day !one || !two ? false : one.year === two.year ? one.month === two.month ? one.day === two.day
? false : one.day < two.day : one.month < two.month : one.year < two.year; ? false : one.day < two.day : one.month < two.month : one.year < two.year;
const after = (one: NgbDateStruct, two: NgbDateStruct) => const after = (one: NgbDateStruct, two: NgbDateStruct) =>
!one || !two ? false : one.year === two.year ? one.month === two.month ? one.day === two.day !one || !two ? false : one.year === two.year ? one.month === two.month ? one.day === two.day
? false : one.day > two.day : one.month > two.month : one.year > two.year; ? false : one.day > two.day : one.month > two.month : one.year > two.year;
@Component({ @Component({
selector: 'fm-map-select-period-modal', selector: 'fm-map-select-period-modal',
templateUrl: 'select-period-modal.component.html', templateUrl: 'select-period-modal.component.html',
styleUrls: ['select-period-modal.component.scss'] styleUrls: ['select-period-modal.component.scss']
}) })
export class SelectPeriodModalComponent { export class SelectPeriodModalComponent {
private modalName: string = 'selectPeriodModal'; private modalName: string = 'selectPeriodModal';
private modalRef: NgbModalRef; private modalRef: NgbModalRef;
private dateAdapter = new NgbDateNativeAdapter(); private dateAdapter = new NgbDateNativeAdapter();
hoveredDate: NgbDateStruct; hoveredDate: NgbDateStruct;
fromDate: NgbDateStruct; fromDate: NgbDateStruct;
toDate: NgbDateStruct; toDate: NgbDateStruct;
@ViewChild('content') _templateModal:ElementRef; @ViewChild('content', { static: true }) _templateModal:ElementRef;
@Input() set modalState(_modalState:any) {; @Input() set modalState(_modalState:any) {;
if(_modalState == this.modalName) { if(_modalState == this.modalName) {
this.openModal() this.openModal()
} else if(this.modalRef) { } else if(this.modalRef) {
this.closeModal(); this.closeModal();
} }
} }
@Input() set startDate(_modalState: Date) { @Input() set startDate(_modalState: Date) {
this.fromDate = this.dateAdapter.fromModel(_modalState); this.fromDate = this.dateAdapter.fromModel(_modalState);
} }
@Input() set endDate(_modalState: Date) { @Input() set endDate(_modalState: Date) {
var d = new Date(_modalState); var d = new Date(_modalState);
d.setDate(d.getDate() - 1); d.setDate(d.getDate() - 1);
this.toDate = this.dateAdapter.fromModel(d); this.toDate = this.dateAdapter.fromModel(d);
} }
@Output() onCloseModal = new EventEmitter<any>(); @Output() onCloseModal = new EventEmitter<any>();
@Output() onSelect = new EventEmitter<{ startDate: Date, endDate: Date }>(); @Output() onSelect = new EventEmitter<{ startDate: Date, endDate: Date }>();
constructor(private modalService: NgbModal, private calendar: NgbCalendar) { } constructor(private modalService: NgbModal, private calendar: NgbCalendar) { }
openModal() { openModal() {
//Timeout trick to avoid ExpressionChangedAfterItHasBeenCheckedError //Timeout trick to avoid ExpressionChangedAfterItHasBeenCheckedError
setTimeout(() => this.modalRef = this.modalService.open(this._templateModal, { backdrop: 'static', keyboard: false})); setTimeout(() => this.modalRef = this.modalService.open(this._templateModal, { backdrop: 'static', keyboard: false}));
} }
closeModal() { closeModal() {
this.modalRef.close(); this.modalRef.close();
} }
ngOnInit(): void { ngOnInit(): void {
} }
onDateChange(date: NgbDateStruct) { onDateChange(date: NgbDateStruct) {
if (!this.fromDate && !this.toDate) { if (!this.fromDate && !this.toDate) {
this.fromDate = date; this.fromDate = date;
} else if (this.fromDate && !this.toDate && after(date, this.fromDate)) { } else if (this.fromDate && !this.toDate && after(date, this.fromDate)) {
this.toDate = date; this.toDate = date;
} else { } else {
this.toDate = null; this.toDate = null;
this.fromDate = date; this.fromDate = date;
} }
} }
handleSelect(event:MouseEvent) { handleSelect(event:MouseEvent) {
event.preventDefault(); event.preventDefault();
if (this.fromDate && this.toDate && before(this.fromDate, this.toDate)) { if (this.fromDate && this.toDate && before(this.fromDate, this.toDate)) {
var endDate = new Date(this.dateAdapter.toModel(this.toDate)); var endDate = new Date(this.dateAdapter.toModel(this.toDate));
endDate.setDate(endDate.getDate() + 1); endDate.setDate(endDate.getDate() + 1);
this.onSelect.emit({startDate:this.dateAdapter.toModel(this.fromDate),endDate:endDate}) this.onSelect.emit({startDate:this.dateAdapter.toModel(this.fromDate),endDate:endDate})
} }
} }
isHovered = date => this.fromDate && !this.toDate && this.hoveredDate && after(date, this.fromDate) && before(date, this.hoveredDate); isHovered = date => this.fromDate && !this.toDate && this.hoveredDate && after(date, this.fromDate) && before(date, this.hoveredDate);
isInside = date => after(date, this.fromDate) && before(date, this.toDate); isInside = date => after(date, this.fromDate) && before(date, this.toDate);
isFrom = date => equals(date, this.fromDate); isFrom = date => equals(date, this.fromDate);
isTo = date => equals(date, this.toDate); isTo = date => equals(date, this.toDate);
} }

View File

@@ -1,40 +1,50 @@
import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject, Type} from '@angular/core'; import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject, Type} from '@angular/core';
import { IItem } from '@farmmaps/common'; import { IItem } from '@farmmaps/common';
import { AbstractSelectedItemComponent, SelectedItemComponent } from '../selected-item/selected-item.component'; import { AbstractSelectedItemComponent, SelectedItemComponent } from '../selected-item/selected-item.component';
import { WidgetHostDirective } from '../widget-host/widget-host.directive'; import { WidgetHostDirective } from '../widget-host/widget-host.directive';
@Component({ @Component({
selector: 'fm-map-selected-item-container', selector: 'fm-map-selected-item-container',
templateUrl: './selected-item-container.component.html', templateUrl: './selected-item-container.component.html',
styleUrls: ['./selected-item-container.component.scss'] styleUrls: ['./selected-item-container.component.scss']
}) })
export class SelectedItemContainerComponent { export class SelectedItemContainerComponent {
constructor(private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractSelectedItemComponent) public selectedItemComponents: AbstractSelectedItemComponent[] ) { constructor(private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractSelectedItemComponent) public selectedItemComponents: AbstractSelectedItemComponent[] ) {
} }
@Input() item: IItem; @Input() item: IItem;
@ViewChild(WidgetHostDirective) widgetHost: WidgetHostDirective; @ViewChild(WidgetHostDirective, { static: true }) widgetHost: WidgetHostDirective;
loadComponent() { loadComponent() {
var componentFactory: ComponentFactory<AbstractSelectedItemComponent> = this.componentFactoryResolver.resolveComponentFactory(SelectedItemComponent); // default let componentFactory: ComponentFactory<AbstractSelectedItemComponent> = this.componentFactoryResolver.resolveComponentFactory(SelectedItemComponent); // default
for (var i = 0; i < this.selectedItemComponents.length; i++) { let firstComponentWithTypeAndTask = this.selectedItemComponents
if (this.selectedItemComponents[i]['forItemType'] == this.item.itemType) { .find(value => value['forSourceTask'] == this.item.sourceTask &&
componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.selectedItemComponents[i]['constructor'] as any); value['forItemType'] == this.item.itemType
} );
}
const viewContainerRef = this.widgetHost.viewContainerRef; if (firstComponentWithTypeAndTask) {
viewContainerRef.clear(); componentFactory = this.componentFactoryResolver.resolveComponentFactory(firstComponentWithTypeAndTask['constructor'] as any);
} else {
const componentRef = viewContainerRef.createComponent(componentFactory); let firstComponentWithType = this.selectedItemComponents
(<AbstractSelectedItemComponent>componentRef.instance).item = this.item; .find(value => value['forItemType'] == this.item.itemType);
}
if (firstComponentWithType) {
ngOnChanges(changes: SimpleChanges) { componentFactory = this.componentFactoryResolver.resolveComponentFactory(firstComponentWithType['constructor'] as any);
if (changes["item"] && changes["item"].currentValue) { }
this.loadComponent(); }
} const viewContainerRef = this.widgetHost.viewContainerRef;
} viewContainerRef.clear();
}
const componentRef = viewContainerRef.createComponent(componentFactory);
(<AbstractSelectedItemComponent>componentRef.instance).item = this.item;
}
ngOnChanges(changes: SimpleChanges) {
if (changes["item"] && changes["item"].currentValue) {
this.loadComponent();
}
}
}

View File

@@ -3,11 +3,15 @@
<div class="card border-0"> <div class="card border-0">
<div class="card-body"> <div class="card-body">
<div><a href="#" (click)="handleBackToList($event)" i18n>Back</a></div> <div><a href="#" (click)="handleBackToList($event)" i18n>Back</a></div>
<h4>Cropfield</h4> <div class="card menu-card">
<h1>{{item.name}}</h1> <h1>Cropfield</h1>
<div>{{item.data.cropTypeName}}</div> <h4>{{item.name}}</h4>
<div><span>{{item.data.startDate|date}}</span> - <span>{{item.data.endDate|date}}</span> </div> <div>{{item.data.cropTypeName}}</div>
<div class="mt-1"><a href="#" (click)="handleOnEdit(item)" i18n><i class="fa fa-pencil" aria-hidden="true" title="Edit"></i> Edit</a></div> <div><span>{{item.data.startDate|date}}</span> - <span>{{item.data.endDate|date}}</span> </div>
<ul class="p-0 mt-2">
<li><a href="#" (click)="handleOnEdit(item)" i18n><i class="fa fa-pencil" aria-hidden="true" title="Edit"></i> Edit</a></li>
</ul>
</div>
</div> </div>
<fm-map-item-list [items]="(items|async)"></fm-map-item-list> <fm-map-item-list [items]="(items|async)"></fm-map-item-list>
<fm-map-item-widget-list [item]="item"></fm-map-item-widget-list> <fm-map-item-widget-list [item]="item"></fm-map-item-widget-list>

View File

@@ -1,5 +1,7 @@
@import "../../_theme.scss"; @import "../../../app/theme.scss";
@import "~bootstrap/scss/bootstrap.scss"; @import "node_modules/bootstrap/scss/functions";
@import "node_modules/bootstrap/scss/variables";
@import "node_modules/bootstrap/scss/mixins";
.big-icon { .big-icon {
width: 100%; width: 100%;
@@ -13,6 +15,10 @@
font-size: 1rem; font-size: 1rem;
} }
.card-body {
padding-bottom: unset;
}
.spacer { .spacer {
display: none; display: none;
height: 4rem; height: 4rem;
@@ -23,3 +29,11 @@
display: block; display: block;
} }
} }
.menu-card {
margin-left: -7px;
padding-left: 7px;
margin-right: -7px;
padding-right: 7px;
margin-bottom: 7px;
}

View File

@@ -1,22 +1,23 @@
<div class="spacer"></div> <div class="spacer"></div>
<div *ngIf="item;let item"> <div *ngIf="item;let item">
<div class="card border-0"> <div class="card border-0">
<div class="card-body"> <div class="card-body">
<div class="mb-2"><a href="#" (click)="handleBackToList($event)" i18n>Back</a></div> <div class="mb-2"><a href="#" (click)="handleBackToList($event)" i18n>Back</a></div>
<h1>{{item.name}}</h1> <div class="card menu-card">
<div class="legend-container" *ngIf="item?.data.layers;let layers"> <h1>{{item.name}}</h1>
<!--<div *ngIf="layers.length>1"> </div>
<select (change)="onLayerChanged($event.target.value)"> <div class="legend-container" *ngIf="item?.data.layers;let layers">
<option *ngFor="let l of layers;let layerIndex = index" [value]="layerIndex">{{l.name}}</option> <div class="card menu-card">
</select> <fm-map-layer-legend [layer]="layers[selectedLayer]" [histogramenabled]="true"></fm-map-layer-legend>
</div>--> </div>
<fm-map-layer-legend [layer]="layers[selectedLayer]" [histogramenabled]="false" histogramunit="ha"></fm-map-layer-legend> </div>
</div> <div class="card menu-card">
<ul class="p-0 mt-2"> <ul class="p-0 mt-2">
<!--<li><a href="/api/v1/items/{{item.code}}/file" class="mt-1 mr-1" i18n><i class="fa fa-download" aria-hidden="true" title="Download"></i> Download</a></li>--> <!--<li><a href="/api/v1/items/{{item.code}}/file" class="mt-1 mr-1" i18n><i class="fa fa-download" aria-hidden="true" title="Download"></i> Download</a></li>-->
<li><a href="#" class="mt-1 mr-1" (click)="handleOnEdit(item)" i18n><i class="fa fa-pencil" aria-hidden="true" title="Edit"></i> Edit</a></li> <li><a href="#" class="mt-1 mr-1" (click)="handleOnEdit(item)" i18n><i class="fa fa-pencil" aria-hidden="true" title="Edit"></i> Edit</a></li>
<li *ngIf="itemTypeService.isLayer(item)"><a href="#" (click)="handleAddAsLayer(item)" class="mt-1 mr-1" i18n><i class="fa fa-eye" aria-hidden="true" title="Add as layer"></i> Add as overlay</a></li> <li *ngIf="itemTypeService.isLayer(item)"><a href="#" (click)="handleAddAsLayer(item)" class="mt-1 mr-1" i18n><i class="fa fa-eye" aria-hidden="true" title="Add as layer"></i> Add as overlay</a></li>
</ul> </ul>
</div> </div>
</div> </div>
</div> </div>
</div>

View File

@@ -1,33 +1,42 @@
@import "../../_theme.scss"; @import "../../_theme.scss";
@import "~bootstrap/scss/bootstrap.scss"; @import "~bootstrap/scss/bootstrap.scss";
.big-icon { .big-icon {
width: 100%; width: 100%;
color: white; color: white;
font-size: 9rem; font-size: 9rem;
padding: 3rem; padding: 3rem;
text-align: center; text-align: center;
} }
.card-title { .card-title {
font-size: 1rem; font-size: 1rem;
} }
ul { ul {
list-style:none; list-style:none;
} }
li { li {
margin-top:1rem; margin-top:1rem;
} }
.spacer { .spacer {
display:none; display:none;
height:4rem; height:4rem;
} }
@media screen and (min-width:44rem) { @media screen and (min-width:44rem) {
.spacer { .spacer {
display:block; display:block;
} }
} }
.menu-card {
margin-left: -7px;
padding-left: 7px;
margin-right: -7px;
padding-right: 7px;
margin-bottom: 7px;
}

View File

@@ -3,20 +3,26 @@
<div class="card border-0"> <div class="card border-0">
<div class="card-body"> <div class="card-body">
<div class="mb-2"><a href="#" (click)="handleBackToList($event)" i18n>Back</a></div> <div class="mb-2"><a href="#" (click)="handleBackToList($event)" i18n>Back</a></div>
<h1>{{item.name}}</h1> <div class="card menu-card">
<div class="legend-container" *ngIf="item?.data.layers;let layers"> <h1>{{item.name}}</h1>
<div *ngIf="layers.length>1">
<select (change)="onLayerChanged($event.target.value)">
<option *ngFor="let l of layers;" [value]="l.index">{{l.name}}</option>
</select>
</div>
<fm-map-layer-legend [showTitle]="layers.length==1" [layer]="layers[selectedLayer]" [histogramenabled]="false" histogramunit="ha"></fm-map-layer-legend>
</div> </div>
<ul class="p-0 mt-2"> <div class="legend-container" *ngIf="item?.data.layers;let layers">
<!--<li><a href="/api/v1/items/{{item.code}}/file" class="mt-1 mr-1" i18n><i class="fa fa-download" aria-hidden="true" title="Download"></i> Download</a></li>--> <div class="card menu-card">
<li><a href="#" class="mt-1 mr-1" (click)="handleOnEdit(item)" i18n><i class="fa fa-pencil" aria-hidden="true" title="Edit"></i> Edit</a></li> <div *ngIf="layers.length>1">
<li *ngIf="itemTypeService.isLayer(item)"><a href="#" (click)="handleAddAsLayer(item,selectedLayer)" class="mt-1 mr-1" i18n><i class="fa fa-eye" aria-hidden="true" title="Add as layer"></i> Add as overlay</a></li> <select (change)="onLayerChanged($event.target.value)">
</ul> <option *ngFor="let l of layers;" [value]="l.index">{{l.name}}</option>
</div> </select>
</div>
<fm-map-layer-legend [showTitle]="layers.length==1" [layer]="layers[selectedLayer]" [histogramenabled]="true"></fm-map-layer-legend>
</div>
</div>
<div class="card menu-card">
<ul class="p-0 mt-2">
<!--<li><a href="/api/v1/items/{{item.code}}/file" class="mt-1 mr-1" i18n><i class="fa fa-download" aria-hidden="true" title="Download"></i> Download</a></li>-->
<li><a href="#" class="mt-1 mr-1" (click)="handleOnEdit(item)" i18n><i class="fa fa-pencil" aria-hidden="true" title="Edit"></i> Edit</a></li>
<li *ngIf="itemTypeService.isLayer(item)"><a href="#" (click)="handleAddAsLayer(item,selectedLayer)" class="mt-1 mr-1" i18n><i class="fa fa-eye" aria-hidden="true" title="Add as layer"></i> Add as overlay</a></li>
</ul>
</div>
</div>
</div> </div>
</div> </div>

View File

@@ -39,3 +39,11 @@ li {
display: block; display: block;
} }
} }
.menu-card {
margin-left: -7px;
padding-left: 7px;
margin-right: -7px;
padding-right: 7px;
margin-bottom: 7px;
}

View File

@@ -1,16 +1,18 @@
<div *ngIf="item;let item"> <div *ngIf="item;let item">
<div class="card border-0"> <div class="card border-0">
<img *ngIf="item.thumbnail" class="card-img-top" [src]="'/api/v1/items/'+item.code+'/thumbnail?v='+item.updated.getTime()" /> <img *ngIf="item.thumbnail" class="card-img-top" [src]="config.getConfig('apiEndPoint') +'/api/v1/items/'+item.code+'/thumbnail?v='+item.updated.getTime()" />
<div *ngIf="!item.thumbnail" class="big-icon" [style.background-color]="itemTypeService.getColor(item.itemType)"> <div *ngIf="!item.thumbnail" class="big-icon" [style.background-color]="itemTypeService.getColor(item.itemType)">
<i [ngClass]="itemTypeService.getIcon(item.itemType)"></i> <i [ngClass]="itemTypeService.getIcon(item.itemType)"></i>
</div> </div>
<div class="card-body"> </div>
<div class="mb-2"><a href="#" (click)="handleBackToList($event)" i18n>Back</a></div> <div class="card">
<h1 class="card-title">{{item.name}}</h1> <div class="card-body">
<a *ngIf="itemTypeService.hasViewer(item)" href="#" (click)="handleOnView(item)" class="btn btn-outline-secondary" i18n><i class="fa fa-eye" aria-hidden="true" title="View"></i> View</a> <div class="mb-2"><a href="#" (click)="handleBackToList($event)" i18n>Back</a></div>
<a href="/api/v1/items/{{item.code}}/data" class="btn btn-outline-secondary" i18n><i class="fa fa-download" aria-hidden="true" title="Download"></i> Download</a> <h1 class="card-title">{{item.name}}</h1>
<a href="#" class="btn btn-outline-secondary" (click)="handleOnEdit(item)" i18n><i class="fa fa-pencil" aria-hidden="true" title="Edit"></i> Edit</a> <a *ngIf="itemTypeService.hasViewer(item)" href="#" (click)="handleOnView(item)" class="btn btn-outline-secondary" i18n><i class="fa fa-eye" aria-hidden="true" title="View"></i> View</a>
<a *ngIf="itemTypeService.isLayer(item)" href="#" (click)="handleAddAsLayer(item)" class="btn btn-outline-secondary" i18n><i class="fa fa-eye" aria-hidden="true" title="Add as layer"></i> Add as overlay</a> <a href="/api/v1/items/{{item.code}}/data" class="btn btn-outline-secondary" i18n><i class="fa fa-download" aria-hidden="true" title="Download"></i> Download</a>
</div> <a href="#" class="btn btn-outline-secondary" (click)="handleOnEdit(item)" i18n><i class="fa fa-pencil" aria-hidden="true" title="Edit"></i> Edit</a>
</div> <a *ngIf="itemTypeService.isLayer(item)" href="#" (click)="handleAddAsLayer(item)" class="btn btn-outline-secondary" i18n><i class="fa fa-eye" aria-hidden="true" title="Add as layer"></i> Add as overlay</a>
</div> </div>
</div>
</div>

View File

@@ -1,56 +1,56 @@
import { Component, Input, Injectable } from '@angular/core'; import { Component, Input, Injectable } from '@angular/core';
import { Location } from '@angular/common'; import { Location } from '@angular/common';
import { Feature } from 'ol'; import { Feature } from 'ol';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import * as mapReducers from '../../reducers/map.reducer'; import * as mapReducers from '../../reducers/map.reducer';
import { commonReducers,ItemTypeService, IItem, Item } from '@farmmaps/common'; import { commonReducers,ItemTypeService, IItem, Item,AppConfig } from '@farmmaps/common';
import * as mapActions from '../../actions/map.actions'; import * as mapActions from '../../actions/map.actions';
import { Router, ActivatedRoute, ParamMap, Event } from '@angular/router'; import { Router, ActivatedRoute, ParamMap, Event } from '@angular/router';
@Injectable() @Injectable()
export abstract class AbstractSelectedItemComponent { export abstract class AbstractSelectedItemComponent {
@Input() item: IItem @Input() item: IItem
constructor(public store: Store<mapReducers.State | commonReducers.State>, public itemTypeService: ItemTypeService, private location: Location, private router: Router) { constructor(public store: Store<mapReducers.State | commonReducers.State>, public itemTypeService: ItemTypeService, private location: Location, private router: Router) {
} }
handleOnView(item: IItem) { handleOnView(item: IItem) {
var itemType = this.itemTypeService.itemTypes[item.itemType]; var itemType = this.itemTypeService.itemTypes[item.itemType];
if (itemType) { if (itemType) {
if (itemType.viewer) { if (itemType.viewer) {
let url = `/viewer/${itemType.viewer}/item/${item.code}`; let url = `/viewer/${itemType.viewer}/item/${item.code}`;
this.router.navigate([url]); this.router.navigate([url]);
} }
} }
return false; return false;
} }
handleOnEdit(item: IItem) { handleOnEdit(item: IItem) {
let url = `/editor/property/item/${item.code}`; let url = `/editor/property/item/${item.code}`;
this.router.navigate([url]); this.router.navigate([url]);
return false; return false;
} }
handleAddAsLayer(item: IItem,layerIndex:number = -1) { handleAddAsLayer(item: IItem,layerIndex:number = -1) {
this.store.dispatch(new mapActions.AddLayer(item,layerIndex)); this.store.dispatch(new mapActions.AddLayer(item,layerIndex));
return false; return false;
} }
handleBackToList(event: MouseEvent) { handleBackToList(event: MouseEvent) {
event.preventDefault(); event.preventDefault();
this.location.back(); this.location.back();
} }
} }
@Injectable() @Injectable()
@Component({ @Component({
selector: 'fm-map-selected-item', selector: 'fm-map-selected-item',
templateUrl: './selected-item.component.html', templateUrl: './selected-item.component.html',
styleUrls: ['./selected-item.component.scss'] styleUrls: ['./selected-item.component.scss']
}) })
export class SelectedItemComponent extends AbstractSelectedItemComponent { export class SelectedItemComponent extends AbstractSelectedItemComponent {
constructor(store: Store<mapReducers.State | commonReducers.State>, itemTypeService: ItemTypeService, location: Location, router: Router) { constructor(store: Store<mapReducers.State | commonReducers.State>, itemTypeService: ItemTypeService, location: Location, router: Router, public config:AppConfig) {
super(store, itemTypeService,location,router); super(store, itemTypeService,location,router);
} }
} }

View File

@@ -1,230 +1,238 @@
import { Injectable, Inject } from '@angular/core'; import { Injectable, Inject } from '@angular/core';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { Store, Action } from '@ngrx/store'; import { Store, Action } from '@ngrx/store';
import { Effect, Actions,ofType } from '@ngrx/effects'; import { Effect, Actions,ofType } from '@ngrx/effects';
import { Observable , of } from 'rxjs'; import { Observable , of } from 'rxjs';
import { withLatestFrom, switchMap, map, catchError, mergeMap, delay} from 'rxjs/operators'; import { withLatestFrom, switchMap, map, catchError, mergeMap, delay} from 'rxjs/operators';
import {GeoJSON} from 'ol/format'; import {GeoJSON,WKT} from 'ol/format';
import {Feature} from 'ol'; import {Feature} from 'ol';
import { getCenter, Extent, createEmpty, extend} from 'ol/extent'; import { getCenter, Extent, createEmpty, extend} from 'ol/extent';
import {Point} from 'ol/geom' import {Point} from 'ol/geom'
import * as mapActions from '../actions/map.actions'; import * as mapActions from '../actions/map.actions';
import * as mapReducers from '../reducers/map.reducer'; import * as mapReducers from '../reducers/map.reducer';
import {commonReducers} from '@farmmaps/common'; import {commonReducers} from '@farmmaps/common';
import {commonActions} from '@farmmaps/common'; import {commonActions} from '@farmmaps/common';
import { IListItem, IItem } from '@farmmaps/common'; import { IListItem, IItem } from '@farmmaps/common';
import { FolderService, ItemService } from '@farmmaps/common'; import { FolderService, ItemService } from '@farmmaps/common';
import { tassign } from 'tassign'; import { tassign } from 'tassign';
@Injectable() @Injectable()
export class MapEffects { export class MapEffects {
private _format: GeoJSON; private _geojsonFormat: GeoJSON;
private _wktFormat: WKT;
private toPointFeature(feature: any): Feature {
var f = this._format.readFeature(feature); private toPointFeature(updateEvent:commonActions.DeviceUpdateEvent): Feature {
var centroid = getCenter(f.getGeometry().getExtent()); var f = this._wktFormat.readFeature(updateEvent.attributes["geometry"],{
f.setGeometry(new Point(centroid)); dataProjection: 'EPSG:4326',
return f; featureProjection: 'EPSG:3857'
} });
f.setId(updateEvent.itemCode);
@Effect() var centroid = getCenter(f.getGeometry().getExtent());
init$: Observable<Action> = this.actions$.pipe( f.setGeometry(new Point(centroid));
ofType(mapActions.INIT), return f;
withLatestFrom(this.store$.select(commonReducers.selectGetRootItems)), }
switchMap(([action, rootItems]) => {
for (let rootItem of rootItems) { @Effect()
if (rootItem.itemType == "UPLOADS_FOLDER") return of(new mapActions.SetParent(rootItem.code)); init$: Observable<Action> = this.actions$.pipe(
} ofType(mapActions.INIT),
return []; withLatestFrom(this.store$.select(commonReducers.selectGetRootItems)),
} switchMap(([action, rootItems]) => {
)); for (let rootItem of rootItems) {
if (rootItem.itemType == "UPLOADS_FOLDER") return of(new mapActions.SetParent(rootItem.code));
@Effect() }
initBaseLayers$: Observable<Action> = this.actions$.pipe( return [];
ofType(mapActions.INIT), }
withLatestFrom(this.store$.select(mapReducers.selectGetProjection)), ));
map(([action, projection]) => new mapActions.LoadBaseLayers(projection)));
@Effect()
@Effect() initBaseLayers$: Observable<Action> = this.actions$.pipe(
loadBaseLayers$: Observable<Action> = this.actions$.pipe( ofType(mapActions.INIT),
ofType(mapActions.LOADBASELAYERS), withLatestFrom(this.store$.select(mapReducers.selectGetProjection)),
switchMap((action: mapActions.LoadBaseLayers) => { map(([action, projection]) => new mapActions.LoadBaseLayers(projection)));
return this.itemService$.getItemList("vnd.farmmaps.itemtype.layer", { "isBaseLayer": true }).pipe(
map((items: IItem[]) => new mapActions.LoadBaseLayersSuccess(items)), @Effect()
catchError(error => of(new commonActions.Fail(error)))); loadBaseLayers$: Observable<Action> = this.actions$.pipe(
})); ofType(mapActions.LOADBASELAYERS),
switchMap((action: mapActions.LoadBaseLayers) => {
@Effect() return this.itemService$.getItemList("vnd.farmmaps.itemtype.layer", { "isBaseLayer": true }).pipe(
initRootItems$: Observable<Action> = this.actions$.pipe( map((items: IItem[]) => new mapActions.LoadBaseLayersSuccess(items)),
ofType(commonActions.INITROOTSUCCESS), catchError(error => of(new commonActions.Fail(error))));
map((action) => new mapActions.Init() }));
));
@Effect()
@Effect() initRootItems$: Observable<Action> = this.actions$.pipe(
startSearch$: Observable<Action> = this.actions$.pipe( ofType(commonActions.INITROOTSUCCESS),
ofType(mapActions.STARTSEARCH), map((action) => new mapActions.Init()
switchMap((action: mapActions.StartSearch) => { ));
console.debug("Start search");
var startDate = action.queryState.startDate; @Effect()
var endDate = action.queryState.endDate; startSearch$: Observable<Action> = this.actions$.pipe(
var newAction; ofType(mapActions.STARTSEARCH),
if (action.queryState.itemCode || action.queryState.parentCode || action.queryState.itemType || action.queryState.query || action.queryState.tags) { switchMap((action: mapActions.StartSearch) => {
newAction= this.itemService$.getFeatures(action.queryState.bbox, "EPSG:3857", action.queryState.query, action.queryState.tags, startDate, endDate, action.queryState.itemType, action.queryState.parentCode).pipe( console.debug("Start search");
switchMap((features: any) => { var startDate = action.queryState.startDate;
for (let f of features.features) { var endDate = action.queryState.endDate;
if (f.properties && f.properties["code"]) { var newAction:Observable<Action>;
f.id = f.properties["code"]; if (action.queryState.itemCode || action.queryState.parentCode || action.queryState.itemType || action.queryState.query || action.queryState.tags) {
} newAction= this.itemService$.getFeatures(action.queryState.bbox, "EPSG:3857", action.queryState.query, action.queryState.tags, startDate, endDate, action.queryState.itemType, action.queryState.parentCode).pipe(
} switchMap((features: any) => {
return of(new mapActions.StartSearchSuccess(this._format.readFeatures(features), action.queryState)); for (let f of features.features) {
} if (f.properties && f.properties["code"]) {
), f.id = f.properties["code"];
catchError(error => of(new commonActions.Fail(error)))); }
} else { }
newAction= of(new commonActions.Escape(true,false)); return of(new mapActions.StartSearchSuccess(this._geojsonFormat.readFeatures(features), action.queryState));
} }
return newAction; ),
})); catchError(error => of(new commonActions.Fail(error))));
} else {
newAction= of(new commonActions.Escape(true,false));
@Effect() }
startSearchSucces$: Observable<Action> = this.actions$.pipe( return newAction;
ofType(mapActions.STARTSEARCHSUCCESS), }));
mergeMap((action: mapActions.StartSearchSuccess) => {
if (action.query.bboxFilter) {
return []; @Effect()
} else { startSearchSucces$: Observable<Action> = this.actions$.pipe(
var extent = createEmpty(); ofType(mapActions.STARTSEARCHSUCCESS),
mergeMap((action: mapActions.StartSearchSuccess) => {
if (extent) { if (action.query.bboxFilter) {
for (let f of action.features) { return [];
extend(extent, (f as Feature).getGeometry().getExtent()); } else {
} var extent = createEmpty();
}
//return []; if (extent) {
return of(new mapActions.SetExtent(extent)); for (let f of action.features) {
} extend(extent, (f as Feature).getGeometry().getExtent());
})); }
}
@Effect() //return [];
selectItem$: Observable<Action> = this.actions$.pipe( return of(new mapActions.SetExtent(extent));
ofType(mapActions.SELECTITEM), }
withLatestFrom(this.store$.select(mapReducers.selectGetSelectedItem)), }));
switchMap(([action, selectedItem]) => {
let a = action as mapActions.SelectItem; @Effect()
let itemCode = selectedItem ? selectedItem.code : ""; selectItem$: Observable<Action> = this.actions$.pipe(
if (a.itemCode != itemCode) { ofType(mapActions.SELECTITEM),
return this.itemService$.getItem(a.itemCode).pipe( withLatestFrom(this.store$.select(mapReducers.selectGetSelectedItem)),
map((item: IItem) => new mapActions.SelectItemSuccess(item)), switchMap(([action, selectedItem]) => {
catchError(error => of(new commonActions.Fail(error)))) let a = action as mapActions.SelectItem;
} else { let itemCode = selectedItem ? selectedItem.code : "";
return []; if (a.itemCode != itemCode) {
} return this.itemService$.getItem(a.itemCode).pipe(
} map((item: IItem) => new mapActions.SelectItemSuccess(item)),
)); catchError(error => of(new commonActions.Fail(error))))
} else {
@Effect() return [];
selectItemSuccess$: Observable<Action> = this.actions$.pipe( }
ofType(mapActions.SELECTITEMSUCCESS), }
switchMap((action:mapActions.SelectItemSuccess) => { ));
return this.itemService$.getFeature(action.item.code, "EPSG:3857").pipe(
map((feature: IItem) => new mapActions.AddFeatureSuccess(this._format.readFeature(feature) )), @Effect()
catchError(error => of(new commonActions.Fail(error)))); selectItemSuccess$: Observable<Action> = this.actions$.pipe(
} ofType(mapActions.SELECTITEMSUCCESS),
)); switchMap((action:mapActions.SelectItemSuccess) => {
return this.itemService$.getFeature(action.item.code, "EPSG:3857").pipe(
@Effect() map((feature: any) => {
uploadedItemClick$: Observable<Action> = this.actions$.pipe( let f = this._geojsonFormat.readFeature(feature);
ofType(commonActions.UPLOADEDFILECLICK), f.setId(action.item.code);
switchMap((action: commonActions.UploadedFileClick) => of(new mapActions.DoQuery(tassign(mapReducers.initialState.query, {itemCode:action.itemCode}))) return new mapActions.AddFeatureSuccess(f );
)); }),
catchError(error => of(new commonActions.Fail(error))));
//@Effect() }
//itemAdded$: Observable<Action> = this.actions$.pipe( ));
// ofType(commonActions.ITEMADDEDEVENT),
// withLatestFrom(this.store$.select(mapReducers.selectGetParentCode)), @Effect()
// mergeMap(([action, parentCode]) => { uploadedItemClick$: Observable<Action> = this.actions$.pipe(
// let itemAddedAction = action as commonActions.ItemAddedEvent; ofType(commonActions.UPLOADEDFILECLICK),
// if (parentCode && itemAddedAction.attributes["parentCode"] == parentCode) { switchMap((action: commonActions.UploadedFileClick) => of(new mapActions.DoQuery(tassign(mapReducers.initialState.query, {itemCode:action.itemCode})))
// return this.itemService$.getFeature(itemAddedAction.itemCode,"EPSG:3857").pipe( ));
// map((feature: Feature) => new mapActions.AddFeatureSuccess(this.toPointFeature(feature))),
// catchError(error => of(new commonActions.Fail(error)))) //@Effect()
// } else //itemAdded$: Observable<Action> = this.actions$.pipe(
// return [ // ofType(commonActions.ITEMADDEDEVENT),
// ]; // withLatestFrom(this.store$.select(mapReducers.selectGetParentCode)),
// })); // mergeMap(([action, parentCode]) => {
// let itemAddedAction = action as commonActions.ItemAddedEvent;
@Effect() // if (parentCode && itemAddedAction.attributes["parentCode"] == parentCode) {
featureUpdate$: Observable<Action> = this.actions$.pipe( // return this.itemService$.getFeature(itemAddedAction.itemCode,"EPSG:3857").pipe(
ofType(commonActions.ITEMCHANGEDEVENT), // map((feature: Feature) => new mapActions.AddFeatureSuccess(this.toPointFeature(feature))),
withLatestFrom(this.store$.select(mapReducers.selectGetFeatures)), // catchError(error => of(new commonActions.Fail(error))))
mergeMap(([action, features]) => { // } else
let itemChangedAction = action as commonActions.ItemChangedEvent; // return [
var feature: Feature = null; // ];
for (let f of features) { // }));
if (f.get("code") == itemChangedAction.itemCode) {
feature = f; @Effect()
break; featureUpdate$: Observable<Action> = this.actions$.pipe(
} ofType(commonActions.DEVICEUPDATEEVENT),
} withLatestFrom(this.store$.select(mapReducers.selectGetFeatures)),
if (feature) { mergeMap(([action, features]) => {
return this.itemService$.getFeature(itemChangedAction.itemCode, "EPSG:3857").pipe( let deviceUpdateEventAction = action as commonActions.DeviceUpdateEvent;
map((feature: any) => new mapActions.UpdateFeatureSuccess(this.toPointFeature(feature))), var feature: Feature = null;
catchError(error => of(new commonActions.Fail(error)))); for (let f of features) {
} else { if (f.getId() == deviceUpdateEventAction.itemCode) {
return []; feature = f;
} break;
})); }
}
@Effect() if (feature) {
itemUpdate$: Observable<Action> = this.actions$.pipe( return of(new mapActions.UpdateFeatureSuccess(this.toPointFeature(deviceUpdateEventAction)));
ofType(commonActions.ITEMCHANGEDEVENT), } else {
withLatestFrom(this.store$.select(mapReducers.selectGetSelectedItem)), return [];
mergeMap(([action, selectedItem]) => { }
let itemChangedAction = action as commonActions.ItemChangedEvent; }));
if (selectedItem && selectedItem.code == itemChangedAction.itemCode) {
return this.itemService$.getItem(itemChangedAction.itemCode).pipe( @Effect()
map((item: IItem) => new mapActions.SelectItemSuccess(item)), itemUpdate$: Observable<Action> = this.actions$.pipe(
catchError(error => of(new commonActions.Fail(error)))); ofType(commonActions.ITEMCHANGEDEVENT),
} else { withLatestFrom(this.store$.select(mapReducers.selectGetSelectedItem)),
return []; mergeMap(([action, selectedItem]) => {
} let itemChangedAction = action as commonActions.ItemChangedEvent;
})); if (selectedItem && selectedItem.code == itemChangedAction.itemCode) {
return this.itemService$.getItem(itemChangedAction.itemCode).pipe(
@Effect() map((item: IItem) => new mapActions.SelectItemSuccess(item)),
setQueryState$: Observable<Action> = this.actions$.pipe( catchError(error => of(new commonActions.Fail(error))));
ofType(mapActions.SETQUERYSTATE), } else {
switchMap((action: mapActions.SetQueryState) => { return [];
var newAction:Action; }
if (action.queryState.itemCode && action.queryState.itemCode != "") { }));
newAction= new mapActions.SelectItem(action.queryState.itemCode);
} else { @Effect()
newAction= new mapActions.StartSearch(action.queryState); setQueryState$: Observable<Action> = this.actions$.pipe(
} ofType(mapActions.SETQUERYSTATE),
return of(newAction); switchMap((action: mapActions.SetQueryState) => {
})); var newAction:Action;
if (action.queryState.itemCode && action.queryState.itemCode != "") {
@Effect() newAction= new mapActions.SelectItem(action.queryState.itemCode);
setState$: Observable<Action> = this.actions$.pipe( } else {
ofType(mapActions.SETSTATE), newAction= new mapActions.StartSearch(action.queryState);
switchMap((action: mapActions.SetState) => { }
var newAction:Action; return of(newAction);
if (action.queryState.itemCode && action.queryState.itemCode != "") { }));
newAction= new mapActions.SelectItem(action.queryState.itemCode);
} else { @Effect()
newAction= new mapActions.StartSearch(action.queryState); setState$: Observable<Action> = this.actions$.pipe(
} ofType(mapActions.SETSTATE),
return of(newAction); switchMap((action: mapActions.SetState) => {
})); var newAction:Action;
if (action.queryState.itemCode && action.queryState.itemCode != "") {
constructor(private actions$: Actions, private store$: Store<mapReducers.State>, private folderService$: FolderService, private itemService$: ItemService) { newAction= new mapActions.SelectItem(action.queryState.itemCode);
this._format = new GeoJSON(); } else {
} newAction= new mapActions.StartSearch(action.queryState);
} }
return of(newAction);
}));
constructor(private actions$: Actions, private store$: Store<mapReducers.State>, private folderService$: FolderService, private itemService$: ItemService) {
this._geojsonFormat = new GeoJSON();
this._wktFormat = new WKT();
}
}

View File

@@ -1,69 +1,72 @@
export interface IColor { export interface IColor {
red: number, red: number,
green: number, green: number,
blue: number, blue: number,
alpha: number, alpha: number,
} }
export interface IColorEntry { export interface IColorEntry {
value: number, value: number,
color: IColor color: IColor,
} label: string
}
export interface IHistogramEntry {
value: number, export interface IHistogramEntry {
freqency: number value: number,
} freqency: number
}
export interface IHistogram {
min: number, export interface IHistogram {
max: number, min: number,
mean: number, max: number,
stddev: number, mean: number,
classes: number, stddev: number,
entries: IHistogramEntry[] classes: number,
} entries: IHistogramEntry[]
}
export interface IGradientstop {
relativestop: number, export interface IGradientstop {
color: IColor relativestop: number,
} color: IColor
}
export interface IColorMap {
gradient: IGradientstop[], export interface IColorMap {
noValue: IColorEntry, gradient: IGradientstop[],
entries: IColorEntry[] noValue: IColorEntry,
} entries: IColorEntry[],
colormapType: string
export interface IBand { }
histogram: IHistogram
} export interface IBand {
histogram: IHistogram
}
export interface IRenderer {
band:IBand,
colorMap: IColorMap export interface IRenderer {
} band:IBand,
colorMap: IColorMap,
export interface IRenderoutput { renderType:string
renderoutputType: string }
}
export interface IRenderoutput {
export interface IRenderoutputTiles { renderoutputType: string
renderoutputType: string, }
minzoom: number,
maxzoom: number export interface IRenderoutputTiles {
} renderoutputType: string,
minzoom: number,
export interface IRenderoutputImage { maxzoom: number
renderoutputType: string, }
extent: [number,number,number,number]
} export interface IRenderoutputImage {
renderoutputType: string,
export interface ILayer { extent: [number,number,number,number]
name: string, }
unit: string,
index: number, export interface ILayer {
renderer: IRenderer, name: string,
rendering: IRenderoutput unit: string,
} index: number,
renderer: IRenderer,
rendering: IRenderoutput
}

View File

@@ -1,7 +0,0 @@
export * from './map.state';
export * from './selected.features';
export * from './item.layer'
export * from './layer.data'
export * from './color.map';
export * from './query.state';
export * from './period.state';

View File

@@ -1,369 +1,372 @@
import { tassign } from 'tassign'; import { tassign } from 'tassign';
import { IItem,Item } from '@farmmaps/common'; import { IItem,Item } from '@farmmaps/common';
import { IItemLayer,ItemLayer, IMapState,IQueryState,IPeriodState} from '../models' import { IItemLayer,ItemLayer} from '../models/item.layer';
import * as mapActions from '../actions/map.actions'; import { IMapState} from '../models/map.state';
import {commonActions} from '@farmmaps/common'; import { IQueryState} from '../models/query.state';
import { createSelector, createFeatureSelector } from '@ngrx/store'; import { IPeriodState} from '../models/period.state';
import * as mapActions from '../actions/map.actions';
import {Feature} from 'ol'; import {commonActions} from '@farmmaps/common';
import { createSelector, createFeatureSelector } from '@ngrx/store';
import { ROUTER_NAVIGATION, RouterNavigationAction } from '@ngrx/router-store';
import {Feature} from 'ol';
import { MODULE_NAME } from '../module-name';
import { ROUTER_NAVIGATION, RouterNavigationAction } from '@ngrx/router-store';
const startDate:Date = new Date(new Date(Date.now()).getFullYear(), new Date(Date.now()).getMonth() - 3, 1);
const endDate:Date = new Date(Date.now()); import { MODULE_NAME } from '../module-name';
export const initialQueryState: IQueryState = { const startDate:Date = new Date(new Date(Date.now()).getFullYear(), new Date(Date.now()).getMonth() - 3, 1);
itemCode: null, const endDate:Date = new Date(Date.now());
parentCode: null,
level: 1, export const initialQueryState: IQueryState = {
itemType: null, itemCode: null,
bboxFilter: false, parentCode: null,
query: null, level: 1,
tags: null, itemType: null,
endDate: null, bboxFilter: false,
startDate: null, query: null,
bbox: [] tags: null,
}; endDate: null,
startDate: null,
export interface State { bbox: []
period:IPeriodState, };
mapState: IMapState,
viewExtent: number[], export interface State {
queryState: IQueryState, period:IPeriodState,
query:IQueryState, mapState: IMapState,
parentCode: string, viewExtent: number[],
features: Array<Feature>, queryState: IQueryState,
panelVisible: boolean, query:IQueryState,
panelCollapsed: boolean, parentCode: string,
selectedFeature: Feature, features: Array<Feature>,
selectedItem:IItem, panelVisible: boolean,
clearEnabled: boolean, panelCollapsed: boolean,
searchCollapsed: boolean, selectedFeature: Feature,
searchMinified: boolean, selectedItem:IItem,
menuVisible: boolean, clearEnabled: boolean,
extent: number[], searchCollapsed: boolean,
baseLayers: Array<IItemLayer> searchMinified: boolean,
overlayLayers: Array<IItemLayer>, menuVisible: boolean,
selectedItemLayer: IItemLayer, extent: number[],
projection: string, baseLayers: Array<IItemLayer>
selectedBaseLayer: IItemLayer, overlayLayers: Array<IItemLayer>,
selectedOverlayLayer: IItemLayer selectedItemLayer: IItemLayer,
} projection: string,
selectedBaseLayer: IItemLayer,
export const initialState: State = { selectedOverlayLayer: IItemLayer
period: { }
startDate: startDate,
endDate: endDate export const initialState: State = {
}, period: {
mapState: { startDate: startDate,
zoom: 8, endDate: endDate
rotation: 0, },
xCenter: 5.377554, mapState: {
yCenter: 52.162422, zoom: 8,
baseLayerCode: "" rotation: 0,
}, xCenter: 5.377554,
viewExtent:[], yCenter: 52.162422,
queryState: tassign(initialQueryState), baseLayerCode: ""
query: tassign(initialQueryState), },
parentCode: null, viewExtent:[],
features: [], queryState: tassign(initialQueryState),
panelVisible: false, query: tassign(initialQueryState),
panelCollapsed: false, parentCode: null,
selectedFeature: null, features: [],
selectedItem: null, panelVisible: false,
clearEnabled: false, panelCollapsed: false,
searchCollapsed: true, selectedFeature: null,
searchMinified:false, selectedItem: null,
menuVisible: true, clearEnabled: false,
extent: null, searchCollapsed: true,
baseLayers: [], searchMinified:false,
overlayLayers: [], menuVisible: true,
projection: "EPSG:3857", extent: null,
selectedBaseLayer: null, baseLayers: [],
selectedOverlayLayer: null, overlayLayers: [],
selectedItemLayer: null projection: "EPSG:3857",
} selectedBaseLayer: null,
selectedOverlayLayer: null,
export function reducer(state = initialState, action: mapActions.Actions | commonActions.Actions | RouterNavigationAction): State { selectedItemLayer: null
switch (action.type) { }
case ROUTER_NAVIGATION: {
let a = action as RouterNavigationAction; export function reducer(state = initialState, action: mapActions.Actions | commonActions.Actions | RouterNavigationAction): State {
return tassign(state); switch (action.type) {
} case ROUTER_NAVIGATION: {
case mapActions.SETMAPSTATE: { let a = action as RouterNavigationAction;
let a = action as mapActions.SetMapState; return tassign(state);
return tassign(state, { }
mapState: a.mapState case mapActions.SETMAPSTATE: {
}); let a = action as mapActions.SetMapState;
} return tassign(state, {
case mapActions.SETQUERYSTATE: { mapState: a.mapState
let a = action as mapActions.SetQueryState; });
return tassign(state, { queryState: tassign(a.queryState )}); }
} case mapActions.SETQUERYSTATE: {
case mapActions.SETSTATE: { let a = action as mapActions.SetQueryState;
let a = action as mapActions.SetState; return tassign(state, { queryState: tassign(a.queryState )});
return tassign(state, { mapState: tassign(a.mapState), queryState: tassign(a.queryState)}); }
} case mapActions.SETSTATE: {
case mapActions.SETVIEWEXTENT: { let a = action as mapActions.SetState;
let a = action as mapActions.SetViewExtent; return tassign(state, { mapState: tassign(a.mapState), queryState: tassign(a.queryState)});
return tassign(state, { viewExtent: a.extent }); }
} case mapActions.SETVIEWEXTENT: {
case mapActions.SETPARENT: { let a = action as mapActions.SetViewExtent;
let a = action as mapActions.SetParent; return tassign(state, { viewExtent: a.extent });
return tassign(state, { }
parentCode : a.parentCode case mapActions.SETPARENT: {
}); let a = action as mapActions.SetParent;
} return tassign(state, {
case mapActions.STARTSEARCHSUCCESS: { parentCode : a.parentCode
let a = action as mapActions.StartSearchSuccess; });
return tassign(state, { }
panelVisible: true, case mapActions.STARTSEARCHSUCCESS: {
clearEnabled: true, let a = action as mapActions.StartSearchSuccess;
searchMinified: true, return tassign(state, {
features: a.features panelVisible: true,
}); clearEnabled: true,
} searchMinified: true,
case mapActions.SELECTFEATURE: { features: a.features
let a = action as mapActions.SelectFeature; });
return tassign(state, { }
selectedFeature: state.selectedItem?state.selectedFeature: a.feature case mapActions.SELECTFEATURE: {
}); let a = action as mapActions.SelectFeature;
} return tassign(state, {
case mapActions.SELECTITEM: { selectedFeature: state.selectedItem?state.selectedFeature: a.feature
return tassign(state, { });
selectedItem: null, }
searchMinified:false, case mapActions.SELECTITEM: {
selectedItemLayer: null, return tassign(state, {
features:[] selectedItem: null,
}); searchMinified:false,
} selectedItemLayer: null,
case mapActions.SELECTITEMSUCCESS: { features:[]
let a = action as mapActions.SelectItemSuccess; });
var itemLayer = null; }
if (a.item && "vnd.farmmaps.itemtype.layer,vnd.farmmaps.itemtype.shape.processed,vnd.farmmaps.itemtype.geotiff.processed".indexOf(a.item.itemType) >=0 ) { case mapActions.SELECTITEMSUCCESS: {
itemLayer = new ItemLayer(a.item); let a = action as mapActions.SelectItemSuccess;
} var itemLayer = null;
return tassign(state, { if (a.item && "vnd.farmmaps.itemtype.layer,vnd.farmmaps.itemtype.shape.processed,vnd.farmmaps.itemtype.geotiff.processed".indexOf(a.item.itemType) >=0 ) {
selectedItem: a.item, itemLayer = new ItemLayer(a.item);
selectedItemLayer: itemLayer, }
panelVisible: a.item != null, return tassign(state, {
clearEnabled: a.item != null, selectedItem: a.item,
searchCollapsed: false, selectedItemLayer: itemLayer,
searchMinified: true, panelVisible: a.item != null,
queryState: tassign(state.queryState, {itemCode:a.item ? a.item.code:null}) clearEnabled: a.item != null,
}); searchCollapsed: false,
} searchMinified: true,
case mapActions.STARTSEARCH: { queryState: tassign(state.queryState, {itemCode:a.item ? a.item.code:null})
let a = action as mapActions.StartSearch; });
return tassign(state, { }
selectedItem: null, case mapActions.STARTSEARCH: {
selectedItemLayer:null, let a = action as mapActions.StartSearch;
queryState: tassign(a.queryState), return tassign(state, {
searchCollapsed: false, selectedItem: null,
searchMinified: true, selectedItemLayer:null,
menuVisible:false queryState: tassign(a.queryState),
}); searchCollapsed: false,
} searchMinified: true,
case mapActions.DOQUERY: { menuVisible:false
let a = action as mapActions.DoQuery; });
return tassign(state, { }
query: tassign(a.query, { bbox: a.query.bboxFilter ? state.viewExtent : [] })}); case mapActions.DOQUERY: {
} let a = action as mapActions.DoQuery;
case mapActions.ADDFEATURESUCCESS: { return tassign(state, {
let a = action as mapActions.AddFeatureSuccess; query: tassign(a.query, { bbox: a.query.bboxFilter ? state.viewExtent : [] })});
let features = state.features.slice(); }
features.push(a.feature); case mapActions.ADDFEATURESUCCESS: {
return tassign(state, { let a = action as mapActions.AddFeatureSuccess;
panelVisible: true, let features = state.features.slice();
selectedFeature: a.feature, features.push(a.feature);
menuVisible: false, return tassign(state, {
extent: a.feature.getGeometry().getExtent(), panelVisible: true,
searchCollapsed: false, selectedFeature: a.feature,
clearEnabled:true, menuVisible: false,
features:features extent: a.feature.getGeometry().getExtent(),
}); searchCollapsed: false,
} clearEnabled:true,
case mapActions.UPDATEFEATURESUCCESS: { features:features
let a = action as mapActions.UpdateFeatureSuccess; });
let features: any[] = []; }
var index = -1; case mapActions.UPDATEFEATURESUCCESS: {
for (var i = 0; i < state.features.length; i++) { let a = action as mapActions.UpdateFeatureSuccess;
if (state.features[i].get("code") == a.feature.get("code")) { let features: any[] = [];
features.push(a.feature); var index = -1;
} else { for (var i = 0; i < state.features.length; i++) {
features.push(state.features[i]); if (state.features[i].getId() == a.feature.getId()) {
} features.push(a.feature);
} } else {
return tassign(state, { features: features }); features.push(state.features[i]);
} }
case mapActions.EXPANDSEARCH: { }
return tassign(state, { searchCollapsed: false }); return tassign(state, { features: features });
} }
case mapActions.COLLAPSESEARCH: { case mapActions.EXPANDSEARCH: {
return tassign(state, { searchCollapsed: state.panelVisible ? false: true}); return tassign(state, { searchCollapsed: false });
} }
case mapActions.TOGGLEMENU: { case mapActions.COLLAPSESEARCH: {
return tassign(state, { menuVisible: !state.menuVisible }); return tassign(state, { searchCollapsed: state.panelVisible ? false: true});
} }
case mapActions.SETEXTENT: { case mapActions.TOGGLEMENU: {
let a = action as mapActions.SetExtent; return tassign(state, { menuVisible: !state.menuVisible });
return tassign(state, { extent: a.extent }); }
} case mapActions.SETEXTENT: {
case mapActions.ADDLAYER: { let a = action as mapActions.SetExtent;
let a = action as mapActions.AddLayer; return tassign(state, { extent: a.extent });
let itemLayers = state.overlayLayers.slice(0); }
let itemLayer = new ItemLayer(a.item); case mapActions.ADDLAYER: {
itemLayer.layerIndex = a.layerIndex == -1 ? 0 : a.layerIndex; let a = action as mapActions.AddLayer;
itemLayers.push(itemLayer); let itemLayers = state.overlayLayers.slice(0);
return tassign(state, { overlayLayers: itemLayers, selectedOverlayLayer: itemLayer }); let itemLayer = new ItemLayer(a.item);
} itemLayer.layerIndex = a.layerIndex == -1 ? 0 : a.layerIndex;
case mapActions.REMOVELAYER: { itemLayers.push(itemLayer);
let a = action as mapActions.RemoveLayer; return tassign(state, { overlayLayers: itemLayers, selectedOverlayLayer: itemLayer });
let newLayers = state.overlayLayers.slice(0); }
let i = state.overlayLayers.indexOf(a.itemLayer); case mapActions.REMOVELAYER: {
var selectedOverlayLayer: IItemLayer = null; let a = action as mapActions.RemoveLayer;
if (i>0 && state.overlayLayers.length > 1) let newLayers = state.overlayLayers.slice(0);
selectedOverlayLayer = state.overlayLayers[i - 1]; let i = state.overlayLayers.indexOf(a.itemLayer);
else if (i == 0 && state.overlayLayers.length > 1) var selectedOverlayLayer: IItemLayer = null;
selectedOverlayLayer = state.overlayLayers[i + 1]; if (i>0 && state.overlayLayers.length > 1)
newLayers.splice(i, 1); selectedOverlayLayer = state.overlayLayers[i - 1];
return tassign(state, { overlayLayers: newLayers, selectedOverlayLayer: selectedOverlayLayer }); else if (i == 0 && state.overlayLayers.length > 1)
} selectedOverlayLayer = state.overlayLayers[i + 1];
case mapActions.SETVISIBILITY: { newLayers.splice(i, 1);
let a = action as mapActions.SetVisibility; return tassign(state, { overlayLayers: newLayers, selectedOverlayLayer: selectedOverlayLayer });
let newLayers = state.overlayLayers.slice(0); }
let i = state.overlayLayers.indexOf(a.itemLayer); case mapActions.SETVISIBILITY: {
newLayers[i].visible = a.visibility; let a = action as mapActions.SetVisibility;
return tassign(state, { overlayLayers: newLayers }); let newLayers = state.overlayLayers.slice(0);
} let i = state.overlayLayers.indexOf(a.itemLayer);
case mapActions.SETOPACITY: { newLayers[i].visible = a.visibility;
let a = action as mapActions.SetOpacity; return tassign(state, { overlayLayers: newLayers });
let newLayers = state.overlayLayers.slice(0); }
let i = state.overlayLayers.indexOf(a.itemLayer); case mapActions.SETOPACITY: {
newLayers[i].opacity = a.opacity; let a = action as mapActions.SetOpacity;
return tassign(state, { overlayLayers: newLayers }); let newLayers = state.overlayLayers.slice(0);
} let i = state.overlayLayers.indexOf(a.itemLayer);
case mapActions.SETLAYERINDEX: { newLayers[i].opacity = a.opacity;
let a = action as mapActions.SetLayerIndex; return tassign(state, { overlayLayers: newLayers });
if (a.itemLayer == null) { }
var newItemlayer = new ItemLayer(state.selectedItemLayer.item); case mapActions.SETLAYERINDEX: {
newItemlayer.layerIndex = a.layerIndex; let a = action as mapActions.SetLayerIndex;
return tassign(state, { selectedItemLayer: newItemlayer}) if (a.itemLayer == null) {
} else { var newItemlayer = new ItemLayer(state.selectedItemLayer.item);
let newLayers = state.overlayLayers.slice(0); newItemlayer.layerIndex = a.layerIndex;
let i = state.overlayLayers.indexOf(a.itemLayer); return tassign(state, { selectedItemLayer: newItemlayer})
newLayers[i].layerIndex = a.layerIndex; } else {
return tassign(state, { overlayLayers: newLayers }); let newLayers = state.overlayLayers.slice(0);
} let i = state.overlayLayers.indexOf(a.itemLayer);
} newLayers[i].layerIndex = a.layerIndex;
case mapActions.LOADBASELAYERSSUCCESS: { return tassign(state, { overlayLayers: newLayers });
let a =action as mapActions.LoadBaseLayersSuccess; }
let baseLayers:ItemLayer[] = []; }
for (let item of a.items) { case mapActions.LOADBASELAYERSSUCCESS: {
var l = new ItemLayer(item); let a =action as mapActions.LoadBaseLayersSuccess;
l.visible = false; let baseLayers:ItemLayer[] = [];
baseLayers.push(l); for (let item of a.items) {
} var l = new ItemLayer(item);
var selectedBaseLayer: IItemLayer = null; l.visible = false;
var mapState = tassign(state.mapState); baseLayers.push(l);
console.debug(`Base layerload: ${mapState.baseLayerCode}`) }
if (baseLayers.length > 0 && mapState.baseLayerCode != "") { var selectedBaseLayer: IItemLayer = null;
selectedBaseLayer = baseLayers.filter(layer => layer.item.code === mapState.baseLayerCode)[0]; var mapState = tassign(state.mapState);
selectedBaseLayer.visible = true; console.debug(`Base layerload: ${mapState.baseLayerCode}`)
} else if (baseLayers.length > 0) { if (baseLayers.length > 0 && mapState.baseLayerCode != "") {
selectedBaseLayer = baseLayers[0]; selectedBaseLayer = baseLayers.filter(layer => layer.item.code === mapState.baseLayerCode)[0];
selectedBaseLayer.visible = true; selectedBaseLayer.visible = true;
mapState.baseLayerCode = selectedBaseLayer.item.code; } else if (baseLayers.length > 0) {
} selectedBaseLayer = baseLayers[0];
return tassign(state, { mapState:mapState, baseLayers: baseLayers, selectedBaseLayer: selectedBaseLayer }); selectedBaseLayer.visible = true;
} mapState.baseLayerCode = selectedBaseLayer.item.code;
case mapActions.SELECTBASELAYER: { }
let a = action as mapActions.SelectBaseLayer; return tassign(state, { mapState:mapState, baseLayers: baseLayers, selectedBaseLayer: selectedBaseLayer });
let baseLayers = state.baseLayers.slice(0); }
baseLayers.forEach((l) => l.visible = false); case mapActions.SELECTBASELAYER: {
let i = state.baseLayers.indexOf(a.itemLayer); let a = action as mapActions.SelectBaseLayer;
baseLayers[i].visible = true; let baseLayers = state.baseLayers.slice(0);
var mapState = tassign(state.mapState); baseLayers.forEach((l) => l.visible = false);
mapState.baseLayerCode = a.itemLayer.item.code; let i = state.baseLayers.indexOf(a.itemLayer);
return tassign(state, {mapState:mapState, baseLayers:baseLayers,selectedBaseLayer:a.itemLayer }); baseLayers[i].visible = true;
} var mapState = tassign(state.mapState);
case mapActions.SELECTOVERLAYLAYER: { mapState.baseLayerCode = a.itemLayer.item.code;
let a = action as mapActions.SelectOverlayLayer; return tassign(state, {mapState:mapState, baseLayers:baseLayers,selectedBaseLayer:a.itemLayer });
return tassign(state, { selectedOverlayLayer: a.itemLayer }); }
} case mapActions.SELECTOVERLAYLAYER: {
case commonActions.ESCAPE: { let a = action as mapActions.SelectOverlayLayer;
let a = action as commonActions.Escape; return tassign(state, { selectedOverlayLayer: a.itemLayer });
let newQueryState = tassign(state.queryState, { query: null, tags: null, itemCode: null, parentCode: null, itemType: null }); }
if (a.escapeKey) { case commonActions.ESCAPE: {
return tassign(state, { let a = action as commonActions.Escape;
panelVisible: false, let newQueryState = tassign(state.queryState, { query: null, tags: null, itemCode: null, parentCode: null, itemType: null });
panelCollapsed:false, if (a.escapeKey) {
selectedItem: null, return tassign(state, {
selectedItemLayer: null, panelVisible: false,
selectedFeature: null, panelCollapsed:false,
queryState: newQueryState, selectedItem: null,
clearEnabled: false, selectedItemLayer: null,
searchCollapsed: true, selectedFeature: null,
searchMinified: false, queryState: newQueryState,
menuVisible:false, clearEnabled: false,
features: [], searchCollapsed: true,
query:initialState.query searchMinified: false,
}); menuVisible:false,
} else { features: [],
return tassign(state, {}); query:initialState.query
} });
} } else {
default: { return tassign(state, {});
return state; }
} }
} default: {
} return state;
}
export const getMapState = (state: State) => state.mapState; }
export const getParentCode = (state: State) => state.parentCode; }
export const getFeatures = (state: State) => state.features;
export const getPanelVisible = (state: State) => state.panelVisible; export const getMapState = (state: State) => state.mapState;
export const getPanelCollapsed = (state: State) => state.panelCollapsed; export const getParentCode = (state: State) => state.parentCode;
export const getSelectedFeature = (state: State) => state.selectedFeature; export const getFeatures = (state: State) => state.features;
export const getSelectedItem = (state: State) => state.selectedItem; export const getPanelVisible = (state: State) => state.panelVisible;
export const getQueryState = (state: State) => state.queryState; export const getPanelCollapsed = (state: State) => state.panelCollapsed;
export const getClearEnabled = (state: State) => state.clearEnabled; export const getSelectedFeature = (state: State) => state.selectedFeature;
export const getSearchCollapsed = (state: State) => state.searchCollapsed; export const getSelectedItem = (state: State) => state.selectedItem;
export const getSearchMinified = (state: State) => state.searchMinified; export const getQueryState = (state: State) => state.queryState;
export const getMenuVisible = (state: State) => state.menuVisible; export const getClearEnabled = (state: State) => state.clearEnabled;
export const getExtent = (state: State) => state.extent; export const getSearchCollapsed = (state: State) => state.searchCollapsed;
export const getOverlayLayers = (state: State) => state.overlayLayers; export const getSearchMinified = (state: State) => state.searchMinified;
export const getBaseLayers = (state: State) => state.baseLayers; export const getMenuVisible = (state: State) => state.menuVisible;
export const getProjection = (state: State) => state.projection; export const getExtent = (state: State) => state.extent;
export const getSelectedBaseLayer = (state: State) => state.selectedBaseLayer; export const getOverlayLayers = (state: State) => state.overlayLayers;
export const getSelectedOverlayLayer = (state: State) => state.selectedOverlayLayer; export const getBaseLayers = (state: State) => state.baseLayers;
export const getQuery = (state: State) => state.query; export const getProjection = (state: State) => state.projection;
export const getSelectedItemLayer = (state: State) => state.selectedItemLayer; export const getSelectedBaseLayer = (state: State) => state.selectedBaseLayer;
export const getPeriod = (state:State) => state.period; export const getSelectedOverlayLayer = (state: State) => state.selectedOverlayLayer;
export const getQuery = (state: State) => state.query;
export const selectMapState = createFeatureSelector<State>(MODULE_NAME); export const getSelectedItemLayer = (state: State) => state.selectedItemLayer;
export const selectGetMapState= createSelector(selectMapState, getMapState); export const getPeriod = (state:State) => state.period;
export const selectGetParentCode = createSelector(selectMapState, getParentCode);
export const selectGetFeatures = createSelector(selectMapState, getFeatures); export const selectMapState = createFeatureSelector<State>(MODULE_NAME);
export const selectGetPanelVisible = createSelector(selectMapState, getPanelVisible); export const selectGetMapState= createSelector(selectMapState, getMapState);
export const selectGetPanelCollapsed = createSelector(selectMapState, getPanelCollapsed); export const selectGetParentCode = createSelector(selectMapState, getParentCode);
export const selectGetSelectedFeature = createSelector(selectMapState, getSelectedFeature); export const selectGetFeatures = createSelector(selectMapState, getFeatures);
export const selectGetSelectedItem = createSelector(selectMapState, getSelectedItem); export const selectGetPanelVisible = createSelector(selectMapState, getPanelVisible);
export const selectGetQueryState = createSelector(selectMapState, getQueryState); export const selectGetPanelCollapsed = createSelector(selectMapState, getPanelCollapsed);
export const selectGetClearEnabled = createSelector(selectMapState, getClearEnabled); export const selectGetSelectedFeature = createSelector(selectMapState, getSelectedFeature);
export const selectGetSearchCollapsed = createSelector(selectMapState, getSearchCollapsed); export const selectGetSelectedItem = createSelector(selectMapState, getSelectedItem);
export const selectGetSearchMinified = createSelector(selectMapState, getSearchMinified); export const selectGetQueryState = createSelector(selectMapState, getQueryState);
export const selectGetMenuVisible = createSelector(selectMapState, getMenuVisible); export const selectGetClearEnabled = createSelector(selectMapState, getClearEnabled);
export const selectGetExtent = createSelector(selectMapState, getExtent); export const selectGetSearchCollapsed = createSelector(selectMapState, getSearchCollapsed);
export const selectGetOverlayLayers = createSelector(selectMapState, getOverlayLayers); export const selectGetSearchMinified = createSelector(selectMapState, getSearchMinified);
export const selectGetBaseLayers = createSelector(selectMapState, getBaseLayers); export const selectGetMenuVisible = createSelector(selectMapState, getMenuVisible);
export const selectGetProjection = createSelector(selectMapState, getProjection); export const selectGetExtent = createSelector(selectMapState, getExtent);
export const selectGetSelectedBaseLayer = createSelector(selectMapState, getSelectedBaseLayer); export const selectGetOverlayLayers = createSelector(selectMapState, getOverlayLayers);
export const selectGetSelectedOverlayLayer = createSelector(selectMapState, getSelectedOverlayLayer); export const selectGetBaseLayers = createSelector(selectMapState, getBaseLayers);
export const selectGetQuery = createSelector(selectMapState, getQuery); export const selectGetProjection = createSelector(selectMapState, getProjection);
export const selectGetSelectedItemLayer = createSelector(selectMapState, getSelectedItemLayer); export const selectGetSelectedBaseLayer = createSelector(selectMapState, getSelectedBaseLayer);
export const selectGetPeriod = createSelector(selectMapState, getPeriod); export const selectGetSelectedOverlayLayer = createSelector(selectMapState, getSelectedOverlayLayer);
export const selectGetQuery = createSelector(selectMapState, getQuery);
export const selectGetSelectedItemLayer = createSelector(selectMapState, getSelectedItemLayer);
export const selectGetPeriod = createSelector(selectMapState, getPeriod);

View File

@@ -0,0 +1,24 @@
import { Injectable } from '@angular/core';
import { Observer, Observable } from 'rxjs';
@Injectable()
export class DeviceOrientationService {
/**
* Tries HTML5 geolocation.
*
* Wraps the Geolocation API into an observable.
*
* @return An observable of Bearing
*/
getCurrentBearing(): Observable<number> {
return Observable.create((observer: Observer<number>) => {
let sensor = new Magnetometer();
sensor.onreading= (ev:Event) => {
observer.next(Math.atan2(sensor.y, sensor.x) * (180 / Math.PI));
};
});
}
}

View File

@@ -1,35 +1,35 @@
{ {
"name": "@farmmaps/common", "name": "@farmmaps/common",
"version": "0.0.1", "version": "0.0.1",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {
"angular-oauth2-oidc": { "angular-oauth2-oidc": {
"version": "5.0.2", "version": "8.0.4",
"resolved": "https://registry.npmjs.org/angular-oauth2-oidc/-/angular-oauth2-oidc-5.0.2.tgz", "resolved": "https://registry.npmjs.org/angular-oauth2-oidc/-/angular-oauth2-oidc-8.0.4.tgz",
"integrity": "sha512-jtOv4IWEjSFfBHVE4seWGWT/ZfWJ95QJ1JaFhVVGJEF64ibGuPwV3ztwTOUl98QHi/Yg4PXXDAisb31JnIbxBw==", "integrity": "sha512-7/3niJBqD7rnElcW+SudE36g7zMWChW4gSq7NpJSzDA4aQadBgvg0hn317MfPm9tpYGrpE3G/z2NMnbzek4TMA==",
"requires": { "requires": {
"jsrsasign": "^8.0.12", "jsrsasign": "^8.0.12",
"tslib": "^1.9.0" "tslib": "^1.9.0"
} }
}, },
"jsrsasign": { "jsrsasign": {
"version": "8.0.12", "version": "8.0.12",
"resolved": "https://registry.npmjs.org/jsrsasign/-/jsrsasign-8.0.12.tgz", "resolved": "https://registry.npmjs.org/jsrsasign/-/jsrsasign-8.0.12.tgz",
"integrity": "sha1-Iqu5ZW00owuVMENnIINeicLlwxY=" "integrity": "sha1-Iqu5ZW00owuVMENnIINeicLlwxY="
}, },
"ngx-uploadx": { "ngx-uploadx": {
"version": "3.1.3", "version": "3.3.2",
"resolved": "https://registry.npmjs.org/ngx-uploadx/-/ngx-uploadx-3.1.3.tgz", "resolved": "https://registry.npmjs.org/ngx-uploadx/-/ngx-uploadx-3.3.2.tgz",
"integrity": "sha512-RX3uEaqMTpjTv5mtdnTQYsDOED3Qg5V3OBU5ohOyL35uL+dllF7I0y+kojJprm9thzHNAWih1DLeTlVWZKo+hQ==", "integrity": "sha512-gRdXXq2cRU9HE6dj65qay9GV8NRC7n8y5LtMzJWqsfu2k3CHMQxo2TqZwA9/l/PqJ76RoO7sTPy1OenFQ+krkQ==",
"requires": { "requires": {
"tslib": "^1.9.0" "tslib": "^1.9.0"
} }
}, },
"tslib": { "tslib": {
"version": "1.10.0", "version": "1.10.0",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz",
"integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==" "integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ=="
} }
} }
} }

View File

@@ -1,24 +1,24 @@
{ {
"name": "@farmmaps/common", "name": "@farmmaps/common",
"version": "0.0.1", "version": "0.0.1",
"publishConfig": { "publishConfig": {
"registry": "https://repository.akkerweb.nl/repository/npm-hosted/" "registry": "https://repository.akkerweb.nl/repository/npm-hosted/"
}, },
"dependencies": { "dependencies": {
"angular-oauth2-oidc": "^5.0.2", "angular-oauth2-oidc": "^8.0.2",
"ngx-uploadx": "^3.1.3" "ngx-uploadx": "^3.3.2"
}, },
"peerDependencies": { "peerDependencies": {
"@ng-bootstrap/ng-bootstrap": "^4.2.1", "@ng-bootstrap/ng-bootstrap": "^4.2.1",
"@angular/common": "^7.2.0", "@angular/common": "^8.2.0",
"@angular/core": "^7.2.0", "@angular/core": "^8.2.0",
"@angular/forms": "^7.2.0", "@angular/forms": "^8.2.0",
"@ngrx/effects": "^7.2", "@ngrx/effects": "^8.2",
"@ngrx/router-store": "^7.2", "@ngrx/router-store": "^8.2",
"@ngrx/store": "^7.2", "@ngrx/store": "^8.2",
"tassign": "^1.0.0", "tassign": "^1.0.0",
"bootstrap": "^4.3.1", "bootstrap": "^4.3.1",
"@aspnet/signalr": "^1.1.4", "@aspnet/signalr": "^1.1.4",
"font-awesome": "^4.7.0" "font-awesome": "^4.7.0"
} }
} }

View File

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

View File

@@ -0,0 +1,106 @@
// angular modules
import { NgModule, APP_INITIALIZER, ModuleWithProviders, Injector,Optional,SkipSelf } 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';
// 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 { AppComponent} from './components/app/app.component';
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 { NotImplementedComponent } from './components/not-implemented/not-implemented.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';
import {AuthConfigFactory} from './shared/authconfigFactory';
export {FolderService,
ItemTypeService,
TimespanService,
ItemService,
EventService,
TypeaheadService,
UserService,
AppConfig,
AccessTokenInterceptor,
AuthGuard,
NavBarGuard,
FullScreenGuard,
AuthCallbackGuard,
ResumableFileUploadService,
NgbDateNativeAdapter
};
@NgModule({
imports: [
OAuthModule.forRoot(),
]
})
export class AppCommonServiceModule {
constructor (@Optional() @SkipSelf() parentModule: AppCommonServiceModule) {
if (parentModule) {
throw new Error(
'AppCommonServiceModule is already loaded. Import it in the AppModule only');
}
}
static forRoot(): ModuleWithProviders {
return {
ngModule: AppCommonServiceModule,
providers: [
AppConfig,
{
provide: APP_INITIALIZER,
useFactory: appConfigFactory,
deps: [Injector, AppConfig, OAuthService,AuthConfigFactory],
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: AccessTokenInterceptor,
multi: true
},
DatePipe
]
};
}
}

View File

@@ -18,25 +18,11 @@ import { AppCommonRoutingModule } from './common-routing.module';
import { MODULE_NAME } from './module-name'; import { MODULE_NAME } from './module-name';
//components //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 { SafePipe } from './shared/safe.pipe';
import { AuthConfigFactory,IAuthconfigFactory} from './shared/authconfigFactory';
import { AppComponent} from './components/app/app.component'; import { AppComponent} from './components/app/app.component';
import { AuthCallbackComponent } from './components/auth-callback/auth-callback.component'; 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 { 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 { ResumableFileUploadComponent } from './components/resumable-file-upload/resumable-file-upload.component';
import { NotFoundComponent } from './components/not-found/not-found.component'; import { NotFoundComponent } from './components/not-found/not-found.component';
import { NotImplementedComponent } from './components/not-implemented/not-implemented.component'; import { NotImplementedComponent } from './components/not-implemented/not-implemented.component';
@@ -54,27 +40,12 @@ import {IUser} from './models/user';
import * as commonActions from './actions/app-common.actions'; import * as commonActions from './actions/app-common.actions';
import * as commonReducers from './reducers/app-common.reducer'; import * as commonReducers from './reducers/app-common.reducer';
import * as commonEffects from './effects/app-common.effects'; import * as commonEffects from './effects/app-common.effects';
import {NgbDateNativeAdapter} from './services/date-adapter.service'
import { from } from 'rxjs';
export {FolderService, export {
ItemTypeService,
TimespanService,
ItemService,
EventService,
TypeaheadService,
UserService,
AppConfig,
AccessTokenInterceptor,
AuthGuard,
NavBarGuard,
FullScreenGuard,
SafePipe, SafePipe,
AuthCallbackComponent, AuthCallbackComponent,
AuthCallbackGuard,
AppComponent, AppComponent,
SessionClearedComponent, SessionClearedComponent,
ResumableFileUploadService,
ResumableFileUploadComponent, ResumableFileUploadComponent,
NotFoundComponent, NotFoundComponent,
NotImplementedComponent, NotImplementedComponent,
@@ -93,7 +64,8 @@ export {FolderService,
IUser, IUser,
commonActions, commonActions,
commonReducers, commonReducers,
NgbDateNativeAdapter IAuthconfigFactory,
AuthConfigFactory
}; };
@NgModule({ @NgModule({
@@ -108,9 +80,6 @@ export {FolderService,
FormsModule, FormsModule,
UploadxModule UploadxModule
], ],
providers: [
DatePipe
],
declarations: [ declarations: [
AppComponent, AppComponent,
AuthCallbackComponent, AuthCallbackComponent,
@@ -141,29 +110,4 @@ export {FolderService,
] ]
}) })
export class AppCommonModule { export class AppCommonModule {
constructor (@Optional() @SkipSelf() parentModule: AppCommonModule) {
if (parentModule) {
throw new Error(
'AppCommonModule is already loaded. Import it in the AppModule only');
}
}
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
}
]
};
}
} }

View File

@@ -1,129 +1,133 @@
import { Component, OnInit, OnDestroy, Inject, ViewEncapsulation, RendererFactory2, PLATFORM_ID, ChangeDetectionStrategy, HostListener } from '@angular/core'; import { Component, OnInit, OnDestroy, Inject, ViewEncapsulation, RendererFactory2, PLATFORM_ID, ChangeDetectionStrategy, HostListener } from '@angular/core';
import { Router, NavigationEnd, RouteConfigLoadStart, RouteConfigLoadEnd, ActivatedRoute, PRIMARY_OUTLET } from '@angular/router'; import { Router, NavigationEnd, RouteConfigLoadStart, RouteConfigLoadEnd, ActivatedRoute, PRIMARY_OUTLET } from '@angular/router';
import { Meta, Title, DOCUMENT, MetaDefinition } from '@angular/platform-browser'; import { Meta, Title, MetaDefinition } from '@angular/platform-browser';import { DOCUMENT } from "@angular/common";
import { Subscription , Observable } from 'rxjs'; import { Subscription , Observable } from 'rxjs';
import { Store, Action } from '@ngrx/store'; import { Store, Action } from '@ngrx/store';
//AppCommon //AppCommon
import { IEventMessage } from '../../models/event.message'; import { IEventMessage } from '../../models/event.message';
import { IListItem} from '../../models/list.item'; import { IListItem} from '../../models/list.item';
import { EventService } from '../../services/event.service'; import { EventService } from '../../services/event.service';
import * as commonActions from '../../actions/app-common.actions'; import * as commonActions from '../../actions/app-common.actions';
import * as appReducers from '../../reducers/app-common.reducer'; import * as appReducers from '../../reducers/app-common.reducer';
@Component({ @Component({
selector: 'fm-app', selector: 'fm-app',
templateUrl: './app.component.html', templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'], styleUrls: ['./app.component.scss'],
encapsulation: ViewEncapsulation.None, encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush changeDetection: ChangeDetectionStrategy.OnPush
}) })
export class AppComponent implements OnInit, OnDestroy { export class AppComponent implements OnInit, OnDestroy {
// This will go at the END of your title for example "Home - Angular Universal..." <-- after the dash (-) // This will go at the END of your title for example "Home - Angular Universal..." <-- after the dash (-)
private endPageTitle: string = 'Farmmaps'; private endPageTitle: string = 'Farmmaps';
// If no Title is provided, we'll use a default one before the dash(-) // If no Title is provided, we'll use a default one before the dash(-)
private defaultPageTitle: string = 'Farmmaps'; private defaultPageTitle: string = 'Farmmaps';
private routerSub$: Subscription; private routerSub$: Subscription;
private eventSub$: Subscription; private eventSub$: Subscription;
public currentFolder: Observable<IListItem>; public currentFolder: Observable<IListItem>;
public folderParents: Observable<IListItem[]>; public folderParents: Observable<IListItem[]>;
public browseFileElement: any; public browseFileElement: any;
public browseDirectoryElement: any; public browseDirectoryElement: any;
public fileDroptarget: any; public fileDroptarget: any;
public fullScreen: Observable<boolean>; public fullScreen: Observable<boolean>;
public routeLoading: Observable<boolean>; public routeLoading: Observable<boolean>;
constructor( constructor(
private router: Router, private router: Router,
private activatedRoute: ActivatedRoute, private activatedRoute: ActivatedRoute,
private title: Title, private title: Title,
private meta: Meta, private meta: Meta,
private store: Store<appReducers.State>, private store: Store<appReducers.State>,
private eventService: EventService, private eventService: EventService,
) { ) {
} }
getActionFromEvent(event: IEventMessage): Action { getActionFromEvent(event: IEventMessage): Action {
var action: Action = null; var action: Action = null;
console.debug(`${event.eventType} Event received`); console.debug(`${event.eventType} Event received`);
switch (event.eventType) { switch (event.eventType) {
case "ItemChanged": { case "ItemChanged": {
action = new commonActions.ItemChangedEvent(event.itemCode, event.attributes); action = new commonActions.ItemChangedEvent(event.itemCode, event.attributes);
break; break;
} }
case "ItemAdded": { case "ItemAdded": {
action = new commonActions.ItemAddedEvent(event.itemCode, event.attributes); action = new commonActions.ItemAddedEvent(event.itemCode, event.attributes);
break; break;
} }
case "ItemDeleted": { case "ItemDeleted": {
action = new commonActions.ItemDeletedEvent(event.itemCode, event.attributes); action = new commonActions.ItemDeletedEvent(event.itemCode, event.attributes);
break; break;
} }
case "taskStart": { case "taskStart": {
action = new commonActions.TaskStartEvent(event.itemCode, event.attributes); action = new commonActions.TaskStartEvent(event.itemCode, event.attributes);
break; break;
} }
case "taskEnd": { case "taskEnd": {
action = new commonActions.TaskEndEvent(event.itemCode, event.attributes); action = new commonActions.TaskEndEvent(event.itemCode, event.attributes);
break; break;
} }
case "taskError": { case "taskError": {
action = new commonActions.TaskErrorEvent(event.itemCode, event.attributes); action = new commonActions.TaskErrorEvent(event.itemCode, event.attributes);
break; break;
} }
} case "deviceUpdate": {
return action; action = new commonActions.DeviceUpdateEvent(event.itemCode, event.attributes);
} break;
}
ngOnInit() { }
this.fullScreen = this.store.select(appReducers.selectGetFullScreen); return action;
this.routeLoading = this.store.select(appReducers.selectGetRouteLoading); }
this.InstallRouteEventHandler();
this.InstallEventServiceEventHandler(); ngOnInit() {
} this.fullScreen = this.store.select(appReducers.selectGetFullScreen);
this.routeLoading = this.store.select(appReducers.selectGetRouteLoading);
@HostListener('document:keyup', ['$event']) this.InstallRouteEventHandler();
keyUp(event: KeyboardEvent) { this.InstallEventServiceEventHandler();
let x = event.keyCode; }
if (x === 27) {
this.store.dispatch(new commonActions.Escape(true,false)); @HostListener('document:keyup', ['$event'])
} keyUp(event: KeyboardEvent) {
} let x = event.keyCode;
if (x === 27) {
ngOnDestroy() { this.store.dispatch(new commonActions.Escape(true,false));
// Subscription clean-up }
if(this.routerSub$) this.routerSub$.unsubscribe(); }
if(this.eventSub$) this.eventSub$.unsubscribe();
} ngOnDestroy() {
// Subscription clean-up
private InstallRouteEventHandler() { if(this.routerSub$) this.routerSub$.unsubscribe();
var other = this; if(this.eventSub$) this.eventSub$.unsubscribe();
this.routerSub$ = this.router.events.subscribe(event => { }
if (event instanceof RouteConfigLoadStart) {
other.store.dispatch(new commonActions.StartRouteLoading()); private InstallRouteEventHandler() {
} var other = this;
if (event instanceof RouteConfigLoadEnd) { this.routerSub$ = this.router.events.subscribe(event => {
other.store.dispatch(new commonActions.EndRouteLoading()); if (event instanceof RouteConfigLoadStart) {
} other.store.dispatch(new commonActions.StartRouteLoading());
}); }
} if (event instanceof RouteConfigLoadEnd) {
other.store.dispatch(new commonActions.EndRouteLoading());
private InstallEventServiceEventHandler() { }
var other = this; });
this.eventSub$ = this.eventService.event.subscribe(event => { }
var action = other.getActionFromEvent(event);
if (action) other.store.dispatch(action); private InstallEventServiceEventHandler() {
}); var other = this;
} this.eventSub$ = this.eventService.event.subscribe(event => {
var action = other.getActionFromEvent(event);
handleClick(event: MouseEvent) { if (action) other.store.dispatch(action);
this.store.dispatch(new commonActions.Escape(false,true)); });
} }
}
handleClick(event: MouseEvent) {
this.store.dispatch(new commonActions.Escape(false,true));
}
}

View File

@@ -2,7 +2,7 @@
<div> <div>
<div class="card"> <div class="card">
<div class="card-header p-3 bg-primary text-white"> <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">Uploading files (<span>{{uploadService.totalProgress | number:'1.1-1'}}</span> %)</span>
<span *ngIf="uploadService.isUploading == false">Uploaded <span>{{uploadService.files.length}}</span> files</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> <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>

View File

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

View File

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

View File

@@ -1 +0,0 @@

View File

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

View File

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

@@ -1,32 +1,35 @@
import {Inject, Injectable} from '@angular/core'; import {Inject, Injectable} from '@angular/core';
import {HttpClient, HttpXhrBackend} from '@angular/common/http'; import { Location,PathLocationStrategy,LocationStrategy } from '@angular/common';
import {Observable} from 'rxjs'; import {HttpClient, HttpXhrBackend} from '@angular/common/http';
import {Observable} from 'rxjs';
@Injectable()
export class AppConfig { @Injectable()
export class AppConfig {
private config: Object = null;
private httpClient: HttpClient; private config: Object = null;
private httpClient: HttpClient;
constructor(xhrBackend: HttpXhrBackend) {
this.httpClient = new HttpClient(xhrBackend); constructor(xhrBackend: HttpXhrBackend,private location:Location) {
this.config = null; this.httpClient = new HttpClient(xhrBackend);
} this.config = null;
}
public getConfig(key: any) {
if (!this.config.hasOwnProperty(key)) { public getConfig(key: any) {
console.error(`Config key ${key} not set`); if (!this.config.hasOwnProperty(key)) {
} console.error(`Config key ${key} not set`);
return this.config[key]; }
} return this.config[key];
}
public load(): Promise<any> {
return this.httpClient.get('/configuration.json') public load(): Promise<any> {
.toPromise() var url = this.location.prepareExternalUrl('/configuration.json');
.then(data => { if(url.startsWith("#")) url='file:///android_asset/www/configuration.json'; // hack for cordova
this.config = data; return this.httpClient.get(url)
//return data; .toPromise()
}) .then(data => {
.catch(error => this.config = null); this.config = data;
}; //return data;
} })
.catch(error => this.config = null);
};
}

View File

@@ -0,0 +1,22 @@
import { AuthConfig } from 'angular-oauth2-oidc';
import {AppConfig} from './app.config';
export interface IAuthconfigFactory {
getAuthConfig(appConfig: AppConfig): AuthConfig;
}
export class AuthConfigFactory implements IAuthconfigFactory {
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;
}
}

View File

@@ -3,3 +3,4 @@
*/ */
export * from './fm/common.module'; export * from './fm/common.module';
export * from './fm/common-service.module';

View File

@@ -1,31 +0,0 @@
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'farmmaps-lib-app'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('farmmaps-lib-app');
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to farmmaps-lib-app!');
});
});

View File

@@ -1,64 +1,73 @@
import { import {
NgModule, NgModule,
Inject, Inject,
APP_BOOTSTRAP_LISTENER, APP_BOOTSTRAP_LISTENER,
InjectionToken, Type, InjectionToken, Type,
} from '@angular/core'; } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'; import { BrowserModule } from '@angular/platform-browser';
import { AppCommonModule, } from '@farmmaps/common'; import { AppCommonModule,AppCommonServiceModule,AuthConfigFactory } from '@farmmaps/common';
import { AppCommonMapModule} from '@farmmaps/common-map'; import { AppCommonMapModule} from '@farmmaps/common-map';
import {AppRootComponent} from './app.component'; import {AppRootComponent} from './app.component';
import {StoreModule, Store} from '@ngrx/store'; import {StoreModule, Store} from '@ngrx/store';
import {EffectsModule, EffectSources} from '@ngrx/effects'; import {EffectsModule, EffectSources} from '@ngrx/effects';
import { StoreRouterConnectingModule} from '@ngrx/router-store'; import { StoreRouterConnectingModule} from '@ngrx/router-store';
import {AppRoutingModule} from './app-routing.module'; import {AppRoutingModule} from './app-routing.module';
import { LogoComponent } from './logo/logo.component'; import { LogoComponent } from './logo/logo.component';
import { MenuComponent } from './menu/menu.component'; import { MenuComponent } from './menu/menu.component';
import { LocalAuthconfigFactory} from './localAuthconfigFactory';
export const BOOTSTRAP_EFFECTS = new InjectionToken('Bootstrap Effects'); import { AuthConfig } from 'angular-oauth2-oidc';
export function bootstrapEffects(effects: Type<any>[], sources: EffectSources) { export const BOOTSTRAP_EFFECTS = new InjectionToken('Bootstrap Effects');
return () => {
effects.forEach(effect => sources.addEffects(effect)); export function bootstrapEffects(effects: Type<any>[], sources: EffectSources) {
}; return () => {
} effects.forEach(effect => sources.addEffects(effect));
};
export function createInstances(...instances: any[]) { }
return instances;
} export function createInstances(...instances: any[]) {
return instances;
export function provideBootstrapEffects(effects: Type<any>[]) { }
return [
effects, export function provideBootstrapEffects(effects: Type<any>[]) {
{provide: BOOTSTRAP_EFFECTS, deps: effects, useFactory: createInstances}, return [
{ effects,
provide: APP_BOOTSTRAP_LISTENER, {provide: BOOTSTRAP_EFFECTS, deps: effects, useFactory: createInstances},
multi: true, {
useFactory: bootstrapEffects, provide: APP_BOOTSTRAP_LISTENER,
deps: [[new Inject(BOOTSTRAP_EFFECTS)], EffectSources], multi: true,
}, useFactory: bootstrapEffects,
]; deps: [[new Inject(BOOTSTRAP_EFFECTS)], EffectSources],
} },
];
@NgModule({ }
declarations: [
AppRootComponent, @NgModule({
LogoComponent, declarations: [
MenuComponent AppRootComponent,
], LogoComponent,
imports: [ MenuComponent
AppRoutingModule, ],
AppCommonModule.forRoot() , imports: [
AppCommonMapModule.forRoot(), AppRoutingModule,
BrowserModule, AppCommonModule,
StoreModule.forRoot({}), AppCommonServiceModule.forRoot(),
EffectsModule.forRoot([]) AppCommonMapModule.forRoot(),
], BrowserModule,
providers: [], StoreModule.forRoot({}),
bootstrap: [AppRootComponent] EffectsModule.forRoot([])
}) ],
export class AppModule { } providers: [
AuthConfigFactory
// {
// provide:AuthConfigFactory,
// useClass:LocalAuthconfigFactory
// }
],
bootstrap: [AppRootComponent]
})
export class AppModule { }

View File

@@ -0,0 +1,22 @@
import {IAuthconfigFactory,AppConfig} from '@farmmaps/common';
import {AuthConfig} from 'angular-oauth2-oidc';
export class LocalAuthconfigFactory implements IAuthconfigFactory {
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.openUri = uri => {
window.alert("OK "+uri);
}
authConfig.requireHttps = appConfig.getConfig("requireHttps");
return authConfig;
}
}

View File

@@ -43,7 +43,7 @@
* *
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
* *
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge * with the following flag, it will bypass `zone.js` patch for IE/Edge

View File

@@ -1,11 +1,11 @@
{ {
"extends": "../tsconfig.json", "extends": "../tsconfig.json",
"compilerOptions": { "compilerOptions": {
"outDir": "../out-tsc/app", "outDir": "../out-tsc/app",
"types": [] "types": []
}, },
"exclude": [ "exclude": [
"test.ts", "test.ts",
"**/*.spec.ts" "**/*.spec.ts"
] ]
} }

View File

@@ -1,18 +1,18 @@
{ {
"extends": "../tsconfig.json", "extends": "../tsconfig.json",
"compilerOptions": { "compilerOptions": {
"outDir": "../out-tsc/spec", "outDir": "../out-tsc/spec",
"types": [ "types": [
"jasmine", "jasmine",
"node" "node"
] ]
}, },
"files": [ "files": [
"test.ts", "test.ts",
"polyfills.ts" "polyfills.ts"
], ],
"include": [ "include": [
"**/*.spec.ts", "**/*.spec.ts",
"**/*.d.ts" "**/*.d.ts"
] ]
} }

View File

@@ -2,15 +2,16 @@
"compileOnSave": false, "compileOnSave": false,
"compilerOptions": { "compilerOptions": {
"baseUrl": "./", "baseUrl": "./",
"downlevelIteration": true,
"outDir": "./dist/out-tsc", "outDir": "./dist/out-tsc",
"sourceMap": true, "sourceMap": true,
"declaration": false, "declaration": false,
"module": "es2015", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "node",
"emitDecoratorMetadata": true, "emitDecoratorMetadata": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"importHelpers": true, "importHelpers": true,
"target": "es5", "target": "es2015",
"typeRoots": [ "typeRoots": [
"node_modules/@types" "node_modules/@types"
], ],

View File

@@ -1,75 +1,75 @@
{ {
"extends": "tslint:recommended", "extends": "tslint:recommended",
"rulesDirectory": [ "rulesDirectory": [
"codelyzer" "codelyzer"
], ],
"rules": { "rules": {
"array-type": false, "array-type": false,
"arrow-parens": false, "arrow-parens": false,
"deprecation": { "deprecation": {
"severity": "warn" "severity": "warn"
}, },
"import-blacklist": [ "import-blacklist": [
true, true,
"rxjs/Rx" "rxjs/Rx"
], ],
"interface-name": false, "interface-name": false,
"max-classes-per-file": false, "max-classes-per-file": false,
"max-line-length": [ "max-line-length": [
true, true,
140 140
], ],
"member-access": false, "member-access": false,
"member-ordering": [ "member-ordering": [
true, true,
{ {
"order": [ "order": [
"static-field", "static-field",
"instance-field", "instance-field",
"static-method", "static-method",
"instance-method" "instance-method"
] ]
} }
], ],
"no-consecutive-blank-lines": false, "no-consecutive-blank-lines": false,
"no-console": [ "no-console": [
true, true,
"debug", "debug",
"info", "info",
"time", "time",
"timeEnd", "timeEnd",
"trace" "trace"
], ],
"no-empty": false, "no-empty": false,
"no-inferrable-types": [ "no-inferrable-types": [
true, true,
"ignore-params" "ignore-params"
], ],
"no-non-null-assertion": true, "no-non-null-assertion": true,
"no-redundant-jsdoc": true, "no-redundant-jsdoc": true,
"no-switch-case-fall-through": true, "no-switch-case-fall-through": true,
"no-use-before-declare": true, "no-use-before-declare": true,
"no-var-requires": false, "no-var-requires": false,
"object-literal-key-quotes": [ "object-literal-key-quotes": [
true, true,
"as-needed" "as-needed"
], ],
"object-literal-sort-keys": false, "object-literal-sort-keys": false,
"ordered-imports": false, "ordered-imports": false,
"quotemark": [ "quotemark": [
true, true,
"single" "single"
], ],
"trailing-comma": false, "trailing-comma": false,
"no-output-on-prefix": true, "no-output-on-prefix": true,
"use-input-property-decorator": true, "no-inputs-metadata-property": true,
"use-output-property-decorator": true, "no-outputs-metadata-property": true,
"use-host-property-decorator": true, "no-host-metadata-property": true,
"no-input-rename": true, "no-input-rename": true,
"no-output-rename": true, "no-output-rename": true,
"use-life-cycle-interface": true, "use-lifecycle-interface": true,
"use-pipe-transform-interface": true, "use-pipe-transform-interface": true,
"component-class-suffix": true, "component-class-suffix": true,
"directive-class-suffix": true "directive-class-suffix": true
} }
} }