Subversion Repositories eFlore/Applications.cel

Rev

Rev 3857 | Rev 3863 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3844 idir 1
export function Utils() {
3638 delphine 2
  this.cheminFichiers = $( '#zone-appli' ).data( 'url-fichiers' );
3
  // système de traduction minimaliste
3844 idir 4
  this.msgs = {
3638 delphine 5
    fr: {
6
      'arbre'                             : 'Arbre',
7
      'dupliquer'                         : 'Dupliquer',
8
      'saisir-plantes'                    : 'Saisir les plantes',
9
      'saisir-lichens'                    : 'Saisir les lichens',
10
      'upload-non-suppote'                : 'Votre navigateur ne permet pas le téléchargement de fichiers.',
11
      'format-non-supporte'               : 'Le format de fichier n\'est pas supporté, les formats acceptés sont',
12
      'image-deja-chargee'                : 'Cette image a déjà été utilisée',
13
      'date-incomplete'                   : 'Format : jj/mm/aaaa.',
14
      'observations-transmises'           : 'observations transmises',
15
      'supprimer-observation-liste'       : 'Supprimer cette observation de la liste à transmettre',
16
      'confirmation-suppression'          : 'Êtes-vous sûr de vouloir supprimer cette observation',
17
      'milieu'                            : 'Milieu',
18
      'commentaires'                      : 'Commentaires',
19
      'non-lie-au-ref'                    : 'non lié au référentiel',
20
      'obs-le'                            : 'le',
21
      'non-connexion'                     : 'Veuillez entrer votre login et votre mot de passe',
22
      'obs-numero'                        : 'Observation n°',
23
      'erreur'                            : 'Erreur',
24
      'erreur-inconnue'                   : 'Erreur inconnue',
25
      'erreur-image'                      : 'Erreur lors du chargement des images',
26
      'erreur-ajax'                       : 'Erreur Ajax',
27
      'erreur-chargement'                 : 'Erreur lors du chargement de l\'observation',
28
      'erreur-chargement-obs-utilisateur' : 'Erreur lors du chargement des observations de cet utilisateur',
29
      'erreur-formulaire'                 : 'Erreur: impossible de charger le formulaire',
30
      'lieu-obs'                          : 'observé à',
31
      'lieu-dit'                          : 'Lieu-dit',
3852 idir 32
      'taxon-ou-image'                    : 'Veuillez transmettre au moins, soit une image, soit une espèce',
3638 delphine 33
      'station'                           : 'Station',
34
      'date-rue'                          : 'Un releve existe dejà à cette date pour cette rue.',
35
      'rechargement-page'                 : 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.',
36
      'courriel-connu'                    : 'Un compte existe pour ce courriel, connectez-vous pour saisir votre observation'
37
    },
38
    en: {
39
      'arbre'                             : 'Tree',
40
      'dupliquer'                         : 'Duplicate',
41
      'saisir-plantes'                    : 'Enter the plants',
42
      'saisir-lichens'                    : 'Enter the lichens',
43
      'upload-non-suppote'                : 'Your browser does not support file upload.',
44
      'format-non-supporte'               : 'The file format is not supported, the accepted formats are',
45
      'image-deja-chargee'                : 'This image has already been used',
46
      'date-incomplete'                   : 'Format: dd/mm/yyyy.',
47
      'observations-transmises'           : 'observations transmitted',
48
      'supprimer-observation-liste'       : 'Delete this observation from the list to be transmitted',
49
      'confirmation-suppression'          : 'Are you sure you want to delete this observation',
50
      'milieu'                            : 'Environment',
51
      'commentaires'                      : 'Comments',
52
      'non-lie-au-ref'                    : 'unrelated to the referencial ',
53
      'obs-le'                            : 'the',
54
      'non-connexion'                     : 'Please enter your login and password',
55
      'obs-numero'                        : 'Observation number ',
56
      'erreur'                            : 'Error',
57
      'erreur-inconnue'                   : 'Unknown error',
58
      'erreur-image'                      : 'Error loading the images',
59
      'erreur-ajax'                       : 'Ajax Error',
60
      'erreur-chargement'                 : 'Error loading the observation',
61
      'erreur-chargement-obs-utilisateur' : 'Error loading this user\'s observations',
62
      'erreur-formulaire'                 : 'Error: couldn\'t load form',
63
      'lieu-obs'                          : 'observed at',
64
      'lieu-dit'                          : 'Locality',
65
      'taxon-ou-image'                    : 'Please transmit at least one image or one species',
66
      'station'                           : 'Place',
67
      'date-rue'                          : 'A record already exists on this date for this street',
68
      'rechargement-page'                 : 'Are you sure you want to leave the page?\nAll untransmitted observations will be lost.',
69
      'courriel-connu'                    : 'An account exists for this email, log in to enter your observation'
70
    }
71
  };
72
};
73
 
