add_build.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. const Features = (() => {
  2. let features = {};
  3. let defines_dictionary = {};
  4. let labels_dictionary = {};
  5. function resetDictionaries() {
  6. defines_dictionary = {}; // clear old dictionary
  7. labels_dictionary = {}; // clear old dictionary
  8. features.forEach((category) => {
  9. category['options'].forEach((option) => {
  10. defines_dictionary[option.define] = labels_dictionary[option.label] = option;
  11. });
  12. });
  13. }
  14. function updateRequiredFor() {
  15. features.forEach((category) => {
  16. category['options'].forEach((option) => {
  17. if (option.dependency != null) {
  18. option.dependency.split(',').forEach((dependency) => {
  19. let dep = getOptionByLabel(dependency);
  20. if (dep.requiredFor == undefined) {
  21. dep.requiredFor = [];
  22. }
  23. dep.requiredFor.push(option.label);
  24. });
  25. }
  26. });
  27. });
  28. }
  29. function reset(new_features) {
  30. features = new_features;
  31. resetDictionaries();
  32. updateRequiredFor();
  33. }
  34. function getOptionByDefine(define) {
  35. return defines_dictionary[define];
  36. }
  37. function getOptionByLabel(label) {
  38. return labels_dictionary[label];
  39. }
  40. function updateDefaults(defines_array) {
  41. // updates default on the basis of define array passed
  42. // the define array consists define in format, EXAMPLE_DEFINE or !EXAMPLE_DEFINE
  43. // we update the defaults in features object by processing those defines
  44. for (let i=0; i<defines_array.length; i++) {
  45. let select_opt = (defines_array[i][0] != '!');
  46. let sanitised_define = (select_opt ? defines_array[i] : defines_array[i].substring(1)); // this removes the leading '!' from define if it contatins
  47. if (getOptionByDefine(sanitised_define)) {
  48. getOptionByDefine(sanitised_define).default = select_opt ? 1 : 0;
  49. }
  50. }
  51. }
  52. function fixDepencencyHelper(feature_label, visited) {
  53. if (visited[feature_label] != undefined ) {
  54. return;
  55. }
  56. visited[feature_label] = true;
  57. document.getElementById(feature_label).checked = true;
  58. let feature = getOptionByLabel(feature_label);
  59. if (feature.dependency == null) {
  60. return;
  61. }
  62. let children = feature.dependency.split(',');
  63. children.forEach((child) => {
  64. fixDepencencyHelper(child, visited);
  65. });
  66. }
  67. function fixAllDependencies() {
  68. var visited = {};
  69. Object.keys(labels_dictionary).forEach((label) => {
  70. if (document.getElementById(label).checked) {
  71. fixDepencencyHelper(label, visited);
  72. }
  73. });
  74. }
  75. function handleDependenciesForFeature(feature_label) {
  76. var visited = {};
  77. if (document.getElementById(feature_label).checked) {
  78. fixDepencencyHelper(feature_label, visited);
  79. } else {
  80. enabled_dependent_features = getEnabledDependentFeaturesFor(feature_label);
  81. if (enabled_dependent_features.length > 0) {
  82. document.getElementById('modalBody').innerHTML = "The feature(s) <strong>"+enabled_dependent_features.join(", ")+"</strong> is/are dependant on <strong>"+feature_label+"</strong>" +
  83. " and hence will be disabled too.<br><strong>Do you want to continue?</strong>";
  84. document.getElementById('modalDisableButton').onclick = () => { disableCheckboxesByIds(enabled_dependent_features); }
  85. document.getElementById('modalCancelButton').onclick = document.getElementById('modalCloseButton').onclick = () => { document.getElementById(feature_label).checked = true; };
  86. var confirmationModal = bootstrap.Modal.getOrCreateInstance(document.getElementById('dependencyCheckModal'));
  87. confirmationModal.show();
  88. }
  89. }
  90. }
  91. function getEnabledDependentFeaturesHelper(feature_label, visited, dependent_features) {
  92. if (visited[feature_label] != undefined || document.getElementById(feature_label).checked == false) {
  93. return;
  94. }
  95. visited[feature_label] = true;
  96. dependent_features.push(feature_label);
  97. let feature = getOptionByLabel(feature_label);
  98. if (feature.requiredFor == null) {
  99. return;
  100. }
  101. feature.requiredFor.forEach((dependent_feature) => {
  102. getEnabledDependentFeaturesHelper(dependent_feature, visited, dependent_features);
  103. });
  104. }
  105. function getEnabledDependentFeaturesFor(feature_label) {
  106. let dependent_features = [];
  107. let visited = {};
  108. if (getOptionByLabel(feature_label).requiredFor) {
  109. getOptionByLabel(feature_label).requiredFor.forEach((dependent_feature) => {
  110. getEnabledDependentFeaturesHelper(dependent_feature, visited, dependent_features);
  111. });
  112. }
  113. return dependent_features;
  114. }
  115. function disableDependents(feature_label) {
  116. if (getOptionByLabel(feature_label).requiredFor == undefined) {
  117. return;
  118. }
  119. getOptionByLabel(feature_label).requiredFor.forEach((dependent_feature) => {
  120. document.getElementById(dependent_feature).checked = false;
  121. });
  122. }
  123. function applyDefaults() {
  124. features.forEach(category => {
  125. category['options'].forEach(option => {
  126. element = document.getElementById(option['label']);
  127. if (element != undefined) {
  128. element.checked = (option['default'] == 1);
  129. }
  130. });
  131. });
  132. fixAllDependencies();
  133. }
  134. function checkUncheckAll(check) {
  135. features.forEach(category => {
  136. category['options'].forEach(option => {
  137. element = document.getElementById(option['label']);
  138. if (element != undefined) {
  139. element.checked = check;
  140. }
  141. });
  142. });
  143. }
  144. return {reset, handleDependenciesForFeature, disableDependents, updateDefaults, applyDefaults, checkUncheckAll};
  145. })();
  146. var init_categories_expanded = false;
  147. var pending_update_calls = 0; // to keep track of unresolved Promises
  148. function init() {
  149. onVehicleChange(document.getElementById("vehicle").value);
  150. }
  151. // enables or disables the elements with ids passed as an array
  152. // if enable is true, the elements are enabled and vice-versa
  153. function enableDisableElementsById(ids, enable) {
  154. for (let i=0; i<ids.length; i++) {
  155. let element = document.getElementById(ids[i]);
  156. if (element) {
  157. element.disabled = (!enable);
  158. }
  159. }
  160. }
  161. // sets a spinner inside the division with given id
  162. // also sets a custom message inside the division
  163. // this indicates that an ajax call related to that element is in progress
  164. function setSpinnerToDiv(id, message) {
  165. let element = document.getElementById(id);
  166. if (element) {
  167. element.innerHTML = '<div class="container-fluid d-flex align-content-between">' +
  168. '<strong>'+message+'</strong>' +
  169. '<div class="spinner-border ms-auto" role="status" aria-hidden="true"></div>' +
  170. '</div>';
  171. }
  172. }
  173. function disableCheckboxesByIds(ids) {
  174. ids.forEach((id) => {
  175. box_element = document.getElementById(id);
  176. if (box_element) {
  177. box_element.checked = false;
  178. }
  179. })
  180. }
  181. function onVehicleChange(new_vehicle) {
  182. // following elemets will be blocked (disabled) when we make the request
  183. let elements_to_block = ['vehicle', 'branch', 'board', 'submit', 'reset_def', 'exp_col_button'];
  184. enableDisableElementsById(elements_to_block, false);
  185. let request_url = '/get_allowed_branches/'+new_vehicle;
  186. setSpinnerToDiv('branch_list', 'Fetching branches...');
  187. pending_update_calls += 1;
  188. sendAjaxRequestForJsonResponse(request_url)
  189. .then((json_response) => {
  190. let new_branch = json_response.default_branch;
  191. let all_branches = json_response.branches;
  192. updateBranches(all_branches, new_branch);
  193. })
  194. .catch((message) => {
  195. console.log("Branch update failed. "+message);
  196. })
  197. .finally(() => {
  198. enableDisableElementsById(elements_to_block, true);
  199. pending_update_calls -= 1;
  200. fetchAndUpdateDefaults();
  201. });
  202. }
  203. function updateBranches(all_branches, new_branch) {
  204. let branch_element = document.getElementById('branch');
  205. let old_branch = branch_element ? branch_element.value : '';
  206. fillBranches(all_branches, new_branch);
  207. if (old_branch != new_branch) {
  208. onBranchChange(new_branch);
  209. }
  210. }
  211. function onBranchChange(new_branch) {
  212. // following elemets will be blocked (disabled) when we make the request
  213. let elements_to_block = ['vehicle', 'branch', 'board', 'submit', 'reset_def', 'exp_col_button'];
  214. enableDisableElementsById(elements_to_block, false);
  215. let request_url = '/boards_and_features/'+new_branch;
  216. // create a temporary container to set spinner inside it
  217. let temp_container = document.createElement('div');
  218. temp_container.id = "temp_container";
  219. temp_container.setAttribute('class', 'container-fluid w-25 mt-3');
  220. let features_list_element = document.getElementById('build_options'); // append the temp container to the main features_list container
  221. features_list_element.innerHTML = "";
  222. features_list_element.appendChild(temp_container);
  223. setSpinnerToDiv('temp_container', 'Fetching features...');
  224. setSpinnerToDiv('board_list', 'Fetching boards...');
  225. pending_update_calls += 1;
  226. sendAjaxRequestForJsonResponse(request_url)
  227. .then((json_response) => {
  228. let boards = json_response.boards;
  229. let new_board = json_response.default_board;
  230. let new_features = json_response.features;
  231. Features.reset(new_features);
  232. updateBoards(boards, new_board);
  233. fillBuildOptions(new_features);
  234. })
  235. .catch((message) => {
  236. console.log("Boards and features update failed. "+message);
  237. })
  238. .finally(() => {
  239. enableDisableElementsById(elements_to_block, true);
  240. pending_update_calls -= 1;
  241. fetchAndUpdateDefaults();
  242. });
  243. }
  244. function updateBoards(all_boards, new_board) {
  245. let board_element = document.getElementById('board');
  246. let old_board = board_element ? board.value : '';
  247. fillBoards(all_boards, new_board);
  248. if (old_board != new_board) {
  249. onBoardChange(new_board);
  250. }
  251. }
  252. function onBoardChange(new_board) {
  253. fetchAndUpdateDefaults();
  254. }
  255. function fetchAndUpdateDefaults() {
  256. // return early if there is an unresolved promise (i.e., there is an ongoing ajax call)
  257. if (pending_update_calls > 0) {
  258. return;
  259. }
  260. elements_to_block = ['reset_def'];
  261. document.getElementById('reset_def').innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Fetching defaults';
  262. enableDisableElementsById(elements_to_block, false);
  263. let branch = document.getElementById('branch').value;
  264. let vehicle = document.getElementById('vehicle').value;
  265. let board = document.getElementById('board').value;
  266. let request_url = '/get_defaults/'+vehicle+'/'+branch+'/'+board;
  267. sendAjaxRequestForJsonResponse(request_url)
  268. .then((json_response) => {
  269. Features.updateDefaults(json_response);
  270. })
  271. .catch((message) => {
  272. console.log("Default reset failed. "+message);
  273. })
  274. .finally(() => {
  275. if (document.getElementById('auto_apply_def').checked) {
  276. Features.applyDefaults();
  277. }
  278. enableDisableElementsById(elements_to_block, true);
  279. document.getElementById('reset_def').innerHTML = '<i class="bi bi-arrow-counterclockwise me-2"></i>Reset feature defaults';
  280. });
  281. }
  282. function fillBoards(boards, default_board) {
  283. let output = document.getElementById('board_list');
  284. output.innerHTML = '<label for="board" class="form-label"><strong>Select Board</strong></label>' +
  285. '<select name="board" id="board" class="form-select" aria-label="Select Board" onchange="onBoardChange(this.value);"></select>';
  286. let boardList = document.getElementById("board")
  287. boards.forEach(board => {
  288. let opt = document.createElement('option');
  289. opt.value = board;
  290. opt.innerHTML = board;
  291. opt.selected = (board === default_board);
  292. boardList.appendChild(opt);
  293. });
  294. }
  295. var toggle_all_categories = (() => {
  296. let all_categories_expanded = init_categories_expanded;
  297. function toggle_method() {
  298. // toggle global state
  299. all_categories_expanded = !all_categories_expanded;
  300. let all_collapse_elements = document.getElementsByClassName('feature-group');
  301. for (let i=0; i<all_collapse_elements.length; i+=1) {
  302. let collapse_element = all_collapse_elements[i];
  303. collapse_instance = bootstrap.Collapse.getOrCreateInstance(collapse_element);
  304. if (all_categories_expanded && !collapse_element.classList.contains('show')) {
  305. collapse_instance.show();
  306. } else if (!all_categories_expanded && collapse_element.classList.contains('show')) {
  307. collapse_instance.hide();
  308. }
  309. }
  310. }
  311. return toggle_method;
  312. })();
  313. function createCategoryCard(category_name, options, expanded) {
  314. options_html = "";
  315. options.forEach(option => {
  316. options_html += '<div class="form-check">' +
  317. '<input class="form-check-input" type="checkbox" value="1" name="'+option['label']+'" id="'+option['label']+'" onclick="Features.handleDependenciesForFeature(this.id);">' +
  318. '<label class="form-check-label" for="'+option['label']+'">' +
  319. option['description'].replace(/enable/i, "") +
  320. '</label>' +
  321. '</div>';
  322. });
  323. let id_prefix = category_name.split(" ").join("_");
  324. let card_element = document.createElement('div');
  325. card_element.setAttribute('class', 'card ' + (expanded == true ? 'h-100' : ''));
  326. card_element.id = id_prefix + '_card';
  327. card_element.innerHTML = '<div class="card-header">' +
  328. '<div class="d-flex justify-content-between">' +
  329. '<span class="d-flex align-items-center"><strong>'+category_name+'</strong></span>' +
  330. '<button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#'+id_prefix+'_collapse" aria-expanded="false" aria-controls="'+id_prefix+'_collapse">' +
  331. '<i class="bi bi-chevron-'+(expanded == true ? 'up' : 'down')+'" id="'+id_prefix+'_icon'+'"></i>' +
  332. '</button>' +
  333. '</div>' +
  334. '</div>';
  335. let collapse_element = document.createElement('div');
  336. collapse_element.setAttribute('class', 'feature-group collapse '+(expanded == true ? 'show' : ''));
  337. collapse_element.id = id_prefix + '_collapse';
  338. collapse_element.innerHTML = '<div class="container-fluid px-2 py-2">'+options_html+'</div>';
  339. card_element.appendChild(collapse_element);
  340. // add relevent event listeners
  341. collapse_element.addEventListener('hide.bs.collapse', () => {
  342. card_element.classList.remove('h-100');
  343. document.getElementById(id_prefix+'_icon').setAttribute('class', 'bi bi-chevron-down');
  344. });
  345. collapse_element.addEventListener('shown.bs.collapse', () => {
  346. card_element.classList.add('h-100');
  347. document.getElementById(id_prefix+'_icon').setAttribute('class', 'bi bi-chevron-up');
  348. });
  349. return card_element;
  350. }
  351. function fillBuildOptions(buildOptions) {
  352. let output = document.getElementById('build_options');
  353. output.innerHTML = `<div class="d-flex mb-3 justify-content-between">
  354. <div class="d-flex d-flex align-items-center">
  355. <p class="card-text"><strong>Available features for the current selection are:</strong></p>
  356. </div>
  357. <button type="button" class="btn btn-outline-primary" id="exp_col_button" onclick="toggle_all_categories();"><i class="bi bi-chevron-expand me-2"></i>Expand/Collapse all categories</button>
  358. </div>`;
  359. buildOptions.forEach((category, cat_idx) => {
  360. if (cat_idx % 4 == 0) {
  361. let new_row = document.createElement('div');
  362. new_row.setAttribute('class', 'row');
  363. new_row.id = 'category_'+parseInt(cat_idx/4)+'_row';
  364. output.appendChild(new_row);
  365. }
  366. let col_element = document.createElement('div');
  367. col_element.setAttribute('class', 'col-md-3 col-sm-6 mb-2');
  368. col_element.appendChild(createCategoryCard(category['name'], category['options'], init_categories_expanded));
  369. document.getElementById('category_'+parseInt(cat_idx/4)+'_row').appendChild(col_element);
  370. });
  371. }
  372. // returns a Promise
  373. // the promise is resolved when we recieve status code 200 from the AJAX request
  374. // the JSON response for the request is returned in such case
  375. // the promise is rejected when the status code is not 200
  376. // the status code is returned in such case
  377. function sendAjaxRequestForJsonResponse(url) {
  378. return new Promise((resolve, reject) => {
  379. var xhr = new XMLHttpRequest();
  380. xhr.open('GET', url);
  381. // disable cache, thanks to: https://stackoverflow.com/questions/22356025/force-cache-control-no-cache-in-chrome-via-xmlhttprequest-on-f5-reload
  382. xhr.setRequestHeader("Cache-Control", "no-cache, no-store, max-age=0");
  383. xhr.setRequestHeader("Expires", "Tue, 01 Jan 1980 1:00:00 GMT");
  384. xhr.setRequestHeader("Pragma", "no-cache");
  385. xhr.onload = function () {
  386. if (xhr.status == 200) {
  387. resolve(JSON.parse(xhr.response));
  388. } else {
  389. reject("Got response:"+xhr.response+" (Status Code: "+xhr.status+")");
  390. }
  391. }
  392. xhr.send();
  393. });
  394. }
  395. function fillBranches(branches, branch_to_select) {
  396. var output = document.getElementById('branch_list');
  397. output.innerHTML = '<label for="branch" class="form-label"><strong>Select Branch</strong></label>' +
  398. '<select name="branch" id="branch" class="form-select" aria-label="Select Branch" onchange="onBranchChange(this.value);"></select>';
  399. branchList = document.getElementById("branch");
  400. branches.forEach(branch => {
  401. opt = document.createElement('option');
  402. opt.value = branch['full_name'];
  403. opt.innerHTML = branch['label'];
  404. opt.selected = (branch['full_name'] === branch_to_select);
  405. branchList.appendChild(opt);
  406. });
  407. }