Reusable TypeScript / JavaScript Recursion Method
Toggling opening and closing UI block level elements. Handles n - level.
Targeting a button, toggles open showing its children elements.
Hooking up UI
$(".toggleSeeds").click((function () {
var state = {},
currentId = null;
return function () {
var id: number = GetId(this.id);
ResetStates(this);
state[id] = typeof state[id] != "undefined" ? state[id] : {
collapsed: true,
toggleSeeds: $("#toggleSeeds_" + id + "> img")[0],
supplierSeeds: $("#supplierSeeds_" + id)
};
if (state[id].collapsed) {
state[id].supplierSeeds.show();
state[id].toggleSeeds.src = "/images/SVG/arrowhead-Down.svg";
if (currentId && currentId != id) {
state[currentId].supplierSeeds.hide();
state[currentId].collapsed = true;
state[currentId].toggleSeeds.src = "/images/SVG/arrowhead-Right.svg";
}
currentId = id;
} else {
state[id].supplierSeeds.hide();
state[id].toggleSeeds.src = "/images/SVG/arrowhead-Right.svg";
currentId = null;
}
state[id].collapsed = !state[id].collapsed;
}
}()));
Tracking states
var ResetStates: (element: HTMLElement) => void = (function () {
var buttonState: HTMLElement[] = [];
return (element: HTMLElement) => {
var state: HTMLElement,
parent: HTMLElement,
stateLevels: RegExpMatchArray,
targetLevels: RegExpMatchArray,
sameLevel: boolean,
sameParent: boolean,
isChild: boolean,
switchedLevels: boolean;
if (buttonState.length == 0) {
buttonState.push(element);
return;
}
state = buttonState[buttonState.length - 1] ?? element;
parent = buttonState[0] ?? element;
stateLevels = state.id.match(/[0-9]+/g);
targetLevels = element.id.match(/[0-9]+/g);
sameParent = stateLevels[0] == targetLevels[0];
sameLevel = stateLevels.length == targetLevels.length;
isChild = (targetLevels.length > stateLevels.length) && sameParent;
switchedLevels = (parent.id != element.id) && !sameParent;
if (state.id != element.id) {
if (sameLevel) {
buttonState[buttonState.length - 1] = null;
state.click();
buttonState.push(element);
} else if (isChild) {
buttonState.push(element);
} else if (switchedLevels || sameParent) {
while (buttonState.length > 0) {
state = buttonState[buttonState.length - 1];
if (state != null) {
buttonState[buttonState.length - 1] = null;
state.click();
}
}
buttonState.push(element);
}
} else {
buttonState.pop();
}
}
}());
This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford
No comments:
Post a Comment