add_build.js 22 KB

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