74
Utils.prototype.init = function() {
75
  // Modale "aide" du projet
76
  this.projetHelpModale();
77
  // Affichage input file
78
  this.inputFile();
79
  // Affichage des List-checkbox
80
  this.inputListCheckbox();
81
  // Affichage des Range
82
  this.inputRangeDisplayNumber()
83
  // Modale "aide"
84
  this.newFieldsHelpModal();
85
  // Ajout/suppression d'un champ texte "Autre"
86
  this.onOtherOption();
87
  // Récupérer les données entrées dans "Autre"
88
  this.collectOtherOption();
89
};
90
 
3844 idir 91
// aide dans le titre du projet
92
Utils.prototype.projetHelpModale = function() {
93
  const lthis = this;
3638 delphine 94
 
3844 idir 95
  $( '#top' ).on ( 'click', '#info-button', function ( event ) {
96
    const fileMimeType = $( this ).data( 'mime-info' ),
97
        label          = 'Aide du projet : ' +  $( '#titre-projet' ).text();
3638 delphine 98
 
3844 idir 99
    if( fileMimeType.match( 'image' ) ) {
100
      const extention = fileMimeType.replace( /(?:imag)?e\/?/g , '' ),
101
          content     = '<img id="modale-aide-img" src="' + lthis.cheminFichiers + 'info.' + extention + '" style="" alt="info projet" />';
102
    }
103
    lthis.activerModale( label, content );
104
  });
3638 delphine 105
};
106
 
107
// Logique d'affichage pour le input type=file
108
Utils.prototype.inputFile = function() {
109
  // Action lorsque la "barre d'espace" ou "Entrée" est pressée
110
  $( '#formulaire' ).on( 'keydown', '.label-file', function( event ) {
111
    if ( event.keyCode == 13 || event.keyCode == 32 ) {
112
      $( '#' + $( this ).attr( 'for' ) + '.input-file' ).click();
113
    }
114
  });
115
};
116
 
117
// Style et affichage des list-checkboxes
118
Utils.prototype.inputListCheckbox = function() {
119
  // On écoute le click sur une list-checkbox ('.selectBox')
120
  // à tout moment de son insertion dans le dom
121
  // _ S'assurer de bien viser la bonne list-checkbox
122
  // _ Au click sur un autre champ remballer la list-checkbox
123
  $( document ).click( function( event ) {
3844 idir 124
    const target = event.target;
3638 delphine 125
 
126
    if ( !$( target ).is( '.overSelect' ) && 0 === $( target ).closest( '.checkboxes' ).length ) {
127
      $( '.checkboxes' ).each( function () {
128
        $( this ).addClass( 'hidden' );
129
      });
130
      $( '.selectBox select.focus', '#zone-appli' ).each( function() {
131
        $( this ).removeClass( 'focus' );
132
      });
133
    }
134
  });
135
  $( '#zone-appli' ).on( 'click' , '.selectBox' , function() {
136
    // afficher/cacher le volet des checkboxes et focus
137
    $( this ).next().toggleClass( 'hidden' );
138
    $( this ).find( 'select' ).toggleClass( 'focus' );
139
 
140
    // Cacher le volet des autres checkboxes et retirer leur focus
3844 idir 141
    const $checkboxes = $( this ).next(),
142
        count         = $( '.checkboxes' ).length;
3638 delphine 143
 
3844 idir 144
    for ( let i = 0; i < count; i++ ) {
3638 delphine 145
      if ( $( '.checkboxes' )[i] !== $checkboxes[0] && !$checkboxes.hasClass( 'hidden' ) ) {
3844 idir 146
        const $otherListCheckboxes = $( '.checkboxes' )[i];
147
 
3638 delphine 148
        if ( !$otherListCheckboxes.classList.contains( 'hidden' ) ) {
149
          $otherListCheckboxes.classList.add( 'hidden' );
150
        }
151
        if( $otherListCheckboxes.previousElementSibling.firstElementChild.classList.contains( 'focus' ) ) {
152
          $otherListCheckboxes.previousElementSibling.firstElementChild.classList.remove( 'focus' );
153
        }
154
      }
155
    }
156
  });
157
};
158
 
