Re-Implemented Div-Menu

This commit is contained in:
Simon Martens
2025-06-04 19:52:52 +02:00
parent 715be79115
commit 3a6dcc0e3d
7 changed files with 413 additions and 640 deletions

View File

@@ -1,32 +1,20 @@
// Define CSS class names as constants, above the component class
const USER_PROVIDED_MENU_BUTTON_CLASS = "div-menu-button";
const TS_POPUP = "ts-menu-popup";
const TS_LIST = "ts-menu-list";
const TS_MENU_LABEL = "menu-label";
const TS_PLACEHOLDER_MESSAGE = "ts-menu-placeholder-message";
const TS_LIST_ITEM = "ts-menu-list-item";
const TS_ITEM_ACTION = "ts-menu-item-action";
const TS_ITEM_IS_SELECTED = "ts-item-is-selected";
const TAILWIND_HIDDEN_CLASS = "hidden";
const TS_MENU_BUTTON_STATE_DISABLED = "ts-menu-button--disabled";
const TS_MENU_LABEL_IN_MENU_STATE = "ts-menu-label--in-menu";
const TS_MENU_LABEL_DISPLAYED_STATE = "ts-menu-label--displayed";
const TS_TARGET_PLACEHOLDER_CLASS = "ts-target-placeholder"; // For the target area placeholder
const TARGET_ID_ATTRIBUTE = "target-id"; // Attribute to specify the target element ID
const DM_STAY_ATTRIBUTE = "dm-stay"; // Attribute to indicate if a div should stay in the menu
const DM_TITLE_ATTRIBUTE = "dm-title"; // Attribute to indicate if a div has a title
const DM_MENU_BUTTON_CLASS = "dm-menu-button"; // Class for the menu button
const DM_TARGET_ATTRIBUTE = "dm-target"; // Attribute to specify the target element ID for the redesigned menu
const DM_STAY_ATTRIBUTE = "dm-stay";
const DM_TITLE_ATTRIBUTE = "dm-title";
const DM_MENU_BUTTON_CLASS = "dm-menu-button";
const DM_TARGET_ATTRIBUTE = "dm-target";
const DM_MENU_CLASS = "dm-menu";
const DM_ITEM_CLASS = "dm-menu-item";
const DM_CLOSE_BUTTON_CLASS = "dm-close-button";
//
// Prereq: child divs must have prop data-value, and a label element
// Prereq: child divs must eiteher have dm-title attr or a label element
// The child divs will be moved to the target element when selected
// The target element must be specified by the attribute target-id on the custom element
// The menu button must have the class div-menu-button
//
// The target element must be specified by the attribute dm-target on the custom element
// The menu button must have the class dm-menu-button
// The child divs can contain a button with the class dm-close-button
export class DivMenuRedesigned extends HTMLElement {
export class DivManager extends HTMLElement {
constructor() {
super();
this.#reset();
@@ -34,6 +22,7 @@ export class DivMenuRedesigned extends HTMLElement {
#reset() {
this._cildren = [];
this._rendered = [];
this._target = null;
this._button = null;
this._menu = null;
@@ -66,321 +55,142 @@ export class DivMenuRedesigned extends HTMLElement {
}
for (const child of this._cildren) {
parentNode.removeChild(child.node);
this.removeChild(child.node);
}
this._button.addEventListener("click", this._toggleMenu.bind(this));
this._button.classList.add("relative");
}
renderMenu() {
this._menu += `<ul class="${TS_P}">`;
}
renderNode() {}
}
export class DivMenu extends HTMLElement {
constructor() {
super();
this._menuItemsMap = new Map();
this._targetElement = null;
this._originalChildDivs = [];
this._observer = null;
this._menuPlaceholderMessageElement = null;
this._menuButton = null;
this._toggleMenu = this._toggleMenu.bind(this);
this._handleMenuItemClick = this._handleMenuItemClick.bind(this);
this._handleClickOutside = this._handleClickOutside.bind(this);
this._handleContentClose = this._handleContentClose.bind(this);
this._handleMutations = this._handleMutations.bind(this);
this._checkMenuPlaceholderAndButton = this._checkMenuPlaceholderAndButton.bind(this);
this._clearFormElements = this._clearFormElements.bind(this);
this._refreshTargetOrder = this._refreshTargetOrder.bind(this); // Bind new method
}
connectedCallback() {
this._menuButton = this.querySelector(`.${USER_PROVIDED_MENU_BUTTON_CLASS}`);
if (!this._menuButton) {
console.error(`TabSelectorMenu: User-provided menu button with class '${USER_PROVIDED_MENU_BUTTON_CLASS}' not found.`);
}
this._originalChildDivs = Array.from(this.children).filter((node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV" && !node.classList.contains(USER_PROVIDED_MENU_BUTTON_CLASS));
this._originalChildDivs.forEach((div) => div.remove());
const componentPopupHTML = `
<div class="${TS_POPUP}">
<ul class="${TS_LIST}">
<li class="${TS_PLACEHOLDER_MESSAGE}"></li>
</ul>
</div>
`;
this.insertAdjacentHTML("beforeend", componentPopupHTML);
this._menuPopupElement = this.querySelector(`.${TS_POPUP}`);
this._menuListElement = this.querySelector(`.${TS_LIST}`);
this._menuPlaceholderMessageElement = this.querySelector(`.${TS_PLACEHOLDER_MESSAGE}`);
if (!this._menuPopupElement || !this._menuListElement || !this._menuPlaceholderMessageElement) {
console.error("CRITICAL: Popup structure parts missing.");
return;
}
const targetId = this.getAttribute("target-id");
if (targetId) {
this._targetElement = document.getElementById(targetId);
if (!this._targetElement) console.warn(`TabSelectorMenu: Target ID '${targetId}' not found.`);
} else {
console.warn(`TabSelectorMenu: 'target-id' attribute missing.`);
}
this._observer = new MutationObserver(this._handleMutations);
this._originalChildDivs.forEach((sourceDiv) => {
const menuLabelElement = sourceDiv.querySelector("label." + TS_MENU_LABEL);
const itemValue = sourceDiv.dataset.value;
if (!menuLabelElement || !itemValue) {
console.warn('TabSelectorMenu: Source div missing <label class="menu-label"> or data-value:', sourceDiv);
return;
}
const isInitiallySelected = !sourceDiv.classList.contains(TAILWIND_HIDDEN_CLASS);
this.appendChild(sourceDiv);
const labelText = menuLabelElement.textContent.trim();
const menuItemHTML = `
<li class="${TS_LIST_ITEM}">
<button type="button" class="${TS_ITEM_ACTION}" data-value="${itemValue}">
${labelText}
</button>
</li>`;
this._menuPlaceholderMessageElement.insertAdjacentHTML("beforebegin", menuItemHTML);
const addedMenuItemButton = this._menuListElement.querySelector(`.${TS_ITEM_ACTION}[data-value="${itemValue}"]`);
this._menuItemsMap.set(itemValue, {
sourceDiv,
menuItemButton: addedMenuItemButton,
menuListItem: addedMenuItemButton.parentElement,
menuLabelElement: menuLabelElement,
selected: isInitiallySelected,
for (const child of this._cildren) {
const closebtns = child.node.querySelectorAll(`.${DM_CLOSE_BUTTON_CLASS}`);
closebtns.forEach((btn) => {
btn.addEventListener("click", (event) => {
this.hideDiv(event, child.node);
});
});
this._observer.observe(sourceDiv, { attributes: true, attributeFilter: ["class"] });
});
this._menuItemsMap.forEach((itemData) => {
this._updateItemState(itemData, false, true);
});
// _refreshTargetOrder() is called within _updateItemState, so target should be correct.
this._checkMenuPlaceholderAndButton();
if (this._menuButton) {
this._menuButton.addEventListener("click", this._toggleMenu);
}
this._menuListElement.addEventListener("click", this._handleMenuItemClick);
document.addEventListener("click", this._handleClickOutside);
}
disconnectedCallback() {
document.removeEventListener("click", this._handleClickOutside);
if (this._observer) {
this._observer.disconnect();
}
if (this._menuButton) {
this._menuButton.removeEventListener("click", this._toggleMenu);
}
}
_clearFormElements(parentElement) {
if (!parentElement) return;
const inputs = parentElement.querySelectorAll("input, textarea, select");
inputs.forEach((el) => {
switch (el.type) {
case "button":
case "submit":
case "reset":
case "image":
break;
case "checkbox":
case "radio":
el.checked = false;
break;
case "file":
el.value = null;
break;
default:
el.value = "";
}
if (el.tagName === "SELECT") el.selectedIndex = 0;
});
}
_refreshTargetOrder() {
if (!this._targetElement) return;
// Detach all currently managed divs from target
const managedDivsInTarget = [];
this._menuItemsMap.forEach((item) => {
if (item.sourceDiv.parentElement === this._targetElement) {
managedDivsInTarget.push(item.sourceDiv);
}
});
managedDivsInTarget.forEach((div) => this._targetElement.removeChild(div));
// Remove existing component-managed placeholder if any
const existingPlaceholder = this._targetElement.querySelector(`.${TS_TARGET_PLACEHOLDER_CLASS}`);
if (existingPlaceholder) {
this._targetElement.removeChild(existingPlaceholder);
}
// Append selected divs in their original order
let hasSelectedItems = false;
this._menuItemsMap.forEach((item) => {
if (item.selected) {
item.sourceDiv.classList.remove(TAILWIND_HIDDEN_CLASS); // Ensure it's visible
this._targetElement.appendChild(item.sourceDiv);
hasSelectedItems = true;
}
});
// Add placeholder if target is empty and no items were selected to be appended
if (!hasSelectedItems) {
const placeholder = document.createElement("p");
placeholder.className = TS_TARGET_PLACEHOLDER_CLASS;
this._targetElement.appendChild(placeholder);
}
}
_checkMenuPlaceholderAndButton() {
if (!this._menuPlaceholderMessageElement || !this._menuButton) return;
let visibleItemCount = 0;
this._menuItemsMap.forEach((itemData) => {
if (itemData.menuListItem.style.display !== "none") {
visibleItemCount++;
}
});
const allItemsSelected = visibleItemCount === 0;
this._menuPlaceholderMessageElement.style.display = allItemsSelected ? "block" : "none";
if (allItemsSelected) {
this._menuButton.classList.add(TS_MENU_BUTTON_STATE_DISABLED);
} else {
this._menuButton.classList.remove(TS_MENU_BUTTON_STATE_DISABLED);
}
}
_handleMutations(mutationsList) {
for (const mutation of mutationsList) {
if (mutation.type === "attributes" && mutation.attributeName === "class") {
const targetDiv = mutation.target;
const itemValue = targetDiv.dataset.value;
const itemData = this._menuItemsMap.get(itemValue);
if (itemData) {
const isNowHiddenByClass = targetDiv.classList.contains(TAILWIND_HIDDEN_CLASS);
if (isNowHiddenByClass && itemData.selected) {
itemData.selected = false;
this._updateItemState(itemData, false, true);
} else if (!isNowHiddenByClass && !itemData.selected) {
itemData.selected = true;
this._updateItemState(itemData, false, true);
}
}
}
}
}
_handleContentClose(event) {
const itemValue = event.currentTarget.dataset.value;
const itemData = this._menuItemsMap.get(itemValue);
if (itemData && itemData.selected) {
itemData.selected = false;
this._updateItemState(itemData, false, true);
}
this.renderMenu();
this.renderIntoTarget();
}
_toggleMenu(event) {
event.preventDefault();
event.stopPropagation();
if (this._menuButton && this._menuButton.classList.contains(TS_MENU_BUTTON_STATE_DISABLED)) {
if (!this._menu) {
this._menu = this.querySelector(`.${DM_MENU_CLASS}`);
}
if (!this._menu) {
console.error("DivManagerMenu: Menu not found.");
return;
}
const isHidden = this._menuPopupElement.style.display === "none" || this._menuPopupElement.style.display === "";
if (isHidden) {
this._checkMenuPlaceholderAndButton();
if (this._menu.classList.contains(TAILWIND_HIDDEN_CLASS)) {
this._menu.classList.remove(TAILWIND_HIDDEN_CLASS);
} else {
this._menu.classList.add(TAILWIND_HIDDEN_CLASS);
}
this._menuPopupElement.style.display = isHidden ? "block" : "none";
}
_closeMenu() {
this._menuPopupElement.style.display = "none";
}
renderButton() {
if (!this._button) {
return;
}
_handleClickOutside(event) {
if (!this.contains(event.target) && this._menuPopupElement.style.display !== "none") {
if (this._menuButton && this._menuButton.contains(event.target)) {
for (const child of this._cildren) {
if (child.hidden()) {
if (this._button.parentElement !== this) {
this._button.classList.remove(TAILWIND_HIDDEN_CLASS);
this.appendChild(this._button);
}
return;
}
this._closeMenu();
}
this._button.classList.add(TAILWIND_HIDDEN_CLASS);
this.removeChild(this._button);
}
_handleMenuItemClick(event) {
const clickedButton = event.target.closest(`.${TS_ITEM_ACTION}`);
if (clickedButton && clickedButton.dataset.value) {
const itemValue = clickedButton.dataset.value;
const itemData = this._menuItemsMap.get(itemValue);
if (itemData) {
if (!itemData.selected) {
itemData.selected = true;
this._updateItemState(itemData, true, true);
}
}
hideDiv(event, node) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
}
_updateItemState(itemData, closeMenuAfterUpdate, manageHiddenClass) {
if (!itemData || !itemData.sourceDiv || !itemData.menuItemButton || !itemData.menuListItem || !itemData.menuLabelElement) {
console.warn("TabSelectorMenu: Incomplete itemData for update:", itemData);
if (!node || !(node instanceof HTMLElement)) {
console.error("DivManagerMenu: Invalid node provided.");
return;
}
const menuLabel = itemData.menuLabelElement;
if (itemData.selected) {
// No direct DOM manipulation of sourceDiv here regarding targetElement
// _refreshTargetOrder will handle placement.
if (manageHiddenClass) itemData.sourceDiv.classList.remove(TAILWIND_HIDDEN_CLASS);
itemData.menuItemButton.classList.add(TS_ITEM_IS_SELECTED);
itemData.menuListItem.style.display = "none";
menuLabel.classList.add(TS_MENU_LABEL_DISPLAYED_STATE);
menuLabel.classList.remove(TS_MENU_LABEL_IN_MENU_STATE);
} else {
if (manageHiddenClass) itemData.sourceDiv.classList.add(TAILWIND_HIDDEN_CLASS);
this._clearFormElements(itemData.sourceDiv);
itemData.menuItemButton.classList.remove(TS_ITEM_IS_SELECTED);
itemData.menuListItem.style.display = "";
menuLabel.classList.add(TS_MENU_LABEL_IN_MENU_STATE);
menuLabel.classList.remove(TS_MENU_LABEL_DISPLAYED_STATE);
// If the div is being hidden, ensure it's moved back to the component
// if it was in the target. _refreshTargetOrder will handle its removal from target.
if (itemData.sourceDiv.parentElement !== this && itemData.sourceDiv.parentElement !== this._targetElement) {
this.appendChild(itemData.sourceDiv);
} else if (itemData.sourceDiv.parentElement === this._targetElement) {
// It will be removed by _refreshTargetOrder, then re-appended to 'this' if needed
// For now, just ensure it's not orphaned if _refreshTargetOrder doesn't run immediately after this.
// Actually, better to let _refreshTargetOrder handle removal from target.
// And if it's not selected, ensure it's a child of 'this' for mutation observer.
}
const child = this._cildren.find((c) => c.node === node);
if (!child) {
console.error("DivManagerMenu: Child not found.");
return;
}
this._refreshTargetOrder(); // Centralize target DOM updates
this._checkMenuPlaceholderAndButton();
if (!child.hidden()) {
child.node.classList.add(TAILWIND_HIDDEN_CLASS);
}
if (closeMenuAfterUpdate) this._closeMenu();
this._target.removeChild(child.node);
// INFO: the order of these matter, dont fuck it up
this.renderButton();
this.renderMenu();
}
showDiv(event, index) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
if (index < 0 || index >= this._cildren.length) {
console.error("DivManagerMenu: Invalid index.");
return;
}
const child = this._cildren[index];
if (child.hidden()) {
child.node.classList.remove(TAILWIND_HIDDEN_CLASS);
}
this._target.appendChild(child.node);
// INFO: the order of these matter, dont fuck it up
this.renderMenu();
this.renderButton();
}
renderMenu() {
if (!this._menu) {
this._button.innerHTML += `<div class="${DM_MENU_CLASS} absolute hidden"></div>`;
this._menu = this._button.querySelector(`.${DM_MENU_CLASS}`);
}
this._menu.innerHTML = `${this._cildren
.map((c, index) => {
if (!c.hidden()) return "";
return `
<button type="button" class="${DM_ITEM_CLASS}" dm-itemno="${index}">
${c.name()}
</button>`;
})
.join("")}`;
this._menu = this.querySelector(`.${DM_MENU_CLASS}`);
const buttons = this._menu.querySelectorAll(`.${DM_ITEM_CLASS}`);
buttons.forEach((button) => {
button.addEventListener("click", (event) => {
this.showDiv(event, parseInt(button.getAttribute("dm-itemno")));
this._toggleMenu(event);
});
});
}
renderIntoTarget() {
this._cildren.forEach((child) => {
if (!child.hidden()) {
this._target.appendChild(child.node);
}
});
}
}

View File

@@ -1,4 +1,8 @@
@layer components {
button {
@apply cursor-pointer disabled:cursor-default;
}
.dbform .inputwrapper {
@apply rounded-xs border-2 border-transparent pl-3 pr-1.5
py-1 pb-1.5 border-l-2 focus-within:border-l-slate-600
@@ -278,26 +282,24 @@
@apply disabled:hidden;
}
.ts-menu-popup {
@apply hidden absolute top-full left-0 bg-white border border-gray-300 rounded-xs shadow z-50 min-w-[200px] mt-1;
.dm-menu-button {
@apply text-gray-700 hover:text-gray-950 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-500;
}
.ts-menu-list {
list-style: none;
padding: 0px 0;
margin: 0;
.dm-menu {
@apply top-full right-0 bg-white border border-gray-300 rounded-xs shadow z-50 mt-1 flex flex-col;
}
.ts-menu-list li {
@apply cursor-pointer ml-0 list-none px-2.5 py-1 hover:bg-gray-100 border-b;
.dm-menu .dm-menu-item {
@apply cursor-pointer ml-0 list-none px-2.5 py-1 hover:bg-gray-100 border-b w-full;
}
.ts-menu-list li:last-child {
.dm-menu .dm-menu-item:last-child {
@apply border-b-0;
}
.ts-menu-list li button {
@apply w-full cursor-pointer text-left text-gray-700;
.dm-menu .dm-menu-item {
@apply cursor-pointer text-left text-gray-700;
}
.form-submit-button {

View File

@@ -13,7 +13,7 @@ import { ImageReel } from "./image-reel.js";
import { MultiSelectRole } from "./multi-select-role.js";
import { MultiSelectSimple } from "./multi-select-simple.js";
import { ResetButton } from "./reset-button.js";
import { DivMenu } from "./div-menu.js";
import { DivManager } from "./div-menu.js";
const FILTER_LIST_ELEMENT = "filter-list";
const SCROLL_BUTTON_ELEMENT = "scroll-button";
@@ -27,7 +27,7 @@ const IMAGE_REEL_ELEMENT = "image-reel";
const MULTI_SELECT_ROLE_ELEMENT = "multi-select-places";
const MULTI_SELECT_SIMPLE_ELEMENT = "multi-select-simple";
const RESET_BUTTON_ELEMENT = "reset-button";
const DIV_MENU_ELEMENT = "div-menu";
const DIV_MANAGER_ELEMENT = "div-manager";
customElements.define(INT_LINK_ELEMENT, IntLink);
customElements.define(ABBREV_TOOLTIPS_ELEMENT, AbbreviationTooltips);
@@ -41,7 +41,7 @@ customElements.define(IMAGE_REEL_ELEMENT, ImageReel);
customElements.define(MULTI_SELECT_ROLE_ELEMENT, MultiSelectRole);
customElements.define(MULTI_SELECT_SIMPLE_ELEMENT, MultiSelectSimple);
customElements.define(RESET_BUTTON_ELEMENT, ResetButton);
customElements.define(DIV_MENU_ELEMENT, DivMenu);
customElements.define(DIV_MANAGER_ELEMENT, DivManager);
function PathPlusQuery() {
const path = window.location.pathname;

View File

@@ -65,7 +65,9 @@ export class ResetButton extends HTMLElement {
el.removeEventListener("change", this.handleInputChange);
});
this._controlledElements = [];
this.initialStates.clear();
// INFO: we don't clear the intitial states here, in case we
// want to reattach the same elements later.
// this.initialStates.clear();
this.lastOverallModifiedState = null;
const controlIds = (this.getAttribute("controls") || "")
@@ -107,6 +109,9 @@ export class ResetButton extends HTMLElement {
}
storeInitialState(element) {
if (this.initialStates.has(element.id)) {
return;
}
let state;
switch (element.type) {
case "checkbox":