This is what you can end up with, managing all possible state changes manually. I've done this myself with jQuery, show/hide, enable/disable elements. Turns into a game of Whac-A-Mole and full-time job for testers. Now imagine adding/removing elements and having to update this monster. No thank you.
Monster? It's very straightforward, functional and easy to follow. You could easily refactor that and break it up without fuss. Not sure what the big deal is here. The fact that it operates on a state machine makes it even easier. You can see all the different ways the UI will render by stubbing the state value.
The problem is when you have a large app with multiple components and plenty of state to manage. These things always look easy when they are small toy isolated projects.
This sort of thing in a production app would be littered with global state, it would be difficult to change anything / refactor without serious anxiety, if you have multiple developers good luck getting them to program the same predictable way, importing libraries see previous point, etc, etc.
Adding a few more fields would require me to update every case plus add some more, no? Resulting in an hard to maintain explosion of state? Or am I missing something.
You can dispense with the whole intermediate state variable and just do everything directly
function calcState() {
// Return field disabled for one-way trips
elems.return.disabled = isOneWay();
let allOk = true;
// All enabled fields are valid?
for (const f of [elems.departure, elems.return]) {
const isInvalid = (
!f.disabled &&
isBadFormat(f.value)
);
setInvalid(f, isInvalid);
if (isInvalid) allOk = false;
}
// Return trip after departure trip?
if (allOk && !isOneWay() && isEarlyReturn()) {
allOk = false;
}
// Enable submit if everything is OK
elems.submit.disabled = !allOk;
}
function setInvalid(elem, invalid) {
elem.setAttribute(ARIA_INVALID, invalid);
}
This follows the problem description quite closely, eg. "The return textfield is enabled if the combobox’s value is return flight" is implemented by one line, and not spread across seven different enable/disable calls.
https://github.com/bradwoods/7guis-html-css-js/blob/19279899...