159
// Style et affichage des input type="range"
160
Utils.prototype.inputRangeDisplayNumber = function() {
161
  $( 'input[type="range"]' ).each( function() {
162
    $( this ).siblings( '.range-live-value' ).text( $( this ).val() );
163
  });
164
  $( '#top' ).on( 'input' , 'input[type="range"]' , function () {
165
    $( this ).siblings( '.range-live-value' ).text( $( this ).val() );
166
  });
167
  $( '#top' ).on( 'click', '#ajouter-obs', function() {
168
    $( '.range-live-value' ).each( function() {
3844 idir 169
      $( this ).text( '' );
3638 delphine 170
    });
171
  });
172
};
173
 
174
// Activation/Desactivation et contenu de la modale Bootstrap
175
// https://getbootstrap.com/docs/3.3/javascript/#modals
176
Utils.prototype.newFieldsHelpModal = function() {
177
  const lthis = this;
178
 
179
  $( '#zone-appli' ).on( 'click' , '.help-button' , function ( event ) {
3844 idir 180
    const thisFieldKey = $( this ).data( 'key' ),
181
        fileMimeType   = $( this ).data( 'mime-type' ),
182
        label          = 'Aide pour : ' +  $( this ).data( 'name' );
3638 delphine 183
 
184
    if( fileMimeType.match( 'image' ) ) {
3861 delphine 185
    	const extention = fileMimeType.replace( /(?:imag)?e\/?/g , '' );
186
 
187
        content = '<img id="modale-aide-img" src="' + lthis.cheminFichiers + thisFieldKey + '.' + extention + '" style="" alt="' + thisFieldKey + '" />';
188
      }
3638 delphine 189
    lthis.activerModale( label, content );
190
  });
191
};
192
 
193
// Activation/Desactivation et contenu de la modale Bootstrap
194
// https://getbootstrap.com/docs/3.3/javascript/#modals
195
Utils.prototype.activerModale = function( label, content = '', buttons = [] ) {
3844 idir 196
  const lthis = this,
197
    buttonsHtmlBase = '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>';
198
  let dismiss     = '',
199
      buttonsHtml = buttonsHtmlBase;
3638 delphine 200
 
201
  // Titre
202
  $( '#fenetre-modal-label' ).text( label );
203
  if ( '' !== content ) {
204
    $( '#print_content' ).append( content );
205
  }
206
  // Sortie avec la touche escape
207
  $( '#fenetre-modal' ).modal( { keyboard : true } );
208
  // Affichage
209
  $( '#fenetre-modal' ).modal({ show: true });
210
  // Remplacer l'autofocus qui ne fonctionne plus en HTML5
211
  // Message dans la doc de bootstrap :
212
  // Due to how HTML5 defines its semantics,
213
  // the autofocus HTML attribute has no effect in Bootstrap modals.
214
  // To achieve the same effect, use some custom JavaScript
215
  $( '#fenetre-modal' ).off( 'shown.bs.modal' ).on( 'shown.bs.modal' , function () {
216
    $( '#myInput' ).trigger( 'focus' );
3852 idir 217
    if( valOk( $( '#modale-aide-img' ) ) ) {
3638 delphine 218
      lthis.redimentionnerImgAide();
219
      $( window ).on( 'resize', lthis.redimentionnerImgAide.bind( lthis ) );
220
    }
221
  });
3852 idir 222
  if ( valOk( buttons ) ) {
3638 delphine 223
    buttonsHtml = '';
224
    $.each( buttons, function( i, button ) {
225
      dismiss = button.dismiss ? 'data-dismiss="modal"' : '';
226
      buttonsHtml += '<button type="button" class="btn ' + button.class + '" ' + dismiss + '>' + button.label + '</button>';
227
    });
228
  }
229
  $( '.modal-footer' ).html( buttonsHtml );
230
  // Réinitialisation
231
  $( '#fenetre-modal' ).on( 'hidden.bs.modal' , function () {
232
    $( '#confirm-modal-label' ).text();
233
    $( '#print_content' ).empty();
234
    $( '.modal-footer' ).html( buttonsHtmlBase );
235
  });
236
};
237
 
