niris-public-community-components 0.0.2 → 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (49) hide show
  1. package/README.md +59 -8
  2. package/dev/form-niris.html +29 -0
  3. package/dev/text-area-niris.html +8 -5
  4. package/dist/form-niris.d.ts +70 -0
  5. package/dist/form-niris.d.ts.map +1 -0
  6. package/dist/form-niris.js +1127 -0
  7. package/dist/form-niris.js.map +1 -0
  8. package/dist/form-to-niris.js +847 -0
  9. package/dist/generated/locale-codes.d.ts +14 -0
  10. package/dist/generated/locale-codes.d.ts.map +1 -0
  11. package/dist/generated/locale-codes.js +23 -0
  12. package/dist/generated/locale-codes.js.map +1 -0
  13. package/dist/generated/locales/ca.d.ts +61 -0
  14. package/dist/generated/locales/ca.d.ts.map +1 -0
  15. package/dist/generated/locales/ca.js +65 -0
  16. package/dist/generated/locales/ca.js.map +1 -0
  17. package/dist/generated/locales/en.d.ts +61 -0
  18. package/dist/generated/locales/en.d.ts.map +1 -0
  19. package/dist/generated/locales/en.js +65 -0
  20. package/dist/generated/locales/en.js.map +1 -0
  21. package/dist/index.js +2 -0
  22. package/dist/locale-codes-c2f86156.js +72 -0
  23. package/dist/map-niris.d.ts +25 -0
  24. package/dist/map-niris.d.ts.map +1 -0
  25. package/dist/map-niris.js +200 -0
  26. package/dist/map-niris.js.map +1 -0
  27. package/dist/styles/globalStyles.d.ts +2 -0
  28. package/dist/styles/globalStyles.d.ts.map +1 -0
  29. package/dist/styles/globalStyles.js +170 -0
  30. package/dist/styles/globalStyles.js.map +1 -0
  31. package/dist/types.d.ts +85 -0
  32. package/dist/types.d.ts.map +1 -0
  33. package/dist/types.js +9 -0
  34. package/dist/types.js.map +1 -0
  35. package/index.html +5 -3
  36. package/package.json +26 -5
  37. package/rollup.config.js +6 -2
  38. package/src/form-niris.ts +1203 -0
  39. package/src/generated/locale-codes.ts +25 -0
  40. package/src/generated/locales/ca.ts +71 -0
  41. package/src/generated/locales/en.ts +71 -0
  42. package/src/lit-localize.json +15 -0
  43. package/src/map-niris.ts +215 -0
  44. package/src/styles/globalStyles.ts +170 -0
  45. package/src/textarea-to-niris.ts +29 -15
  46. package/src/types.ts +90 -0
  47. package/src/xliff/ca.xlf +239 -0
  48. package/src/xliff/en.xlf +239 -0
  49. package/dist/textarea-to-niris.js +0 -222
