add_build.js 20 KB

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