add_build.js 22 KB

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