hide-cell.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. Add buttons to hide code cells
  3. */
  4. var setCodeCellVisibility = function (inputField, kind) {
  5. // Update the image and class for hidden
  6. var id = inputField.getAttribute('data-id');
  7. var codeCell = document.querySelector(`#${id} div.highlight`);
  8. if (kind === "visible") {
  9. codeCell.classList.remove('hidden');
  10. inputField.checked = true;
  11. } else {
  12. codeCell.classList.add('hidden');
  13. inputField.checked = false;
  14. }
  15. }
  16. var toggleCodeCellVisibility = function (event) {
  17. // The label is clicked, and now we decide what to do based on the input field's clicked status
  18. if (event.target.tagName === "LABEL") {
  19. var inputField = event.target.previousElementSibling;
  20. } else {
  21. // It is the span inside the target
  22. var inputField = event.target.parentElement.previousElementSibling;
  23. }
  24. if (inputField.checked === true) {
  25. setCodeCellVisibility(inputField, "visible");
  26. } else {
  27. setCodeCellVisibility(inputField, "hidden");
  28. }
  29. }
  30. // Button constructor
  31. const hideCodeButton = id => `<input class="hidebtn" type="checkbox" id="hidebtn${id}" data-id="${id}"><label title="Toggle cell" for="hidebtn${id}" class="plusminus"><span class="pm_h"></span><span class="pm_v"></span></label>`
  32. var addHideButton = function () {
  33. // If a hide button is already added, don't add another
  34. if (document.querySelector('div.tag_hide_input input') !== null) {
  35. return;
  36. }
  37. // Find the input cells and add a hide button
  38. pageElements['inputCells'].forEach(function (inputCell) {
  39. if (!inputCell.classList.contains("tag_hide_input")) {
  40. // Skip the cell if it doesn't have a hidecode class
  41. return;
  42. }
  43. const id = inputCell.getAttribute('id')
  44. // Insert the button just inside the end of the next div
  45. inputCell.querySelector('div.input').insertAdjacentHTML('beforeend', hideCodeButton(id))
  46. // Set up the visibility toggle
  47. hideLink = document.querySelector(`#${id} div.inner_cell + input + label`);
  48. hideLink.addEventListener('click', toggleCodeCellVisibility)
  49. });
  50. }
  51. // Initialize the hide buttos
  52. var initHiddenCells = function () {
  53. // Add hide buttons to the cells
  54. addHideButton();
  55. // Toggle the code cells that should be hidden
  56. document.querySelectorAll('div.tag_hide_input input').forEach(function (item) {
  57. setCodeCellVisibility(item, 'hidden');
  58. item.checked = true;
  59. })
  60. }
  61. initFunction(initHiddenCells);