add_build.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. console.log(selected_options + "/" + total_options);
  162. let global_checkbox = document.getElementById("check-uncheck-all");
  163. let indeterminate_state = false;
  164. switch (selected_options) {
  165. case 0:
  166. global_checkbox.checked = false;
  167. break
  168. case total_options:
  169. global_checkbox.checked = true;
  170. break;
  171. default:
  172. indeterminate_state = true;
  173. break;
  174. }
  175. global_checkbox.indeterminate = indeterminate_state;
  176. }
  177. function getEnabledDependentFeaturesHelper(feature_label, visited, dependent_features) {
  178. if (visited[feature_label] != undefined || document.getElementById(feature_label).checked == false) {
  179. return;
  180. }
  181. visited[feature_label] = true;
  182. dependent_features.push(feature_label);
  183. let feature = getOptionByLabel(feature_label);
  184. if (feature.requiredFor == null) {
  185. return;
  186. }
  187. feature.requiredFor.forEach((dependent_feature) => {
  188. getEnabledDependentFeaturesHelper(dependent_feature, visited, dependent_features);
  189. });
  190. }
  191. function getEnabledDependentFeaturesFor(feature_label) {
  192. let dependent_features = [];
  193. let visited = {};
  194. if (getOptionByLabel(feature_label).requiredFor) {
  195. getOptionByLabel(feature_label).requiredFor.forEach((dependent_feature) => {
  196. getEnabledDependentFeaturesHelper(dependent_feature, visited, dependent_features);
  197. });
  198. }
  199. return dependent_features;
  200. }
  201. function applyDefaults() {
  202. features.forEach(category => {
  203. category['options'].forEach(option => {
  204. const check = featureisEnabledByDefault(option.label);
  205. checkUncheckOptionByLabel(option.label, check);
  206. });
  207. });
  208. }
  209. function checkUncheckOptionByLabel(label, check) {
  210. let element = document.getElementById(label);
  211. if (element == undefined || element.checked == check) {
  212. return;
  213. }
  214. element.checked = check;
  215. const triggered_by_ui = false;
  216. handleOptionStateChange(label, triggered_by_ui);
  217. }
  218. function checkUncheckAll(check) {
  219. features.forEach(category => {
  220. checkUncheckCategory(category.name, check);
  221. });
  222. }
  223. function checkUncheckCategory(category_name, check) {
  224. getCategoryByName(category_name).options.forEach(option => {
  225. checkUncheckOptionByLabel(option.label, check);
  226. });
  227. }
  228. return {reset, handleOptionStateChange, getCategoryIdByName, updateDefaults, applyDefaults, checkUncheckAll, checkUncheckCategory};
  229. })();
  230. var init_categories_expanded = false;
  231. var pending_update_calls = 0; // to keep track of unresolved Promises
  232. function init() {
  233. onVehicleChange(document.getElementById("vehicle").value);
  234. }
  235. // enables or disables the elements with ids passed as an array
  236. // if enable is true, the elements are enabled and vice-versa
  237. function enableDisableElementsById(ids, enable) {
  238. for (let i=0; i<ids.length; i++) {
  239. let element = document.getElementById(ids[i]);
  240. if (element) {
  241. element.disabled = (!enable);
  242. }
  243. }
  244. }
  245. // sets a spinner inside the division with given id
  246. // also sets a custom message inside the division
  247. // this indicates that an ajax call related to that element is in progress
  248. function setSpinnerToDiv(id, message) {
  249. let element = document.getElementById(id);
  250. if (element) {
  251. element.innerHTML = '<div class="container-fluid d-flex align-content-between">' +
  252. '<strong>'+message+'</strong>' +
  253. '<div class="spinner-border ms-auto" role="status" aria-hidden="true"></div>' +
  254. '</div>';
  255. }
  256. }
  257. function onVehicleChange(new_vehicle) {
  258. // following elemets will be blocked (disabled) when we make the request
  259. let elements_to_block = ['vehicle', 'branch', 'board', 'submit', 'reset_def', 'exp_col_button'];
  260. enableDisableElementsById(elements_to_block, false);
  261. let request_url = '/get_allowed_branches/'+new_vehicle;
  262. setSpinnerToDiv('branch_list', 'Fetching branches...');
  263. pending_update_calls += 1;
  264. sendAjaxRequestForJsonResponse(request_url)
  265. .then((json_response) => {
  266. let new_branch = json_response.default_branch;
  267. let all_branches = json_response.branches;
  268. updateBranches(all_branches, new_branch);
  269. })
  270. .catch((message) => {
  271. console.log("Branch update failed. "+message);
  272. })
  273. .finally(() => {
  274. enableDisableElementsById(elements_to_block, true);
  275. pending_update_calls -= 1;
  276. fetchAndUpdateDefaults();
  277. });
  278. }
  279. function updateBranches(all_branches, new_branch) {
  280. let branch_element = document.getElementById('branch');
  281. let old_branch = branch_element ? branch_element.value : '';
  282. fillBranches(all_branches, new_branch);
  283. if (old_branch != new_branch) {
  284. onBranchChange(new_branch);
  285. }
  286. }
  287. function onBranchChange(new_branch) {
  288. // following elemets will be blocked (disabled) when we make the request
  289. let elements_to_block = ['vehicle', 'branch', 'board', 'submit', 'reset_def', 'exp_col_button'];
  290. enableDisableElementsById(elements_to_block, false);
  291. let request_url = '/boards_and_features/'+new_branch;
  292. // create a temporary container to set spinner inside it
  293. let temp_container = document.createElement('div');
  294. temp_container.id = "temp_container";
  295. temp_container.setAttribute('class', 'container-fluid w-25 mt-3');
  296. let features_list_element = document.getElementById('build_options'); // append the temp container to the main features_list container
  297. features_list_element.innerHTML = "";
  298. features_list_element.appendChild(temp_container);
  299. setSpinnerToDiv('temp_container', 'Fetching features...');
  300. setSpinnerToDiv('board_list', 'Fetching boards...');
  301. pending_update_calls += 1;
  302. sendAjaxRequestForJsonResponse(request_url)
  303. .then((json_response) => {
  304. let boards = json_response.boards;
  305. let new_board = json_response.default_board;
  306. let new_features = json_response.features;
  307. Features.reset(new_features);
  308. updateBoards(boards, new_board);
  309. fillBuildOptions(new_features);
  310. })
  311. .catch((message) => {
  312. console.log("Boards and features update failed. "+message);
  313. })
  314. .finally(() => {
  315. enableDisableElementsById(elements_to_block, true);
  316. pending_update_calls -= 1;
  317. fetchAndUpdateDefaults();
  318. });
  319. }
  320. function updateBoards(all_boards, new_board) {
  321. let board_element = document.getElementById('board');
  322. let old_board = board_element ? board.value : '';
  323. fillBoards(all_boards, new_board);
  324. if (old_board != new_board) {
  325. onBoardChange(new_board);
  326. }
  327. }
  328. function onBoardChange(new_board) {
  329. fetchAndUpdateDefaults();
  330. }
  331. function fetchAndUpdateDefaults() {
  332. // return early if there is an unresolved promise (i.e., there is an ongoing ajax call)
  333. if (pending_update_calls > 0) {
  334. return;
  335. }
  336. elements_to_block = ['reset_def'];
  337. document.getElementById('reset_def').innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Fetching defaults';
  338. enableDisableElementsById(elements_to_block, false);
  339. let branch = document.getElementById('branch').value;
  340. let vehicle = document.getElementById('vehicle').value;
  341. let board = document.getElementById('board').value;
  342. let request_url = '/get_defaults/'+vehicle+'/'+branch+'/'+board;
  343. sendAjaxRequestForJsonResponse(request_url)
  344. .then((json_response) => {
  345. Features.updateDefaults(json_response);
  346. })
  347. .catch((message) => {
  348. console.log("Default reset failed. "+message);
  349. })
  350. .finally(() => {
  351. if (document.getElementById('auto_apply_def').checked) {
  352. Features.applyDefaults();
  353. }
  354. enableDisableElementsById(elements_to_block, true);
  355. document.getElementById('reset_def').innerHTML = '<i class="bi bi-arrow-counterclockwise me-2"></i>Reset feature defaults';
  356. });
  357. }
  358. function fillBoards(boards, default_board) {
  359. let output = document.getElementById('board_list');
  360. output.innerHTML = '<label for="board" class="form-label"><strong>Select Board</strong></label>' +
  361. '<select name="board" id="board" class="form-select" aria-label="Select Board" onchange="onBoardChange(this.value);"></select>';
  362. let boardList = document.getElementById("board")
  363. boards.forEach(board => {
  364. let opt = document.createElement('option');
  365. opt.value = board;
  366. opt.innerHTML = board;
  367. opt.selected = (board === default_board);
  368. boardList.appendChild(opt);
  369. });
  370. }
  371. var toggle_all_categories = (() => {
  372. let all_categories_expanded = init_categories_expanded;
  373. function toggle_method() {
  374. // toggle global state
  375. all_categories_expanded = !all_categories_expanded;
  376. let all_collapse_elements = document.getElementsByClassName('feature-group');
  377. for (let i=0; i<all_collapse_elements.length; i+=1) {
  378. let collapse_element = all_collapse_elements[i];
  379. collapse_instance = bootstrap.Collapse.getOrCreateInstance(collapse_element);
  380. if (all_categories_expanded && !collapse_element.classList.contains('show')) {
  381. collapse_instance.show();
  382. } else if (!all_categories_expanded && collapse_element.classList.contains('show')) {
  383. collapse_instance.hide();
  384. }
  385. }
  386. }
  387. return toggle_method;
  388. })();
  389. function createCategoryCard(category_name, options, expanded) {
  390. options_html = "";
  391. options.forEach(option => {
  392. options_html += '<div class="form-check">' +
  393. '<input class="form-check-input" type="checkbox" value="1" name="'+option['label']+'" id="'+option['label']+'" onclick="Features.handleOptionStateChange(this.id, true);">' +
  394. '<label class="form-check-label ms-2" for="'+option['label']+'">' +
  395. option['description'].replace(/enable/i, "") +
  396. '</label>' +
  397. '</div>';
  398. });
  399. let id_prefix = Features.getCategoryIdByName(category_name);
  400. let card_element = document.createElement('div');
  401. card_element.setAttribute('class', 'card ' + (expanded == true ? 'h-100' : ''));
  402. card_element.id = id_prefix + '_card';
  403. card_element.innerHTML = '<div class="card-header ps-3">' +
  404. '<div class="d-flex justify-content-between">' +
  405. '<div class="d-inline-flex">' +
  406. '<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>' +
  407. '<strong>' +
  408. '<label for="check-uncheck-category">' + category_name + '</label>' +
  409. '</strong>' +
  410. '</div>' +
  411. '<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">' +
  412. '<i class="bi bi-chevron-'+(expanded == true ? 'up' : 'down')+'" id="'+id_prefix+'_icon'+'"></i>' +
  413. '</button>' +
  414. '</div>' +
  415. '</div>';
  416. let collapse_element = document.createElement('div');
  417. collapse_element.setAttribute('class', 'feature-group collapse '+(expanded == true ? 'show' : ''));
  418. collapse_element.id = id_prefix + '_collapse';
  419. collapse_element.innerHTML = '<div class="container-fluid px-3 py-2">'+options_html+'</div>';
  420. card_element.appendChild(collapse_element);
  421. // add relevent event listeners
  422. collapse_element.addEventListener('hide.bs.collapse', () => {
  423. card_element.classList.remove('h-100');
  424. document.getElementById(id_prefix+'_icon').setAttribute('class', 'bi bi-chevron-down');
  425. });
  426. collapse_element.addEventListener('shown.bs.collapse', () => {
  427. card_element.classList.add('h-100');
  428. document.getElementById(id_prefix+'_icon').setAttribute('class', 'bi bi-chevron-up');
  429. });
  430. return card_element;
  431. }
  432. function fillBuildOptions(buildOptions) {
  433. let output = document.getElementById('build_options');
  434. output.innerHTML = `<div class="d-flex mb-3 justify-content-between">
  435. <div class="d-flex d-flex align-items-center">
  436. <p class="card-text"><strong>Available features for the current selection are:</strong></p>
  437. </div>
  438. <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>
  439. </div>`;
  440. buildOptions.forEach((category, cat_idx) => {
  441. if (cat_idx % 4 == 0) {
  442. let new_row = document.createElement('div');
  443. new_row.setAttribute('class', 'row');
  444. new_row.id = 'category_'+parseInt(cat_idx/4)+'_row';
  445. output.appendChild(new_row);
  446. }
  447. let col_element = document.createElement('div');
  448. col_element.setAttribute('class', 'col-md-3 col-sm-6 mb-2');
  449. col_element.appendChild(createCategoryCard(category['name'], category['options'], init_categories_expanded));
  450. document.getElementById('category_'+parseInt(cat_idx/4)+'_row').appendChild(col_element);
  451. });
  452. }
  453. // returns a Promise
  454. // the promise is resolved when we recieve status code 200 from the AJAX request
  455. // the JSON response for the request is returned in such case
  456. // the promise is rejected when the status code is not 200
  457. // the status code is returned in such case
  458. function sendAjaxRequestForJsonResponse(url) {
  459. return new Promise((resolve, reject) => {
  460. var xhr = new XMLHttpRequest();
  461. xhr.open('GET', url);
  462. // disable cache, thanks to: https://stackoverflow.com/questions/22356025/force-cache-control-no-cache-in-chrome-via-xmlhttprequest-on-f5-reload
  463. xhr.setRequestHeader("Cache-Control", "no-cache, no-store, max-age=0");
  464. xhr.setRequestHeader("Expires", "Tue, 01 Jan 1980 1:00:00 GMT");
  465. xhr.setRequestHeader("Pragma", "no-cache");
  466. xhr.onload = function () {
  467. if (xhr.status == 200) {
  468. resolve(JSON.parse(xhr.response));
  469. } else {
  470. reject("Got response:"+xhr.response+" (Status Code: "+xhr.status+")");
  471. }
  472. }
  473. xhr.send();
  474. });
  475. }
  476. function fillBranches(branches, branch_to_select) {
  477. var output = document.getElementById('branch_list');
  478. output.innerHTML = '<label for="branch" class="form-label"><strong>Select Branch</strong></label>' +
  479. '<select name="branch" id="branch" class="form-select" aria-label="Select Branch" onchange="onBranchChange(this.value);"></select>';
  480. branchList = document.getElementById("branch");
  481. branches.forEach(branch => {
  482. opt = document.createElement('option');
  483. opt.value = branch['full_name'];
  484. opt.innerHTML = branch['label'];
  485. opt.selected = (branch['full_name'] === branch_to_select);
  486. branchList.appendChild(opt);
  487. });
  488. }