@@ -0,0 +1,1203 @@
1
+ import {LitElement, html, css, nothing} from 'lit';
2
+ import {property, state} from 'lit/decorators.js';
3
+ import {styleMap} from 'lit/directives/style-map.js';
4
+ import {choose} from 'lit/directives/choose.js';
5
+ import {ifDefined} from 'lit/directives/if-defined.js';
6
+ import {when} from 'lit/directives/when.js';
7
+ import {Task} from '@lit/task';
8
+ import {globalStyles} from './styles/globalStyles';
9
+ import {Icon, LeafletMouseEvent, Map, Marker} from 'leaflet';
10
+ import {msg, localized } from '@lit/localize';
11
+ import {
12
+ Characteristic,
13
+ CharacteristicElement,
14
+ CharacteristicTypeEnum,
15
+ Districte,
16
+ FormDataIncidents,
17
+ } from './types';
18
+ import {configureLocalization} from '@lit/localize';
19
+ // Generated via output.localeCodesModule
20
+ import {sourceLocale, targetLocales} from './generated/locale-codes.js';
21
+
22
+ // https://github.com/Leaflet/Leaflet/issues/7055
23
+ // https://github.com/Leaflet/Leaflet/pull/7174
24
+ // https://github.com/Leaflet/Leaflet/pull/6239
25
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
26
+ // @ts-ignore
27
+ import * as L from 'leaflet/dist/leaflet-src.esm.js';
28
+
29
+
30
+ export const {getLocale, setLocale} = configureLocalization({
31
+ sourceLocale,
32
+ targetLocales,
33
+ loadLocale: (locale) => import(`./generated/locales/${locale}.js`),
34
+ });
35
+
36
+ /* TODO:
37
+ - Boton volver, ruta por property o volver atras mirando hsitory
38
+ - Mascaras
39
+ - Validaciones archivos extensiones.
40
+ */
41
+
42
+ /**
43
+ * An example element.
44
+ */
45
+ @localized()
46
+ export class FormNiris extends LitElement {
47
+ @property({type: Number}) detailID: Number | undefined;
48
+ @property({type: String}) actionUrl: string;
49
+ @property({type: String}) apiUrl: string;
50
+
51
+ @property({type: String}) area: string;
52
+ @property({type: String}) element: string;
53
+ @property({type: String}) detail: string;
54
+ @property({type: Array}) characteristics: Characteristic[];
55
+
56
+ private _marker!: Marker | null;
57
+ private _map!: Map;
58
+ private _markerIcon!: Icon;
59
+
60
+ @property({type: String}) defaultLat: string = '39.5701058'; // Palma de Mallorca
61
+ @property({type: String}) defaultLon: string = '2.6487098';
62
+
63
+ @property({type: String}) locale: 'es' | 'en' | 'ca' = 'es';
64
+
65
+ @state()
66
+ private isCitizen: Boolean = true;
67
+
68
+ @state()
69
+ private activeMap: boolean = false;
70
+
71
+ @state()
72
+ private ubiDistricts: Object[] = [];
73
+
74
+ @state()
75
+ private submited: boolean = false;
76
+
77
+ @state()
78
+ private error: boolean = false;
79
+
80
+ @state()
81
+ private incidenceId: string = '';
82
+
83
+ @state()
84
+ private extensionFiles: string = '';
85
+
86
+ /* Map */
87
+ @property({type: String}) domain: string =
88
+ 'https://iris2-backend-demo-iris-community.labs.apsl.io/services/iris/api-public';
89
+ // TODO property for lat and lon
90
+
91
+ @state()
92
+ private street: string = '';
93
+
94
+ @state()
95
+ private streetNumber: string = '';
96
+
97
+ @state()
98
+ private latitude: string = '';
99
+
100
+ @state()
101
+ private longitude: string = '';
102
+
103
+ @state()
104
+ private loading: boolean = false;
105
+
106
+ constructor() {
107
+ super();
108
+ this.detailID = undefined;
109
+ this.actionUrl = '';
110
+ this.apiUrl = '';
111
+
112
+ this.area = '';
113
+ this.element = '';
114
+ this.detail = '';
115
+ this.extensionFiles = '';
116
+ this.characteristics = [];
117
+
118
+ this.locale = this.locale ? this.locale : 'es';
119
+ setLocale(this.locale);
120
+
121
+ // Map
122
+ L.Icon.Default.imagePath = `https://unpkg.com/leaflet@${L.version}/dist/images/`;
123
+ this._markerIcon = new L.Icon({
124
+ iconUrl:
125
+ 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png',
126
+ shadowUrl:
127
+ 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
128
+ iconSize: [25, 41],
129
+ iconAnchor: [12, 41],
130
+ popupAnchor: [1, -34],
131
+ shadowSize: [41, 41],
132
+ });
133
+ }
134
+
135
+ getApiUrl() {
136
+ if (this.apiUrl.endsWith('/')) {
137
+ return this.apiUrl.slice(0, this.apiUrl.lastIndexOf('/'));
138
+ } else {
139
+ return this.apiUrl;
140
+ }
141
+ }
142
+
143
+ _loadMap() {
144
+ const mapEl = this.shadowRoot?.querySelector('#map');
145
+ this._map = L.map(mapEl, {
146
+ markerZoomAnimation: false,
147
+ attributionControl: false,
148
+ }).setView([this.defaultLat, this.defaultLon], 15);
149
+
150
+ L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
151
+ attribution:
152
+ '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
153
+ }).addTo(this._map);
154
+
155
+ this._map.on('click', (e) => this.onMapClick(e));
156
+ }
157
+
158
+ override firstUpdated() {
159
+ /* Disable default form validation */
160
+ const form = this.shadowRoot?.querySelector('form');
161
+ form?.setAttribute('novalidate', '');
162
+ this.addOnChangEventToInputs()
163
+ }
164
+
165
+ addOnChangEventToInputs() {
166
+ const inputs: HTMLInputElement[] = Array.from(this.shadowRoot?.querySelectorAll('input') ?? []);
167
+ inputs.forEach((input: HTMLInputElement) => {
168
+ input.addEventListener('keyup', () => {
169
+ input.setCustomValidity('');
170
+ });
171
+ });
172
+ }
173
+
174
+ /* Lifecycle */
175
+ override connectedCallback() {
176
+ super.connectedCallback();
177
+ this._fetchDistricts();
178
+ }
179
+
180
+ private async _fetchDistricts() {
181
+ const response = await fetch(`${this.getApiUrl()}/districts`, {
182
+ headers: {
183
+ 'Accept-Language': this.locale,
184
+ },
185
+ });
186
+ if (!response.ok) {
187
+ throw new Error(response.statusText);
188
+ }
189
+ const data = await response.json();
190
+
191
+ data.results.map((district: Districte) => {
192
+ this.ubiDistricts.push({value: `${district.id}`, label: district.name});
193
+ });
194
+ }
195
+
196
+ private _fetchFields = new Task(this, {
197
+ task: async ([detailID], {signal}) => {
198
+ const response = await fetch(
199
+ `${this.getApiUrl()}/details/${detailID}/fields`,
200
+ {
201
+ headers: {
202
+ 'Accept-Language': this.locale,
203
+ },
204
+ signal
205
+ }
206
+ );
207
+ if (!response.ok) {
208
+ this.error = true;
209
+ }
210
+ const data = await response.json();
211
+ this.area = data.area;
212
+ this.element = data.element;
213
+ this.detail = data.detail;
214
+ this.characteristics = data.characteristics as Characteristic[];
215
+ this.extensionFiles = data.extension_files;
216
+ const ubiInfo = data.mandatory_drupal_fields.ubication;
217
+ if (ubiInfo?.street_name && ubiInfo?.number) {
218
+ this.activeMap = true;
219
+ this._loadMap();
220
+ }
221
+
222
+ return data;
223
+ },
224
+ args: () => [this.detailID],
225
+ });
226
+
227
+ override updated() {
228
+ this.addOnChangEventToInputs();
229
+ }
230
+
231
+ private changeTab(value: Boolean) {
232
+ this.isCitizen = value;
233
+ }
234
+
235
+ override render() {
236
+ let content = html``;
237
+
238
+ if (this.error || this.submited) {
239
+ content = this.error ? this.renderError() : this.renderSuccess();
240
+ } else {
241
+ content = this.renderForm();
242
+ }
243
+
244
+ return html` ${this.renderHeader()}
245
+ <main class="container">${content}</main>`;
246
+ }
247
+
248
+ renderError() {
249
+ return html`
250
+ <section class="success-submit">
251
+ <article class="success-submit__card success-submit__card--error ">
252
+ <svg
253
+ class="succes-submit__svg succes-submit__svg--error"
254
+ xmlns="http://www.w3.org/2000/svg"
255
+ width="100px"
256
+ height="100px"
257
+ viewBox="0 0 24 24"
258
+ fill="none"
259
+ >
260
+ <path
261
+ d="M10.0303 8.96965C9.73741 8.67676 9.26253 8.67676 8.96964 8.96965C8.67675 9.26255 8.67675 9.73742 8.96964 10.0303L10.9393 12L8.96966 13.9697C8.67677 14.2625 8.67677 14.7374 8.96966 15.0303C9.26255 15.3232 9.73743 15.3232 10.0303 15.0303L12 13.0607L13.9696 15.0303C14.2625 15.3232 14.7374 15.3232 15.0303 15.0303C15.3232 14.7374 15.3232 14.2625 15.0303 13.9696L13.0606 12L15.0303 10.0303C15.3232 9.73744 15.3232 9.26257 15.0303 8.96968C14.7374 8.67678 14.2625 8.67678 13.9696 8.96968L12 10.9393L10.0303 8.96965Z"
262
+ />
263
+ <path
264
+ fill-rule="evenodd"
265
+ clip-rule="evenodd"
266
+ d="M12 1.25C6.06294 1.25 1.25 6.06294 1.25 12C1.25 17.9371 6.06294 22.75 12 22.75C17.9371 22.75 22.75 17.9371 22.75 12C22.75 6.06294 17.9371 1.25 12 1.25ZM2.75 12C2.75 6.89137 6.89137 2.75 12 2.75C17.1086 2.75 21.25 6.89137 21.25 12C21.25 17.1086 17.1086 21.25 12 21.25C6.89137 21.25 2.75 17.1086 2.75 12Z"
267
+ />
268
+ </svg>
269
+ <h2 class="succes-submit__title">${msg('Ha ocurrido un error')}</h2>
270
+ <p class="success-submit__text">
271
+ ${msg('Sentimos las molestias. Vuelva a intentelo más tarde')}.
272
+ </p>
273
+ <a class="success-submit__anchor btn btn-error text-center" href="/"
274
+ >${msg('Volver')}</a
275
+ >
276
+ </article>
277
+ </section>
278
+ `;
279
+ }
280
+ renderSuccess() {
281
+ return html`
282
+ <section class="success-submit">
283
+ <article class="success-submit__card">
284
+ <svg
285
+ class="succes-submit__svg"
286
+ xmlns="http://www.w3.org/2000/svg"
287
+ width="100px"
288
+ height="100px"
289
+ viewBox="0 0 24 24"
290
+ fill="none"
291
+ >
292
+ <path
293
+ d="M16.0303 10.0303C16.3232 9.73744 16.3232 9.26256 16.0303 8.96967C15.7374 8.67678 15.2626 8.67678 14.9697 8.96967L10.5 13.4393L9.03033 11.9697C8.73744 11.6768 8.26256 11.6768 7.96967 11.9697C7.67678 12.2626 7.67678 12.7374 7.96967 13.0303L9.96967 15.0303C10.2626 15.3232 10.7374 15.3232 11.0303 15.0303L16.0303 10.0303Z"
294
+ />
295
+ <path
296
+ fill-rule="evenodd"
297
+ clip-rule="evenodd"
298
+ d="M12 1.25C6.06294 1.25 1.25 6.06294 1.25 12C1.25 17.9371 6.06294 22.75 12 22.75C17.9371 22.75 22.75 17.9371 22.75 12C22.75 6.06294 17.9371 1.25 12 1.25ZM2.75 12C2.75 6.89137 6.89137 2.75 12 2.75C17.1086 2.75 21.25 6.89137 21.25 12C21.25 17.1086 17.1086 21.25 12 21.25C6.89137 21.25 2.75 17.1086 2.75 12Z"
299
+ />
300
+ </svg>
301
+ <h2 class="succes-submit__title">${msg('¡Ficha creada!')}</h2>
302
+ <p class="success-submit__text">
303
+ ${msg('El codi de seguiment és')}:
304
+ <strong class="color-primary">${this.incidenceId}</strong>
305
+ </p>
306
+ <button type="button" class="success-submit__anchor btn text-center" @click="${() => history.back()}">${msg('Volver')}:</button>
307
+ </article>
308
+ </section>
309
+ `;
310
+ }
311
+
312
+ renderHeader() {
313
+ return html`
314
+ <header class="header">
315
+ <h1 class="header__title">
316
+ ${this.area} &gt; ${this.element} &gt; ${this.detail}
317
+ </h1>
318
+ <p class="header__info">
319
+ ${msg('Agradecemos que nos haya hecho llegar su reconocimiento, el cual se hará llegar al departamento responsable. Con esta información, damos por contestada su comunicación')}.
320
+ </p>
321
+ <p class="header__info info--danger">
322
+ ${msg('Los campos marcados con un (*) son obligatorios.')}
323
+ </p>
324
+ </header>
325
+ `;
326
+ }
327
+
328
+ renderForm() {
329
+ const classesActiveCitizen = this.isCitizen ? 'tablink--active' : '';
330
+ const classesActiveCompnay = !this.isCitizen ? 'tablink--active' : '';
331
+
332
+ const stylesCharacteristics = {
333
+ display: this.characteristics.length == 0 ? 'none' : '',
334
+ };
335
+
336
+ return html`
337
+ <section class="record">
338
+ <h2 class="record__comment">${msg('Mensaje')}</h2>
339
+ <form method="post" @submit=${this.onSubmit}>
340
+ <input
341
+ type="hidden"
342
+ name="detailId"
343
+ value="${ifDefined(this.detailID)}"
344
+ />
345
+ <label for="comments">${msg('Escriba brevemente su mensaje')}*:</label>
346
+ <textarea
347
+ id="comments"
348
+ name="comments"
349
+ required
350
+ minlength="4"
351
+ placeholder=${msg('Escribe tu consulta aquí')}
352
+ ></textarea>
353
+ <label for="file">${msg('Añadir archivo')}</label>
354
+ <input
355
+ multiple
356
+ accept=".${this.extensionFiles.split(';').join(',.')}"
357
+ type="file"
358
+ name="file"
359
+ id="input_1"
360
+ aria-describedby="help-input_1"
361
+ />
362
+ <p class="text-error"></p>
363
+ <div class="help-text" id="file">
364
+ ${msg('Aceptados:')} ${this.extensionFiles}
365
+ </div>
366
+
367
+ <section class="map">
368
+ <h2 class="text-center">${msg('Ubicación')}</h2>
369
+ <div id="map" ?hidden=${!this.activeMap}></div>
370
+ ${when(
371
+ this.activeMap,
372
+ () => this.renderMap(),
373
+ () =>
374
+ this.ubiDistricts.length > 0
375
+ ? html`
376
+ <div>
377
+ <label for="map-district">${msg('Distrito*:')}</label>
378
+ <select
379
+ required
380
+ id="map-district"
381
+ name="location.district"
382
+ >
383
+ ${this.ubiDistricts.map(
384
+ (district: any) =>
385
+ html`<option value="${district.value}">
386
+ ${district.label}
387
+ </option>`
388
+ )}
389
+ </select>
390
+ </div>
391
+ `
392
+ : html``
393
+ )}
394
+ </section>
395
+
396
+ <h2
397
+ class="text-center color-primary"
398
+ style=${styleMap(stylesCharacteristics)}
399
+ >
400
+ ${msg('Características de la petición')}
401
+ </h2>
402
+ <section class="characteristics-form">
403
+ ${this._fetchFields.render({
404
+ pending: () => html`<p>${msg('Cargando formulario')}...</p>`,
405
+ complete: () => html`
406
+ ${this.characteristics.map(
407
+ (characteristic) => html`
408
+ <div>
409
+ <label for="niris-${characteristic.id}"
410
+ >${characteristic.title}${characteristic.mandatory
411
+ ? '*'
412
+ : ''}:</label
413
+ >
414
+ ${choose(
415
+ characteristic.type,
416
+ [
417
+ [
418
+ CharacteristicTypeEnum.Number,
419
+ () =>
420
+ html`<input
421
+ id="niris-${characteristic.id}"
422
+ name="characteristic-${characteristic.id}"
423
+ type="number"
424
+ ?required=${characteristic.mandatory}
425
+ placeholder=${characteristic.explanatory_text}
426
+ />`,
427
+ ],
428
+ [
429
+ CharacteristicTypeEnum.Options,
430
+ () => html`<select
431
+ id="niris-${characteristic.id}"
432
+ name="characteristic-${characteristic.id}"
433
+ ?required=${characteristic.mandatory}
434
+ >
435
+ ${characteristic.options.map(
436
+ (option) =>
437
+ html`<option value="${option}">
438
+ ${option}
439
+ </option>`
440
+ )}
441
+ </select>`,
442
+ ],
443
+ [
444
+ CharacteristicTypeEnum.Date,
445
+ () =>
446
+ html`<input
447
+ id="niris-${characteristic.id}"
448
+ name="characteristic-${characteristic.id}"
449
+ type="date"
450
+ ?required=${characteristic.mandatory}
451
+ />`,
452
+ ],
453
+ [
454
+ CharacteristicTypeEnum.Time,
455
+ () =>
456
+ html`<input
457
+ id="niris-${characteristic.id}"
458
+ name="characteristic-${characteristic.id}"
459
+ type="time"
460
+ ?required=${characteristic.mandatory}
461
+ />`,
462
+ ],
463
+ [
464
+ CharacteristicTypeEnum.Text,
465
+ () =>
466
+ html`<input
467
+ id="niris-${characteristic.id}"
468
+ name="characteristic-${characteristic.id}"
469
+ type="text"
470
+ ?required=${characteristic.mandatory}
471
+ placeholder=${characteristic.explanatory_text}
472
+ />`,
473
+ ],
474
+ ],
475
+ () => html`<p>${msg('Not implemented')}</p>`
476
+ )}
477
+ </div>
478
+ `
479
+ )}
480
+ `,
481
+ error: () => html`<p>${msg('Error cargando el formulario')}</p>`,
482
+ })}
483
+ </section>
484
+
485
+ <h2 class="text-center">${msg('Datos personales')}</h2>
486
+ <div class="tab">
487
+ <div
488
+ class="tab__tablink ${classesActiveCitizen}"
489
+ @click=${() => this.changeTab(true)}
490
+ >
491
+ ${msg('Ciudadano')}
492
+ </div>
493
+ <div
494
+ class="tab__tablink ${classesActiveCompnay}"
495
+ @click="${() => this.changeTab(false)}"
496
+ >
497
+ ${msg('Empresa/Entidad')}
498
+ </div>
499
+ </div>
500
+ <div class="tab__tabcontent">
501
+ ${this.isCitizen
502
+ ? this.renderCitizenForm()
503
+ : this.renderCompanyForm()}
504
+ </div>
505
+ <button id="submit-btn" type="submit" ?disabled=${this.loading}>
506
+ <div class="loader" ?hidden=${!this.loading} id="loader"></div>
507
+ ${this.loading ? 'Enviando' : 'Enviar'}
508
+ <!-- TODO -->
509
+ </button>
510
+ </form>
511
+ </section>
512
+ `;
513
+ }
514
+
515
+ renderCitizenForm() {
516
+ return html`
517
+ <div>
518
+ <label for="nameCitizen">${msg('Nombre')}*:</label>
519
+ <input id="nameCitizen" name="nameCitizen" type="text" required />
520
+ </div>
521
+
522
+ <div>
523
+ <label for="firstSurname">${msg('Primer apellido')}*:</label>
524
+ <input id="firstSurname" name="firstSurname" type="text" />
525
+ </div>
526
+
527
+ <div>
528
+ <label for="secondSurname">${msg('Segundo apellido')}*:</label>
529
+ <input id="secondSurname" name="secondSurname" type="text" required />
530
+ </div>
531
+
532
+ <div>
533
+ <label for="document-type">${msg('Tipo de Documento')}*:</label>
534
+ <select id="typeDocument" name="typeDocument" required>
535
+ <option value="0" selected>${msg('NIF/DNI')}</option>
536
+ <option value="1">${msg('NIE')}</option>
537
+ <option value="2">${msg('Passaporte')}</option>
538
+ </select>
539
+ </div>
540
+
541
+ <div>
542
+ <label for="numberDocument">${msg('Núm. Documento')}*:</label>
543
+ <input
544
+ id="numberDocument"
545
+ name="numberDocument"
546
+ type="text"
547
+ required
548
+ />
549
+ </div>
550
+
551
+ <div>
552
+ <label for="birthYear">${msg('Año de nacimiento')}:</label>
553
+ <select id="birthYear" name="birthYear">
554
+ ${this.years().map(
555
+ (year) => html`<option value="${year}">${year}</option>`
556
+ )}
557
+ </select>
558
+ </div>
559
+
560
+ ${this.ubiDistricts.length > 0
561
+ ? html`
562
+ <div>
563
+ <label for="district">${msg('Distrito')}*:</label>
564
+ <select required id="district" name="district">
565
+ ${this.ubiDistricts.map(
566
+ (district: any) =>
567
+ html`<option value="${district.value}">
568
+ ${district.label}
569
+ </option>`
570
+ )}
571
+ </select>
572
+ </div>
573
+ `
574
+ : nothing}
575
+
576
+ <div>
577
+ <label for="email">${msg('Correo electrónico')}*:</label>
578
+ <input
579
+ id="email"
580
+ name="email"
581
+ type="email"
582
+ required
583
+ placeholder=${msg('Escribe tu correo')}
584
+ />
585
+ </div>
586
+
587
+ <div>
588
+ <label for="email_confirm">${msg('Confirma correo electrónico')}*:</label>
589
+ <input
590
+ id="email_confirm"
591
+ name="email_confirm"
592
+ @focusout=${(event: FocusEvent) => this.confirmEmail(event as FocusEvent)}
593
+ type="email"
594
+ required
595
+ placeholder=${msg('Confirma tu correo')}
596
+ />
597
+ <span class="text-error" hidden id="email_confirm_error"
598
+ >${msg('Los emails no conciden')}</span
599
+ >
600
+ </div>
601
+
602
+ <div>
603
+ <label for="phone">${msg('Teléfono')}*:</label>
604
+ <input
605
+ id="phone"
606
+ name="phone"
607
+ type="tel"
608
+ minlength="9"
609
+ placeholder=${msg('Escribe tu teléfono')}
610
+ />
611
+ </div>
612
+ `;
613
+ }
614
+
615
+ renderCompanyForm() {
616
+ return html`
617
+ <div>
618
+ <label for="socialReason">${msg('Razón social')}*:</label>
619
+ <input id="socialReason" name="socialReason" type="text" required />
620
+ </div>
621
+
622
+ <div>
623
+ <label for="contactPerson">${msg('Persona de contacto')}*:</label>
624
+ <input id="contactPerson" name="contactPerson" type="text" required />
625
+ </div>
626
+
627
+ <div>
628
+ <label for="cif">${msg('CIF')}*:</label>
629
+ <input id="cif" name="cif" type="text" required />
630
+ </div>
631
+
632
+ <div>
633
+ <label for="email">${msg('Email')}*:</label>
634
+ <input
635
+ id="email"
636
+ name="email"
637
+ type="text"
638
+ type="email"
639
+ required
640
+ />
641
+ </div>
642
+
643
+ <div>
644
+ <label for="email_confirm">${msg('Confirma el email')}*:</label>
645
+ <input
646
+ id="email_confirm"
647
+ name="email_confirm"
648
+ type="text"
649
+ type="email"
650
+ required
651
+ @focusout=${(event: FocusEvent) => this.confirmEmail(event as FocusEvent)}
652
+ />
653
+ <span class="text-error" hidden id="email_confirm_error"
654
+ >${msg('Los emails no conciden')}</span
655
+ >
656
+ </div>
657
+
658
+ <div>
659
+ <label for="phone">${msg('Idioma de la respuesta')}*:</label>
660
+ <select id="phone" name="language" required>
661
+ <option value="es" selected>${msg('Español')}</option>
662
+ <option value="ca">${msg('Catalán')}</option>
663
+ <option value="en">${msg('Inglés')}</option>
664
+ </select>
665
+ </div>
666
+ `;
667
+ }
668
+
669
+ renderMap() {
670
+ return html`
671
+ <link
672
+ rel="stylesheet"
673
+ href="https://cdn.skypack.dev/leaflet/dist/leaflet.css"
674
+ />
675
+ <section class="map-form">
676
+ <div>
677
+ <label for="map-address">${msg('Calle')}*:</label>
678
+ <input
679
+ id="map-address"
680
+ required
681
+ type="text"
682
+ @keyup="${(event: KeyboardEvent) =>
683
+ (this.street = (event.target as HTMLInputElement).value)}"
684
+ .value="${this.street}"
685
+ name="address"
686
+ />
687
+ <input name="latitude" hidden .value="${this.latitude}" />
688
+ <input name="longitude" hidden .value="${this.longitude}" />
689
+ </div>
690
+
691
+ <div>
692
+ <label for="map-number">${msg('Número')}*:</label>
693
+ <input
694
+ id="map-number"
695
+ @keyup="${(event: KeyboardEvent) =>
696
+ (this.streetNumber = (event.target as HTMLInputElement).value)}"
697
+ .value="${this.streetNumber}"
698
+ required
699
+ type="text"
700
+ name="number"
701
+ />
702
+ </div>
703
+
704
+ <div>
705
+ <button
706
+ type="button"
707
+ .disabled="${!Boolean(this.street.length)}"
708
+ @click="${this.searchAddress}"
709
+ >
710
+ ${msg('Buscar')}
711
+ </button>
712
+ </div>
713
+ </section>
714
+
715
+ <section class="map-form-grid">
716
+ <div>
717
+ <label for="map-floor">${msg('Piso')}:</label>
718
+ <input id="map-floor" type="text" name="floor" />
719
+ </div>
720
+
721
+ <div>
722
+ <label for="map-stair">${msg('Escalera')}:</label>
723
+ <input id="map-stair" type="text" name="stair" />
724
+ </div>
725
+
726
+ <div>
727
+ <label for="map-door">${msg('Puerta')}:</label>
728
+ <input id="map-door" type="text" name="door" />
729
+ </div>
730
+ </section>
731
+ `;
732
+ }
733
+
734
+ async onSubmit(event: SubmitEvent) {
735
+ this.loading = true;
736
+ event.preventDefault();
737
+ event.stopImmediatePropagation();
738
+
739
+ const form = event.target as HTMLFormElement;
740
+
741
+ if (!form.checkValidity()) {
742
+ form.reportValidity();
743
+ this.loading = false;
744
+ return;
745
+ }
746
+
747
+ const files = form.file.files;
748
+ const formData = new FormData();
749
+ const value: FormDataIncidents = Object.fromEntries(
750
+ new FormData(form).entries()
751
+ );
752
+
753
+ if (this.activeMap) {
754
+ value.location = {};
755
+ value.location['address'] = value.address;
756
+ value.location['number'] = value.number;
757
+ value.location['latitude'] = value.latitude;
758
+ value.location['longitude'] = value.longitude;
759
+ value.location['floor'] = value.floor;
760
+ value.location['stair'] = value.stair;
761
+ value.location['door'] = value.door;
762
+ } else {
763
+ value.location = {district: value.district};
764
+ }
765
+
766
+ //Save the file separated from the body
767
+ value.file = [];
768
+ if (files.length > 0) {
769
+ for (let i = 0; i < files.length; i++) {
770
+ const file = {
771
+ filename: files[i].name,
772
+ file: files[i],
773
+ };
774
+ value.file.push(file);
775
+ }
776
+ }
777
+
778
+ // add inputs with name starting with "characteristic-" to the values object adding a new key "characteristics"
779
+ const characteristics = Object.keys(value).filter((key) =>
780
+ key.startsWith('characteristic-')
781
+ );
782
+ value.characteristics = characteristics.map((key) => {
783
+ const id = key.split('-')[1];
784
+ // @ts-ignore
785
+ const val = value[key];
786
+ // @ts-ignore
787
+ delete value[key];
788
+
789
+ return {id, value: val} as unknown as CharacteristicElement;
790
+ });
791
+
792
+ formData.append('body', JSON.stringify(value));
793
+
794
+ const response = await fetch(`${this.getApiUrl()}/incidences`, {
795
+ headers: {
796
+ 'Accept-Language': this.locale,
797
+ },
798
+ method: 'POST',
799
+ body: formData,
800
+ });
801
+
802
+ if (!response.ok && response.status !== 400) {
803
+ this.error = true;
804
+ this.loading = false;
805
+ return;
806
+ }
807
+
808
+ if (response.status === 400) {
809
+ const data = await response.json();
810
+ this.handlerError(data);
811
+ } else {
812
+ const data = await response.json();
813
+ this.incidenceId = data.incidenceId;
814
+ this.submited = true;
815
+ }
816
+ this.loading = false;
817
+ }
818
+
819
+ handlerError(data: any) {
820
+ const errors = data;
821
+ Object.keys(errors).map((key) => {
822
+ const input = this.shadowRoot?.getElementById(
823
+ `${key}`
824
+ ) as HTMLInputElement;
825
+ if (key in errors && input) {
826
+ input.setCustomValidity(errors[key]);
827
+ input.reportValidity();
828
+ }
829
+ });
830
+
831
+ if ('characteristics' in errors) {
832
+ const characteristics = errors['characteristics'];
833
+ for (let [key, errors] of characteristics.entries()) {
834
+ if (Object.keys(errors).length !== 0) {
835
+ debugger;
836
+ const input = this.shadowRoot?.getElementById(
837
+ `niris-${key}`
838
+ ) as HTMLInputElement;
839
+ errors.value.forEach((error: string) => {
840
+ input.setCustomValidity(error);
841
+ input.reportValidity();
842
+ });
843
+ }
844
+ }
845
+ }
846
+ }
847
+
848
+ confirmEmail(event: FocusEvent) {
849
+ const email = this.shadowRoot?.getElementById('email') as HTMLInputElement;
850
+ const emailConfirm = this.shadowRoot?.getElementById(
851
+ 'email_confirm'
852
+ ) as HTMLInputElement;
853
+ const error = this.shadowRoot?.getElementById(
854
+ 'email_confirm_error'
855
+ ) as HTMLElement;
856
+ const submit = this.shadowRoot?.getElementById(
857
+ 'submit-btn'
858
+ ) as HTMLButtonElement;
859
+
860
+ if (email.value !== emailConfirm.value) {
861
+ error.hidden = false;
862
+ submit.disabled = true;
863
+ emailConfirm.classList.add('invalid');
864
+ } else {
865
+ error.hidden = true;
866
+ submit.disabled = false;
867
+ emailConfirm.classList.remove('invalid');
868
+ }
869
+
870
+ (event.target as HTMLInputElement).reportValidity();
871
+ }
872
+
873
+ years(): number[] {
874
+ const currentYear = new Date().getFullYear();
875
+ const years = [];
876
+ for (let i = currentYear - 100; i <= currentYear; i++) {
877
+ years.push(i);
878
+ }
879
+
880
+ years.reverse();
881
+ return years;
882
+ }
883
+
884
+ async onMapClick(e: LeafletMouseEvent) {
885
+ if (this._marker) {
886
+ this._map.removeLayer(this._marker);
887
+ }
888
+ this._marker = new L.marker([e.latlng.lat, e.latlng.lng], {
889
+ icon: this._markerIcon,
890
+ }).addTo(this._map);
891
+ try {
892
+ const response = await fetch(
893
+ `${this.domain}/geo_proxy/ubication/reverse/?lat=${e.latlng.lat}&lon=${e.latlng.lng}`,
894
+ {
895
+ headers: {
896
+ 'Accept-Language': this.locale,
897
+ },
898
+ }
899
+ );
900
+ if (!response.ok) {
901
+ throw new Error(response.statusText);
902
+ } else {
903
+ const ubi = await response.json();
904
+ this.street = ubi.street;
905
+ this.streetNumber = ubi.street2;
906
+ this.latitude = ubi.latitude;
907
+ this.longitude = ubi.longitude;
908
+ }
909
+ } catch (error) {
910
+ console.info(error);
911
+ }
912
+ }
913
+
914
+ async searchAddress() {
915
+ try {
916
+ const response = await fetch(
917
+ `${this.domain}/geo_proxy/ubication/search/?q=${this.street}, ${this.streetNumber}`,
918
+ {
919
+ headers: {
920
+ 'Accept-Language': this.locale,
921
+ },
922
+ }
923
+ );
924
+ if (this._marker) {
925
+ this._map.removeLayer(this._marker);
926
+ }
927
+ const data = await response.json();
928
+ this._marker = new L.marker([data[0].lat, data[0].lon]).addTo(this._map);
929
+ this._map.setView([data[0].lat, data[0].lon], 15);
930
+ } catch (error) {
931
+ console.error(error);
932
+ }
933
+ }
934
+
935
+ static override styles = [
936
+ globalStyles,
937
+ css`
938
+ :host {
939
+ --primary-color: #03599d;
940
+ --padding: 0.7rem 0.7rem;
941
+ --font-size: 1rem;
942
+ --border-radius: 0rem;
943
+ --font-weight: 500;
944
+ --font-family: 'Arial', sans-serif;
945
+ --color-button: #fff;
946
+ --error-color: #c23939;
947
+ --tab-secondary-color: #ced1d7;
948
+ }
949
+ /* Style the tab */
950
+ .tab {
951
+ overflow: hidden;
952
+ background-color: #e5e7eb;
953
+ width: 100%;
954
+ }
955
+
956
+ /* Style the buttons inside the tab */
957
+ .tab__tablink {
958
+ background-color: inherit;
959
+ float: left;
960
+ border: none;
961
+ outline: none;
962
+ cursor: pointer;
963
+ padding: 14px 0px;
964
+ transition: 0.3s;
965
+ font-size: 17px;
966
+ line-height: 20px;
967
+ width: 50%;
968
+ text-align: center;
969
+ font-weight: bold;
970
+ color: #4b5563;
971
+ border-top: 4px solid var(--tab-secondary-color);
972
+ background-color: var(--tab-secondary-color);
973
+ }
974
+ .tab__tabcontent {
975
+ display: grid;
976
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
977
+ gap: 0.5rem;
978
+ justify-content: space-between;
979
+ width: 100%;
980
+ background-color: #e5e7eb;
981
+ padding: 1.5rem;
982
+ color: #676774;
983
+ font-size: 16px;
984
+ line-height: 20px;
985
+ font-weight: 500;
986
+ }
987
+
988
+ .tablink--active {
989
+ background-color: #e5e7eb;
990
+ color: #4b5563;
991
+ border-top: 4px solid var(--primary-color);
992
+ }
993
+
994
+ .tab__tablink:not(.tablink--active):hover {
995
+ filter: brightness(90%);
996
+ color: #545466;
997
+ }
998
+
999
+ .container {
1000
+ max-width: 1280px;
1001
+ width: 100%;
1002
+ margin: 0 auto;
1003
+ }
1004
+
1005
+ .header {
1006
+ padding: 2rem;
1007
+ text-align: center;
1008
+ margin: 0 auto;
1009
+ background-color: #f5f5f5;
1010
+ }
1011
+
1012
+ .header__info {
1013
+ margin: 0.5rem auto;
1014
+ max-width: 1280px;
1015
+ color: #676774;
1016
+ }
1017
+ .header__title {
1018
+ font-size: 1.8rem;
1019
+ }
1020
+
1021
+ .info--danger {
1022
+ color: red;
1023
+ }
1024
+
1025
+ .record {
1026
+ width: 70%;
1027
+ margin: 0 auto;
1028
+ }
1029
+
1030
+ .record__comment {
1031
+ font-size: 1.5rem;
1032
+ margin-bottom: 2rem;
1033
+ text-align: center;
1034
+ }
1035
+
1036
+ /* utility classes */
1037
+ .color-primary {
1038
+ color: var(--primary-color);
1039
+ }
1040
+
1041
+ .hide {
1042
+ display: none;
1043
+ }
1044
+
1045
+ .text-center {
1046
+ text-align: center;
1047
+ }
1048
+
1049
+ .mx-auto {
1050
+ margin: 0 auto;
1051
+ }
1052
+
1053
+ .self-center {
1054
+ align-self: center;
1055
+ }
1056
+
1057
+ .help-text {
1058
+ font-size: 0.9rem;
1059
+ color: #676774;
1060
+ }
1061
+
1062
+ /* characteristics-form" */
1063
+ .characteristics-form {
1064
+ display: grid;
1065
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
1066
+ gap: 0.5rem;
1067
+ }
1068
+
1069
+ /* Success Card */
1070
+ .success-submit {
1071
+ display: flex;
1072
+ justify-content: center;
1073
+ align-items: center;
1074
+ }
1075
+
1076
+ .success-submit__card {
1077
+ margin: 4rem 0;
1078
+ width: 25rem;
1079
+ height: 35rem;
1080
+ -webkit-box-shadow: 2px 2px 15px 0px rgba(77, 77, 77, 0.5);
1081
+ -moz-box-shadow: 2px 2px 15px 0px rgba(77, 77, 77, 0.5);
1082
+ box-shadow: 2px 2px 15px 0px rgba(77, 77, 77, 0.5);
1083
+ display: flex;
1084
+ flex-direction: column;
1085
+ justify-content: space-between;
1086
+ align-items: center;
1087
+ border-top: 5px solid var(--primary-color);
1088
+ }
1089
+
1090
+ .success-submit__card:hover {
1091
+ -webkit-box-shadow: 2px 2px 15px 0px rgba(77, 77, 77, 0.5);
1092
+ -moz-box-shadow: 2px 2px 15px 0px rgba(77, 77, 77, 0.5);
1093
+ box-shadow: 4px 4px 17px 2px rgba(77, 77, 77, 0.5);
1094
+ transition: 0.5s;
1095
+ }
1096
+
1097
+ .success-submit__card--error {
1098
+ border-top: 5px solid var(--error-color);
1099
+ }
1100
+
1101
+ .succes-submit__svg {
1102
+ margin-top: 20%;
1103
+ fill: var(--primary-color);
1104
+ filter: opacity(70%);
1105
+ }
1106
+
1107
+ .succes-submit__svg:hover {
1108
+ transform: rotate(360deg);
1109
+ transition: 0.5s;
1110
+ }
1111
+
1112
+ .succes-submit__svg--error {
1113
+ fill: var(--error-color);
1114
+ }
1115
+
1116
+ .succes-submit__title {
1117
+ font-size: 1.8rem;
1118
+ margin-bottom: 2rem;
1119
+ color: #373e47;
1120
+ }
1121
+
1122
+ .success-submit__text {
1123
+ font-size: 1.3rem;
1124
+ padding: 0 3rem;
1125
+ text-align: center;
1126
+ }
1127
+
1128
+ .success-submit__anchor {
1129
+ font-size: 1.2rem;
1130
+ text-decoration: none;
1131
+ width: 100%;
1132
+ padding: 1rem;
1133
+ }
1134
+
1135
+ /* Map */
1136
+ #map {
1137
+ margin-bottom: 2rem;
1138
+ width: 100%;
1139
+ height: 30vh;
1140
+ border: 1px solid #676774;
1141
+ }
1142
+ .map-form {
1143
+ display: flex;
1144
+ justify-content: space-between;
1145
+ align-items: flex-end;
1146
+ gap: 1rem;
1147
+ }
1148
+
1149
+ .map-form div:nth-child(1) {
1150
+ flex-basis: 60%;
1151
+ }
1152
+ .map-form div:nth-child(2) {
1153
+ flex-basis: 30%;
1154
+ }
1155
+ .map-form button {
1156
+ flex-basis: 20%;
1157
+ margin-bottom: 0.5rem;
1158
+ }
1159
+
1160
+ .map-form-grid {
1161
+ display: grid;
1162
+ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
1163
+ gap: 1rem;
1164
+ }
1165
+
1166
+ .loader {
1167
+ width: 18px;
1168
+ padding: 4px;
1169
+ float: left;
1170
+ aspect-ratio: 1;
1171
+ border-radius: 50%;
1172
+ background: #ffffff;
1173
+ --_m:
1174
+ conic-gradient(#22222200 10%,#000),
1175
+ linear-gradient(#000 0 0) content-box;
1176
+ -webkit-mask: var(--_m);
1177
+ mask: var(--_m);
1178
+ -webkit-mask-composite: source-out;
1179
+ mask-composite: subtract;
1180
+ animation: l3 1s infinite linear;
1181
+ }
1182
+ @keyframes l3 {to{transform: rotate(1turn)}}
1183
+
1184
+ /* Media queries */
1185
+ @media screen and (max-width: 640px) {
1186
+ .record {
1187
+ width: 96%;
1188
+ }
1189
+ .success-submit__card {
1190
+ width: 80%;
1191
+ }
1192
+ }
1193
+ `,
1194
+ ];
1195
+ }
1196
+
1197
+ customElements.define('form-niris', FormNiris);
1198
+
1199
+ declare global {
1200
+ interface HTMLElementTagNameMap {
1201
+ 'form-niris': FormNiris;
1202
+ }
1203
+ }