From 4dd10f88d8efbc8d468d586a0761d2673f8a22cc Mon Sep 17 00:00:00 2001 From: Varixo Date: Tue, 23 Jul 2024 22:07:31 +0200 Subject: [PATCH] fix(v2): more useOn fixes --- .../src/core/v2/shared/component-execution.ts | 9 ++- .../qwik/src/core/v2/tests/use-on.spec.tsx | 58 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/packages/qwik/src/core/v2/shared/component-execution.ts b/packages/qwik/src/core/v2/shared/component-execution.ts index 175b9728cad..c7ca956b644 100644 --- a/packages/qwik/src/core/v2/shared/component-execution.ts +++ b/packages/qwik/src/core/v2/shared/component-execution.ts @@ -145,9 +145,16 @@ function addUseOnEvents( if (jsxElement) { addUseOnEvent(jsxElement, 'document:onQinit$', useOnEvents[key]); } + } else if (key.startsWith('document:') || key.startsWith('window:')) { + jsxElement = addScriptNodeForInvisibleComponents(jsx); + if (jsxElement) { + addUseOnEvent(jsxElement, key, useOnEvents[key]); + } } else if (isDev) { logWarn( - 'You are trying to add an event using `useOn` hook, ' + + 'You are trying to add an event "' + + key + + '" using `useOn` hook, ' + 'but a node to which you can add an event is not found. ' + 'Please make sure that the component has a valid element node. ' ); diff --git a/packages/qwik/src/core/v2/tests/use-on.spec.tsx b/packages/qwik/src/core/v2/tests/use-on.spec.tsx index d1eb5b118a3..dc8ea48a865 100644 --- a/packages/qwik/src/core/v2/tests/use-on.spec.tsx +++ b/packages/qwik/src/core/v2/tests/use-on.spec.tsx @@ -228,6 +228,35 @@ describe.each([ ); }); + it('should work with empty component', async () => { + const Counter = component$((props: { initial: number }) => { + const count = useSignal(props.initial); + useOnDocument( + 'click', + $(() => count.value++) + ); + return <>Count: {count.value}!; + }); + + const { vNode, container } = await render(, { debug }); + expect(vNode).toMatchVDOM( + + + Count: {'123'}! + + + ); + + await trigger(container.element, 'script', ':document:click'); + expect(vNode).toMatchVDOM( + + + Count: {'124'}! + + + ); + }); + it('should update value with mixed listeners', async () => { const Counter = component$((props: { initial: number }) => { const count = useSignal(props.initial); @@ -295,6 +324,35 @@ describe.each([ ); }); + it('should work with empty component', async () => { + const Counter = component$((props: { initial: number }) => { + const count = useSignal(props.initial); + useOnWindow( + 'click', + $(() => count.value++) + ); + return <>Count: {count.value}!; + }); + + const { vNode, container } = await render(, { debug }); + expect(vNode).toMatchVDOM( + + + Count: {'123'}! + + + ); + + await trigger(container.element, 'script', ':window:click'); + expect(vNode).toMatchVDOM( + + + Count: {'124'}! + + + ); + }); + it('should update value for window event on element and useOnWindow', async () => { const Counter = component$((props: { initial: number }) => { const count = useSignal(props.initial);