hybridsjs / hybrids

Extraordinary JavaScript UI framework with unique declarative and functional architecture
https://hybrids.js.org
MIT License
3.03k stars 85 forks source link

how to implement focus management? #228

Closed Qsppl closed 7 months ago

Qsppl commented 8 months ago

When dynamically creating html elements, there is a problem with the element losing focus.

For example, in this example we go to the desired interactive element by pressing the tab key 7 times: image

Next, when clicked, we transfer focus from the button to the component. [1]

Then we delete the button that was clicked and generate another one instead. [2]

And at the end we return focus to the newly generated button. [3]

image

As a result, the focus is on the desired element and you can continue working.

image

This is all called focus management and is most often used when creating modal windows.

I'm having difficulty returning focus to generated elements. [3] I can't call the handler when the content of a component is updated. Does this need to be done using MutationObserver?

smalluban commented 8 months ago

I am not sure if this issue is related to hybrids. Your example is a pure class-based custom element. Can you provide some more details, which relate to this project?

In hybrids the focus events are supported just in the same way as others, you can attach the event listener to any "focusable" element (you can even make a div focusable by just addingtabindex="0"). You can save the element, or some kind of id in the component, and manage it then...

Qsppl commented 8 months ago

When the markup is changed using the render() function, the button that has the focus will be removed. Therefore, the focus will be moved to document. In the example above, I manually transfer focus to the new button after the render() function is executed. But in hybrids I can't do anything after the render() function is executed. image

I can write an example on hybrids if I didn’t explain it well.

Qsppl commented 7 months ago

I faced the same problem in another task. When opening a dialog, I need to immediately focus on the input field.

I can't apply focus to a form element that doesn't already exist. It is impossible to understand when this html element already exists.

After the hybrids component example, I've added a working JS example to explain what I mean.

example: https://codesandbox.io/p/sandbox/focus-managment-in-hybrids-ffc334?file=%2Findex.html%3A33%2C54

Qsppl commented 7 months ago

Moved to https://github.com/hybridsjs/hybrids/issues/231