From 90d85ed4affcff56f2278f4f657b9d0713353069 Mon Sep 17 00:00:00 2001 From: Sergiotarxz Date: Tue, 21 Nov 2023 19:16:30 +0100 Subject: [PATCH] Splitting login logic to a separated file to make the code easier to work with. --- js-src/conquer/index.ts | 255 ++---------------------------- js-src/conquer/login.ts | 267 ++++++++++++++++++++++++++++++++ public/css/styles.scss | 7 + public/js/bundle.js | 13 +- templates/conquer/index.html.ep | 2 + 5 files changed, 300 insertions(+), 244 deletions(-) create mode 100644 js-src/conquer/login.ts diff --git a/js-src/conquer/index.ts b/js-src/conquer/index.ts index 3ca5013..f235aea 100644 --- a/js-src/conquer/index.ts +++ b/js-src/conquer/index.ts @@ -16,6 +16,7 @@ import CircleStyle from 'ol/style/Circle' import Style from 'ol/style/Style' import BaseEvent from 'ol/events/Event' import {click} from 'ol/events/condition' +import ConquerLogin from '@burguillosinfo/conquer/login' type StylesInterface = Record export default class Conquer { @@ -26,20 +27,6 @@ export default class Conquer { private rotationOffset = 0 private heading = 0 private disableSetRotationOffset = false - private conquerLogin: HTMLDivElement - private conquerLoginGoToRegister: HTMLAnchorElement - private conquerLoginError: HTMLParagraphElement - private conquerLoginSuccess: HTMLParagraphElement - private conquerLoginUsername: HTMLInputElement - private conquerLoginPassword: HTMLInputElement - private conquerLoginSubmit: HTMLButtonElement - private conquerRegisterGoToLogin: HTMLAnchorElement - private conquerRegister: HTMLDivElement - private conquerRegisterUsername: HTMLInputElement - private conquerRegisterPassword: HTMLInputElement - private conquerRegisterRepeatPassword: HTMLInputElement - private conquerRegisterSubmit: HTMLButtonElement - private conquerRegisterError: HTMLParagraphElement private currentPositionFeature: Feature | null private vectorLayer: VectorLayer | null = null private alpha = 0 @@ -68,92 +55,7 @@ export default class Conquer { alert('Error de interfaz') throw new Error(error) } - fillConquerLogin() { - const conquerLogin = document.querySelector('.conquer-login') - if (conquerLogin === null || !(conquerLogin instanceof HTMLDivElement)) { - Conquer.fail('conquerLogin is invalid') - } - this.conquerLogin = conquerLogin - const conquerLoginGoToRegister = document.querySelector('.conquer-login-go-to-register') - if (conquerLoginGoToRegister === null || !(conquerLoginGoToRegister instanceof HTMLAnchorElement)) { - Conquer.fail('Link to go to register from login is invalid.') - } - this.conquerLoginGoToRegister = conquerLoginGoToRegister - this.conquerLoginGoToRegister.addEventListener('click', () => { - this.goToRegister() - }) - const conquerLoginError = document.querySelector('.conquer-login-error') - if (conquerLoginError === null || !(conquerLoginError instanceof HTMLParagraphElement)) { - Conquer.fail('Unable to find conquer login error.') - } - this.conquerLoginError = conquerLoginError - const conquerLoginSuccess = document.querySelector('.conquer-login-success') - if (conquerLoginSuccess === null || !(conquerLoginSuccess instanceof HTMLParagraphElement)) { - Conquer.fail('Unable to find conquer login success.') - } - this.conquerLoginSuccess = conquerLoginSuccess - const conquerLoginUsername = document.querySelector('.conquer-login-username') - if (conquerLoginUsername === null || !(conquerLoginUsername instanceof HTMLInputElement)) { - Conquer.fail('Unable to find conquer login username field.') - } - this.conquerLoginUsername = conquerLoginUsername - const conquerLoginPassword = document.querySelector('.conquer-login-password') - if (conquerLoginPassword === null || !(conquerLoginPassword instanceof HTMLInputElement)) { - Conquer.fail('Unable to find conquer login password field.') - } - this.conquerLoginPassword = conquerLoginPassword - const conquerLoginSubmit = document.querySelector('.conquer-login-submit') - if (conquerLoginSubmit === null || !(conquerLoginSubmit instanceof HTMLButtonElement)) { - Conquer.fail('Unable to find the submit button for the login.') - } - this.conquerLoginSubmit = conquerLoginSubmit - this.conquerLoginSubmit.addEventListener('click', (event: Event) => { - event.preventDefault() - this.onLoginRequested() - }) - } - async onLoginRequested(): Promise { - const username = this.conquerLoginUsername.value - const password = this.conquerLoginPassword.value - const urlUser = new URL('/conquer/user/login', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) - let responseJson - let status - try { - const response = await fetch(urlUser, { - method: 'POST', - body: JSON.stringify({ - username: username, - password: password, - }) - }) - responseJson = await response.json() - status = response.status - } catch(e) { - console.error(e) - this.addNewLoginError('El servidor ha enviado datos inesperados.') - return - } - if (status !== 200) { - this.addNewLoginError(responseJson.error) - return - } - this.unsetLoginAndRegisterErrors() - const isLogged = await this.isLogged() - if (isLogged) { - this.onLoginSuccess() - } - } - async onLoginSuccess(): Promise { - await this.removeLoginRegisterCombo() - const currentPositionFeature = this.currentPositionFeature - if (currentPositionFeature === null) { - return - } - this.map.on('click', (event: MapEvent) => { - this.onClickMap(event) - }) - } async onClickMap(event: MapEvent): Promise { if (this.vectorLayer === null) { @@ -199,138 +101,22 @@ export default class Conquer { } } - async goToRegister(): Promise { - const isLogged = await this.isLogged() - await this.removeLoginRegisterCombo() - if (!isLogged) { - this.conquerRegister.classList.remove('conquer-display-none') + async onLoginSuccess(): Promise { + const currentPositionFeature = this.currentPositionFeature + if (currentPositionFeature === null) { + return } - } - async goToLogin(): Promise { - const isLogged = await this.isLogged() - await this.removeLoginRegisterCombo() - if (!isLogged) { - this.conquerLogin.classList.remove('conquer-display-none') - } - } - - async removeLoginRegisterCombo(): Promise { - this.conquerLogin.classList.add('conquer-display-none') - this.conquerRegister.classList.add('conquer-display-none') - } - - fillConquerRegister() { - const conquerRegister = document.querySelector('.conquer-register') - if (conquerRegister === null || !(conquerRegister instanceof HTMLDivElement)) { - Conquer.fail('conquerRegister is invalid') - } - this.conquerRegister = conquerRegister - const conquerRegisterGoToLogin = document.querySelector('.conquer-register-go-to-login') - if (conquerRegisterGoToLogin === null || !(conquerRegisterGoToLogin instanceof HTMLAnchorElement)) { - Conquer.fail('Link to go to login from register is invalid.') - } - this.conquerRegisterGoToLogin = conquerRegisterGoToLogin - this.conquerRegisterGoToLogin.addEventListener('click', () => { - this.goToLogin() + this.map.on('click', (event: MapEvent) => { + this.onClickMap(event) }) - const conquerRegisterUsername = document.querySelector('.conquer-register-username') - if (conquerRegisterUsername === null || !(conquerRegisterUsername instanceof HTMLInputElement)) { - Conquer.fail('No username field in conquer register.') - } - this.conquerRegisterUsername = conquerRegisterUsername - const conquerRegisterPassword = document.querySelector('.conquer-register-password') - if (conquerRegisterPassword === null || !(conquerRegisterPassword instanceof HTMLInputElement)) { - Conquer.fail('No password field in conquer register.') - } - this.conquerRegisterPassword = conquerRegisterPassword - const conquerRegisterRepeatPassword = document.querySelector('.conquer-register-repeat-password') - if (conquerRegisterRepeatPassword === null || !(conquerRegisterRepeatPassword instanceof HTMLInputElement)) { - Conquer.fail('No repeat password field in conquer register.') - } - this.conquerRegisterRepeatPassword = conquerRegisterRepeatPassword - const conquerRegisterSubmit = document.querySelector('.conquer-register-submit') - if (conquerRegisterSubmit === null || !(conquerRegisterSubmit instanceof HTMLButtonElement)) { - Conquer.fail('No register submit button found.') - } - this.conquerRegisterSubmit = conquerRegisterSubmit - this.conquerRegisterSubmit.addEventListener('click', (event: Event) => { - event.preventDefault() - this.onRegisterRequest() - }) - const conquerRegisterError = document.querySelector('.conquer-register-error') - if (conquerRegisterError === null || !(conquerRegisterError instanceof HTMLParagraphElement)) { - Conquer.fail('Unable to find the conquer error element.') - } - this.conquerRegisterError = conquerRegisterError - } - unsetLoginAndRegisterErrors() { - this.conquerRegisterError.classList.add('conquer-display-none') - this.conquerLoginError.classList.add('conquer-display-none') - } - - async onRegisterRequest(): Promise { - const username = this.conquerRegisterUsername.value - const password = this.conquerRegisterPassword.value - const repeatPassword = this.conquerRegisterRepeatPassword.value - const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) - let responseJson - let status - try { - const response = await fetch(urlUser, { - method: 'PUT', - body: JSON.stringify({ - username: username, - password: password, - repeat_password: repeatPassword - }) - }) - responseJson = await response.json() - status = response.status - } catch(e) { - console.error(e) - this.addNewRegisterError('El servidor ha enviado datos inesperados.') - return - } - if (status !== 200) { - this.addNewRegisterError(responseJson.error) - return - } - this.addNewLoginSuccessText(`Usuario registrado ${username}.`) - this.goToLogin() - } - addNewLoginSuccessText(message: string): void { - this.unsetLoginAndRegisterErrors() - this.conquerLoginSuccess.innerText = message - this.conquerLoginSuccess.classList.remove('conquer-display-none') - - } - addNewLoginError(error: string): void { - this.unsetLoginAndRegisterErrors() - this.conquerLoginSuccess.classList.add('conquer-display-none') - this.conquerLoginError.innerText = error - this.conquerLoginError.classList.remove('conquer-display-none') - } - addNewRegisterError(error: string): void { - this.unsetLoginAndRegisterErrors() - this.conquerLoginSuccess.classList.add('conquer-display-none') - this.conquerRegisterError.innerText = error - this.conquerRegisterError.classList.remove('conquer-display-none') - } - - async checkLogin(): Promise { - const isLogged = await this.isLogged() - if (!isLogged) { - this.conquerLogin.classList.remove('conquer-display-none') - return - } - this.onLoginSuccess() - } async run() { - this.fillConquerLogin() - this.fillConquerRegister() - this.checkLogin() + const conquerLogin = new ConquerLogin() + conquerLogin.on('login', () => { + this.onLoginSuccess() + }) + conquerLogin.enableLogIfNeeded() const conquerContainer = this.conquerContainer //layer.on('prerender', (evt) => { // // return @@ -498,21 +284,4 @@ export default class Conquer { constructor(conquerContainer: HTMLDivElement) { this.conquerContainer = conquerContainer } - private async addNewLoginRegisterError(message: string): Promise { - this.addNewRegisterError(message) - this.addNewLoginError(message) - } - private async isLogged(): Promise { - const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) - let responseJson - let status - try { - const response = await fetch(urlUser) - status = response.status - } catch { - this.addNewLoginRegisterError('Error del servidor') - return false - } - return status === 200 - } } diff --git a/js-src/conquer/login.ts b/js-src/conquer/login.ts new file mode 100644 index 0000000..6dbb65c --- /dev/null +++ b/js-src/conquer/login.ts @@ -0,0 +1,267 @@ +import Conquer from '@burguillosinfo/conquer' + +export type ConquerLoginEventCallback = () => void +export default class Login { + private conquerLogin: HTMLDivElement + private conquerLoginGoToRegister: HTMLAnchorElement + private conquerLoginError: HTMLParagraphElement + private conquerLoginSuccess: HTMLParagraphElement + private conquerLoginUsername: HTMLInputElement + private conquerLoginPassword: HTMLInputElement + private conquerLoginSubmit: HTMLButtonElement + private conquerRegisterGoToLogin: HTMLAnchorElement + private conquerRegister: HTMLDivElement + private conquerRegisterUsername: HTMLInputElement + private conquerRegisterPassword: HTMLInputElement + private conquerRegisterRepeatPassword: HTMLInputElement + private conquerRegisterSubmit: HTMLButtonElement + private conquerRegisterError: HTMLParagraphElement + + + public async enableLogIfNeeded() { + this.fillConquerLogin() + this.fillConquerRegister() + this.checkLogin() + } + + private async fillConquerLogin() { + const conquerLogin = document.querySelector('.conquer-login') + if (conquerLogin === null || !(conquerLogin instanceof HTMLDivElement)) { + Conquer.fail('conquerLogin is invalid') + } + this.conquerLogin = conquerLogin + const conquerLoginGoToRegister = document.querySelector('.conquer-login-go-to-register') + if (conquerLoginGoToRegister === null || !(conquerLoginGoToRegister instanceof HTMLAnchorElement)) { + Conquer.fail('Link to go to register from login is invalid.') + } + this.conquerLoginGoToRegister = conquerLoginGoToRegister + this.conquerLoginGoToRegister.addEventListener('click', () => { + this.goToRegister() + }) + const conquerLoginError = document.querySelector('.conquer-login-error') + if (conquerLoginError === null || !(conquerLoginError instanceof HTMLParagraphElement)) { + Conquer.fail('Unable to find conquer login error.') + } + this.conquerLoginError = conquerLoginError + const conquerLoginSuccess = document.querySelector('.conquer-login-success') + if (conquerLoginSuccess === null || !(conquerLoginSuccess instanceof HTMLParagraphElement)) { + Conquer.fail('Unable to find conquer login success.') + } + this.conquerLoginSuccess = conquerLoginSuccess + const conquerLoginUsername = document.querySelector('.conquer-login-username') + if (conquerLoginUsername === null || !(conquerLoginUsername instanceof HTMLInputElement)) { + Conquer.fail('Unable to find conquer login username field.') + } + this.conquerLoginUsername = conquerLoginUsername + const conquerLoginPassword = document.querySelector('.conquer-login-password') + if (conquerLoginPassword === null || !(conquerLoginPassword instanceof HTMLInputElement)) { + Conquer.fail('Unable to find conquer login password field.') + } + this.conquerLoginPassword = conquerLoginPassword + const conquerLoginSubmit = document.querySelector('.conquer-login-submit') + if (conquerLoginSubmit === null || !(conquerLoginSubmit instanceof HTMLButtonElement)) { + Conquer.fail('Unable to find the submit button for the login.') + } + this.conquerLoginSubmit = conquerLoginSubmit + this.conquerLoginSubmit.addEventListener('click', (event: Event) => { + event.preventDefault() + this.onLoginRequested() + }) + } + private async fillConquerRegister() { + const conquerRegister = document.querySelector('.conquer-register') + if (conquerRegister === null || !(conquerRegister instanceof HTMLDivElement)) { + Conquer.fail('conquerRegister is invalid') + } + this.conquerRegister = conquerRegister + const conquerRegisterGoToLogin = document.querySelector('.conquer-register-go-to-login') + if (conquerRegisterGoToLogin === null || !(conquerRegisterGoToLogin instanceof HTMLAnchorElement)) { + Conquer.fail('Link to go to login from register is invalid.') + } + this.conquerRegisterGoToLogin = conquerRegisterGoToLogin + this.conquerRegisterGoToLogin.addEventListener('click', () => { + this.goToLogin() + }) + const conquerRegisterUsername = document.querySelector('.conquer-register-username') + if (conquerRegisterUsername === null || !(conquerRegisterUsername instanceof HTMLInputElement)) { + Conquer.fail('No username field in conquer register.') + } + this.conquerRegisterUsername = conquerRegisterUsername + const conquerRegisterPassword = document.querySelector('.conquer-register-password') + if (conquerRegisterPassword === null || !(conquerRegisterPassword instanceof HTMLInputElement)) { + Conquer.fail('No password field in conquer register.') + } + this.conquerRegisterPassword = conquerRegisterPassword + const conquerRegisterRepeatPassword = document.querySelector('.conquer-register-repeat-password') + if (conquerRegisterRepeatPassword === null || !(conquerRegisterRepeatPassword instanceof HTMLInputElement)) { + Conquer.fail('No repeat password field in conquer register.') + } + this.conquerRegisterRepeatPassword = conquerRegisterRepeatPassword + const conquerRegisterSubmit = document.querySelector('.conquer-register-submit') + if (conquerRegisterSubmit === null || !(conquerRegisterSubmit instanceof HTMLButtonElement)) { + Conquer.fail('No register submit button found.') + } + this.conquerRegisterSubmit = conquerRegisterSubmit + this.conquerRegisterSubmit.addEventListener('click', (event: Event) => { + event.preventDefault() + this.onRegisterRequest() + }) + const conquerRegisterError = document.querySelector('.conquer-register-error') + if (conquerRegisterError === null || !(conquerRegisterError instanceof HTMLParagraphElement)) { + Conquer.fail('Unable to find the conquer error element.') + } + this.conquerRegisterError = conquerRegisterError + + } + + private async unsetLoginAndRegisterErrors() { + this.conquerRegisterError.classList.add('conquer-display-none') + this.conquerLoginError.classList.add('conquer-display-none') + } + + private async onRegisterRequest(): Promise { + const username = this.conquerRegisterUsername.value + const password = this.conquerRegisterPassword.value + const repeatPassword = this.conquerRegisterRepeatPassword.value + const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) + let responseJson + let status + try { + const response = await fetch(urlUser, { + method: 'PUT', + body: JSON.stringify({ + username: username, + password: password, + repeat_password: repeatPassword + }) + }) + responseJson = await response.json() + status = response.status + } catch(e) { + console.error(e) + this.addNewRegisterError('El servidor ha enviado datos inesperados.') + return + } + if (status !== 200) { + this.addNewRegisterError(responseJson.error) + return + } + this.addNewLoginSuccessText(`Usuario registrado ${username}.`) + this.goToLogin() + } + private async addNewLoginSuccessText(message: string): Promise { + this.unsetLoginAndRegisterErrors() + this.conquerLoginSuccess.innerText = message + this.conquerLoginSuccess.classList.remove('conquer-display-none') + + } + private async addNewLoginError(error: string): Promise { + this.unsetLoginAndRegisterErrors() + this.conquerLoginSuccess.classList.add('conquer-display-none') + this.conquerLoginError.innerText = error + this.conquerLoginError.classList.remove('conquer-display-none') + } + private async addNewRegisterError(error: string): Promise { + this.unsetLoginAndRegisterErrors() + this.conquerLoginSuccess.classList.add('conquer-display-none') + this.conquerRegisterError.innerText = error + this.conquerRegisterError.classList.remove('conquer-display-none') + } + private async removeLoginRegisterCombo(): Promise { + this.conquerLogin.classList.add('conquer-display-none') + this.conquerRegister.classList.add('conquer-display-none') + } + + private async checkLogin(): Promise { + const isLogged = await this.isLogged() + if (!isLogged) { + this.conquerLogin.classList.remove('conquer-display-none') + return + } + this.onLoginSuccess() + } + + private callbacks: Record> = {} + public async on(name: string, callback: ConquerLoginEventCallback) { + if (this.callbacks[name] === undefined) { + this.callbacks[name] = [] + this.callbacks[name].push(callback) + } + } + + private async onLoginSuccess(): Promise { + await this.removeLoginRegisterCombo() + for (const callback of this.callbacks.login) { + callback() + } + } + + private async goToRegister(): Promise { + const isLogged = await this.isLogged() + await this.removeLoginRegisterCombo() + if (!isLogged) { + this.conquerRegister.classList.remove('conquer-display-none') + } else { + this.onLoginSuccess() + } + } + private async goToLogin(): Promise { + const isLogged = await this.isLogged() + await this.removeLoginRegisterCombo() + if (!isLogged) { + this.conquerLogin.classList.remove('conquer-display-none') + } else { + this.onLoginSuccess() + } + } + private async onLoginRequested(): Promise { + const username = this.conquerLoginUsername.value + const password = this.conquerLoginPassword.value + const urlUser = new URL('/conquer/user/login', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) + let responseJson + let status + try { + const response = await fetch(urlUser, { + method: 'POST', + body: JSON.stringify({ + username: username, + password: password, + }) + }) + responseJson = await response.json() + status = response.status + } catch(e) { + console.error(e) + this.addNewLoginError('El servidor ha enviado datos inesperados.') + return + } + if (status !== 200) { + this.addNewLoginError(responseJson.error) + return + } + this.unsetLoginAndRegisterErrors() + const isLogged = await this.isLogged() + if (isLogged) { + this.onLoginSuccess() + } + } + + private async addNewLoginRegisterError(message: string): Promise { + this.addNewRegisterError(message) + this.addNewLoginError(message) + } + + private async isLogged(): Promise { + const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) + let status + try { + const response = await fetch(urlUser) + status = response.status + } catch { + this.addNewLoginRegisterError('Error del servidor') + return false + } + return status === 200 + } + +} diff --git a/public/css/styles.scss b/public/css/styles.scss index 8a9c768..cb67827 100644 --- a/public/css/styles.scss +++ b/public/css/styles.scss @@ -28,6 +28,13 @@ body { p.conquer-login-success { color: green; } + div.conquer-overlay-transparent { + width: 100%; + height: 100%; + position: fixed; + top: 0; + left: 0; + } div.conquer-login,div.conquer-register { form { width: 100%; diff --git a/public/js/bundle.js b/public/js/bundle.js index 4279529..c551269 100644 --- a/public/js/bundle.js +++ b/public/js/bundle.js @@ -57,7 +57,18 @@ eval(";(function() {\n function Tablesort(el, options) {\n if (!(this instan /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ Conquer)\n/* harmony export */ });\n/* harmony import */ var ol_Map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ol/Map */ \"./node_modules/ol/Map.js\");\n/* harmony import */ var ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ol/MapBrowserEvent */ \"./node_modules/ol/MapBrowserEvent.js\");\n/* harmony import */ var ol_View__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ol/View */ \"./node_modules/ol/View.js\");\n/* harmony import */ var ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ol/proj/Projection.js */ \"./node_modules/ol/proj/Projection.js\");\n/* harmony import */ var ol_layer_Tile__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ol/layer/Tile */ \"./node_modules/ol/layer/Tile.js\");\n/* harmony import */ var ol_source_OSM__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ol/source/OSM */ \"./node_modules/ol/source/OSM.js\");\n/* harmony import */ var ol_proj__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ol/proj */ \"./node_modules/ol/proj.js\");\n/* harmony import */ var ol_Feature__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ol/Feature */ \"./node_modules/ol/Feature.js\");\n/* harmony import */ var ol_geom_Point__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ol/geom/Point */ \"./node_modules/ol/geom/Point.js\");\n/* harmony import */ var ol_layer_Vector__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ol/layer/Vector */ \"./node_modules/ol/layer/Vector.js\");\n/* harmony import */ var ol_source_Vector__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ol/source/Vector */ \"./node_modules/ol/source/Vector.js\");\n/* harmony import */ var ol_style_Stroke__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ol/style/Stroke */ \"./node_modules/ol/style/Stroke.js\");\n/* harmony import */ var ol_style_Fill__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ol/style/Fill */ \"./node_modules/ol/style/Fill.js\");\n/* harmony import */ var ol_style_Circle__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ol/style/Circle */ \"./node_modules/ol/style/Circle.js\");\n/* harmony import */ var ol_style_Style__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ol/style/Style */ \"./node_modules/ol/style/Style.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass Conquer {\n static start() {\n const conquerContainer = document.querySelector(\".conquer-container\");\n if (conquerContainer !== null) {\n if (!(conquerContainer instanceof HTMLDivElement)) {\n console.error(\".conquer-container is not a div.\");\n return;\n }\n const conquer = new Conquer(conquerContainer);\n conquer.run();\n }\n }\n setCenterDisplaced(lat, lon) {\n const olCoordinates = this.realCoordinatesToOl(lat, lon);\n const size = this.map.getSize();\n if (size === undefined) {\n return;\n }\n this.map.getView().centerOn(olCoordinates, size, [size[0] / 2, size[1] - 60]);\n }\n static fail(error) {\n alert('Error de interfaz');\n throw new Error(error);\n }\n fillConquerLogin() {\n const conquerLogin = document.querySelector('.conquer-login');\n if (conquerLogin === null || !(conquerLogin instanceof HTMLDivElement)) {\n Conquer.fail('conquerLogin is invalid');\n }\n this.conquerLogin = conquerLogin;\n const conquerLoginGoToRegister = document.querySelector('.conquer-login-go-to-register');\n if (conquerLoginGoToRegister === null || !(conquerLoginGoToRegister instanceof HTMLAnchorElement)) {\n Conquer.fail('Link to go to register from login is invalid.');\n }\n this.conquerLoginGoToRegister = conquerLoginGoToRegister;\n this.conquerLoginGoToRegister.addEventListener('click', () => {\n this.goToRegister();\n });\n const conquerLoginError = document.querySelector('.conquer-login-error');\n if (conquerLoginError === null || !(conquerLoginError instanceof HTMLParagraphElement)) {\n Conquer.fail('Unable to find conquer login error.');\n }\n this.conquerLoginError = conquerLoginError;\n const conquerLoginSuccess = document.querySelector('.conquer-login-success');\n if (conquerLoginSuccess === null || !(conquerLoginSuccess instanceof HTMLParagraphElement)) {\n Conquer.fail('Unable to find conquer login success.');\n }\n this.conquerLoginSuccess = conquerLoginSuccess;\n const conquerLoginUsername = document.querySelector('.conquer-login-username');\n if (conquerLoginUsername === null || !(conquerLoginUsername instanceof HTMLInputElement)) {\n Conquer.fail('Unable to find conquer login username field.');\n }\n this.conquerLoginUsername = conquerLoginUsername;\n const conquerLoginPassword = document.querySelector('.conquer-login-password');\n if (conquerLoginPassword === null || !(conquerLoginPassword instanceof HTMLInputElement)) {\n Conquer.fail('Unable to find conquer login password field.');\n }\n this.conquerLoginPassword = conquerLoginPassword;\n const conquerLoginSubmit = document.querySelector('.conquer-login-submit');\n if (conquerLoginSubmit === null || !(conquerLoginSubmit instanceof HTMLButtonElement)) {\n Conquer.fail('Unable to find the submit button for the login.');\n }\n this.conquerLoginSubmit = conquerLoginSubmit;\n this.conquerLoginSubmit.addEventListener('click', (event) => {\n event.preventDefault();\n this.onLoginRequested();\n });\n }\n async onLoginRequested() {\n const username = this.conquerLoginUsername.value;\n const password = this.conquerLoginPassword.value;\n const urlUser = new URL('/conquer/user/login', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n let responseJson;\n let status;\n try {\n const response = await fetch(urlUser, {\n method: 'POST',\n body: JSON.stringify({\n username: username,\n password: password,\n })\n });\n responseJson = await response.json();\n status = response.status;\n }\n catch (e) {\n console.error(e);\n this.addNewLoginError('El servidor ha enviado datos inesperados.');\n return;\n }\n if (status !== 200) {\n this.addNewLoginError(responseJson.error);\n return;\n }\n this.unsetLoginAndRegisterErrors();\n const isLogged = await this.isLogged();\n if (isLogged) {\n this.onLoginSuccess();\n }\n }\n async onLoginSuccess() {\n await this.removeLoginRegisterCombo();\n const currentPositionFeature = this.currentPositionFeature;\n if (currentPositionFeature === null) {\n return;\n }\n this.map.on('click', (event) => {\n this.onClickMap(event);\n });\n }\n async onClickMap(event) {\n if (this.vectorLayer === null) {\n return;\n }\n if (!(event instanceof ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_1__[\"default\"])) {\n return;\n }\n if (event.dragging) {\n return;\n }\n const pixel = event.pixel;\n const features = this.map.getFeaturesAtPixel(pixel);\n const feature = features.length ? features[0] : undefined;\n if (feature === undefined) {\n return;\n }\n if (!(feature instanceof ol_Feature__WEBPACK_IMPORTED_MODULE_2__[\"default\"])) {\n return;\n }\n this.onClickFeature(feature);\n }\n async onClickSelf() {\n alert('Pulsaste en ti mismo');\n }\n async onClickFeature(feature) {\n if (this.isFeatureEnabledMap[feature.getProperties().type] === undefined) {\n this.isFeatureEnabledMap[feature.getProperties().type] = true;\n }\n if (!this.isFeatureEnabledMap[feature.getProperties().type]) {\n return;\n }\n this.isFeatureEnabledMap[feature.getProperties().type] = false;\n window.setTimeout(() => {\n this.isFeatureEnabledMap[feature.getProperties().type] = true;\n }, 100);\n if (feature === this.currentPositionFeature) {\n this.onClickSelf();\n return;\n }\n }\n async goToRegister() {\n const isLogged = await this.isLogged();\n await this.removeLoginRegisterCombo();\n if (!isLogged) {\n this.conquerRegister.classList.remove('conquer-display-none');\n }\n }\n async goToLogin() {\n const isLogged = await this.isLogged();\n await this.removeLoginRegisterCombo();\n if (!isLogged) {\n this.conquerLogin.classList.remove('conquer-display-none');\n }\n }\n async removeLoginRegisterCombo() {\n this.conquerLogin.classList.add('conquer-display-none');\n this.conquerRegister.classList.add('conquer-display-none');\n }\n fillConquerRegister() {\n const conquerRegister = document.querySelector('.conquer-register');\n if (conquerRegister === null || !(conquerRegister instanceof HTMLDivElement)) {\n Conquer.fail('conquerRegister is invalid');\n }\n this.conquerRegister = conquerRegister;\n const conquerRegisterGoToLogin = document.querySelector('.conquer-register-go-to-login');\n if (conquerRegisterGoToLogin === null || !(conquerRegisterGoToLogin instanceof HTMLAnchorElement)) {\n Conquer.fail('Link to go to login from register is invalid.');\n }\n this.conquerRegisterGoToLogin = conquerRegisterGoToLogin;\n this.conquerRegisterGoToLogin.addEventListener('click', () => {\n this.goToLogin();\n });\n const conquerRegisterUsername = document.querySelector('.conquer-register-username');\n if (conquerRegisterUsername === null || !(conquerRegisterUsername instanceof HTMLInputElement)) {\n Conquer.fail('No username field in conquer register.');\n }\n this.conquerRegisterUsername = conquerRegisterUsername;\n const conquerRegisterPassword = document.querySelector('.conquer-register-password');\n if (conquerRegisterPassword === null || !(conquerRegisterPassword instanceof HTMLInputElement)) {\n Conquer.fail('No password field in conquer register.');\n }\n this.conquerRegisterPassword = conquerRegisterPassword;\n const conquerRegisterRepeatPassword = document.querySelector('.conquer-register-repeat-password');\n if (conquerRegisterRepeatPassword === null || !(conquerRegisterRepeatPassword instanceof HTMLInputElement)) {\n Conquer.fail('No repeat password field in conquer register.');\n }\n this.conquerRegisterRepeatPassword = conquerRegisterRepeatPassword;\n const conquerRegisterSubmit = document.querySelector('.conquer-register-submit');\n if (conquerRegisterSubmit === null || !(conquerRegisterSubmit instanceof HTMLButtonElement)) {\n Conquer.fail('No register submit button found.');\n }\n this.conquerRegisterSubmit = conquerRegisterSubmit;\n this.conquerRegisterSubmit.addEventListener('click', (event) => {\n event.preventDefault();\n this.onRegisterRequest();\n });\n const conquerRegisterError = document.querySelector('.conquer-register-error');\n if (conquerRegisterError === null || !(conquerRegisterError instanceof HTMLParagraphElement)) {\n Conquer.fail('Unable to find the conquer error element.');\n }\n this.conquerRegisterError = conquerRegisterError;\n }\n unsetLoginAndRegisterErrors() {\n this.conquerRegisterError.classList.add('conquer-display-none');\n this.conquerLoginError.classList.add('conquer-display-none');\n }\n async onRegisterRequest() {\n const username = this.conquerRegisterUsername.value;\n const password = this.conquerRegisterPassword.value;\n const repeatPassword = this.conquerRegisterRepeatPassword.value;\n const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n let responseJson;\n let status;\n try {\n const response = await fetch(urlUser, {\n method: 'PUT',\n body: JSON.stringify({\n username: username,\n password: password,\n repeat_password: repeatPassword\n })\n });\n responseJson = await response.json();\n status = response.status;\n }\n catch (e) {\n console.error(e);\n this.addNewRegisterError('El servidor ha enviado datos inesperados.');\n return;\n }\n if (status !== 200) {\n this.addNewRegisterError(responseJson.error);\n return;\n }\n this.addNewLoginSuccessText(`Usuario registrado ${username}.`);\n this.goToLogin();\n }\n addNewLoginSuccessText(message) {\n this.unsetLoginAndRegisterErrors();\n this.conquerLoginSuccess.innerText = message;\n this.conquerLoginSuccess.classList.remove('conquer-display-none');\n }\n addNewLoginError(error) {\n this.unsetLoginAndRegisterErrors();\n this.conquerLoginSuccess.classList.add('conquer-display-none');\n this.conquerLoginError.innerText = error;\n this.conquerLoginError.classList.remove('conquer-display-none');\n }\n addNewRegisterError(error) {\n this.unsetLoginAndRegisterErrors();\n this.conquerLoginSuccess.classList.add('conquer-display-none');\n this.conquerRegisterError.innerText = error;\n this.conquerRegisterError.classList.remove('conquer-display-none');\n }\n async checkLogin() {\n const isLogged = await this.isLogged();\n if (!isLogged) {\n this.conquerLogin.classList.remove('conquer-display-none');\n return;\n }\n this.onLoginSuccess();\n }\n async run() {\n this.fillConquerLogin();\n this.fillConquerRegister();\n this.checkLogin();\n const conquerContainer = this.conquerContainer;\n //layer.on('prerender', (evt) => {\n // // return\n // if (evt.context) {\n // const context = evt.context as CanvasRenderingContext2D\n // context.filter = 'grayscale(80%) invert(100%) '\n // context.globalCompositeOperation = 'source-over'\n // }\n //})\n //layer.on('postrender', (evt) => {\n // if (evt.context) {\n // const context = evt.context as CanvasRenderingContext2D\n // context.filter = 'none'\n // }\n //})\n ol_proj__WEBPACK_IMPORTED_MODULE_0__.useGeographic();\n this.map = new ol_Map__WEBPACK_IMPORTED_MODULE_3__[\"default\"]({\n target: conquerContainer,\n layers: [\n new ol_layer_Tile__WEBPACK_IMPORTED_MODULE_4__[\"default\"]({\n source: new ol_source_OSM__WEBPACK_IMPORTED_MODULE_5__[\"default\"]()\n })\n ],\n view: new ol_View__WEBPACK_IMPORTED_MODULE_6__[\"default\"]({\n zoom: 21,\n maxZoom: 22,\n }),\n });\n this.setLocationChangeTriggers();\n this.setRotationChangeTriggers();\n }\n setRotationChangeTriggers() {\n if (window.DeviceOrientationEvent) {\n window.addEventListener(\"deviceorientation\", (event) => {\n if (event.alpha !== null && event.beta !== null && event.gamma !== null) {\n this.onRotate(event.alpha, event.beta, event.gamma);\n }\n }, true);\n }\n }\n addCurrentLocationMarkerToMap(currentLatitude, currentLongitude) {\n const currentPositionFeature = new ol_Feature__WEBPACK_IMPORTED_MODULE_2__[\"default\"]({\n type: 'currentPositionFeature',\n geometry: new ol_geom_Point__WEBPACK_IMPORTED_MODULE_7__[\"default\"](this.realCoordinatesToOl(currentLatitude, currentLongitude))\n });\n this.currentPositionFeature = currentPositionFeature;\n }\n processLocation(location) {\n this.currentLatitude = location.coords.latitude;\n this.currentLongitude = location.coords.longitude;\n if (location.coords.heading !== null && (this.alpha != 0 || this.beta != 0 || this.gamma != 0) && !this.disableSetRotationOffset) {\n this.disableSetRotationOffset = true;\n this.heading = location.coords.heading;\n this.rotationOffset = this.compassHeading(this.alpha, this.beta, this.gamma) + (location.coords.heading * Math.PI * 2) / 360;\n }\n this.setCenterDisplaced(this.currentLatitude, this.currentLongitude);\n this.addCurrentLocationMarkerToMap(this.currentLatitude, this.currentLongitude);\n this.refreshLayers();\n }\n refreshLayers() {\n if (this.currentPositionFeature === null) {\n return;\n }\n const styles = {\n currentPositionFeature: new ol_style_Style__WEBPACK_IMPORTED_MODULE_8__[\"default\"]({\n image: new ol_style_Circle__WEBPACK_IMPORTED_MODULE_9__[\"default\"]({\n radius: 14,\n fill: new ol_style_Fill__WEBPACK_IMPORTED_MODULE_10__[\"default\"]({ color: 'white' }),\n stroke: new ol_style_Stroke__WEBPACK_IMPORTED_MODULE_11__[\"default\"]({\n color: 'blue',\n width: 2,\n })\n })\n })\n };\n const vectorLayer = new ol_layer_Vector__WEBPACK_IMPORTED_MODULE_12__[\"default\"]({\n source: new ol_source_Vector__WEBPACK_IMPORTED_MODULE_13__[\"default\"]({\n features: [this.currentPositionFeature]\n }),\n });\n if (this.vectorLayer !== null) {\n this.map.removeLayer(this.vectorLayer);\n }\n vectorLayer.setStyle((feature) => {\n return styles[feature.getProperties().type];\n });\n this.map.addLayer(vectorLayer);\n this.vectorLayer = vectorLayer;\n this.map.on('click', (event) => {\n this.onClickMap(event);\n });\n }\n setLocationChangeTriggers() {\n window.setInterval(() => {\n this.disableSetRotationOffset = false;\n }, 10000);\n this.currentPositionFeature = null;\n window.setTimeout(() => {\n window.setInterval(() => {\n navigator.geolocation.getCurrentPosition((location) => {\n this.processLocation(location);\n }, () => {\n return;\n }, {\n enableHighAccuracy: true,\n });\n }, 3000);\n }, 1000);\n const initialLatitude = 37.58237;\n const initialLongitude = -5.96766;\n this.setCenterDisplaced(initialLatitude, initialLongitude);\n this.addCurrentLocationMarkerToMap(initialLatitude, initialLongitude);\n this.refreshLayers();\n navigator.geolocation.watchPosition((location) => {\n this.processLocation(location);\n }, (err) => {\n return;\n }, {\n enableHighAccuracy: true,\n });\n }\n realCoordinatesToOl(lat, lon) {\n return ol_proj__WEBPACK_IMPORTED_MODULE_0__.transform([lon, lat], new ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_14__[\"default\"]({ code: \"WGS84\" }), new ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_14__[\"default\"]({ code: \"EPSG:900913\" }));\n }\n compassHeading(alpha, beta, gamma) {\n const alphaRad = alpha * (Math.PI / 180);\n return alphaRad;\n }\n logToServer(logValue) {\n const urlLog = new URL('/conquer/log', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n urlLog.searchParams.append('log', logValue);\n fetch(urlLog).then(() => {\n return;\n }).catch((error) => {\n console.error(error);\n });\n }\n onRotate(alpha, beta, gamma) {\n if (this.enabledOnRotate) {\n this.alpha = alpha;\n this.beta = beta;\n this.gamma = gamma;\n this.enabledOnRotate = false;\n this.map.getView().setRotation((this.compassHeading(alpha, beta, gamma) - this.rotationOffset));\n window.setTimeout(() => {\n this.enabledOnRotate = true;\n }, 10);\n }\n this.setCenterDisplaced(this.currentLatitude, this.currentLongitude);\n }\n constructor(conquerContainer) {\n this.rotationOffset = 0;\n this.heading = 0;\n this.disableSetRotationOffset = false;\n this.vectorLayer = null;\n this.alpha = 0;\n this.beta = 0;\n this.gamma = 0;\n this.isFeatureEnabledMap = {};\n this.enabledOnRotate = true;\n this.conquerContainer = conquerContainer;\n }\n async addNewLoginRegisterError(message) {\n this.addNewRegisterError(message);\n this.addNewLoginError(message);\n }\n async isLogged() {\n const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n let responseJson;\n let status;\n try {\n const response = await fetch(urlUser);\n status = response.status;\n }\n catch {\n this.addNewLoginRegisterError('Error del servidor');\n return false;\n }\n return status === 200;\n }\n}\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/index.ts?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ Conquer)\n/* harmony export */ });\n/* harmony import */ var ol_Map__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ol/Map */ \"./node_modules/ol/Map.js\");\n/* harmony import */ var ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ol/MapBrowserEvent */ \"./node_modules/ol/MapBrowserEvent.js\");\n/* harmony import */ var ol_View__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ol/View */ \"./node_modules/ol/View.js\");\n/* harmony import */ var ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ol/proj/Projection.js */ \"./node_modules/ol/proj/Projection.js\");\n/* harmony import */ var ol_layer_Tile__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ol/layer/Tile */ \"./node_modules/ol/layer/Tile.js\");\n/* harmony import */ var ol_source_OSM__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ol/source/OSM */ \"./node_modules/ol/source/OSM.js\");\n/* harmony import */ var ol_proj__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ol/proj */ \"./node_modules/ol/proj.js\");\n/* harmony import */ var ol_Feature__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ol/Feature */ \"./node_modules/ol/Feature.js\");\n/* harmony import */ var ol_geom_Point__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ol/geom/Point */ \"./node_modules/ol/geom/Point.js\");\n/* harmony import */ var ol_layer_Vector__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ol/layer/Vector */ \"./node_modules/ol/layer/Vector.js\");\n/* harmony import */ var ol_source_Vector__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ol/source/Vector */ \"./node_modules/ol/source/Vector.js\");\n/* harmony import */ var ol_style_Stroke__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ol/style/Stroke */ \"./node_modules/ol/style/Stroke.js\");\n/* harmony import */ var ol_style_Fill__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ol/style/Fill */ \"./node_modules/ol/style/Fill.js\");\n/* harmony import */ var ol_style_Circle__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ol/style/Circle */ \"./node_modules/ol/style/Circle.js\");\n/* harmony import */ var ol_style_Style__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ol/style/Style */ \"./node_modules/ol/style/Style.js\");\n/* harmony import */ var _burguillosinfo_conquer_login__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @burguillosinfo/conquer/login */ \"./js-src/conquer/login.ts\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass Conquer {\n static start() {\n const conquerContainer = document.querySelector(\".conquer-container\");\n if (conquerContainer !== null) {\n if (!(conquerContainer instanceof HTMLDivElement)) {\n console.error(\".conquer-container is not a div.\");\n return;\n }\n const conquer = new Conquer(conquerContainer);\n conquer.run();\n }\n }\n setCenterDisplaced(lat, lon) {\n const olCoordinates = this.realCoordinatesToOl(lat, lon);\n const size = this.map.getSize();\n if (size === undefined) {\n return;\n }\n this.map.getView().centerOn(olCoordinates, size, [size[0] / 2, size[1] - 60]);\n }\n static fail(error) {\n alert('Error de interfaz');\n throw new Error(error);\n }\n async onClickMap(event) {\n if (this.vectorLayer === null) {\n return;\n }\n if (!(event instanceof ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_2__[\"default\"])) {\n return;\n }\n if (event.dragging) {\n return;\n }\n const pixel = event.pixel;\n const features = this.map.getFeaturesAtPixel(pixel);\n const feature = features.length ? features[0] : undefined;\n if (feature === undefined) {\n return;\n }\n if (!(feature instanceof ol_Feature__WEBPACK_IMPORTED_MODULE_3__[\"default\"])) {\n return;\n }\n this.onClickFeature(feature);\n }\n async onClickSelf() {\n alert('Pulsaste en ti mismo');\n }\n async onClickFeature(feature) {\n if (this.isFeatureEnabledMap[feature.getProperties().type] === undefined) {\n this.isFeatureEnabledMap[feature.getProperties().type] = true;\n }\n if (!this.isFeatureEnabledMap[feature.getProperties().type]) {\n return;\n }\n this.isFeatureEnabledMap[feature.getProperties().type] = false;\n window.setTimeout(() => {\n this.isFeatureEnabledMap[feature.getProperties().type] = true;\n }, 100);\n if (feature === this.currentPositionFeature) {\n this.onClickSelf();\n return;\n }\n }\n async onLoginSuccess() {\n const currentPositionFeature = this.currentPositionFeature;\n if (currentPositionFeature === null) {\n return;\n }\n this.map.on('click', (event) => {\n this.onClickMap(event);\n });\n }\n async run() {\n const conquerLogin = new _burguillosinfo_conquer_login__WEBPACK_IMPORTED_MODULE_1__[\"default\"]();\n conquerLogin.on('login', () => {\n this.onLoginSuccess();\n });\n conquerLogin.enableLogIfNeeded();\n const conquerContainer = this.conquerContainer;\n //layer.on('prerender', (evt) => {\n // // return\n // if (evt.context) {\n // const context = evt.context as CanvasRenderingContext2D\n // context.filter = 'grayscale(80%) invert(100%) '\n // context.globalCompositeOperation = 'source-over'\n // }\n //})\n //layer.on('postrender', (evt) => {\n // if (evt.context) {\n // const context = evt.context as CanvasRenderingContext2D\n // context.filter = 'none'\n // }\n //})\n ol_proj__WEBPACK_IMPORTED_MODULE_0__.useGeographic();\n this.map = new ol_Map__WEBPACK_IMPORTED_MODULE_4__[\"default\"]({\n target: conquerContainer,\n layers: [\n new ol_layer_Tile__WEBPACK_IMPORTED_MODULE_5__[\"default\"]({\n source: new ol_source_OSM__WEBPACK_IMPORTED_MODULE_6__[\"default\"]()\n })\n ],\n view: new ol_View__WEBPACK_IMPORTED_MODULE_7__[\"default\"]({\n zoom: 21,\n maxZoom: 22,\n }),\n });\n this.setLocationChangeTriggers();\n this.setRotationChangeTriggers();\n }\n setRotationChangeTriggers() {\n if (window.DeviceOrientationEvent) {\n window.addEventListener(\"deviceorientation\", (event) => {\n if (event.alpha !== null && event.beta !== null && event.gamma !== null) {\n this.onRotate(event.alpha, event.beta, event.gamma);\n }\n }, true);\n }\n }\n addCurrentLocationMarkerToMap(currentLatitude, currentLongitude) {\n const currentPositionFeature = new ol_Feature__WEBPACK_IMPORTED_MODULE_3__[\"default\"]({\n type: 'currentPositionFeature',\n geometry: new ol_geom_Point__WEBPACK_IMPORTED_MODULE_8__[\"default\"](this.realCoordinatesToOl(currentLatitude, currentLongitude))\n });\n this.currentPositionFeature = currentPositionFeature;\n }\n processLocation(location) {\n this.currentLatitude = location.coords.latitude;\n this.currentLongitude = location.coords.longitude;\n if (location.coords.heading !== null && (this.alpha != 0 || this.beta != 0 || this.gamma != 0) && !this.disableSetRotationOffset) {\n this.disableSetRotationOffset = true;\n this.heading = location.coords.heading;\n this.rotationOffset = this.compassHeading(this.alpha, this.beta, this.gamma) + (location.coords.heading * Math.PI * 2) / 360;\n }\n this.setCenterDisplaced(this.currentLatitude, this.currentLongitude);\n this.addCurrentLocationMarkerToMap(this.currentLatitude, this.currentLongitude);\n this.refreshLayers();\n }\n refreshLayers() {\n if (this.currentPositionFeature === null) {\n return;\n }\n const styles = {\n currentPositionFeature: new ol_style_Style__WEBPACK_IMPORTED_MODULE_9__[\"default\"]({\n image: new ol_style_Circle__WEBPACK_IMPORTED_MODULE_10__[\"default\"]({\n radius: 14,\n fill: new ol_style_Fill__WEBPACK_IMPORTED_MODULE_11__[\"default\"]({ color: 'white' }),\n stroke: new ol_style_Stroke__WEBPACK_IMPORTED_MODULE_12__[\"default\"]({\n color: 'blue',\n width: 2,\n })\n })\n })\n };\n const vectorLayer = new ol_layer_Vector__WEBPACK_IMPORTED_MODULE_13__[\"default\"]({\n source: new ol_source_Vector__WEBPACK_IMPORTED_MODULE_14__[\"default\"]({\n features: [this.currentPositionFeature]\n }),\n });\n if (this.vectorLayer !== null) {\n this.map.removeLayer(this.vectorLayer);\n }\n vectorLayer.setStyle((feature) => {\n return styles[feature.getProperties().type];\n });\n this.map.addLayer(vectorLayer);\n this.vectorLayer = vectorLayer;\n this.map.on('click', (event) => {\n this.onClickMap(event);\n });\n }\n setLocationChangeTriggers() {\n window.setInterval(() => {\n this.disableSetRotationOffset = false;\n }, 10000);\n this.currentPositionFeature = null;\n window.setTimeout(() => {\n window.setInterval(() => {\n navigator.geolocation.getCurrentPosition((location) => {\n this.processLocation(location);\n }, () => {\n return;\n }, {\n enableHighAccuracy: true,\n });\n }, 3000);\n }, 1000);\n const initialLatitude = 37.58237;\n const initialLongitude = -5.96766;\n this.setCenterDisplaced(initialLatitude, initialLongitude);\n this.addCurrentLocationMarkerToMap(initialLatitude, initialLongitude);\n this.refreshLayers();\n navigator.geolocation.watchPosition((location) => {\n this.processLocation(location);\n }, (err) => {\n return;\n }, {\n enableHighAccuracy: true,\n });\n }\n realCoordinatesToOl(lat, lon) {\n return ol_proj__WEBPACK_IMPORTED_MODULE_0__.transform([lon, lat], new ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_15__[\"default\"]({ code: \"WGS84\" }), new ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_15__[\"default\"]({ code: \"EPSG:900913\" }));\n }\n compassHeading(alpha, beta, gamma) {\n const alphaRad = alpha * (Math.PI / 180);\n return alphaRad;\n }\n logToServer(logValue) {\n const urlLog = new URL('/conquer/log', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n urlLog.searchParams.append('log', logValue);\n fetch(urlLog).then(() => {\n return;\n }).catch((error) => {\n console.error(error);\n });\n }\n onRotate(alpha, beta, gamma) {\n if (this.enabledOnRotate) {\n this.alpha = alpha;\n this.beta = beta;\n this.gamma = gamma;\n this.enabledOnRotate = false;\n this.map.getView().setRotation((this.compassHeading(alpha, beta, gamma) - this.rotationOffset));\n window.setTimeout(() => {\n this.enabledOnRotate = true;\n }, 10);\n }\n this.setCenterDisplaced(this.currentLatitude, this.currentLongitude);\n }\n constructor(conquerContainer) {\n this.rotationOffset = 0;\n this.heading = 0;\n this.disableSetRotationOffset = false;\n this.vectorLayer = null;\n this.alpha = 0;\n this.beta = 0;\n this.gamma = 0;\n this.isFeatureEnabledMap = {};\n this.enabledOnRotate = true;\n this.conquerContainer = conquerContainer;\n }\n}\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/index.ts?"); + +/***/ }), + +/***/ "./js-src/conquer/login.ts": +/*!*********************************!*\ + !*** ./js-src/conquer/login.ts ***! + \*********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ Login)\n/* harmony export */ });\n/* harmony import */ var _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @burguillosinfo/conquer */ \"./js-src/conquer/index.ts\");\n\nclass Login {\n constructor() {\n this.callbacks = {};\n }\n async enableLogIfNeeded() {\n this.fillConquerLogin();\n this.fillConquerRegister();\n this.checkLogin();\n }\n async fillConquerLogin() {\n const conquerLogin = document.querySelector('.conquer-login');\n if (conquerLogin === null || !(conquerLogin instanceof HTMLDivElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('conquerLogin is invalid');\n }\n this.conquerLogin = conquerLogin;\n const conquerLoginGoToRegister = document.querySelector('.conquer-login-go-to-register');\n if (conquerLoginGoToRegister === null || !(conquerLoginGoToRegister instanceof HTMLAnchorElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('Link to go to register from login is invalid.');\n }\n this.conquerLoginGoToRegister = conquerLoginGoToRegister;\n this.conquerLoginGoToRegister.addEventListener('click', () => {\n this.goToRegister();\n });\n const conquerLoginError = document.querySelector('.conquer-login-error');\n if (conquerLoginError === null || !(conquerLoginError instanceof HTMLParagraphElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('Unable to find conquer login error.');\n }\n this.conquerLoginError = conquerLoginError;\n const conquerLoginSuccess = document.querySelector('.conquer-login-success');\n if (conquerLoginSuccess === null || !(conquerLoginSuccess instanceof HTMLParagraphElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('Unable to find conquer login success.');\n }\n this.conquerLoginSuccess = conquerLoginSuccess;\n const conquerLoginUsername = document.querySelector('.conquer-login-username');\n if (conquerLoginUsername === null || !(conquerLoginUsername instanceof HTMLInputElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('Unable to find conquer login username field.');\n }\n this.conquerLoginUsername = conquerLoginUsername;\n const conquerLoginPassword = document.querySelector('.conquer-login-password');\n if (conquerLoginPassword === null || !(conquerLoginPassword instanceof HTMLInputElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('Unable to find conquer login password field.');\n }\n this.conquerLoginPassword = conquerLoginPassword;\n const conquerLoginSubmit = document.querySelector('.conquer-login-submit');\n if (conquerLoginSubmit === null || !(conquerLoginSubmit instanceof HTMLButtonElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('Unable to find the submit button for the login.');\n }\n this.conquerLoginSubmit = conquerLoginSubmit;\n this.conquerLoginSubmit.addEventListener('click', (event) => {\n event.preventDefault();\n this.onLoginRequested();\n });\n }\n async fillConquerRegister() {\n const conquerRegister = document.querySelector('.conquer-register');\n if (conquerRegister === null || !(conquerRegister instanceof HTMLDivElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('conquerRegister is invalid');\n }\n this.conquerRegister = conquerRegister;\n const conquerRegisterGoToLogin = document.querySelector('.conquer-register-go-to-login');\n if (conquerRegisterGoToLogin === null || !(conquerRegisterGoToLogin instanceof HTMLAnchorElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('Link to go to login from register is invalid.');\n }\n this.conquerRegisterGoToLogin = conquerRegisterGoToLogin;\n this.conquerRegisterGoToLogin.addEventListener('click', () => {\n this.goToLogin();\n });\n const conquerRegisterUsername = document.querySelector('.conquer-register-username');\n if (conquerRegisterUsername === null || !(conquerRegisterUsername instanceof HTMLInputElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('No username field in conquer register.');\n }\n this.conquerRegisterUsername = conquerRegisterUsername;\n const conquerRegisterPassword = document.querySelector('.conquer-register-password');\n if (conquerRegisterPassword === null || !(conquerRegisterPassword instanceof HTMLInputElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('No password field in conquer register.');\n }\n this.conquerRegisterPassword = conquerRegisterPassword;\n const conquerRegisterRepeatPassword = document.querySelector('.conquer-register-repeat-password');\n if (conquerRegisterRepeatPassword === null || !(conquerRegisterRepeatPassword instanceof HTMLInputElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('No repeat password field in conquer register.');\n }\n this.conquerRegisterRepeatPassword = conquerRegisterRepeatPassword;\n const conquerRegisterSubmit = document.querySelector('.conquer-register-submit');\n if (conquerRegisterSubmit === null || !(conquerRegisterSubmit instanceof HTMLButtonElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('No register submit button found.');\n }\n this.conquerRegisterSubmit = conquerRegisterSubmit;\n this.conquerRegisterSubmit.addEventListener('click', (event) => {\n event.preventDefault();\n this.onRegisterRequest();\n });\n const conquerRegisterError = document.querySelector('.conquer-register-error');\n if (conquerRegisterError === null || !(conquerRegisterError instanceof HTMLParagraphElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fail('Unable to find the conquer error element.');\n }\n this.conquerRegisterError = conquerRegisterError;\n }\n async unsetLoginAndRegisterErrors() {\n this.conquerRegisterError.classList.add('conquer-display-none');\n this.conquerLoginError.classList.add('conquer-display-none');\n }\n async onRegisterRequest() {\n const username = this.conquerRegisterUsername.value;\n const password = this.conquerRegisterPassword.value;\n const repeatPassword = this.conquerRegisterRepeatPassword.value;\n const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n let responseJson;\n let status;\n try {\n const response = await fetch(urlUser, {\n method: 'PUT',\n body: JSON.stringify({\n username: username,\n password: password,\n repeat_password: repeatPassword\n })\n });\n responseJson = await response.json();\n status = response.status;\n }\n catch (e) {\n console.error(e);\n this.addNewRegisterError('El servidor ha enviado datos inesperados.');\n return;\n }\n if (status !== 200) {\n this.addNewRegisterError(responseJson.error);\n return;\n }\n this.addNewLoginSuccessText(`Usuario registrado ${username}.`);\n this.goToLogin();\n }\n async addNewLoginSuccessText(message) {\n this.unsetLoginAndRegisterErrors();\n this.conquerLoginSuccess.innerText = message;\n this.conquerLoginSuccess.classList.remove('conquer-display-none');\n }\n async addNewLoginError(error) {\n this.unsetLoginAndRegisterErrors();\n this.conquerLoginSuccess.classList.add('conquer-display-none');\n this.conquerLoginError.innerText = error;\n this.conquerLoginError.classList.remove('conquer-display-none');\n }\n async addNewRegisterError(error) {\n this.unsetLoginAndRegisterErrors();\n this.conquerLoginSuccess.classList.add('conquer-display-none');\n this.conquerRegisterError.innerText = error;\n this.conquerRegisterError.classList.remove('conquer-display-none');\n }\n async removeLoginRegisterCombo() {\n this.conquerLogin.classList.add('conquer-display-none');\n this.conquerRegister.classList.add('conquer-display-none');\n }\n async checkLogin() {\n const isLogged = await this.isLogged();\n if (!isLogged) {\n this.conquerLogin.classList.remove('conquer-display-none');\n return;\n }\n this.onLoginSuccess();\n }\n async on(name, callback) {\n if (this.callbacks[name] === undefined) {\n this.callbacks[name] = [];\n this.callbacks[name].push(callback);\n }\n }\n async onLoginSuccess() {\n await this.removeLoginRegisterCombo();\n for (const callback of this.callbacks.login) {\n callback();\n }\n }\n async goToRegister() {\n const isLogged = await this.isLogged();\n await this.removeLoginRegisterCombo();\n if (!isLogged) {\n this.conquerRegister.classList.remove('conquer-display-none');\n }\n else {\n this.onLoginSuccess();\n }\n }\n async goToLogin() {\n const isLogged = await this.isLogged();\n await this.removeLoginRegisterCombo();\n if (!isLogged) {\n this.conquerLogin.classList.remove('conquer-display-none');\n }\n else {\n this.onLoginSuccess();\n }\n }\n async onLoginRequested() {\n const username = this.conquerLoginUsername.value;\n const password = this.conquerLoginPassword.value;\n const urlUser = new URL('/conquer/user/login', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n let responseJson;\n let status;\n try {\n const response = await fetch(urlUser, {\n method: 'POST',\n body: JSON.stringify({\n username: username,\n password: password,\n })\n });\n responseJson = await response.json();\n status = response.status;\n }\n catch (e) {\n console.error(e);\n this.addNewLoginError('El servidor ha enviado datos inesperados.');\n return;\n }\n if (status !== 200) {\n this.addNewLoginError(responseJson.error);\n return;\n }\n this.unsetLoginAndRegisterErrors();\n const isLogged = await this.isLogged();\n if (isLogged) {\n this.onLoginSuccess();\n }\n }\n async addNewLoginRegisterError(message) {\n this.addNewRegisterError(message);\n this.addNewLoginError(message);\n }\n async isLogged() {\n const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n let status;\n try {\n const response = await fetch(urlUser);\n status = response.status;\n }\n catch {\n this.addNewLoginRegisterError('Error del servidor');\n return false;\n }\n return status === 200;\n }\n}\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/login.ts?"); /***/ }), diff --git a/templates/conquer/index.html.ep b/templates/conquer/index.html.ep index 8874c4e..7e69e58 100644 --- a/templates/conquer/index.html.ep +++ b/templates/conquer/index.html.ep @@ -8,6 +8,8 @@ +
+