238
Utils.prototype.redimentionnerImgAide = function() {
3844 idir 239
  const espHorizDisp = $( '.modal-dialog' ).innerWidth() <= 1200 ? $( '.modal-dialog' ).innerWidth() - 30 : 1200,
3852 idir 240
      cssImg         = {
241
        'width': espHorizDisp,
242
        'height' : 'auto'
243
      };
3638 delphine 244
 
245
  $( '#modale-aide-img' ).css(cssImg).show(50);
246
};
247
 
248
// Faire apparaitre un champ text "Autre"
249
Utils.prototype.onOtherOption = function() {
3844 idir 250
  const lthis = this,
251
    PREFIX = 'collect-other-';
3638 delphine 252
  // Ajouter un champ texte pour "Autre"
3844 idir 253
  const optionAdd = (
254
      otherId,
255
      $target,
256
      element,
257
      dataName,
258
      dataLabel
259
    ) => {
260
      $target.after(
261
        '<div class="control-group">'+
262
          '<label'+
263
            ' for="' + otherId + '"'+
264
            ' class="' + otherId + '"'+
265
          '>'+
266
            'Autre option "' + dataLabel.toLowerCase() + '" :'+
267
          '</label>'+
268
          '<input'+
269
            ' type="text"'+
270
            ' id="' + otherId + '"'+
271
            ' name="' + otherId + '"'+
272
            ' class="collect-other form-control"'+
273
            ' data-name="' + dataName + '"'+
274
            ' data-element="' + element + '"'+
275
          '>'+
276
        '</div>'
277
      );
278
      $( '#' + otherId ).focus();
279
    };
3638 delphine 280
  // Supprimer un champ texte pour "Autre"
3844 idir 281
  const optionRemove = otherId => $( '#' + otherId ).closest('.control-group').remove();
3638 delphine 282
 
3844 idir 283
  let dataName  = '',
284
      otherId   = '',
285
      dataLabel = '',
286
      element   = '';
287
 
3638 delphine 288
  $( '.other', '#formulaire' ).each( function() {
289
    if( $( this ).hasClass( 'is-select' ) ) {
3844 idir 290
      dataName  = $( this ).data( 'name' );
291
      otherId   = PREFIX + dataName;
292
      dataLabel = $( '.select' ).data( 'label' );
3638 delphine 293
      // Insertion du champ "Autre" après les boutons
3852 idir 294
      if ( !valOk( $( '#'+otherId ) ) ) {
3638 delphine 295
        optionAdd( otherId, $( this ).parent( '.add-field-select' ), 'select', dataName, dataLabel );
296
      }
297
    } else if ( $( this ).is( ':checked' ) ) {
3844 idir 298
      dataName  = $( this ).data( 'name' );
299
      otherId   = PREFIX + dataName;
300
      dataLabel = $( this ).data( 'label' );
301
      element = $( this ).data( 'element' );
3638 delphine 302
      // Insertion du champ "Autre" après les boutons
3852 idir 303
      if ( !valOk( $( '#'+ otherId ) ) ) {
3638 delphine 304
        optionAdd( otherId, $( this ).parent( 'label' ), element, dataName, dataLabel );
305
      }
306
    }
307
  });
308
 
309
  $( '#formulaire' ).on( 'change', '.select', function () {
3844 idir 310
    dataName  = $( this ).data( 'name' );
311
    otherId   = PREFIX + dataName;
312
    dataLabel = $( this ).data( 'label' );
3638 delphine 313
    if( 'other' === $( this ).val() ) {
314
        // Insertion du champ "Autre" après les boutons
3852 idir 315
        if ( !valOk( $( '#'+otherId ) ) ) {
3638 delphine 316
          optionAdd( otherId, $( this ).parent( '.add-field-select' ), 'select', dataName, dataLabel );
317
        }
318
      } else {
319
        // Suppression du champ autre
320
        optionRemove( otherId );
321
        $( this ).find( '.other' ).val( 'other' );
322
      }
323
  });
324
 
325
  $( '#formulaire' ).on( 'change', 'input[type=radio]', function () {
3844 idir 326
    dataName = $( this ).data( 'name' );
327
    otherId  = PREFIX + dataName;
328
    dataLabel = $( this ).data( 'label' );
3638 delphine 329
    if( 'other' === $( this ).val() ) {
330
      // Insertion du champ "Autre" après les boutons
3852 idir 331
      if ( !valOk( $( '#'+otherId ) ) ) {
3638 delphine 332
        optionAdd( otherId, $( this ).parent( 'label' ), 'radio', dataName, dataLabel );
333
      }
334
    } else {
335
      // Suppression du champ autre
336
      optionRemove( otherId );
337
      $( this ).closest( '.radio' ).find( '.other' ).val( 'other' );
338
    }
339
  });
340
 
341
  $( '#formulaire' ).on( 'click', '.list-checkbox .other,.checkbox .other', function () {
3844 idir 342
    dataName = $( this ).data( 'name' );
343
    otherId  = PREFIX + dataName;
344
    dataLabel = $( this ).data( 'label' );
345
    element = $( this ).data( 'element' );
3638 delphine 346
    if( $( this ).is( ':checked' ) ) {
347
        // Insertion du champ "Autre" après les boutons
3852 idir 348
        if ( !valOk( $( '#'+otherId ) ) ) {
3638 delphine 349
          optionAdd( otherId, $( this ).parent( 'label' ), element, dataName, dataLabel );
350
        }
351
      } else {
352
        // Suppression du champ autre
353
        optionRemove( otherId );
354
        $( this ).val( 'other' );
355
      }
356
  });
357
};
358
 
