add_build.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. return {reset, handleDependenciesForFeature, disableDependents, updateDefaults, applyDefaults};
  148. })();
  149. var all_categories_expanded = false;
  150. var pending_update_calls = 0; // to keep track of unresolved Promises
  151. function init() {
  152. onVehicleChange(document.getElementById("vehicle").value);
  153. }
  154. // enables or disables the elements with ids passed as an array
  155. // if enable is true, the elements are enabled and vice-versa
  156. function enableDisableElementsById(ids, enable) {
  157. for (let i=0; i<ids.length; i++) {
  158. let element = document.getElementById(ids[i]);
  159. if (element) {
  160. element.disabled = (!enable);
  161. }
  162. }
  163. }
  164. // sets a spinner inside the division with given id
  165. // also sets a custom message inside the division
  166. // this indicates that an ajax call related to that element is in progress
  167. function setSpinnerToDiv(id, message) {
  168. let element = document.getElementById(id);
  169. if (element) {
  170. element.innerHTML = '<div class="container-fluid d-flex align-content-between">' +
  171. '<strong>'+message+'</strong>' +
  172. '<div class="spinner-border ms-auto" role="status" aria-hidden="true"></div>' +
  173. '</div>';
  174. }
  175. }
  176. function disableCheckboxesByIds(ids) {
  177. ids.forEach((id) => {
  178. box_element = document.getElementById(id);
  179. if (box_element) {
  180. box_element.checked = false;
  181. }
  182. })
  183. }
  184. function onVehicleChange(new_vehicle) {
  185. // following elemets will be blocked (disabled) when we make the request
  186. let elements_to_block = ['vehicle', 'branch', 'board', 'submit', 'reset_def', 'exp_col_button'];
  187. enableDisableElementsById(elements_to_block, false);
  188. let request_url = '/get_allowed_branches/'+new_vehicle;
  189. setSpinnerToDiv('branch_list', 'Fetching branches...');
  190. pending_update_calls += 1;
  191. sendAjaxRequestForJsonResponse(request_url)
  192. .then((json_response) => {
  193. let new_branch = json_response.default_branch;
  194. let all_branches = json_response.branches;
  195. updateBranches(all_branches, new_branch);
  196. })
  197. .catch((message) => {
  198. console.log("Branch update failed. "+message);
  199. })
  200. .finally(() => {
  201. enableDisableElementsById(elements_to_block, true);
  202. pending_update_calls -= 1;
  203. fetchAndUpdateDefaults();
  204. });
  205. }
  206. function updateBranches(all_branches, new_branch) {
  207. let branch_element = document.getElementById('branch');
  208. let old_branch = branch_element ? branch_element.value : '';
  209. fillBranches(all_branches, new_branch);
  210. if (old_branch != new_branch) {
  211. onBranchChange(new_branch);
  212. }
  213. }
  214. function onBranchChange(new_branch) {
  215. // following elemets will be blocked (disabled) when we make the request
  216. let elements_to_block = ['vehicle', 'branch', 'board', 'submit', 'reset_def', 'exp_col_button'];
  217. enableDisableElementsById(elements_to_block, false);
  218. let request_url = '/boards_and_features/'+new_branch;
  219. // create a temporary container to set spinner inside it
  220. let temp_container = document.createElement('div');
  221. temp_container.id = "temp_container";
  222. temp_container.setAttribute('class', 'container-fluid w-25 mt-3');
  223. let features_list_element = document.getElementById('build_options'); // append the temp container to the main features_list container
  224. features_list_element.innerHTML = "";
  225. features_list_element.appendChild(temp_container);
  226. setSpinnerToDiv('temp_container', 'Fetching features...');
  227. setSpinnerToDiv('board_list', 'Fetching boards...');
  228. pending_update_calls += 1;
  229. sendAjaxRequestForJsonResponse(request_url)
  230. .then((json_response) => {
  231. let boards = json_response.boards;
  232. let new_board = json_response.default_board;
  233. let new_features = json_response.features;
  234. Features.reset(new_features);
  235. updateBoards(boards, new_board);
  236. fillBuildOptions(new_features);
  237. })
  238. .catch((message) => {
  239. console.log("Boards and features update failed. "+message);
  240. })
  241. .finally(() => {
  242. enableDisableElementsById(elements_to_block, true);
  243. pending_update_calls -= 1;
  244. fetchAndUpdateDefaults();
  245. });
  246. }
  247. function updateBoards(all_boards, new_board) {
  248. let board_element = document.getElementById('board');
  249. let old_board = board_element ? board.value : '';
  250. fillBoards(all_boards, new_board);
  251. if (old_board != new_board) {
  252. onBoardChange(new_board);
  253. }
  254. }
  255. function onBoardChange(new_board) {
  256. fetchAndUpdateDefaults();
  257. }
  258. function fetchAndUpdateDefaults() {
  259. // return early if there is an unresolved promise (i.e., there is an ongoing ajax call)
  260. if (pending_update_calls > 0) {
  261. return;
  262. }
  263. elements_to_block = ['reset_def'];
  264. document.getElementById('reset_def').innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Fetching defaults';
  265. enableDisableElementsById(elements_to_block, false);
  266. let branch = document.getElementById('branch').value;
  267. let vehicle = document.getElementById('vehicle').value;
  268. let board = document.getElementById('board').value;
  269. let request_url = '/get_defaults/'+vehicle+'/'+branch+'/'+board;
  270. sendAjaxRequestForJsonResponse(request_url)
  271. .then((json_response) => {
  272. Features.updateDefaults(json_response);
  273. })
  274. .catch((message) => {
  275. console.log("Default reset failed. "+message);
  276. })
  277. .finally(() => {
  278. if (document.getElementById('auto_apply_def').checked) {
  279. Features.applyDefaults();
  280. }
  281. enableDisableElementsById(elements_to_block, true);
  282. document.getElementById('reset_def').innerHTML = '<i class="bi bi-arrow-counterclockwise me-2"></i>Reset feature defaults';
  283. });
  284. }
  285. function fillBoards(boards, default_board) {
  286. let output = document.getElementById('board_list');
  287. output.innerHTML = '<label for="board" class="form-label"><strong>Select Board</strong></label>' +
  288. '<select name="board" id="board" class="form-select" aria-label="Select Board" onchange="onBoardChange(this.value);"></select>';
  289. let boardList = document.getElementById("board")
  290. boards.forEach(board => {
  291. let opt = document.createElement('option');
  292. opt.value = board;
  293. opt.innerHTML = board;
  294. opt.selected = (board === default_board);
  295. boardList.appendChild(opt);
  296. });
  297. }
  298. function toggle_all_categories() {
  299. // toggle global state
  300. all_categories_expanded = !all_categories_expanded;
  301. all_collapse_elements = document.getElementsByClassName('collapse');
  302. for (let i=0; i<all_collapse_elements.length;) {
  303. collapse_instance = bootstrap.Collapse.getOrCreateInstance(all_collapse_elements[i]);
  304. if (all_categories_expanded) {
  305. collapse_instance.show();
  306. } else {
  307. collapse_instance.hide();
  308. }
  309. }
  310. }
  311. function createCategoryCard(category_name, options, expanded) {
  312. options_html = "";
  313. options.forEach(option => {
  314. options_html += '<div class="form-check">' +
  315. '<input class="form-check-input" type="checkbox" value="1" name="'+option['label']+'" id="'+option['label']+'" onclick="Features.handleDependenciesForFeature(this.id);">' +
  316. '<label class="form-check-label" for="'+option['label']+'">' +
  317. option['description'].replace(/enable/i, "") +
  318. '</label>' +
  319. '</div>';
  320. });
  321. let id_prefix = category_name.split(" ").join("_");
  322. let card_element = document.createElement('div');
  323. card_element.setAttribute('class', 'card ' + (expanded == true ? 'h-100' : ''));
  324. card_element.id = id_prefix + '_card';
  325. card_element.innerHTML = '<div class="card-header">' +
  326. '<div class="d-flex justify-content-between">' +
  327. '<span class="d-flex align-items-center"><strong>'+category_name+'</strong></span>' +
  328. '<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">' +
  329. '<i class="bi bi-chevron-'+(expanded == true ? 'up' : 'down')+'" id="'+id_prefix+'_icon'+'"></i>' +
  330. '</button>' +
  331. '</div>' +
  332. '</div>';
  333. let collapse_element = document.createElement('div');
  334. collapse_element.setAttribute('class', 'collapse '+(expanded == true ? 'show' : ''));
  335. collapse_element.id = id_prefix + '_collapse';
  336. collapse_element.innerHTML = '<div class="container-fluid px-2 py-2">'+options_html+'</div>';
  337. card_element.appendChild(collapse_element);
  338. // add relevent event listeners
  339. collapse_element.addEventListener('hide.bs.collapse', () => {
  340. card_element.classList.remove('h-100');
  341. document.getElementById(id_prefix+'_icon').setAttribute('class', 'bi bi-chevron-down');
  342. });
  343. collapse_element.addEventListener('shown.bs.collapse', () => {
  344. card_element.classList.add('h-100');
  345. document.getElementById(id_prefix+'_icon').setAttribute('class', 'bi bi-chevron-up');
  346. });
  347. return card_element;
  348. }
  349. function fillBuildOptions(buildOptions) {
  350. let output = document.getElementById('build_options');
  351. output.innerHTML = '<p class="card-text"><strong>Available features for the current selection are:</strong></p>';
  352. buildOptions.forEach((category, cat_idx) => {
  353. if (cat_idx % 4 == 0) {
  354. let new_row = document.createElement('div');
  355. new_row.setAttribute('class', 'row');
  356. new_row.id = 'category_'+parseInt(cat_idx/4)+'_row';
  357. output.appendChild(new_row);
  358. }
  359. let col_element = document.createElement('div');
  360. col_element.setAttribute('class', 'col-md-3 col-sm-6 mb-2');
  361. col_element.appendChild(createCategoryCard(category['name'], category['options'], all_categories_expanded));
  362. document.getElementById('category_'+parseInt(cat_idx/4)+'_row').appendChild(col_element);
  363. });
  364. }
  365. // returns a Promise
  366. // the promise is resolved when we recieve status code 200 from the AJAX request
  367. // the JSON response for the request is returned in such case
  368. // the promise is rejected when the status code is not 200
  369. // the status code is returned in such case
  370. function sendAjaxRequestForJsonResponse(url) {
  371. return new Promise((resolve, reject) => {
  372. var xhr = new XMLHttpRequest();
  373. xhr.open('GET', url);
  374. // disable cache, thanks to: https://stackoverflow.com/questions/22356025/force-cache-control-no-cache-in-chrome-via-xmlhttprequest-on-f5-reload
  375. xhr.setRequestHeader("Cache-Control", "no-cache, no-store, max-age=0");
  376. xhr.setRequestHeader("Expires", "Tue, 01 Jan 1980 1:00:00 GMT");
  377. xhr.setRequestHeader("Pragma", "no-cache");
  378. xhr.onload = function () {
  379. if (xhr.status == 200) {
  380. resolve(JSON.parse(xhr.response));
  381. } else {
  382. reject("Got response:"+xhr.response+" (Status Code: "+xhr.status+")");
  383. }
  384. }
  385. xhr.send();
  386. });
  387. }
  388. function fillBranches(branches, branch_to_select) {
  389. var output = document.getElementById('branch_list');
  390. output.innerHTML = '<label for="branch" class="form-label"><strong>Select Branch</strong></label>' +
  391. '<select name="branch" id="branch" class="form-select" aria-label="Select Branch" onchange="onBranchChange(this.value);"></select>';
  392. branchList = document.getElementById("branch");
  393. branches.forEach(branch => {
  394. opt = document.createElement('option');
  395. opt.value = branch['full_name'];
  396. opt.innerHTML = branch['label'];
  397. opt.selected = (branch['full_name'] === branch_to_select);
  398. branchList.appendChild(opt);
  399. });
  400. }