add_build.js 21 KB

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