Loading

Yvan

  1. const app = {
  2.     init: () => document.addEventListener('deviceready', app.onDeviceReady, false),
  3.     onDeviceReady: () => {
  4.         drupalClient.util.init();
  5.         app.showElement('.appbody');
  6.         document.addEventListener('backbutton', drupalClient.util.backButton, false);
  7.     },
  8.     showElement: (selector) => document.querySelector(selector).classList.remove('hidden')
  9. };
  10. app.init();
  11.  
  12. const menuItems = Array.from(document.querySelectorAll('div.menu > .item'));
  13. const formBlocks = Array.from(document.querySelectorAll('.form-block'));
  14.  
  15. const drupalClient = {};
  16. drupalClient.config = {}
  17. drupalClient.storage = {db: {}};
  18. drupalClient.util = {};
  19. drupalClient.web = {}
  20. drupalClient.debug = {};
  21.  
  22. drupalClient.config.host = `http://treasury.ddns.net`;
  23. drupalClient.config.url = `${drupalClient.config.host}/senelection`;
  24. drupalClient.config.user = '';
  25. drupalClient.config.pass = '';
  26. drupalClient.config.dbName = {
  27.     pollingStations: 'pollingStations',
  28.     pendingFormData: 'pendingFormData',
  29. }
  30.  
  31. drupalClient.storage.openDatabase = database => new Promise((resolve, reject) => drupalClient.storage.db[database] = window.sqlitePlugin.openDatabase({name: `${database}.db`, location: 'default', createFromLocation: 1}, resolve, reject));
  32. drupalClient.storage.runQuery = (database, query, params = []) => new Promise((resolve, reject) => {
  33.     const doQuery = () => drupalClient.storage.db[database].executeSql(query, params, resolve, reject);
  34.     if (!drupalClient.storage.db[database]) {
  35.         drupalClient.storage.openDatabase(database).then(() => doQuery());
  36.     } else {
  37.         doQuery();
  38.     }
  39. });
  40.  
  41. // rxjs.from(xy_promise)
  42.  
  43. drupalClient.storage.storeAuthData = (loginData) => {
  44.     localStorage.setItem('authData', JSON.stringify(loginData));
  45. }
  46.  
  47. drupalClient.storage.getAuthData = () => {
  48.     try {
  49.         return JSON.parse(localStorage.getItem('authData'));
  50.     } catch (e) {
  51.         return {};
  52.     }
  53. }
  54.  
  55. drupalClient.storage.clearAuthData = () => localStorage.removeItem('authData');
  56.  
  57. drupalClient.debug.getPendingRow = id => {
  58.     drupalClient.storage.runQuery(
  59.         drupalClient.config.dbName.pendingFormData,
  60.         `SELECT * FROM pending_form_data WHERE id = ?`,
  61.         [id]
  62.     ).then(result => console.log(result.rows.item(0))).catch(console.warn);
  63.     return true;
  64. }
  65.  
  66. drupalClient.web.request = (url, method = 'GET', body = null, headers = {}) => {
  67.     headers = Object.assign({ 'Content-Type': 'application/json' }, headers);
  68.     return new Promise((resolve, reject) => {
  69.         const xhr = new XMLHttpRequest();
  70.         xhr.open(method, url, true);
  71.         Object.keys(headers).map(key => xhr.setRequestHeader(key, headers[key]));
  72.         xhr.onload = () => resolve({
  73.             response: xhr.responseText,
  74.             code: xhr.status,
  75.         });
  76.         xhr.onerror = () => reject({
  77.             response: xhr.statusText,
  78.             code: xhr.status,
  79.         });
  80.         xhr.send(body);
  81.     });
  82. }
  83.  
  84. drupalClient.web.getCsrfToken = () => {
  85.     return drupalClient.web.request(`${drupalClient.config.url}/rest/session/token`);
  86. }
  87.  
  88. drupalClient.web.checkLogin = () => {
  89.     return drupalClient.web.request(`${drupalClient.config.url}/user/login_status?_format=json`);
  90. }
  91.  
  92. drupalClient.web.register = (name, email, password) => {
  93.     return drupalClient.web.request(`${drupalClient.config.url}/user/register?_format=json`, 'POST', JSON.stringify({
  94.         name: { value: name },
  95.         mail: { value: email },
  96.         field_mobile_number: { value: mobile_number },
  97.         pass: { value: password },
  98.     }));
  99. }
  100.  
  101. drupalClient.web.login = (userName, password) => {
  102.     return drupalClient.web.request(`${drupalClient.config.url}/user/login?_format=json`, 'POST', JSON.stringify({
  103.         name: userName,
  104.         pass: password,
  105.     }));
  106. }
  107.  
  108. drupalClient.web.logout = () => {
  109.     authData = drupalClient.storage.getAuthData();
  110.     headers = {
  111.         'X-CSRF-Token': authData.csrf_token,
  112.     }
  113.     return drupalClient.web.request(
  114.         `${drupalClient.config.url}/user/logout?_format=json&token=${authData.logout_token}`,
  115.         'GET', null, headers
  116.     );
  117. }
  118.  
  119. drupalClient.web.postFile = (id, fileSource, nodeType) => new Promise((resolve, reject) => {
  120.     window.resolveLocalFileSystemURL(fileSource, fileEntry => {
  121.         fileEntry.file(file => {
  122.             // for some reason xhr refuses to work with File(), so we pass the binary string to it
  123.             const fileReader = new Promise((resolve, reject) => {
  124.                 reader = new FileReader();
  125.                 reader.onload = () => resolve(reader.result);
  126.                 reader.onerror = () => {
  127.                     reader.abort();
  128.                     reject(reader.error);
  129.                 };
  130.                 reader.readAsArrayBuffer(file);
  131.             });
  132.             fileReader.then(fileContents => {
  133.                 // filename: nodetype_fieldname_timestamp
  134.                 const currentTime = Date.now();
  135.                 authData = drupalClient.storage.getAuthData();
  136.                 const headers = {
  137.                     'X-CSRF-Token': authData.csrf_token,
  138.                     'Content-Type': 'application/octet-stream',
  139.                     'Content-Disposition': `file; filename="${nodeType}_image_${currentTime}.jpg"`
  140.                 };
  141.                 drupalClient.web.request(
  142.                     `${drupalClient.config.url}/file/upload/node/${nodeType}/field_image?_format=json`,
  143.                     'POST', fileContents, headers
  144.                 ).then(imageUploadResult => resolve({
  145.                     id: id,
  146.                     response: imageUploadResult.response,
  147.                 })).catch(() => reject({
  148.                     id: id,
  149.                     response: false,
  150.                 }));
  151.             }).catch(reject);
  152.         });
  153.     }, err => console.log(err));
  154. });
  155.  
  156. drupalClient.web.handleSubmitResponseCode = code => {
  157.     drupalClient.util.hideDimmer();
  158.     if (code > 399) {
  159.         drupalClient.util.alert('Erreur', 'Impossible de télécharger les données du formulaire.');
  160.     } else {
  161.         drupalClient.util.alert('Succès', 'Téléchargement complet.');
  162.         drupalClient.util.resetForms();
  163.         drupalClient.util.showMenu();
  164.     }
  165. }
  166.  
  167. drupalClient.util.getSavedPendingNode = (id, sent = 0) => {
  168.     const query = `SELECT * FROM pending_form_data WHERE id = ? AND sent=?`;
  169.     return new Promise(resolve => drupalClient.storage.runQuery(drupalClient.config.dbName.pendingFormData, query, [id, sent]).then(resolve));
  170. }
  171.  
  172. drupalClient.util.getSavedPendingAttachments = (id, sent = 0) => {
  173.     const query = `SELECT * FROM pending_form_data WHERE parent_id = ? AND sent=?`;
  174.     return new Promise(resolve => drupalClient.storage.runQuery(drupalClient.config.dbName.pendingFormData, query, [id, sent]).then(resolve));
  175. }
  176.  
  177. // 14 drupalClient.util.postSavedNode(22, a => console.log(a));
  178. drupalClient.util.postSavedNode = id => {
  179.     const postNode = nodeData => new Promise((resolve, reject) => {
  180.         authData = drupalClient.storage.getAuthData();
  181.         const headers = {
  182.             'Content-Type': 'application/hal+json',
  183.             'X-CSRF-Token': authData.csrf_token,
  184.         }
  185.         drupalClient.web.request(
  186.             `${drupalClient.config.url}/node?_format=hal_json`,
  187.             'POST', JSON.stringify(nodeData), headers
  188.         ).then(result => resolve(result.code)).catch(result => reject(result.code));
  189.     });
  190.  
  191.     return new Promise((resolve, reject) => {
  192.         // get all unsaved attachments, post them, update database
  193.         drupalClient.util.getSavedPendingAttachments(id).then(dbResult => {
  194.             if (dbResult.rows.length) {
  195.                 // there are attachments, post them one by one, then post the node
  196.                 const attachments = [];
  197.                 for(var i = 0; i < dbResult.rows.length; i++) {
  198.                     attachments.push(drupalClient.web.postFile(dbResult.rows.item(i).id, dbResult.rows.item(i).data, dbResult.rows.item(i).node_type).catch(() => false));
  199.                 }
  200.                 Promise.all(attachments).then(values => {
  201.                     // values is an array of resolved promise results
  202.                     const hasFailed = values.some(value => value.response === false);
  203.                     if (hasFailed) {
  204.                         const savedQuery = `UPDATE pending_form_data SET sent=1 WHERE ID IN (?)`;
  205.                         const failedQuery = `UPDATE pending_form_data SET fail_counter=fail_counter+1 WHERE ID IN (?)`;
  206.                         const savedParam = values.filter(value.response !== false).join(',');
  207.                         const failedParam = values.filter(value.response === false).join(',');
  208.                         const updateSaved = drupalClient.storage.runQuery(drupalClient.config.dbName.pendingFormData, savedQuery, [savedParam]);
  209.                         const updateFailed = drupalClient.storage.runQuery(drupalClient.config.dbName.pendingFormData, failedQuery, [failedParam]);
  210.                         Promise.all(updateFailed, updateSaved).then(reject);
  211.                     } else {
  212.                         const query = `UPDATE pending_form_data SET sent=1, data=? WHERE id = ?`;
  213.                         const savedAttachments = [];
  214.                         values.map(value => savedAttachments.push(drupalClient.storage.runQuery(drupalClient.config.dbName.pendingFormData, query, [drupalClient.util.parseImageResult(value.response).fileID, value.id ])));
  215.                         Promise.all(savedAttachments).then(() => {
  216.                             // fetch all saved attachments with the id's, and add them to the post
  217.                             drupalClient.util.getSavedPendingAttachments(id, 1).then(attachments => {
  218.                                 const attachmentFields = [];
  219.                                 for (var i = 0; i < attachments.rows.length; i++) {
  220.                                     attachmentFields.push({ target_id: attachments.rows.item(i).data });
  221.                                 }
  222.                                 drupalClient.util.getSavedPendingNode(id).then(nodeResult => {
  223.                                     const nodeData = JSON.parse(nodeResult.rows.item(0).data);
  224.                                     postNode(Object.assign({field_image: attachmentFields}, nodeData))
  225.                                         .then(code => drupalClient.storage.runQuery(drupalClient.config.dbName.pendingFormData, `UPDATE pending_form_data SET sent=1 WHERE id = ?`, [id]).then(() => resolve(code)))
  226.                                         .catch(reject);
  227.                                 });
  228.                             });
  229.                         });
  230.                     }
  231.                 });
  232.             } else {
  233.                 // no attachments, only post the node
  234.                 drupalClient.util.getSavedPendingNode(id).then(nodeResult => {
  235.                     postNode(JSON.parse(nodeResult.rows.item(0).data))
  236.                         .then(code => drupalClient.storage.runQuery(drupalClient.config.dbName.pendingFormData, `UPDATE pending_form_data SET sent=1 WHERE id = ?`, [id]).then(() => resolve(code)))
  237.                         .catch(reject);
  238.                 });
  239.             }
  240.         });
  241.     });
  242. }
  243.  
  244. drupalClient.web.saveAndSubmit = form => {
  245.     navigator.geolocation.getCurrentPosition(
  246.         position => {
  247.             const nodeType = form.dataset.nodeType;
  248.             const currentTime = new Date(position.timestamp);
  249.             const nodeData = {
  250.                 _links: { type: { href: `${drupalClient.config.url}/rest/type/node/${nodeType}` } },
  251.                 type: { target_id: nodeType },
  252.                 field_time: { value: dateFns.format(currentTime, 'YYYY-MM-DD\THH:mm:ss') },
  253.                 field_geolocation: { value: { lat: position.coords.latitude, lng: position.coords.longitude } },
  254.             };
  255.             const formData = new FormData(form);
  256.             Array.from(formData.keys()).map(name => {
  257.                 if (name == 'field_polling_station_tags') {
  258.                     nodeData[name] = JSON.parse(formData.get(name)).map(id => ({ target_id: id}));
  259.                 } else if(name == 'field_polling_station') {
  260.                     nodeData[name] = [{ target_id: formData.get(name) }]
  261.                 } else {
  262.                     nodeData[name] = { value: formData.get(name) }
  263.                 }
  264.             });
  265.        
  266.             const nodeQuery = `INSERT INTO pending_form_data (type, node_type, data) VALUES (?, ?, ?)`;
  267.             const params = [0, nodeType, JSON.stringify(nodeData)];
  268.             drupalClient.storage.runQuery(drupalClient.config.dbName.pendingFormData, nodeQuery, params).then(resultSet => {
  269.                 const imageSrc = document.getElementById(`${form.dataset.nodeType}_photo`).src;
  270.                 if (imageSrc) {
  271.                     const attachmentQuery = `INSERT INTO pending_form_data (parent_id, type, node_type, data) VALUES (?, ?, ?, ?)`;
  272.                     const attachmentParams = [resultSet.insertId, 1, nodeType, imageSrc];
  273.                     drupalClient.storage.runQuery(drupalClient.config.dbName.pendingFormData, attachmentQuery, attachmentParams).then(() => {
  274.                         drupalClient.util.postSavedNode(resultSet.insertId).then(code => drupalClient.web.handleSubmitResponseCode(code));
  275.                     });
  276.                 } else {
  277.                     drupalClient.util.postSavedNode(resultSet.insertId).then(code => drupalClient.web.handleSubmitResponseCode(code));
  278.                 }
  279.             });
  280.         },
  281.         err => console.log(err),
  282.         { maximumAge: 30000, timeout: 10000, enableHighAccuracy: true }
  283.     );
  284. }
  285.  
  286. drupalClient.web.submit = event => {
  287.     event.preventDefault();
  288.     drupalClient.util.showDimmer();
  289.     drupalClient.web.checkLogin().then(checkResponse => {
  290.         if (checkResponse.response == 0) {
  291.             drupalClient.web.login(drupalClient.config.user, drupalClient.config.pass).then(loginResponse => {
  292.                 const loginData = JSON.parse(loginResponse.response);
  293.                 drupalClient.storage.storeAuthData(loginData);
  294.                 drupalClient.web.saveAndSubmit(event.target);
  295.             });
  296.         } else {
  297.             drupalClient.web.saveAndSubmit(event.target);
  298.         }
  299.     });
  300. }
  301.  
  302. drupalClient.util.login = event => {
  303.     event.preventDefault();
  304.     drupalClient.util.showDimmer();
  305.     drupalClient.web.checkLogin().then(checkResponse => {
  306.         if (checkResponse.response == 0) {
  307.             const form = event.target;
  308.             drupalClient.web.login(form.name.value.trim(), form.password.value.trim()).then(loginResponse => {
  309.                 if (loginResponse.code < 300) {
  310.                     const loginData = JSON.parse(loginResponse.response);
  311.                     drupalClient.storage.storeAuthData(loginData);
  312.                     drupalClient.util.showMenu();
  313.                     drupalClient.config.user = form.name.value.trim();
  314.                     drupalClient.config.pass = form.password.value.trim();
  315.                     drupalClient.util.hideDimmer();
  316.                 } else {
  317.                     drupalClient.util.alert('Erreur', "Erreur d'authentification").then(() => {
  318.                         drupalClient.util.hideDimmer();
  319.                     });
  320.                 }
  321.             }, () => drupalClient.util.alert('Erreur', "Erreur d'authentification").then(() => {
  322.                 drupalClient.util.hideDimmer();
  323.             }));
  324.         } else {
  325.             drupalClient.util.showMenu();
  326.             drupalClient.util.hideDimmer();
  327.         }
  328.     });
  329. }
  330.  
  331. drupalClient.util.logout = () => {
  332.     drupalClient.util.showDimmer();
  333.     drupalClient.web.logout().then(() => {
  334.         drupalClient.util.hideMenu();
  335.         drupalClient.storage.clearAuthData();
  336.         drupalClient.util.hideDimmer();
  337.         drupalClient.util.showLogin();
  338.     }, () => {
  339.         drupalClient.util.hideMenu();
  340.         drupalClient.storage.clearAuthData();
  341.         drupalClient.util.hideDimmer();
  342.         drupalClient.util.showLogin();
  343.         drupalClient.util.alert('Warning', 'Could not log out in a clear fashion.').then();
  344.     });
  345. }
  346.  
  347. drupalClient.util.hideMenu = () => document.getElementById('main_menu').classList.add('hidden');
  348.  
  349. drupalClient.util.showMenu = () => {
  350.     window.scrollTo(0, 0);
  351.     formBlocks.map(block => block.classList.add('hidden'));
  352.     document.getElementById('main_menu').classList.remove('hidden');
  353.     drupalClient.util.showNews();
  354. }
  355.  
  356. drupalClient.util.hideLogin = () => {
  357.     document.getElementById('sign_in').classList.add('hidden');
  358.     drupalClient.util.showMenu();
  359. }
  360.  
  361. drupalClient.util.showLogin = () => {
  362.     drupalClient.util.hideMenu();
  363.     document.getElementById('sign_in').classList.remove('hidden');
  364. }
  365.  
  366. drupalClient.util.takePhoto = (event) => {
  367.     const options = {
  368.         quality: 50,
  369.         sourceType: Camera.PictureSourceType.CAMERA,
  370.         destinationType: Camera.DestinationType.FILE_URI,
  371.         encodingType: Camera.EncodingType.JPEG,
  372.         mediaType: Camera.MediaType.PICTURE,
  373.         correctOrientation: true,
  374.         targetWidth: 1024,
  375.         targetHeight: 1024
  376.     };
  377.     navigator.camera.getPicture(
  378.         imageURI => document.getElementById(`${event.target.form.dataset.nodeType}_photo`).src = imageURI,
  379.         err => console.log(err),
  380.         options
  381.     );
  382. }
  383.  
  384. drupalClient.util.selectPhoto = (event) => {
  385.     const options = {
  386.         quality: 50,
  387.         sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
  388.         destinationType: Camera.DestinationType.FILE_URI,
  389.         encodingType: Camera.EncodingType.JPEG,
  390.         mediaType: Camera.MediaType.PICTURE,
  391.         correctOrientation: true,
  392.         targetWidth: 1024,
  393.         targetHeight: 1024
  394.     };
  395.     navigator.camera.getPicture(
  396.         imageURI => document.getElementById(`${event.target.form.dataset.nodeType}_photo`).src = imageURI,
  397.         err => console.log(err),
  398.         options
  399.     );
  400. }
  401.  
  402. drupalClient.util.parseImageResult = (imageUploadResult) => {
  403.     parsed = JSON.parse(imageUploadResult);
  404.     return {
  405.         fileID: parsed.fid[0].value,
  406.         filename: parsed.filename[0].value,
  407.         url: parsed.uri[0].url,
  408.     }
  409. }
  410.  
  411. drupalClient.util.alert = (title, message) => {
  412.     return new Promise((resolve) => navigator.notification.alert(message, resolve, title));
  413. }
  414.  
  415. drupalClient.util.confirm = (title, message) => {
  416.     return new Promise(resolve => navigator.notification.confirm(message, resolve, title));
  417. }
  418.  
  419. drupalClient.util.showDimmer = () => {
  420.     document.querySelector('.dimmer').classList.add('active');
  421. }
  422.  
  423. drupalClient.util.hideDimmer = () => {
  424.     document.querySelector('.dimmer').classList.remove('active');
  425. }
  426.  
  427. drupalClient.util.initSubSelect = () => {
  428.     // Pre-populate polling_station root selects
  429.     const pollingStationRootQuery = `SELECT * FROM polling_stations WHERE parent_id IS NULL;`;
  430.     drupalClient.storage.runQuery(drupalClient.config.dbName.pollingStations, pollingStationRootQuery, []).then(resultSet => {
  431.         const pollingStationsRoots = Array.from(document.querySelectorAll('.polling-station-root'));
  432.         pollingStationsRoots.map(selectElement => {
  433.             for(var i = 0; i < resultSet.rows.length; i++) {
  434.                 selectElement.add(new Option(resultSet.rows.item(i).name, resultSet.rows.item(i).id));
  435.             }
  436.             selectElement.addEventListener('change', event => drupalClient.util.subSelectChange(event.target));
  437.         });
  438.     });
  439. }
  440.  
  441. drupalClient.util.resetForms = () => {
  442.     Array.from(document.querySelectorAll('form')).map(form => form.reset());
  443.     Array.from(document.querySelectorAll('div.polling-station div.field:not(.select-level-0)')).map(select => select.parentElement.removeChild(select));
  444. }
  445.  
  446. drupalClient.util.subSelectChange = select => {
  447.     Array.from(select.parentElement.parentElement.querySelectorAll(`.field.select-level-${select.dataset.selectLevel} ~ .field`)).map(field => field.remove());
  448.     const query = `SELECT * FROM polling_stations WHERE parent_id = ? ORDER BY name;`;
  449.     drupalClient.storage.runQuery(drupalClient.config.dbName.pollingStations, query, [select.value]).then(resultSet => {
  450.         if (resultSet.rows.length) {
  451.             const newSelect = document.createElement('select');
  452.             newSelect.required = true;
  453.             newSelect.dataset.selectLevel = Number(select.dataset.selectLevel) + 1;
  454.             newSelect.add(new Option('Choisir', ''));
  455.             for(var i = 0; i < resultSet.rows.length; i++) {
  456.                 newSelect.add(new Option(resultSet.rows.item(i).name, resultSet.rows.item(i).id));
  457.             }
  458.             newSelect.addEventListener('change', event => drupalClient.util.subSelectChange(event.target));
  459.  
  460.             const div = document.createElement('div');
  461.             div.classList.add('field');
  462.             div.classList.add(`select-level-${newSelect.dataset.selectLevel}`);
  463.             div.appendChild(newSelect);
  464.  
  465.             select.parentElement.parentElement.appendChild(div);
  466.         }
  467.         select.form.querySelector('input[type=hidden].polling-station').value = select.value;
  468.         select.form.querySelector('input[type=hidden].polling-station-tags').value = JSON.stringify(Array.from(select.form.querySelectorAll('div.polling-station option:checked')).filter(option => Number(option.value)).map(option => option.value));
  469.     });
  470. }
  471.  
  472. drupalClient.util.showNews = () => {
  473.     drupalClient.web.request(`${drupalClient.config.url}/rest/news?_format=json`, 'GET').then(newsResult => {
  474.         newsDiv = document.querySelector('div.news');
  475.         Array.from(newsDiv.childNodes).map(child => newsDiv.removeChild(child));
  476.         news = JSON.parse(newsResult.response);
  477.         news.map(newsItem => {
  478.             const itemDiv = document.createElement('div');
  479.             itemDiv.classList.add('item');
  480.  
  481.             // Header
  482.             const hDiv = document.createElement('h2');
  483.             hDiv.innerHTML = newsItem.title.trim();
  484.             itemDiv.appendChild(hDiv);
  485.  
  486.             // Image
  487.             if (newsItem.field_image) {
  488.                 const imgDiv = document.createElement('div');
  489.                 imgDiv.classList.add('fullwidthimage');
  490.                 itemDiv.appendChild(imgDiv);
  491.                 const img = document.createElement('img');
  492.                 img.src = drupalClient.config.host + newsItem.field_image.trim();
  493.                 imgDiv.appendChild(img);
  494.             }
  495.  
  496.             // Body
  497.             const bDiv = document.createElement('div');
  498.             bDiv.classList.add('content');
  499.             bDiv.innerHTML = newsItem.body.trim();
  500.             itemDiv.appendChild(bDiv);
  501.  
  502.             // Date
  503.             const dDiv = document.createElement('div');
  504.             dDiv.classList.add('meta');
  505.             dDiv.innerHTML = newsItem.changed.trim();
  506.             bDiv.appendChild(dDiv);
  507.  
  508.             // Add the news element to the view
  509.             newsDiv.appendChild(itemDiv);
  510.         });
  511.     });
  512. }
  513.  
  514. drupalClient.util.init = () => {
  515.     // Navigate to register screen from login
  516.     document.querySelector('.button.show-register').addEventListener('click', () => {
  517.         document.getElementById('sign_in').classList.add('hidden');
  518.         document.getElementById('register').classList.remove('hidden');
  519.     });
  520.  
  521.     // Navigate back to login from registration
  522.     document.querySelector('.button.cancel-register').addEventListener('click', () => {
  523.         document.getElementById('register').classList.add('hidden');
  524.         document.getElementById('sign_in').classList.remove('hidden');
  525.     });
  526.  
  527.     // Submit registration form
  528.     document.querySelector('form.register-form').addEventListener('submit', event => {
  529.         event.preventDefault();
  530.         const form = event.target;
  531.         drupalClient.web.register(form.name.value, form.email.value, form.password.value).then(regResult => {
  532.             if (regResult.code < 400) {
  533.                 drupalClient.util.alert('Succès', "l'utilisateur a été enregistré").then(() => {
  534.                     document.getElementById('register').classList.add('hidden');
  535.                     document.getElementById('sign_in').classList.remove('hidden');
  536.                 });
  537.             } else {
  538.                 drupalClient.util.alert('Erreur', "Impossible d'enregistrer l'utilisateur").then();
  539.             }
  540.         });
  541.     });
  542.  
  543.     // Log in/out
  544.     document.querySelector('form.login-form').addEventListener('submit', drupalClient.util.login);
  545.     document.querySelector('.logout-button').addEventListener('click', drupalClient.util.logout);
  546.  
  547.     // Bind menu buttons
  548.     Array.from(document.querySelectorAll('div.menu > .item')).map(menu => menu.addEventListener('click', event => {
  549.         window.scrollTo(0, 0);
  550.         menuItems.map(item => item.classList.remove('active'));
  551.         event.target.classList.add('active');
  552.  
  553.         formBlocks.filter(block => block.id != event.target.dataset.menuId).map(block => block.classList.add('hidden'));
  554.         formBlocks.filter(block => block.id == event.target.dataset.menuId).map(block => block.classList.remove('hidden'));
  555.         drupalClient.util.hideMenu();
  556.     }));
  557.  
  558.     // Take new photo
  559.     const takePhotoButtons = Array.from(document.querySelectorAll('.take-photo'));
  560.     takePhotoButtons.map(button => button.addEventListener("click", drupalClient.util.takePhoto));
  561.  
  562.     // Select photo from album
  563.     const selectPhotoButtons = Array.from(document.querySelectorAll('.select-photo'));
  564.     selectPhotoButtons.map(button => button.addEventListener("click", drupalClient.util.selectPhoto));
  565.  
  566.     // Cancel form screen and go back to main menu
  567.     const cancelButtons = Array.from(document.querySelectorAll('button.cancel-form'));
  568.     cancelButtons.map(button => button.addEventListener('click', drupalClient.util.showMenu));
  569.  
  570.     // Submit the current form
  571.     const dataForms = Array.from(document.querySelectorAll('form.data-form'));
  572.     dataForms.map(form => form.addEventListener("submit", drupalClient.web.submit));
  573.  
  574.     drupalClient.util.initSubSelect();
  575.  
  576.     drupalClient.util.showDimmer();
  577.     drupalClient.web.checkLogin().then(checkResponse => {
  578.         if (checkResponse.response == 1) {
  579.             drupalClient.util.hideLogin();
  580.             drupalClient.util.showMenu();
  581.         }
  582.         drupalClient.util.hideDimmer();
  583.     });
  584. }
  585.  
  586. // this is not so elegant, there should be some navigation state handling so we could use the history stack
  587. drupalClient.util.backButton = () => {
  588.     // register is visible, so go back to login
  589.     if (!document.getElementById('register').classList.contains('hidden')) {
  590.         drupalClient.util.showLogin();
  591.         return;
  592.     }
  593.  
  594.     // main menu is visible, so we quit
  595.     if (!document.getElementById('main_menu').classList.contains('hidden')) {
  596.         drupalClient.util.confirm('Quitter?', "Voulez-vous quitter l'application?").then(choice => { if (choice == 1) navigator.app.exitApp() });
  597.         return;
  598.     }
  599.  
  600.     // login is visible, so we quit
  601.     if (!document.getElementById('sign_in').classList.contains('hidden')) {
  602.         drupalClient.util.confirm('Quitter?', "Voulez-vous quitter l'application?").then(choice => { if (choice == 1) navigator.app.exitApp() });
  603.         return;
  604.     }
  605.  
  606.     // in any other case we navigate back to the main menu
  607.     drupalClient.util.showMenu();
  608. }

Comments