New file |
0,0 → 1,1840 |
import {Geoloc} from './tb-geoloc/js/Geoloc.js'; |
import {Utils,valOk} from './Utils.js'; |
|
export const utils = new Utils(); |
/** |
* WidgetsSaisiesCommun |
* Methodes communes aux widgets de saisie |
*/ |
export function WidgetsSaisiesCommun(){} |
|
WidgetsSaisiesCommun.prototype.init = function() { |
this.geoloc = new Geoloc(); |
// ASL : APA, sTREETs, Lichen's Go! |
// const ASL = ['tb_aupresdemonarbre','tb_streets','tb_lichensgo']; |
// this.isASL = ( valOk( this.projet ) && -1 < $.inArray( this.projet , ASL ) ); |
this.initForm(); |
this.initEvts(); |
}; |
|
WidgetsSaisiesCommun.prototype.initFormConnection = function() { |
this.urlBaseAuth = this.urlRacine + '/service:annuaire:auth'; |
$( '#inscription' ).attr( 'href', this.urlSiteTb() + 'inscription' ); |
if ( this.isASL ) { |
$( '#mdp' ).val( '' ); |
$( '#oublie' ).attr( 'href', this.urlSiteTb() + 'wp-login.php?action=lostpassword' ); |
} |
}; |
|
WidgetsSaisiesCommun.prototype.initFormTaxonListe = function() { |
const lthis = this; |
|
this.surChangementTaxonListe(); |
$( '#taxon-liste' ).on( 'change', lthis.surChangementTaxonListe ); |
$( '#taxon-liste' ).on( 'change', lthis.surChangementValeurTaxon.bind( lthis ) ); |
if ( this.debug ) { |
console.dir( 'Selected taxon:' + $( '#taxon-liste option:selected' ).val()); |
} |
}; |
|
WidgetsSaisiesCommun.prototype.initEvtsConnection = function() { |
const lthis = this; |
|
this.chargerStatutSSO(); |
$( '#utilisateur-connecte .volet-toggle, #profil-utilisateur a, #deconnexion a' ).on( 'click', function( event ) { |
if( $( this ).hasClass( 'volet-toggle' ) ) { |
event.preventDefault(); |
} |
$( '#utilisateur-connecte .volet-menu' ).toggleClass( 'hidden' ); |
}); |
$( '#deconnexion a' ).on( 'click', function( event ) { |
event.preventDefault(); |
lthis.deconnecterUtilisateur(); |
}); |
if ( !this.isASL ) { |
$( '#bouton-anonyme' ).on( 'click', function( event ) { |
lthis.arreter( event ); |
$( this ).css({ |
'background-color': 'rgba(0, 159, 184, 0.7)', |
'color': '#fff' |
}); |
$( '#identite' ).removeClass( 'hidden' ); |
$( '#courriel' ).focus(); |
}); |
if ( '' === $( '#nom-complet').text() ) { |
$( '#courriel' ).on( 'blur', this.requeterIdentiteCourriel.bind( this ) ); |
$( '#courriel' ).on( 'keypress', this.testerLancementRequeteIdentite.bind( this ) ); |
} |
$( '#prenom' ).on( 'change', function() { |
lthis.formaterPrenom(); |
lthis.reduireVoletIdentite(); |
}); |
$( '#nom' ).on( 'change', function() { |
lthis.formaterNom(); |
lthis.reduireVoletIdentite(); |
}); |
$( '#courriel_confirmation' ).on( 'paste', this.bloquerCopierCollerCourriel.bind( this ) ); |
$( '#courriel_confirmation' ).on( 'blur', this.reduireVoletIdentite.bind( this ) ); |
$( '#courriel_confirmation' ).on( 'keypress', function( event ) { |
if ( valOk( event.which, true, 13 ) ) { |
lthis.reduireVoletIdentite(); |
event.preventDefault(); |
event.stopPropagation(); |
} |
}); |
} |
}; |
|
WidgetsSaisiesCommun.prototype.initEvtsFichier = function() { |
const lthis = this; |
|
const fileInputFonctionne = () => { |
const ua = navigator.userAgent; |
|
if ( |
ua.match( /(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0))|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|(Kindle\/(1.0|2.0|2.5|3.0))/ ) || |
ua.match( /\swv\).+(chrome)\/([\w\.]+)/i ) |
) { |
return false; |
} |
|
const elem = document.createElement( 'input' ); |
|
elem.type = 'file'; |
|
return !elem.disabled; |
} |
|
if ( fileInputFonctionne() ) { |
// Sur téléchargement image |
$( '#fichier' ).on( 'change', function ( event ) { |
lthis.arreter ( event ); |
|
const options = { |
beforeSend : function ( jqXHR, settings ) { |
$( '#miniatures' ).on( 'click', '.effacer-miniature', function() { |
jqXHR.abort(jqXHR); |
}); |
}, |
success: lthis.afficherMiniature.bind( lthis ), // post-submit callback |
dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type) |
resetForm: true // reset the form after successful submit |
}, |
imgCheminTmp = $( '#fichier' ).val(), |
parts = imgCheminTmp.split( '\\' ), |
nomImage = parts[ parts.length - 1 ], |
formatImgOk = lthis.verifierFormat( nomImage ), |
imgNonDupliquee = lthis.verifierDuplication( nomImage ); |
|
if( formatImgOk && imgNonDupliquee ) { |
$( '#form-upload' ).ajaxSubmit( options ); |
$( '#miniatures' ).append( |
'<div class="miniature mr-3 miniature-chargement loading">'+ |
'<img class="miniature-img chargement-img" alt="chargement" src="' + lthis.chargementImageIconeUrl + '" style="min-height:100%;"/>'+ |
'<a class="effacer-miniature">Supprimer</a>'+ |
'</div>' |
); |
$( '#ajouter-obs' ).addClass( 'hidden' ); |
$( '#message-chargement' ).removeClass( 'hidden' ); |
} else { |
$( '#form-upload' )[0].reset(); |
if ( !formatImgOk ) { |
utils.activerModale( lthis.msgTraduction( 'format-non-supporte' ) + ' : ' + $( '#fichier' ).attr( 'accept' ) ); |
} |
if ( !imgNonDupliquee ) { |
utils.activerModale( lthis.msgTraduction( 'image-deja-chargee' ) ); |
} |
} |
return false; |
}); |
$( 'body' ).on( 'click', '.effacer-miniature', function() { |
$( this ).parent().remove(); |
if ( !valOk( $('.miniature-chargement' ) ) ) { |
$( '#ajouter-obs' ).removeClass( 'hidden' ); |
$( '#message-chargement' ).addClass( 'hidden' ); |
} |
}); |
} else { |
$( '#form-upload' ) |
.addClass( 'hidden' ) |
.after( |
'<div class="alert alert-info" role="alert">'+ |
this.msgTraduction( 'upload-non-suppote' )+ |
'</div>' |
); |
} |
|
}; |
|
WidgetsSaisiesCommun.prototype.initEvtsGeoloc = function( isFormArbre = false ) { |
const lthis = this; |
|
let ancre = '-observation', |
complementSelecteur = ''; |
|
if ( isFormArbre ) { |
ancre = '-arbres'; |
complementSelecteur = ancre; |
} |
|
const $mapEl = $( '#tb-geolocation' + complementSelecteur ); |
|
if( valOk( $mapEl ) ) { |
const typeLocalisation = $mapEl.data( 'typeLocalisation' ) || 'point'; |
|
this.geoloc.init(complementSelecteur); |
$( '#coord' ).toggleClass( 'hidden', 'point' !== typeLocalisation ); |
// evenement location |
$mapEl.on( 'location' , this.locationHandler.bind( this ) ); |
|
if ( 'rue' === typeLocalisation ) { |
$( '#geoloc-label .help-button' ).on( 'click' , function () { |
let label = 'Aide : Géolocaliser une rue ou un linéaire', |
modaleContent = '<img id="modale-aide-img" src="' + URL_HELP_GEOLOC_POLYLINE + '" style="" alt="photo-aide-geoloc" />'; |
|
utils.activerModale( label, modaleContent, [] ); |
}); |
} |
} |
}; |
|
WidgetsSaisiesCommun.prototype.initEvtsObs = function() { |
const lthis = this; |
|
$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) ); |
$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) ); |
$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) { |
event.preventDefault(); |
lthis.defilerMiniatures( $( this ) ); |
}); |
$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) { |
event.preventDefault(); |
lthis.defilerMiniatures( $( this ) ); |
}); |
// mécanisme de suppression d'une obs |
$( '#liste-obs' ).on( 'click', '.supprimer-obs', function() { |
const buttons = [ |
{ |
label : 'Annuler', |
class : 'btn-secondary', |
dismiss : true |
}, |
{ |
label : 'Confirmer', |
class : 'btn-success confirmer', |
dismiss : true |
} |
]; |
// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM) |
const that = this, |
suppObs = lthis.supprimerObs.bind( lthis ); |
|
utils.activerModale( lthis.msgTraduction( 'confirmation-suppression' ), '', buttons ); |
$( '.confirmer' ).on( 'click', function() { |
suppObs( that ); |
}); |
}); |
$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) ); |
}; |
|
// Alertes et aides |
WidgetsSaisiesCommun.prototype.initEvtsAlertes = function() { |
$( '.alert .close' ).on( 'click', this.fermerPanneauAlert ); |
$( '#btn-aide' ).on( 'click', this.basculerAffichageAide ); |
}; |
|
/** |
* Interroge le SSO pour connaître le statut de l'utilisateur, et change le menu |
* à droite de la barre en fonction |
*/ |
WidgetsSaisiesCommun.prototype.chargerStatutSSO = function() { |
const lthis = this; |
let urlAuth = this.urlBaseAuth + '/identite'; |
|
if( 'local' !== this.mode ) { |
this.connexion( urlAuth, true ); |
if( this.isASL) { |
$( '#connexion' ).on( 'click', function( event ) { |
event.preventDefault(); |
if( $( '#utilisateur-connecte' ).hasClass( 'hidden' ) || !valOk( $( '#nom-complet' ).text() ) ) { |
const login = $( '#courriel' ).val(), |
mdp = $( '#mdp' ).val(); |
|
if ( valOk( login ) && valOk( mdp ) ) { |
urlAuth = lthis.urlBaseAuth + '/connexion?login=' + login + '&password=' + mdp; |
lthis.connexion( urlAuth, true ); |
} else { |
utils.activerModale( lthis.msgTraduction( 'non-connexion' ) ); |
} |
} |
}); |
} |
} else { |
urlAuth = this.urlWidgets + 'modules/saisie/test-token.json'; |
// Pour tester le bouton de connexion : |
// $( '#connexion' ).on( 'click', function( event ) { |
// event.preventDefault(); |
// lthis.connexion( urlAuth, true ); |
this.connexion( urlAuth, true ); |
// }); |
} |
}; |
|
/** |
* Déconnecte l'utilisateur du SSO |
*/ |
WidgetsSaisiesCommun.prototype.deconnecterUtilisateur = function() { |
const urlAuth = this.urlBaseAuth + '/deconnexion'; |
|
if( 'local' === this.mode ) { |
this.definirUtilisateur(); |
window.location.reload(); |
return; |
} |
this.connexion( urlAuth, false ); |
}; |
|
WidgetsSaisiesCommun.prototype.connexion = function( urlAuth, connexionOnOff ) { |
const lthis = this; |
|
$.ajax({ |
url: urlAuth, |
type: "GET", |
dataType: 'json', |
xhrFields: { |
withCredentials: true |
} |
}) |
.done( function( data ) { |
if( connexionOnOff ) { |
// connecté |
lthis.definirUtilisateur( data.token ); |
} else { |
lthis.definirUtilisateur(); |
window.location.reload(); |
} |
}) |
.fail( function( error ) { |
// @TODO gérer l'affichage de l'erreur, mais pas facile à placer |
// dans l'interface actuelle sans que ce soit moche |
//afficherErreurServeur(); |
}); |
}; |
|
WidgetsSaisiesCommun.prototype.definirUtilisateur = function( jeton ) { |
const thisObj = this; |
let idUtilisateur = '', |
prenom = '', |
nom = '', |
nomComplet = '', |
courriel = ''; |
|
// affichage |
if ( undefined !== jeton ) { |
// décodage jeton |
this.infosUtilisateur = this.decoderJeton( jeton ); |
idUtilisateur = this.infosUtilisateur.id; |
prenom = this.infosUtilisateur.prenom; |
nom = this.infosUtilisateur.nom; |
nomComplet = this.infosUtilisateur.intitule; |
courriel = this.infosUtilisateur.sub; |
$( '#courriel' ).attr( 'disabled', 'disabled' ); |
$( '#utilisateur-connecte, #identite' ).removeClass( 'hidden' ); |
if ( this.isASL ) { |
$( '#bloc-connexion' ).addClass( 'hidden' ); |
} else { |
$( '#courriel_confirmation' ).attr( 'disabled', 'disabled' ); |
$( '#prenom' ).attr( 'disabled', 'disabled' ); |
$( '#nom' ).attr( 'disabled', 'disabled' ); |
$( '#bouton-connexion, #creation-compte' ).addClass( 'hidden' ); |
$( '#zone-courriel, #zone-prenom-nom' ).addClass( 'hidden' ); |
$( '#date-releve' ).focus(); |
} |
} |
$( '#id_utilisateur' ).val( idUtilisateur ); |
$( '#prenom' ).val( prenom ); |
$( '#nom' ).val( nom ); |
$( '#nom-complet' ).html( nomComplet ); |
$( '#courriel' ).val( courriel ); |
$( '#profil-utilisateur a' ).attr( 'href', this.urlSiteTb() + 'membres/me' ); |
if ( this.isASL ) { |
if ( valOk( idUtilisateur ) ) { |
const nomSquelette = $( '#charger-form' ).data( 'load' ) || 'arbres'; |
this.chargerForm( nomSquelette, thisObj ); |
} |
} else { |
$( '.warning' ).remove(); |
$( '#courriel_confirmation' ).val( courriel ); |
} |
}; |
|
/** |
* Décodage à l'arrache d'un jeton JWT, ATTENTION CONSIDERE QUE LE |
* JETON EST VALIDE, ne pas décoder n'importe quoi - pas trouvé de lib simple |
*/ |
WidgetsSaisiesCommun.prototype.decoderJeton = function( jeton ) { |
const parts = jeton.split( '.' ); |
let payload = parts[1]; |
|
payload = this.b64d( payload ); |
payload = JSON.parse( payload, true ); |
|
return payload; |
}; |
|
/** |
* Décodage "url-safe" des chaînes base64 retournées par le SSO (lib jwt) |
*/ |
WidgetsSaisiesCommun.prototype.b64d = function( input ) { |
const remainder = input.length % 4; |
|
if ( 0 !== remainder ) { |
const padlen = 4 - remainder; |
|
for ( let i = 0; i < padlen; i++ ) { |
input += '='; |
} |
} |
input = input.replace( '-', '+' ); |
input = input.replace( '_', '/' ); |
|
return atob( input ); |
}; |
|
WidgetsSaisiesCommun.prototype.urlSiteTb = function() { |
const urlPart = ( 'test' === this.mode ) ? '/test/' : '/'; |
|
return this.urlRacine + urlPart; |
}; |
|
// uniquement utilisé si taxon-liste ******************************************/ |
/** |
* Affiche/Cache le champ taxon |
*/ |
WidgetsSaisiesCommun.prototype.surChangementTaxonListe = function() { |
if ( valOk( $( '#taxon-liste' ).val() ) ) { |
if ( 'autre' !== $( '#taxon-liste' ).val() ) { |
$( '#taxon-input-groupe' ) |
.hide( 200, function () { |
$( this ).addClass( 'hidden' ).show(); |
}) |
.find( '#taxon-autre' ).val( '' ); |
} else { |
$( '#taxon-input-groupe' ) |
.hide() |
.removeClass( 'hidden' ) |
.show(200) |
.find( '#taxon-autre' ) |
.on( 'change', function() { |
if( !valOk( $( '#taxon-autre' ).data( 'numNomSel' ) ) ) { |
$( '#taxon' ).val( $( '#taxon-autre' ).val() ) |
.data( 'value', $( '#taxon-autre' ).val() ) |
.removeData([ |
'numNomSel', |
'nomRet', |
'numNomRet', |
'nt', |
'famille' |
]); |
} |
$( '#taxon' ).trigger( 'change' ); |
}); |
} |
} |
}; |
|
WidgetsSaisiesCommun.prototype.surChangementValeurTaxon = function() { |
if( valOk( $( '#taxon-liste' ).val() ) ) { |
if( 'autre' === $( '#taxon-liste' ).val() ) { |
this.ajouterAutocompletionNoms(); |
} else { |
const optionRetenue = $( '#taxon-liste' ).find( 'option[value="' + $( '#taxon-liste' ).val() + '"]' ); |
|
$( '#taxon' ).val( $( '#taxon-liste' ).val() ) |
.data( 'value', $( '#taxon-liste' ).val() ) |
.data( 'numNomSel', optionRetenue.data( 'num-nom-sel' ) ) |
.data( 'nomRet', optionRetenue.data( 'nom-ret' ) ) |
.data( 'numNomRet', optionRetenue.data( 'num-nom-ret' ) ) |
.data( 'nt', optionRetenue.data( 'nt' ) ) |
.data( 'famille', optionRetenue.data( 'famille' ) ); |
$( '#taxon' ).trigger( 'change' ); |
|
const numNomSel = $( '#taxon' ).data( 'numNomSel' ); |
|
// Si l'espèce est mal déterminée la certitude est "à déterminer" |
if( !valOk( numNomSel ) ) { |
$( '#certitude' ).find( 'option' ).each( function() { |
if ( $( this ).hasClass( 'aDeterminer' ) ) { |
$( this ).attr( 'selected', true ); |
} else { |
$( this ).attr( 'selected', false ); |
} |
}); |
} |
} |
} |
}; |
|
// Autocompletion taxons ******************************************************/ |
/** |
* Initialise l'autocompletion taxons |
*/ |
WidgetsSaisiesCommun.prototype.ajouterAutocompletionNoms = function() { |
const lthis = this; |
let taxonSelecteur = '#taxon'; |
|
if ( valOk( $( '#taxon-liste' ).val(), true, 'autre' ) ) { |
taxonSelecteur += '-autre'; |
} |
$( taxonSelecteur ).autocomplete({ |
source: function( requete, add ) { |
// la variable de requête doit être vidée car sinon le parametre "term" est ajouté |
requete = ''; |
if( valOk( $( '#referentiel' ).val(), false, 'autre' ) ) { |
const url = lthis.getUrlAutocompletionNomsSci(); |
|
$( '#taxon-autocomplete-label' ).addClass( 'loading' ); |
$.getJSON( url, requete, function( data ) { |
let suggestions = lthis.traiterRetourNomsSci( data ); |
add( suggestions ); |
}) |
.fail( function() { |
$( '#certitude' ).find( 'option' ).each( function() { |
if ( $( this ).hasClass( 'aDeterminer' ) ) { |
$( this ).prop( 'selected', true ); |
} else { |
$( this ).prop( 'selected', false ); |
} |
}); |
}) |
.always(function() { |
$( '#taxon-autocomplete-label' ).removeClass( 'loading' ); |
}); |
} |
}, |
html: true |
}); |
$( taxonSelecteur ).on( 'autocompleteselect', this.surAutocompletionTaxon ); |
}; |
|
WidgetsSaisiesCommun.prototype.getUrlAutocompletionNomsSci = function() { |
let taxonSelecteur = '#taxon'; |
|
if ( valOk( $( '#taxon-liste' ).val(), true, 'autre' ) ) { |
taxonSelecteur += '-autre'; |
} |
const mots = $( taxonSelecteur ).val(), |
url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel ); |
|
return url.replace( '{masque}', mots ); |
}; |
|
/** |
* Objet taxons pour autocompletion en fonction de la recherche |
*/ |
WidgetsSaisiesCommun.prototype.traiterRetourNomsSci = function( data ) { |
let taxonSelecteur = '#taxon', |
suggestions = []; |
|
if ( valOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) { |
taxonSelecteur += '-autre'; |
} |
if ( undefined != data.resultat ) { |
$.each( data.resultat, function( i, val ) { |
val.nn = i; |
|
const nom = { |
label : '', |
value : '', |
nt : 0, |
nomSel : '', |
nomSelComplet : '', |
numNomSel : 0, |
nomRet : '', |
numNomRet : 0, |
famille : '', |
retenu : false |
}; |
if ( suggestions.length >= this.autocompletionElementsNbre ) { |
nom.label = '...'; |
nom.value = $( taxonSelecteur ).val(); |
suggestions.push( nom ); |
return false; |
} else { |
nom.label = val.nom_sci_complet; |
nom.value = val.nom_sci_complet; |
nom.nt = val.num_taxonomique; |
nom.nomSel = val.nom_sci; |
nom.nomSelComplet = val.nom_sci_complet; |
nom.numNomSel = val.nn; |
nom.nomRet = val.nom_retenu_complet; |
nom.numNomRet = val['nom_retenu.id']; |
nom.famille = val.famille; |
// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ? |
// en tout cas c'est harmonisé avec le CeL |
nom.retenu = ( 'true' == val.retenu ); |
suggestions.push( nom ); |
} |
}); |
} |
return suggestions; |
}; |
|
/** |
* charge les données dans #taxon |
*/ |
WidgetsSaisiesCommun.prototype.surAutocompletionTaxon = function( event, ui ) { |
if ( valOk( ui ) ) { |
$( '#taxon' ).val( ui.item.value ); |
$( '#taxon' ).data( 'value', ui.item.value ) |
.data( 'numNomSel', ui.item.numNomSel ) |
.data( 'nomRet', ui.item.nomRet ) |
.data( 'numNomRet', ui.item.numNomRet ) |
.data( 'nt', ui.item.nt ) |
.data( 'famille', ui.item.famille ); |
if ( ui.item.retenu ) { |
$( '#taxon' ).addClass( 'ns-retenu' ); |
} else { |
$( '#taxon' ).removeClass( 'ns-retenu' ); |
} |
// Si l'espèce est mal déterminée la certitude est "à déterminer" |
if( !valOk( $( '#taxon' ).data( 'numNomSel' ) ) ) { |
$( '#certitude' ).find( 'option' ).each( function() { |
if ( $( this ).hasClass( 'aDeterminer' ) ) { |
$( this ).attr( 'selected', true ); |
} else { |
$( this ).attr( 'selected', false ); |
} |
}); |
} |
} |
$( '#taxon' ).change(); |
}; |
|
// Fichier Images *************************************************************/ |
/** |
* Affiche temporairement (formulaire) |
* la miniature d'une image ajoutée à l'obs |
*/ |
WidgetsSaisiesCommun.prototype.afficherMiniature = function( reponse ) { |
const message = $( 'message', reponse ).text(), |
$blocMiniature = $( '#miniatures .miniature.loading').first(); |
|
if( valOk( $blocMiniature ) ) { |
if ( valOk( message ) ) { |
$( '.miniature-msg' ).text( message ); |
$blocMiniature.remove(); |
|
} else { |
this.creerWidgetMiniature( reponse, $blocMiniature ); |
$blocMiniature.removeClass('loading'); |
} |
if ( !valOk( $( '.miniature-chargement' ) ) ) { |
$( '#ajouter-obs' ).removeClass( 'hidden' ); |
$( '#message-chargement' ).addClass( 'hidden' ); |
} |
$( '#ajouter-obs' ).removeAttr( 'disabled' ); |
} |
}; |
|
/** |
* Crée la miniature temporaire (formulaire) + bouton pour l'effacer |
*/ |
WidgetsSaisiesCommun.prototype.creerWidgetMiniature = function( reponse, $blocMiniature ) { |
const miniatureUrl = $( 'miniature-url', reponse ).text(), |
imgNom = $( 'image-nom', reponse ).text(); |
|
$blocMiniature.removeClass( 'miniature-chargement' ); |
$( '.miniature-img', $blocMiniature ) |
.removeClass( 'chargement-img' ) |
.attr({ |
'alt' : imgNom, |
'src' : miniatureUrl |
}); |
}; |
|
/** |
* Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg |
*/ |
WidgetsSaisiesCommun.prototype.verifierFormat = function( nomImage ) { |
const parts = nomImage.split( '.' ), |
extension = parts[ parts.length - 1 ]; |
|
return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() ); |
}; |
|
/** |
* Check les miniatures déjà téléchargées |
* renvoie false si le même nom est rencontré 2 fois |
* renvoie true sinon |
*/ |
WidgetsSaisiesCommun.prototype.verifierDuplication = function( nomImage ) { |
const lthis = this; |
let thisSrcParts = [], |
thisNomImage = '', |
nonDupliquee = true; |
|
nomImage = nomImage.toLowerCase(); |
|
$( 'img.miniature-img,img.miniature' ).each( function() { |
// vérification avec alt de l'image |
if ( valOk ( $( this ).attr( 'alt' ) ) && $( this ).attr('alt' ).toLowerCase() === nomImage ) { |
nonDupliquee = false; |
|
return false;// Pas besoin de poursuivre la boucle |
} else { // sinon vérifie aussi avec l'adresse (src) de l'image |
thisSrcParts = $( this ).attr( 'src' ).split( '/' ); |
thisNomImage = thisSrcParts[ thisSrcParts.length - 1 ].replace( '_min', '' ).toLowerCase(); |
if ( valOk( thisNomImage, true, nomImage ) ) { |
nonDupliquee = false; |
|
return false; |
} |
} |
}); |
|
return nonDupliquee; |
}; |
|
/** |
* Efface une miniature (formulaire) |
*/ |
WidgetsSaisiesCommun.prototype.supprimerMiniature = function( miniature ) { |
miniature.parents( '.miniature' ).remove(); |
}; |
|
// Geoloc *********************************************************************/ |
WidgetsSaisiesCommun.prototype.transfererCarto = function( donnees ) { |
const typeLocalisation = donnees.typeLocalisation || 'point', |
suffixe = valOk( donnees.suffixe ) ? '-' + donnees.suffixe : '', |
formSuffixe = '-arbres' === suffixe ? suffixe : '', |
$cartoRemplacee = donnees.cartoRemplacee || $( '#tb-geolocation' ), |
latitude = donnees.latitude || '', |
longitude = donnees.longitude || '', |
zoomInit = donnees.zoomInit || '', |
$mapContainer = $cartoRemplacee.closest('#map-container'); |
|
if ( valOk( formSuffixe ) || 'point' !== typeLocalisation ) { |
$mapContainer.siblings('#tb-places-zone').remove(); |
} |
|
if ( 'tb-geolocation' + suffixe !== $cartoRemplacee.attr('id') ) { |
$mapContainer.remove(); |
$( '#geoloc' + suffixe ).append( |
'<div id="map-container">'+ |
'<div'+ |
' id="tb-geolocation' + suffixe +'"'+ |
' data-layer="' + donnees.layer + '"'+ |
' data-zoom="' + zoomInit + '"'+ |
' data-type-localisation="' + typeLocalisation + '"'+ |
' data-form-suffix="' + formSuffixe + '"'+ |
' style="height: 400px;width: 100%"'+ |
'>'+ |
'</div>'+ |
'</div>' |
); |
|
$( '#coord' ).toggleClass( 'hidden', 'point' !== typeLocalisation ); |
|
if( valOk( this.geoloc.map ) ) { |
this.geoloc.closeMap(); |
} |
|
this.initEvtsGeoloc( true ); |
} else { |
this.geoloc.reSetDrawControl(); |
} |
|
this.geoloc.setMapCoordinates({'lat': latitude, 'lng': longitude}); |
}; |
|
// Ajouter Obs ****************************************************************/ |
/** |
* Ajoute une observation à la liste des obs à transmettre |
* (résumé obs) |
*/ |
WidgetsSaisiesCommun.prototype.ajouterObs = function() { |
if ( this.isASL ) { |
this.scrollFormTop( '#zone-' + this.sujet ); |
} |
// Fermeture automatique des dialogue de transmission de données |
// @WARNING TEST |
$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' ); |
if ( this.validerForm() ) { |
this.masquerPanneau( '#dialogue-form-invalide' ); |
this.obsNbre += 1; |
if ( this.isASL && 'arbres' === this.sujet ) { |
this.numArbre += 1; |
// bouton info de cet arbre et affichage numéro du prochain arbre |
this.lienArbreInfo( this.numArbre ); |
$( '#arbre-nb' ).text( this.numArbre + 1 ); |
} |
$( '.obs-nbre' ).text( this.obsNbre ); |
$( '.obs-nbre' ).triggerHandler( 'changement' ); |
//formatage des données |
const obsData = this.formaterFormObsData(); |
|
this.afficherObs( obsData ); |
this.stockerObsData( obsData ); |
if ( this.isASL && 'arbres' === this.sujet ) { |
const arbreData = obsData.sujet; |
|
// Ajout de donnée utiles puis stockage dans input hidden "releve-data" |
arbreData['date_rue_commune'] = obsData.releve.date + obsData.releve.rue + obsData.releve['commune-nom']; |
arbreData['id_observation'] = 0; |
this.releveDatas = $.parseJSON( $( '#releve-data' ).val() ); |
this.releveDatas[this.obsNbre] = arbreData; |
$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) ); |
this.modeArbresBasculerActivation( false ); |
} else { |
this.reinitialiserForm(); |
} |
$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre ); |
$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) ); |
} else { |
this.afficherPanneau( '#dialogue-form-invalide' ); |
} |
}; |
|
/** |
* Formatage des données du formulaire pour stockage et envoi |
*/ |
WidgetsSaisiesCommun.prototype.formaterFormObsData = function() { |
const obsData = { obsNum : this.obsNbre, sujet : {}}, |
numNomSel = $( '#taxon' ).data( 'numNomSel' ), |
nomSel = $( '#taxon' ).val(), |
nomRet = $( '#taxon' ).data( 'nomRet' ), |
numNomRet = $( '#taxon' ).data( 'numNomRet' ), |
numTaxon = $( '#taxon' ).data( 'nt' ), |
famille = $( '#taxon' ).data( 'famille' ), |
referentiel = ( valOk( numNomSel ) ) ? this.nomSciReferentiel : 'autre', |
certitude = ( valOk( numNomSel ) ) ? $( '#certitude' ).val() : 'à determiner'; |
let imgB64 = [], |
imgNom = [], |
date = '', |
notes = '', |
pays = '', |
communeNom = '', |
communeInsee = '', |
geometry = '', |
latitude = '', |
longitude = '', |
altitude = '', |
obsEtendue = []; |
|
if( !this.isASL ) { |
notes = $( '#notes' ).val().trim() || ''; |
pays = $( '#pays' ).val() || ''; |
communeNom = $( '#commune-nom' ).val(); |
communeInsee = $( '#commune-insee' ).val() || ''; |
geometry = $( '#geometry' ).val(); |
latitude = $( '#latitude' ).val(); |
longitude = $( '#longitude' ).val(); |
altitude = $( '#altitude' ).val(); |
obsEtendue = this.getObsChpSpecifiques(); |
date = this.fournirDate( $('#date_releve').val()); |
} else { |
const miniatureImg = []; |
|
notes = $( '#commentaire' ).val() || ''; |
if ( 'arbres' === this.sujet ) { |
// Dans ce cas cette fonction doit renvoyer des données au même format que l'input hidden "releve-data" |
// car les données dans stockerObsData provenir soit de cette fonction soit de l'input |
$( '.miniature-img' ).each( function() { |
if ( $( this ).hasClass( 'b64' ) ) { |
imgB64 = $( this ).attr( 'src' ) || ''; |
} else if ( $( this ).hasClass( 'b64-canvas' ) ) { |
imgB64 = $( this ).data( 'b64' ) || ''; |
} |
miniatureImg.push({ |
'nom' : $( this ).attr( 'alt' ), |
'src' : $( this ).attr( 'src' ), |
'b64' : imgB64 |
}); |
}); |
obsData.sujet = { |
'num-arbre' : this.numArbre, |
taxon : { |
'numNomSel' : numNomSel, |
'value' : nomSel, |
'nomRet' : nomRet, |
'numNomRet' : numNomRet, |
'nt' : numTaxon, |
'famille' : famille |
}, |
'referentiel' : referentiel, |
'certitude' : certitude, |
'rue-arbres' : ( $( '#rue-arbres' ).val() ) ? $('#rue-arbres').val() : '', |
'geometry-arbres' : $( '#geometry-arbres' ).val(), |
'latitude-arbres' : $( '#latitude-arbres' ).val(), |
'longitude-arbres' : $( '#longitude-arbres' ).val(), |
'altitude-arbres' : $( '#altitude-arbres' ).val(), |
'circonference' : $( '#circonference' ).val(), |
'com-arbres' : ( $( '#com-arbres' ).val() ) ? $('#com-arbres').val() : '', |
'miniature-img' : miniatureImg |
}; |
obsData.releve = { |
'date' : this.fournirDate( $( '#releve-date' ).val() ), |
'rue' : $( '#rue' ).val(), |
'geometry-releve' : $( '#geometry-releve' ).val(), |
'latitude-releve' : $( '#latitude-releve' ).val(), |
'longitude-releve' : $( '#longitude-releve' ).val(), |
'altitude-releve' : $( '#altitude-releve' ).val(), |
'commune-nom' : $( '#commune-nom' ).val(), |
'commune-insee' : ( $( '#commune-insee' ).val() ) ? $('#commune-insee').val() : '', |
'pays' : ( $( '#pays' ).val() ) ? $('#pays').val() : '', |
'commentaires' : notes |
}; |
if ( 'tb_lichensgo' !== this.projet ) { |
obsData.sujet['surface-pied'] = $( '#surface-pied' ).val(); |
obsData.sujet['equipement-pied-arbre'] = $( '#equipement-pied-arbre' ).val(); |
obsData.sujet['tassement'] = $( '#tassement' ).val() || ''; |
obsData.sujet['dejections'] = $( '#dejections input:checked' ).val() || ''; |
obsData.releve['zone-pietonne'] = $( '#zone-pietonne input:checked' ).val(); |
obsData.releve['pres-lampadaires'] = $( '#pres-lampadaires input:checked' ).val() || ''; |
} |
if ( 'tb_streets' !== this.projet ) { |
const faceOmbre = []; |
|
$( '#face-ombre input' ).each( function() { |
if( $( this ).is( ':checked' ) ) { |
faceOmbre.push( $( this ).val() ); |
} |
}); |
obsData.sujet['face-ombre'] = faceOmbre; |
} |
} else { |
this.releveDatas = $.parseJSON( $( '#releve-data' ).val() ); |
obsData.numArbre = $( '#choisir-arbre' ).val(); |
pays = this.releveDatas[0].pays || ''; |
communeNom = this.releveDatas[0]['commune-nom']; |
communeInsee = this.releveDatas[0]['commune-insee'] || ''; |
geometry = this.releveDatas[obsData.numArbre]['geometry-arbres']; |
latitude = this.releveDatas[obsData.numArbre]['latitude-arbres']; |
longitude = this.releveDatas[obsData.numArbre]['longitude-arbres']; |
altitude = this.releveDatas[obsData.numArbre]['altitude-arbres']; |
obsEtendue = this.getObsChpSpecifiques( obsData.numArbre ); |
date = this.fournirDate( $( '#obs-date' ).val() ); |
} |
} |
if ( !this.isASL || 'arbres' !== this.sujet ) { |
imgNom = this.getNomsImgsOriginales(); |
imgB64 = this.getB64ImgsOriginales(); |
|
obsData.sujet = { |
'num_nom_sel' : numNomSel, |
'nom_sel' : nomSel, |
'nom_ret' : nomRet, |
'num_nom_ret' : numNomRet, |
'num_taxon' : numTaxon, |
'famille' : famille, |
'referentiel' : referentiel, |
'certitude' : certitude, |
'date' : date, |
'notes' : notes, |
'pays' : pays, |
'commune_nom' : communeNom, |
'commune_code_insee' : communeInsee, |
'geometry' : geometry, |
'latitude' : latitude, |
'longitude' : longitude, |
'altitude' : altitude, |
//Ajout des champs images |
'image_nom' : imgNom, |
'image_b64' : imgB64, |
// Ajout des champs étendus de l'obs |
'obs_etendue' : obsEtendue |
}; |
if ( !this.isASL ) { |
obsData.sujet['lieudit'] = $( '#lieudit' ).val() || ''; |
obsData.sujet['station'] = $( '#station' ).val() || ''; |
obsData.sujet['milieu'] = $( '#milieu' ).val() || ''; |
} |
} |
return obsData; |
}; |
|
/** |
* Affiche une observation dans la liste des observations à transmettre |
*/ |
WidgetsSaisiesCommun.prototype.afficherObs = function( datasObs ) { |
// différences html liéees au responsive |
let responsivDiff1 = '', |
responsivDiff2 = '', |
responsivDiff3 = '', |
responsivDiff4 = '', |
responsivDiff5 = '', |
responsivDiff6 = ''; |
if ( window.matchMedia( '(min-width: 576px)' ).matches ) { |
/* La largeur minimum de l'affichage est 600 px inclus */ |
responsivDiff1 = ' droite'; |
responsivDiff2 = '<div></div>'; |
responsivDiff3 = '<div class="row">'; |
responsivDiff4 = ( !this.isASL ) ? ' col-md-2 col-sm-4' : ' col-md-4 col-sm-5'; |
responsivDiff5 = ( !this.isASL ) ? ' class="col-md-9 col-sm-7"' : ' class="col-md-7 col-sm-6"'; |
responsivDiff6 = '</div>'; |
} |
|
const obsNum = datasObs.obsNum; |
let numNomSel = datasObs.sujet['num_nom_sel'] || '', |
taxon = '', |
miniatures = '', |
notes = '', |
commentaires = '', |
date = '', |
geometry = '', |
latitude = '', |
longitude = '', |
coordonnees = '', |
commune = '', |
lieuObs = '', |
inseeCommune = '', |
inseeCommuneText = '', |
referentiel = '', |
nn = '', |
lieudit = '', |
station = '', |
milieu = '', |
certitude = '', |
numArbre = '', |
obsArbre = ''; |
|
if ( !this.isASL ) { |
geometry = datasObs.sujet['geometry'] || ''; |
latitude = datasObs.sujet['latitude'] || ''; |
longitude = datasObs.sujet['longitude'] || ''; |
inseeCommune = datasObs.sujet['commune_code_insee'] || ''; |
commune = datasObs.sujet['commune_nom'] || ''; |
if ( valOk( inseeCommune ) ) { |
inseeCommuneText = '(INSEE Commune:' + inseeCommune + ') '; |
} |
if ( valOk( numNomSel ) ) { |
referentiel = '<span class="referentiel-obs">' + '[' + datasObs.sujet['referentiel'] + ']' + '</span>'; |
} |
if ( valOk( datasObs.sujet['lieudit'] ) ) { |
lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + datasObs.sujet['lieudit'] + ' '; |
} |
if ( valOk( datasObs.sujet['station'] ) ) { |
station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + datasObs.sujet['station'] + ' '; |
} |
if ( valOk( datasObs.sujet['milieu'] ) ) { |
milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + datasObs.sujet['milieu'] + ' '; |
} |
nn = this.ajouterNumNomSel( numNomSel ); |
} else { |
certitude = ' [certitude : ' + datasObs.sujet.certitude + ']'; |
if ( 'arbres' === this.sujet ) { |
numArbre = datasObs.sujet['num-arbre']; |
numNomSel = datasObs.sujet.taxon.numNomSel; |
taxon = datasObs.sujet.taxon.value; |
miniatures = this.ajouterImgMiniatureAuTransfert(datasObs.sujet['miniature-img'] ); |
notes = datasObs.sujet['com-arbres'] || ''; |
geometry = datasObs.sujet['geometry-arbres']; |
latitude = datasObs.sujet['latitude-arbres']; |
longitude = datasObs.sujet['longitude-arbres']; |
// s'assurer que la date est au bon format |
date = this.fournirDate( datasObs.releve.date ); |
commune = datasObs.releve['commune-nom'] || ''; |
} else { |
numArbre = datasObs.numArbre; |
} |
obsArbre = '<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>'; |
} |
if ( !this.isASL || 'arbres' !== this.sujet ) { |
taxon = datasObs.sujet['nom_sel']; |
miniatures = this.ajouterImgMiniatureAuTransfert(); |
notes = datasObs.sujet['notes'] || ''; |
date = this.fournirDate( datasObs.sujet.date ); |
} |
if( !this.isASL || 'arbres' === this.sujet ) { |
if ( valOk( commune ) ) { |
lieuObs = ' ' + this.msgTraduction( 'lieu-obs' ) + ' ' + '<span class="commune">' + commune + '</span> '; |
} |
if ( valOk( latitude ) && valOk( longitude ) ) { |
coordonnees = '[' + latitude + ' / ' + longitude + ']'; |
} |
} |
if ( valOk( notes ) ) { |
commentaires = |
this.msgTraduction( 'commentaires' ) + |
' : <span>'+ |
notes + |
'</span> '; |
} |
// html du bloc résumé de l'obs |
$( '#liste-obs' ).prepend( |
'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+ |
'<div '+ |
'class="obs-action" '+ |
'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+ |
'>'+ |
'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.msgTraduction( 'obs-numero' ) + obsNum + '">'+ |
'<i class="far fa-trash-alt"></i>'+ |
'</button>'+ |
responsivDiff2 + |
'</div> '+ |
responsivDiff3 + |
'<div class="thumbnail' + responsivDiff4 + '">'+ |
miniatures + |
'</div>'+ |
'<div' + responsivDiff5 + '>'+ |
'<ul class="unstyled">'+ |
'<li>'+ |
// isASL |
obsArbre + |
// toujours |
'<span class="nom-sci">' + taxon + '</span> '+ |
// !isASL |
nn + |
referentiel + |
// isASL |
certitude + |
// !this.isASL || 'arbres' === this.sujet |
lieuObs + |
// !isASL |
inseeCommuneText + |
// !this.isASL || 'arbres' === this.sujet |
coordonnees + |
// toujours |
' ' + this.msgTraduction( 'obs-le' ) + ' '+ |
'<span class="date">' + date + '</span>'+ |
'</li>'+ |
'<li>'+ |
// !isASL |
lieudit + |
station + |
milieu + |
'</li>'+ |
'<li>'+ |
// valOk( notes ) |
commentaires + |
'</li>'+ |
'</ul>'+ |
'</div>'+ |
responsivDiff6+ |
'</div>' |
); |
|
$( '#zone-liste-obs' ).removeClass( 'hidden' ); |
}; |
|
/** |
* Ajoute une boîte de miniatures avec défilement des images, |
* pour une obs de la liste des obs à transmettre |
*/ |
WidgetsSaisiesCommun.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages = undefined ) { |
const lthis = this; |
let html = |
'<div class="defilement-miniatures">'+ |
'<figure class="centre">'+ |
'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+ |
'</figure>'+ |
'</div>', |
miniatures = '', |
centre = '', |
defilVisible = '', |
length = 0; |
|
if ( valOk( chargerImages ) || valOk( $( '#miniatures img' ) ) ) { |
if ( valOk( chargerImages ) ) { |
$.each( chargerImages, function( i, value ) { |
let imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee', |
css = ( valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature', |
src = value.src, |
alt = value.nom, |
miniature = '<img class="' + css + ' ' + imgVisible + ' align-middle" alt="' + alt + '"src="' + src + '" width="80%" />'; |
|
miniatures += miniature; |
}); |
length = chargerImages.length; |
} else { |
let premiere = true; |
$( '#miniatures img' ).each( function() { |
let imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee'; |
|
premiere = false; |
|
let css = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature', |
src = $( this ).attr( 'src' ), |
alt = $( this ).attr( 'alt' ), |
miniature = '<img class="' + css + ' ' + imgVisible + ' align-middle" alt="' + alt + '"src="' + src + '" width="80%" />'; |
|
miniatures += miniature; |
}); |
length = $( '#miniatures img' ).length; |
} |
if ( 1 === length ) { |
centre = 'centre'; |
defilVisible = ' defilement-miniatures-cache'; |
} |
html = |
'<div class="defilement-miniatures">'+ |
'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+ |
'<figure class="' + centre + '">'+ |
miniatures+ |
'</figure>'+ |
'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+ |
'</div>'; |
} |
|
return html; |
}; |
|
/** |
* Construit le html à afficher pour le numNom |
*/ |
WidgetsSaisiesCommun.prototype.ajouterNumNomSel = function( numNomSel ) { |
let nn = '<span class="nn">[nn' + numNomSel + ']</span>'; |
|
if ( !valOk( numNomSel ) ) { |
nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>'; |
} |
|
return nn; |
}; |
|
/** |
* Stocke des données d'obs à envoyer à la bdd |
*/ |
WidgetsSaisiesCommun.prototype.stockerObsData = function( obsDatas ) { |
if ( this.isASL && 'arbres' === this.sujet ) { |
// Dans ce cas la fonction formaterFormObsData renvoie des données au même format que l'input hidden "releve-data" |
// car les données peuvent provenir soit de la formaterFormObsData soit de cet input |
const lthis = this; |
// si releve dupliqué on ne stocke pas l'image : |
let stockerImg = valOk( obsDatas.sujet['miniature-img'] ), |
imgNom = [], |
imgB64 = []; |
|
// Si on a bien un 'miniature-img' dans les données |
if( stockerImg ) { |
$.each( obsDatas.sujet['miniature-img'], function( i, obj ) { |
if( obj.hasOwnProperty( 'id' ) ) { |
stockerImg = false; |
} |
return stockerImg; |
}); |
} |
// Si les miniatures ne sont pas déjà stockées (résultat de la loop précédente) |
if( stockerImg ) { |
$.each( obsDatas.sujet['miniature-img'] , function( i, obj ) { |
if( valOk( obj.nom ) ) { |
imgNom.push( obj.nom ); |
} |
if( valOk( obj['b64'] ) ) { |
imgB64.push( obj['b64'] ); |
} |
}); |
} else { |
imgNom = lthis.getNomsImgsOriginales(); |
imgB64 = lthis.getB64ImgsOriginales(); |
} |
// Stockage en data des données d'obs à transmettre |
$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, { |
'num_nom_sel' : obsDatas.sujet.taxon.numNomSel, |
'nom_sel' : obsDatas.sujet.taxon.value, |
'nom_ret' : obsDatas.sujet.taxon.nomRet, |
'num_nom_ret' : obsDatas.sujet.taxon.numNomRet, |
'num_taxon' : obsDatas.sujet.taxon.nt, |
'famille' : obsDatas.sujet.taxon.famille, |
'referentiel' : obsDatas.sujet.referentiel, |
'certitude' : obsDatas.sujet.certitude, |
// La date provenant de input "releve-data" n'est pas au bon format |
'date' : this.fournirDate( obsDatas.releve.date ), |
'notes' : obsDatas.releve.commentaires.trim(), |
'pays' : obsDatas.releve.pays, |
'commune_nom' : obsDatas.releve['commune-nom'], |
'commune_code_insee' : obsDatas.releve['commune-insee'], |
'geometry' : obsDatas.sujet['geometry-arbres'], |
'latitude' : obsDatas.sujet['latitude-arbres'], |
'longitude' : obsDatas.sujet['longitude-arbres'], |
'altitude' : obsDatas.sujet['altitude-arbres'], |
'image_nom' : imgNom, |
'image_b64' : imgB64, |
// Ajout des champs étendus de l'obs |
'obs_etendue' : lthis.getObsChpSpecifiques( obsDatas ) |
}); |
} else { |
// Stockage en data des données d'obs à transmettre |
$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, obsDatas.sujet ); |
} |
}; |
|
WidgetsSaisiesCommun.prototype.getNomsImgsOriginales = function() { |
const noms = []; |
|
$( '.miniature-img' ).each( function() { |
noms.push( $( this ).attr( 'alt' ) ); |
}); |
|
return noms; |
}; |
|
WidgetsSaisiesCommun.prototype.getB64ImgsOriginales = function() { |
const b64 = []; |
|
$( '.miniature-img' ).each( function() { |
if ( $( this ).hasClass( 'b64' ) ) { |
b64.push( $( this ).attr( 'src' ) ); |
} else if ( $( this ).hasClass( 'b64-canvas' ) ) { |
b64.push( $( this ).data( 'b64' ) ); |
} |
}); |
|
return b64; |
}; |
|
/** |
* Efface toutes les miniatures (formulaire) |
*/ |
WidgetsSaisiesCommun.prototype.supprimerMiniatures = function() { |
if ( !this.isASL ) { |
// Déconnection MutationObserver miniatures |
// Sinon on a une erreur avant la création d'une nouvelle obs |
this.observer.disconnect(); |
$( '#miniatures' ).empty(); |
// Validation miniatures reprend à 0 pour une nouvelle obs |
this.surPresenceAbsenceMiniature(); |
} else { |
$( '#miniatures' ).empty(); |
} |
$( '#miniature-msg' ).empty(); |
}; |
|
WidgetsSaisiesCommun.prototype.surChangementNbreObs = function() { |
if ( 0 === this.obsNbre ) { |
$( '#transmettre-obs' ).attr( 'disabled', 'disabled' ); |
} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) { |
$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' ); |
} else if ( this.obsNbre >= this.obsMaxNbre ) { |
$( '#ajouter-obs' ).attr( 'disabled', 'disabled' ); |
this.afficherPanneau( '#dialogue-bloquer-creer-obs' ); |
} |
if ( this.isASL && 'arbres' === this.sujet ) { |
if ( 0 <= this.obsNbre && this.obsNbre < this.obsMaxNbre ) { |
$( '#bloc-form-arbres' ).removeClass( 'hidden' ); |
} else { |
$( '#bloc-form-arbres' ).addClass( 'hidden' ); |
} |
} |
}; |
|
WidgetsSaisiesCommun.prototype.defilerMiniatures = function( element ) { |
const miniatureSelectionne = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' ); |
|
miniatureSelectionne.removeClass( 'miniature-selectionnee' ); |
miniatureSelectionne.addClass( 'miniature-cachee' ); |
|
let miniatureAffichee = miniatureSelectionne; |
|
if( element.hasClass( 'defilement-miniatures-gauche' ) ) { |
if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) { |
miniatureAffichee = miniatureSelectionne.prev( '.miniature' ); |
} else { |
miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last(); |
} |
} else { |
if( 0 !== miniatureSelectionne.next('.miniature').length ) { |
miniatureAffichee = miniatureSelectionne.next( '.miniature' ); |
} else { |
miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first(); |
} |
} |
miniatureAffichee.addClass( 'miniature-selectionnee' ); |
miniatureAffichee.removeClass( 'miniature-cachee' ); |
}; |
|
WidgetsSaisiesCommun.prototype.supprimerObs = function( selector ) { |
let obsId = $( selector ).val(); |
|
// Problème avec IE 6 et 7 |
if ( 'Supprimer' === obsId ) { |
obsId = $( selector ).attr( 'title' ); |
} |
this.supprimerObsParId( obsId ); |
}; |
|
/** |
* Supprime l'obs et les data de l'obs |
* et remonte les suivantes d'un cran |
*/ |
WidgetsSaisiesCommun.prototype.supprimerObsParId = function( obsId, transmission = false ) { |
let arbreExId = 0, |
arbreId = 0; |
|
if ( this.isASL && 'arbres' === this.sujet ) { |
if ( !transmission ) { |
this.releveData = $.parseJSON( $( '#releve-data' ).val() ); |
this.releveData.splice( obsId , 1 ); |
$( '#releve-data' ).val( JSON.stringify( this.releveData ) ); |
} |
$( '#arbre-info-' + ( this.numArbre ) ).remove(); |
$( '#arbre-nb' ).text( this.numArbre ); |
this.numArbre -= 1; |
if ( 1 > this.numArbre ) { |
$( '#bloc-info-arbres-title' ).addClass( 'hidden' ); |
} |
} |
this.obsNbre -= 1; |
$( '.obs-nbre' ).text( this.obsNbre ); |
$( '.obs-nbre' ).triggerHandler( 'changement' ); |
$( '.obs' + obsId ).remove(); |
obsId = parseInt(obsId); |
|
if ( !transmission ) { |
const listObsData = $( '#liste-obs' ).data(); |
let exId = 0, |
indexObs = '', |
exIndexOb = ''; |
|
for ( let id = obsId; id <= ( this.obsNbre + 1 ); id++ ) { |
exId = parseInt(id) + 1; |
indexObs = 'obsId' + id; |
exIndexObs = 'obsId' + exId; |
$( '#liste-obs' ).removeData( indexObs ); |
$( '#obs' + exId ) |
.attr( 'id', 'obs' + id ) |
.removeClass( 'obs' + exId ) |
.addClass( 'obs' + id ) |
.find( '.supprimer-obs' ) |
.attr( 'title', 'Observation n°' + id ) |
.val( id ); |
|
if ( this.isASL && 'arbres' === this.sujet ) { |
arbreExId = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) ); |
arbreId = arbreExId - 1; |
$( '#obs-arbre-' + arbreExId ) |
.attr( 'id', 'obs-arbre-' + arbreId ) |
.attr( 'data-arbre', arbreId ) |
.data( 'arbre', arbreId ) |
.text( 'Arbre ' + arbreId ); |
// modification du numero d'arbre dans les obs étendues |
if ( valOk( listObsData[exIndexObs] ) ) { |
$.each( listObsData[exIndexObs].obs_etendue, function( i, obsE ) { |
if ('num_arbre' === obsE.cle ) { |
listObsData[exIndexObs].obs_etendue[i].valeur = arbreId; |
return false; |
} |
}); |
} |
} |
|
// Mise à jour des données à transmettre |
if ( valOk( listObsData[exIndexObs] ) ) { |
$( '#liste-obs' ).data( indexObs, listObsData[exIndexObs] ); |
} |
if ( parseInt( id ) !== this.obsNbre ) { |
id = parseInt(id); |
} |
} |
} else { |
$( '#liste-obs' ).removeData( 'obsId' + obsId ); |
} |
}; |
|
WidgetsSaisiesCommun.prototype.transmettreObs = function() { |
const lthis = this, |
observations = $( '#liste-obs' ).data(); |
|
if ( this.debug ) { |
console.dir( observations ); |
} |
if ( !valOk( typeof observations, true, 'object' ) ) { |
this.afficherPanneau( '#dialogue-zero-obs' ); |
} else { |
this.nbObsEnCours = 1; |
this.nbObsTransmises = 0; |
this.totalObsATransmettre = $.map( observations, function( n, i ) { |
return i; |
}).length; |
this.depilerObsPourEnvoi(); |
} |
|
return false; |
}; |
|
WidgetsSaisiesCommun.prototype.depilerObsPourEnvoi = function() { |
const observations = $( '#liste-obs' ).data(); |
// la boucle est factice car on utilise un tableau |
// dont on a besoin de n'extraire que le premier élément |
// or javascript n'a pas de méthode cross browsers pour extraire les clés |
// TODO: utiliser var.keys quand ça sera plus répandu |
// ou bien utiliser un vrai tableau et pas un objet |
for ( let obsNum in observations ) { |
const obsATransmettre = { |
'id_projet' : this.idProjet, |
'projet' : this.projet, |
'tag-obs' : this.tagObs, |
'tag-img' : this.tagImg |
}, |
utilisateur = { |
id_utilisateur : $( '#id_utilisateur' ).val(), |
prenom : $( '#prenom' ).val(), |
nom : $( '#nom' ).val(), |
courriel : $( '#courriel' ).val() |
}; |
|
obsATransmettre['utilisateur'] = utilisateur; |
obsATransmettre[obsNum] = observations[obsNum]; |
|
const idObsNumerique = obsNum.replace( 'obsId', '' ); |
|
if( '' !== idObsNumerique ) { |
this.envoyerObsAuCel( idObsNumerique, obsATransmettre ); |
} |
break; |
} |
}; |
|
WidgetsSaisiesCommun.prototype.envoyerObsAuCel = function( idObs, observation ) { |
const lthis = this; |
let erreurMsg = ''; |
|
$.ajax({ |
url : lthis.serviceSaisieUrl, |
type : 'POST', |
data : observation, |
dataType : 'json', |
beforeSend : function() { |
$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' ); |
$( '.alert-txt' ).empty(); |
$( '.alert-txt .msg-erreur,.alert-txt .msg-debug' ).remove(); |
$( '#chargement' ).removeClass( 'hidden' ); |
}, |
success : function( transfertDatas, textStatus, jqXHR ) { |
if( lthis.isASL && 'arbres' === lthis.sujet ) { |
// actualisation de id_observation dans '#releve-data' |
lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id ); |
} |
// mise à jour du nombre d'obs à transmettre |
// et suppression de l'obs |
lthis.supprimerObsParId( idObs, true ); |
lthis.nbObsEnCours++; |
// mise à jour du statut |
lthis.mettreAJourProgression(); |
if( 0 < lthis.obsNbre ) { |
// dépilement de la suivante |
lthis.depilerObsPourEnvoi(); |
} |
}, |
statusCode : { |
500 : function( jqXHR, textStatus, errorThrown ) { |
erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n'; |
} |
}, |
error : function( jqXHR, textStatus, errorThrown ) { |
erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n'; |
try { |
reponse = jQuery.parseJSON( jqXHR.responseText ); |
if ( null !== reponse ) { |
$.each( reponse, function( cle, valeur ) { |
erreurMsg += valeur + '\n'; |
}); |
} |
} catch( e ) { |
erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText; |
} |
}, |
complete : function( jqXHR, textStatus ) { |
const debugMsg = lthis.extraireEnteteDebug( jqXHR ); |
|
if ( '' !== erreurMsg ) { |
if ( lthis.debug ) { |
$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' ); |
$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' ); |
} |
const hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+ |
'subject=Dysfonctionnement du widget de saisie ' + lthis.tagsMotsCles+ |
'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg; |
|
$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' ); |
$( '#dialogue-obs-transaction-ko .alert-txt' ).append( |
$( '#tpl-transmission-ko' ).clone() |
.find( '.courriel-erreur' ) |
.attr( 'href', hrefCourriel ) |
.end() |
.html() |
); |
$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' ); |
$( '#chargement' ).addClass( 'hidden' ); |
lthis.initialiserBarreProgression; |
} else { |
if ( lthis.debug ) { |
$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' ); |
} |
if( 0 === lthis.obsNbre ) { |
setTimeout( function() { |
if ( lthis.isASL ) { |
if ( 'arbres' === lthis.sujet ) { |
if ( 'tb_streets' !== lthis.projet ) { |
$( '#bouton-saisir-lichens' ).removeClass( 'hidden' ); |
} |
if ( 'tb_lichensgo' !== lthis.projet ) { |
$( '#bouton-saisir-plantes' ).removeClass( 'hidden' ); |
} |
} else { |
$( '#bouton-poursuivre' ).removeClass( 'hidden' ); |
} |
$( '#bloc-controle-liste-obs,#bloc-gauche' ).addClass( 'hidden' ); |
} |
$( '#chargement' ).addClass( 'hidden' ); |
$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() ); |
$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' ); |
}, 1500 ); |
} |
} |
} |
}); |
}; |
|
WidgetsSaisiesCommun.prototype.mettreAJourProgression = function() { |
this.nbObsTransmises++; |
|
const pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100; |
|
$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises ); |
$( '#barre-progression-upload' ).css( 'width', pct + '%' ); |
$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) ); |
if( 0 === this.obsNbre ) { |
$( '.progress' ).removeClass( 'active' ); |
$( '.progress' ).removeClass( 'progress-bar-striped' ); |
} |
}; |
|
WidgetsSaisiesCommun.prototype.initialiserBarreProgression = function() { |
$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 ); |
$( '#barre-progression-upload' ).css( 'width', '0%' ); |
$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) ); |
$( '.progress' ).addClass( 'active' ); |
$( '.progress' ).addClass( 'progress-bar-striped' ); |
}; |
|
// Form Validator *************************************************************/ |
WidgetsSaisiesCommun.prototype.configurerFormValidator = function() { |
const lthis = this; |
|
$.validator.addMethod( |
'dateCel', |
function ( value, element ) { |
return ( valOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) ); |
}, |
lthis.msgTraduction( 'date-incomplete' ) |
); |
$.validator.addMethod( |
'userEmailOk', |
function ( value, element ) { |
return ( valOk( value ) ); |
}, |
'' |
); |
$.validator.addMethod( |
'minMaxOk', |
function ( value, element, param ) { |
$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message; |
return lthis.validerMinMax( element ).cond; |
}, |
$.validator.messages.minMaxOk |
); |
$.validator.addMethod( |
'listFields', |
function ( value, element ) { |
return ( valOk( value ) ); |
}, |
'' |
); |
$.extend( $.validator.defaults, { |
errorElement: 'span', |
errorPlacement: function( error, element ) { |
if ( lthis.isASL && 'arbres' === lthis.sujet && ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) ) { |
error.appendTo( element.closest( '.list' ) ); |
} else { |
element.after( error ); |
} |
}, |
onfocusout: function( element ) { |
if( valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) { |
if ( $( element ).valid() ) { |
$( element ).closest( '.control-group' ).removeClass( 'error' ); |
} else { |
$( element ).closest( '.control-group' ).addClass( 'error' ); |
} |
} |
}, |
onkeyup : function( element ) { |
if( valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) { |
if ( $( element ).valid() ) { |
$( element ).closest( '.control-group' ).removeClass( 'error' ); |
} else { |
$( element ).closest( '.control-group' ).addClass( 'error' ); |
} |
} |
}, |
unhighlight: function( element ) { |
if( valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) { |
$( element ).closest( '.control-group' ).removeClass( 'error' ); |
} |
}, |
highlight: function( element ) { |
$( element ).closest( '.control-group' ).addClass( 'error' ); |
} |
}); |
}; |
|
// Formatage date *************************************************************/ |
WidgetsSaisiesCommun.prototype.fournirDate = function( dateObs ) { |
if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) { |
|
return dateObs; |
} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) { |
const dateArray = dateObs.split( '-' ); |
|
return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0] |
} else { |
console.dir( 'erreur date : ' + dateObs ) |
} |
}; |
|
// scroll vers le formulaire |
WidgetsSaisiesCommun.prototype.scrollFormTop = function( scrollSelecteur, focus = '' ) { |
$( 'html, body' ).stop().animate({ |
scrollTop: $( scrollSelecteur ).offset().top |
}, 300, function() { |
if ( valOk( focus ) ) { |
$( focus ).focus(); |
} else { |
return; |
} |
}); |
}; |
|
// Controle des panneaux d'infos **********************************************/ |
|
WidgetsSaisiesCommun.prototype.afficherPanneau = function( selecteur ) { |
$( selecteur ) |
.removeClass( 'hidden' ) |
.hide() |
.show( 600 ) |
.delay( this.dureeMessage ) |
.hide( 600 ); |
this.scrollFormTop( selecteur ); |
}; |
|
WidgetsSaisiesCommun.prototype.masquerPanneau = function( selecteur ) { |
$( selecteur ).addClass( 'hidden' ); |
}; |
|
WidgetsSaisiesCommun.prototype.fermerPanneauAlert = function() { |
$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' ); |
}; |
|
/** |
* Si la langue est définie dans this.langue, et si des messages sont définis |
* dans this.msgs, tente de trouver le message dont la clé est [cle] dans la |
* langue en cours. S'il n'est pas trouvé, retourne la version française (par |
* défaut); si celle-ci n'exite pas, retourne "N/A". |
*/ |
WidgetsSaisiesCommun.prototype.msgTraduction = function( cle ) { |
let msg = 'N/A'; |
|
if ( utils.msgs ) { |
if ( this.langue in utils.msgs && cle in utils.msgs[this.langue] ) { |
msg = utils.msgs[this.langue][cle]; |
} else if ( cle in utils.msgs['fr'] ) { |
msg = utils.msgs['fr'][cle]; |
} |
} |
return msg; |
}; |
|
/** |
* Stope l'évènement courant quand on clique sur un lien. |
* Utile pour Chrome, Safari... |
*/ |
WidgetsSaisiesCommun.prototype.arreter = function( event ) { |
if ( event.stopPropagation ) { |
event.stopPropagation(); |
} |
if ( event.preventDefault ) { |
event.preventDefault(); |
} |
|
return false; |
}; |
|
/** |
* Extrait les données de désinsectisation d'une requête AJAX de jQuery |
* @param jqXHR |
* @returns {String} |
*/ |
WidgetsSaisiesCommun.prototype.extraireEnteteDebug = function( jqXHR ) { |
let msgDebug = ''; |
|
if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) { |
const debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ); |
|
if ( null !== debugInfos ) { |
$.each( debugInfos, function( cle, valeur ) { |
msgDebug += valeur + '\n'; |
}); |
} |
} |
|
return msgDebug; |
}; |
|
|
WidgetsSaisiesCommun.prototype.confirmerSortie = function() { |
$( window ).off( 'beforeunload' ).on( 'beforeunload', function( event ) { |
if ( !event ) { |
event = window.event; |
} |
return false; |
}); |
}; |
|
// Lib hors objet |
|
/* |
* jQuery UI Autocomplete HTML Extension |
* |
* Copyright 2010, Scott González (http://scottgonzalez.com) |
* Dual licensed under the MIT or GPL Version 2 licenses. |
* |
* http://github.com/scottgonzalez/jquery-ui-extensions |
* |
* Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides |
*/ |
( function( $ ) { |
const proto = $.ui.autocomplete.prototype, |
initSource = proto._initSource; |
|
WidgetsSaisiesCommun.prototype.filter = function( array, term ) { |
const matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' ); |
|
return $.grep( array, function( value ) { |
|
return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() ); |
}); |
} |
$.extend( proto, { |
_initSource: function() { |
if ( this.options.html && $.isArray( this.options.source ) ) { |
this.source = function( request, response ) { |
response( filter( this.options.source, request.term ) ); |
}; |
} else { |
initSource.call( this ); |
} |
}, |
_renderItem: function( ul, item) { |
if ( item.retenu ) { |
item.label = '<strong>' + item.label + '</strong>'; |
} |
|
return $( '<li></li>' ) |
.data( 'item.autocomplete', item ) |
.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) ) |
.appendTo( ul ); |
} |
}); |
})( jQuery ); |