nicegui: Events such as keydown and keyup are not triggered by an ui.input when not assigned directly upon creation
Description
During the development of a Typeahead component which attaches itself visually to the bottom of an ui.input field to (later) show search result data from a DB, i stumbled over a potential bug when modifying certain event_listeners such as keydown and keyup via the element.on method “post creation”.
Situation:
- An ui.input field is created
- A focus handler is set up via
.on("focus", handle_focus)and a blur_handler is setup viaon("blur", handle_blur) - In
handle_focusthe.on("keydown", handle_keydown)is assigned to track cursor key presses - In
handle_blurthe event listener is removed again.- As NiceGUI doesn’t officially support removal of event listeners added via
.onyet there is a helper class involved which “cleans up again” / can unassign event listeners, but that just as side note and has no impact on this report / test as you can see in the example code attached below.
- As NiceGUI doesn’t officially support removal of event listeners added via
- Expected behavior: handle_keydown will be called when a key is pressed.
- Actual behavior: It is not
If a “keypress” or “keyup” listener is assigned later and not directly upon creation of the input field, so e.g. delayed by a timer or an event, then the handlers will never be called. If they are assigned directly upon creation, so before everything goes through the websocket from Python to JS, then they work though.
If I assign the same events directly via JavaScript to the DOM element w/ help of the new getHtmlElement function though then everything works perfectly fine. Thus there seems to be some synchronization kind of issue for certain events. A delayed assigned blur event just for example works like a charm.
from nicegui import ui
@ui.page('/')
async def index():
log_area = ui.scroll_area().style('height: 200px; width: 400px')
def log_key(e):
with log_area:
ui.label(f"Key pressed: {e.args['key']}").classes('font-mono text-xs').style('line-height: 1; margin: 0; padding: 0;')
log_area.scroll_to(percent=1.0)
with ui.row():
input1 = ui.input()
ui.run_javascript(f'''
getHtmlElement({input1.id}).addEventListener("keydown", () => console.log("keydown on input1 via js"));
''')
input1.on('keydown', log_key) # will be triggered
input1.on('keydown', js_handler='() => console.log("keydown on input1")') # will be triggered
input2 = ui.input()
def attach_event():
input2.on('keydown', log_key) # will NOT be triggered
input2.on('keydown', js_handler='() => console.log("keydown on input2")') # will NOT be triggered
input2.on('blur', lambda e: print('blur')) # will be triggered
ui.run_javascript(f'''
getHtmlElement({input2.id}).addEventListener("keydown", () => console.log("keydown on input2 via js"));
''') # will be triggered
# setup timer which attaches the event
ui.timer(1.0, attach_event, once=True, immediate=False)
ui.run()
About this issue
- Original URL
- State: open
- Created 2 years ago
- Reactions: 1
- Comments: 17 (9 by maintainers)
(from @falkoschindler)
This does appear to be the problem:
In the case of button, it looks like button has an internal click handler that emits events, hence why you can add an event handler after the fact… I’d have to dig more at this to verify https://github.com/quasarframework/quasar/blob/259a400d258c26fc5b7fd068e9247e189f574af4/ui/src/components/btn/QBtn.js#L294
Here’s a self contained example (pure vue/quasar) - this example shows adding a keydown event to show the last key pressed. If you set
hasKeydownListenerto true initially, you end up being able to add and remove the handler. If it starts as false, adding it has no effect.And here is another self container example using a possible work around of using
v-if/elsein templates to force complete re-render of the component:It seems to me like, given we are wrapping q-input in a component with some other functionality, a plausible solution to this problem could be to give NiceGUI input a bunch of handlers that emit events, similar to what Quasar does with QBtn.
Sorry for the long post!
I managed to make it work, but it makes no sense whatsoever!!
So, first of all, an apology. I thought I was working on the latest NiceGUI 2.12.1 in my venv. Turns out I was editing the system installation. Guess the version of that? 2.3.0! It’s from Oct 4, 2024… 🤦♂️
But, it’s fine, because it is too strange to explain always.
So now, we have established that the issue basically has to be either
nicegui.jsorinput.js. Definitely not a.pyfile, because the issue would then not be selective with regards to pre/postawait ui.context.client.connected()I have tried to comment out or remove all suspicious lines in
input.js. Victims include:@keydown.tab="perform_autocomplete"e.preventDefault();Then, I took a shot at
nicegui.js. As a guy who knows nothing about the debugger, console.log was the (only?) way to go.Left verbatim from NiceGUI 2.3.0, freshly installed in fact. Right modified.
Now, you see, all I added was console.log statements, and magically the one with the console.log statement worked on the /page2 which was broken otherwise
Did console.log statements fix the code? How’s that supposed to work??
My modification: https://gist.github.com/evnchn/74769527c4a23913804b63e69ba4e7c0
Diff report: diff-nicegui-2.3.0-modded.pdf
I am using a “nonstandard browser” though? But it is https://github.com/win32ss/supermium
@falkoschindler I need help with JavaScript, which is quite outside of my comfort zone. Can you potentially help from this point? Do you know anyone that can help?
Thanks for the investigation @falkoschindler. I will have a look into this again once I’ve got a bit air to breathe as one can work around it now, even though that is not satisfying in the long term.
I also assume though its tightly related to the translation into HTML once the element is rendered.
@Alyxion Ooops, I meant sleeping or awaiting
ui.context.client.connected(). I updated my comment.Does anyone have an idea how to approach this issue? I wonder if it is caused by Vue or Quasar and the way they handle UI updates. But other elements, even similar ones like
ui.editorandui.codemirrorwork as expected. What is so special aboutui.input?Interesting observation, @Alyxion!
This handler does not work:
But button click handlers can be assigned this way. So it’s not a general event registration problem.
And as far as I can tell, the event listeners are registered correctly and sent to the client. But there is no websocket message sent to the server when a key is pressed. Very strange!