From 6ddba30a1f3f74c1f811d5b53109be1d74360098 Mon Sep 17 00:00:00 2001 From: benoit74 Date: Mon, 11 Nov 2024 10:39:57 +0000 Subject: [PATCH] Collapse entries of categories/books when there is more than 5 --- zimui/src/services/collapse.ts | 65 ++++++++++++++++++++++++++++++++++ zimui/src/stores/main.ts | 4 +++ 2 files changed, 69 insertions(+) create mode 100644 zimui/src/services/collapse.ts diff --git a/zimui/src/services/collapse.ts b/zimui/src/services/collapse.ts new file mode 100644 index 0000000..ddbb7b1 --- /dev/null +++ b/zimui/src/services/collapse.ts @@ -0,0 +1,65 @@ +/* +Service to handle DOM manipulation to collapse subpages of books when there are too many + +See e.g. https://geo.libretexts.org/Courses/Fullerton_College (page ID 32303) +*/ + +const maxVisibleItems = 5 + +class CollapseService { + handle_page_load() { + // Remove show all buttons which migth have been added previously + const previousShowAllButtons = document.querySelectorAll('button.zim-show-all-button') + for (const previousShowAllButton of previousShowAllButtons) { + previousShowAllButton.remove() + } + + // Load all ul elements corresponding to a category (e.g. books) + const ulElements = document.querySelectorAll( + 'div.mt-category-container dd.mt-listing-detailed-subpages ul' + ) + + for (const ulElement of ulElements) { + if (!ulElement.parentNode) { + continue // Failsafe, just in case + } + const listItems = ulElement.querySelectorAll('li') + + // Check if there are more than 5 items + if (listItems.length <= maxVisibleItems) { + return + } + + // Hide all list items after the 5th one + listItems.forEach((item, index) => { + if (index >= maxVisibleItems) { + item.style.display = 'none' + } + }) + + // Create the "Show all" button + const showAllButton = document.createElement('button') + showAllButton.className = + 'mt-icon-expand-collapse mt-reveal-listing-expand-link zim-show-all-button' + showAllButton.title = 'Show all' + + // Insert the button after the