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”.

image

Situation:

  • An ui.input field is created
  • A focus handler is set up via .on("focus", handle_focus) and a blur_handler is setup via on("blur", handle_blur)
  • In handle_focus the.on("keydown", handle_keydown) is assigned to track cursor key presses
  • In handle_blur the event listener is removed again.
    • As NiceGUI doesn’t officially support removal of event listeners added via .on yet 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.
  • 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)

Most upvoted comments

And apparently Vue doesn’t manage to update event handlers once the q-input tag has been translated into HTML.

(from @falkoschindler)

This does appear to be the problem:

This is a fundamental limitation in Vue’s reactivity system and how it handles event binding. Here’s why:

  1. When Vue compiles a template, it creates a render function that includes all the event listeners specified in the template. These listeners are bound during the initial component mounting.
  2. When you try to dynamically add an event listener after mounting (either through v-on or computed props), Vue doesn’t actually re-compile the template or update the underlying event binding system. It only updates the reactive data.
  3. The event system in Vue is designed to be declarative rather than imperative. It expects all event bindings to be declared upfront in the template, and it’s optimized for this use case.

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 hasKeydownListener to true initially, you end up being able to add and remove the handler. If it starts as false, adding it has no effect.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Quasar UMD App</title>

  <!-- Quasar UMD CSS -->
  <link href="https://cdn.jsdelivr.net/npm/quasar@2.14.3/dist/quasar.min.css" rel="stylesheet" type="text/css">
</head>

<body>
    <div id="app">
        <q-input
        v-model="text"
        label="Type something"
        v-bind="inputProps"
        ></q-input>

        <q-btn
            class="q-mt-md"
            color="primary"
            @click="toggleKeydownListener"
        >
            {{ hasKeydownListener ? 'Remove Listener' : 'Add Keydown Listener' }}
        </q-btn>

        <p v-if="hasKeydownListener">Last key pressed: {{ lastKey }}</p>
        </div>

  <script src="https://cdn.jsdelivr.net/npm/vue@3.4.38/dist/vue.global.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/quasar@2.16.9/dist/quasar.umd.js"></script>
  <script>
    const { createApp, ref, computed } = Vue

    const app = createApp({
      setup() {
        const text = ref('')
        const lastKey = ref('')
        const hasKeydownListener = ref(true) // when initially true, keydown can be added and removed, when initially false, it cannot be added.

        const handleKeyDown = (event) => {
          lastKey.value = event.key
          console.log('Key pressed:', event.key)
        }

        const inputProps = computed(() => {
          const props = {
            // Base props that are always present
            label: 'Type something',
            // Add keydown event only when hasKeydownListener is true
            ...(hasKeydownListener.value ? { onKeydown: handleKeyDown } : {})
          }
          console.log("inputProps: ", props)
          return props
        })

        const toggleKeydownListener = () => {
          hasKeydownListener.value = !hasKeydownListener.value
        }

        return {
          text,
          lastKey,
          hasKeydownListener,
          inputProps,
          handleKeyDown,
          toggleKeydownListener
        }
      }
    })

    app.use(Quasar)
    app.mount('#app')
  </script>
</body>
</html>

And here is another self container example using a possible work around of using v-if/else in templates to force complete re-render of the component:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Quasar UMD App</title>

  <!-- Quasar UMD CSS -->
  <link href="https://cdn.jsdelivr.net/npm/quasar@2.14.3/dist/quasar.min.css" rel="stylesheet" type="text/css">
</head>

<body>
  <div id="app">
    <div v-if="hasKeydownListener">
      <q-input
        v-model="text"
        label="Type something"
        @keydown="handleKeyDown"
      ></q-input>
    </div>
    <div v-else>
      <q-input
        v-model="text"
        label="Type something"
      ></q-input>
    </div>

    <q-btn
      class="q-mt-md"
      color="primary"
      @click="toggleKeydownListener"
    >
      {{ hasKeydownListener ? 'Remove Listener' : 'Add Keydown Listener' }}
    </q-btn>

    <p v-if="hasKeydownListener">Last key pressed: {{ lastKey }}</p>
  </div>


  <script src="https://cdn.jsdelivr.net/npm/vue@3.4.38/dist/vue.global.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/quasar@2.16.9/dist/quasar.umd.js"></script>
  <script>
    const { createApp, ref } = Vue

    const app = createApp({
      setup() {
        const text = ref('')
        const lastKey = ref('')
        const hasKeydownListener = ref(false)

        const handleKeyDown = (event) => {
          lastKey.value = event.key
          console.log('Key pressed:', event.key)
        }

        const toggleKeydownListener = () => {
          hasKeydownListener.value = !hasKeydownListener.value
        }

        return {
          text,
          lastKey,
          hasKeydownListener,
          handleKeyDown,
          toggleKeydownListener
        }
      }
    })

    app.use(Quasar)
    app.mount('#app')
  </script>
</body>
</html>

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.js or input.js. Definitely not a .py file, because the issue would then not be selective with regards to pre/post await 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.

Image

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.editor and ui.codemirror work as expected. What is so special about ui.input?

Interesting observation, @Alyxion!

This handler does not work:

i = ui.input()
ui.timer(1.0, lambda: i.on('keydown', ui.notify), once=True)

But button click handlers can be assigned this way. So it’s not a general event registration problem.

b = ui.button()
ui.timer(1.0, lambda: b.on('click', ui.notify), once=True)

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!