359
Utils.prototype.collectOtherOption = function() {
360
  $( '#formulaire' ).on( 'change', '.collect-other', function () {
3844 idir 361
    const otherIdSuffix = $( this ).data( 'name' ).replace( '[]', '' ),
362
      element           = $( this ).data( 'element' );
3638 delphine 363
 
364
    if ( '' === $( this ).val() ){
365
      if ( 'select' === element ) {
366
        $( '#' + otherIdSuffix ).find( '.other' ).prop( 'selected', false ).val( 'other' );
367
      } else {
368
        $( '#other-' + otherIdSuffix ).prop( 'checked', false ).val( 'other' );
369
      }
370
      $( 'label.collect-other-' + otherIdSuffix ).remove();
371
      $( this ).remove();
372
    } else {
373
      if ( 'select' === element ) {
374
        $( '#' +  otherIdSuffix ).find( '.other' ).val( $( this ).val() );
375
        $( '#' +  otherIdSuffix ).val( $( this ).val() );
376
        $( '#' +  otherIdSuffix + ' option').not( '.other' ).prop( 'selected', false );
377
        $( '#' +  otherIdSuffix ).find( '.other' ).prop( 'selected', true );
378
      } else {
379
        if ( 'radio' === element ) {
380
          $( 'input[name=' + otherIdSuffix + ']' ).not( '#other-' + otherIdSuffix ).prop( 'checked', false );
381
        }
382
        $( '#other-' + otherIdSuffix ).val( $( this ).val() );
383
        $( '#other-' + otherIdSuffix ).prop( 'checked', true );
384
      }
385
    }
386
  });
387
};
388
 
3844 idir 389
/**
390
* Permet à la fois de vérifier qu'une valeur ou objet existe et n'est pas vide
391
* et de comparer à une autre valeur :
392
* Vérifie qu'une variable ou objet n'est pas : vide, null, undefined, NaN
393
* Si comparer est défini on le compare à valeur en fonction de sensComparaison
394
* Un booléen est une variable valide : on retourne true
395
* @param { string || number || object || undefined } valeur
396
* @param { boolean } sensComparaison : true = rechercher, false = refuser
397
* @param { string || number || object || undefined || boolean } comparer :valeur à comparer
398
* @returns {boolean}
399
*/
400
export const valOk = (
401
  valeur,
402
  sensComparaison = true,
403
  comparer = undefined
404
) => {
405
  let retour = true;
406
 
407
  if ( 'boolean' !== typeof valeur ) {
408
    switch( typeof valeur ) {
409
      case 'string' :
410
        retour = ( '' !== valeur );
411
       break;
412
      case 'number' :
413
          retour = ( NaN !== valeur );
414
        break;
415
      case 'object' :
416
          retour = ( null !== valeur && undefined !== valeur && !$.isEmptyObject( valeur ) );
417
          if (  null !== valeur && undefined !== valeur.length ) {
418
            retour = ( retour  && 0 < valeur.length );
419
          }
420
        break;
421
      case 'undefined' :
422
      default :
423
        retour = false;
424
    }
425
    if ( retour && comparer !== undefined ) {
426
      const resultComparaison = ( comparer === valeur );
427
 
428
      retour = ( sensComparaison ) ? resultComparaison : !resultComparaison ;
429
    }
430
 
431
    return retour;
432
 
433
  } else {
434
    // Un booléen est une valeur valable
435
    return true;
436
  }
437
};