Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retire JQuery de content-helps.js #6116

Merged
merged 9 commits into from
Jul 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,7 @@ function jsPackages() {
function js() {
return gulp.src([
// Used by other scripts, must be first
'assets/js/modal.js',
'assets/js/tooltips.js',
'assets/js/common/*.js',
// All the scripts
'assets/js/*.js'
], { base: '.', sourcemaps: true })
Expand Down
55 changes: 55 additions & 0 deletions assets/js/common/ajax.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* ZDS ajax library
* This library was created to reduce code duplication when we use ajax and ease up the JQuery removal
* We use fetch API
*/
class ZDSAjax {
constructor() {
this._crsf = document.querySelector("input[name='csrfmiddlewaretoken']").getAttribute('value')
}

get(url, dataCallback, errorCallback = (error) => console.error(error)) {
const headers = new Headers()
headers.append('Accept', 'application/json')
headers.append('X-CSRFToken', this._crsf)
headers.append('X-REQUESTED-WITH', 'XMLHttpRequest')
const init = {
method: 'GET',
headers: headers,
mode: 'cors',
cache: 'default'
}
fetch(new Request(url, init), init).then(response => {
if (response.ok) {
return Promise.resolve(response.json())
}
throw response.error()
}).then(dataCallback).catch(errorCallback)
}

put(url, jsonOrFormData, dataCallback, errorCallback) {
return this._sendRequestWithData(jsonOrFormData, 'PUT', url, dataCallback, errorCallback)
}

post(url, jsonOrFormData, dataCallback, errorCallback) {
return this._sendRequestWithData(jsonOrFormData, 'POST', url, dataCallback, errorCallback)
}

_sendRequestWithData(jsonOrFormData, method, url, dataCallback, errorCallback) {
const headers = new Headers()
headers.append('Accept', 'application/json')
headers.append('X-CSRFToken', this._crsf)
headers.append('X-REQUESTED-WITH', 'XMLHttpRequest')
const init = {
method: method,
headers: headers,
mode: 'cors',
cache: 'default',
body: jsonOrFormData
}
return fetch(url, init).then(response => {
return Promise.resolve(response.json())
}).then(dataCallback).catch(errorCallback)
}
}
window.ajax = new ZDSAjax()
File renamed without changes.
File renamed without changes.
49 changes: 23 additions & 26 deletions assets/js/content-helps.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,34 @@
(function($) {
function changeHelpButtonState($helpButton, state) {
const helpButtonClasses = $helpButton[0].classList
(function(ajax) {
function changeHelpButtonState(helpButton, state) {
const helpButtonClasses = helpButton.classList

helpButtonClasses.toggle('selected', state)
helpButtonClasses.toggle('ico-after', state)
helpButtonClasses.toggle('tick', state)
helpButtonClasses.toggle('green', state)

$helpButton.attr('data-activated', state.toString())
$helpButton.blur()
helpButton.setAttribute('data-activated', state.toString())

$helpButton.parent().find('input[name="activated"]').val((!state).toString())
helpButton.parentNode.querySelector('input[name="activated"]')
.setAttribute('value', (!state).toString())
}

$('.help-toggle').click((e) => {
e.preventDefault()
document.querySelectorAll('.help-toggle')
.forEach((element) => element.addEventListener('click', e => {
const current = e.target

const $current = $(e.target)
const $form = $current.parent()
const data = $form.serialize()
const newActivation = $current.attr('data-activated') !== 'true'
const form = current.parentElement
const data = new FormData(form)
const newActivation = current.getAttribute('data-activated') !== 'true'
// Change status before request for instant feeling.
// Will be changed back on error.
changeHelpButtonState(current, newActivation)
e.preventDefault()
e.stopPropagation()

// Change status before request for instant feeling.
// Will be changed back on error.
// This update the form so serialize must be called before/
changeHelpButtonState($current, newActivation)

$.ajax($form.attr('action'), {
method: 'POST',
data,
success: resultData => changeHelpButtonState($current,
resultData.help_wanted),
error: () => changeHelpButtonState($current, !newActivation)
})
})
})(jQuery)
ajax.post(form.getAttribute('action'), data,
(result) => changeHelpButtonState(current, result.help_wanted),
() => changeHelpButtonState(current, !newActivation)
)
}))
})(window.ajax)
28 changes: 28 additions & 0 deletions doc/source/front-end/helpers-js.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,31 @@ Cette fonction retourne un objet ``Karma`` qui permet de manipuler et mettre à
``$("#p42").karma().vote("like")`` permet par exemple d'ajouter (ou de l'enlever si l'utilisateur a déjà voté) un +1 sur le post n°42 sur la page.

L'API complète de l'objet ``Karma`` est documentée dans le fichier ``assets/js/karma.js``.


``window.ajax``
===============

Afin de faciliter la migration du code JS du site pour ne plus utiliser JQuery,
nous avons créé un helper ajax qui vous permettra de manipuler rapidement les
requêtes vers les fonctionnalités du site qui prennent un formulaire ou du json en entrée
et retournent un json en réponse.

Cet objet est défini dans ``assets/js/common/ajax.js``. Il vous permet d'appeler nativement
les méthodes get/post/put et sera vu par django comme un appel ajax.
Vous pourrez à chaque fois définir une méthode à appeler en cas de succès de la **communication**
(c'est-à-dire si la requête a pu être envoyée au serveur et obtenir un retour au format json, peu importe son code de retour)
et en cas d'erreur.

La première méthode prend en argument un objet issu de la désérialisation du JSON.

Exemple:

.. sourcecode:: javascript

const form = document.querySelector('.monFormulaire')
const data = new FormData(form)
ajax.post(form.getAttribute('action'), data,
result) => maFonctionEnCasDeSucces(result.une_valeur_retournee_par_le_serveur),
() => maFonctionEnCasDEchec()
)