Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

chore: add stricter types for useEventListener (#2943)

Myles Scolnick460f5e359137
diff --git a/frontend/src/hooks/__tests__/useEventListener.test.tsx b/frontend/src/hooks/__tests__/useEventListener.test.tsx
index a69296466c..06da8fff78 100644
--- a/frontend/src/hooks/__tests__/useEventListener.test.tsx
+++ b/frontend/src/hooks/__tests__/useEventListener.test.tsx
@@ -1,8 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { expect, describe, it } from "vitest";
+import { expect, describe, it, beforeEach, vi } from "vitest";
import { renderHook } from "@testing-library/react-hooks";
import { useRef } from "react";
-import { isRefObject } from "../useEventListener";
+import {
+ type HTMLElementNotDerivedFromRef,
+ isRefObject,
+ useEventListener,
+} from "../useEventListener";
describe("isRefObject", () => {
it("should return true for React ref objects", () => {
@@ -22,3 +26,122 @@ describe("isRefObject", () => {
expect(isRefObject({ current: document.createElement("div") })).toBe(true);
});
});
+
+describe("useEventListener", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("should attach event listener to document", () => {
+ const listener = vi.fn();
+ const addSpy = vi.spyOn(document, "addEventListener");
+ const removeSpy = vi.spyOn(document, "removeEventListener");
+
+ const { unmount } = renderHook(() =>
+ useEventListener(document, "click", listener),
+ );
+
+ // Verify listener was attached
+ expect(addSpy).toHaveBeenCalledWith(
+ "click",
+ expect.any(Function),
+ undefined,
+ );
+
+ // Simulate click
+ document.dispatchEvent(new Event("click"));
+ expect(listener).toHaveBeenCalled();
+
+ // Cleanup
+ unmount();
+ expect(removeSpy).toHaveBeenCalled();
+ });
+
+ it("should attach event listener to window", () => {
+ const listener = vi.fn();
+ const addSpy = vi.spyOn(window, "addEventListener");
+
+ renderHook(() => useEventListener(window, "resize", listener));
+
+ expect(addSpy).toHaveBeenCalledWith(
+ "resize",
+ expect.any(Function),
+ undefined,
+ );
+ });
+
+ it("should attach event listener to HTML element", () => {
+ const element = document.createElement("div");
+ const listener = vi.fn();
+ const addSpy = vi.spyOn(element, "addEventListener");
+
+ renderHook(() =>
+ useEventListener(
+ element as HTMLElementNotDerivedFromRef<HTMLDivElement>,
+ "click",
+ listener,
+ ),
+ );
+
+ expect(addSpy).toHaveBeenCalledWith(
+ "click",
+ expect.any(Function),
+ undefined,
+ );
+ });
+
+ it("should attach event listener to ref", () => {
+ const element = document.createElement("div");
+ const ref = { current: element };
+ const listener = vi.fn();
+ const addSpy = vi.spyOn(element, "addEventListener");
+
+ renderHook(() => useEventListener(ref, "click", listener));
+
+ expect(addSpy).toHaveBeenCalledWith(
+ "click",
+ expect.any(Function),
+ undefined,
+ );
+ });
+
+ it("should not attach listener if target is null", () => {
+ const listener = vi.fn();
+ const ref = { current: null };
+ const addSpy = vi.spyOn(document, "addEventListener");
+
+ renderHook(() => useEventListener(ref, "click", listener));
+
+ expect(addSpy).not.toHaveBeenCalled();
+ });
+
+ it("should update listener when callback changes", () => {
+ const listener1 = vi.fn();
+ const listener2 = vi.fn();
+
+ const { rerender } = renderHook(
+ ({ cb }) => useEventListener(document, "click", cb),
+ { initialProps: { cb: listener1 } },
+ );
+
+ document.dispatchEvent(new Event("click"));
+ expect(listener1).toHaveBeenCalledTimes(1);
+ expect(listener2).not.toHaveBeenCalled();
+
+ rerender({ cb: listener2 });
+
+ document.dispatchEvent(new Event("click"));
+ expect(listener1).toHaveBeenCalledTimes(1);
+ expect(listener2).toHaveBeenCalledTimes(1);
+ });
+
+ it("should handle options parameter", () => {
+ const listener = vi.fn();
+ const options = { capture: true };
+ const addSpy = vi.spyOn(document, "addEventListener");
+
+ renderHook(() => useEventListener(document, "click", listener, options));
+
+ expect(addSpy).toHaveBeenCalledWith("click", expect.any(Function), options);
+ });
+});
diff --git a/frontend/src/hooks/useEventListener.ts b/frontend/src/hooks/useEventListener.ts
index 96736b7cc3..80b2e9eafc 100644
--- a/frontend/src/hooks/useEventListener.ts
+++ b/frontend/src/hooks/useEventListener.ts
@@ -1,27 +1,43 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { useRef, useEffect, type RefObject } from "react";
-type Target = Document | HTMLElement | Window | null;
-type TargetRef = RefObject<Target>;
+/**
+ * A type that makes it clear that an `HTMLElement` is not derived from a `RefObject`.
+ * If an `HTMLElement` is derived from a `RefObject`, then pass that in directly.
+ *
+ * This doesn't actually do anything at runtime (it is just a type annotation), but
+ * this forces the user to check that the `targetValue` is not a `RefObject`.
+ */
+export type HTMLElementNotDerivedFromRef<T = HTMLElement> = T & {
+ __brand: "HTMLElementNotDerivedFromRef";
+};
-type EventMap<T extends Target> = T extends Document
- ? DocumentEventMap
- : T extends HTMLElement
- ? HTMLElementEventMap
- : T extends Window
- ? WindowEventMap
- : never;
-
-export function isRefObject<T>(
- target: T | RefObject<T>,
-): target is RefObject<T> {
+export function isRefObject<T>(target: unknown): target is RefObject<T> {
return target !== null && typeof target === "object" && "current" in target;
}
-export function useEventListener<T extends Target, K extends keyof EventMap<T>>(
- targetValue: T | TargetRef,
- type: K & string,
- listener: (ev: EventMap<T>[K]) => unknown,
+export function useEventListener<K extends keyof DocumentEventMap>(
+ targetValue: Document,
+ type: K,
+ listener: (ev: DocumentEventMap[K]) => unknown,
+ options?: boolean | AddEventListenerOptions,
+): void;
+export function useEventListener<K extends keyof WindowEventMap>(
+ targetValue: Window,
+ type: K,
+ listener: (ev: WindowEventMap[K]) => unknown,
+ options?: boolean | AddEventListenerOptions,
+): void;
+export function useEventListener<K extends keyof HTMLElementEventMap>(
+ targetValue: HTMLElementNotDerivedFromRef | RefObject<HTMLElement> | null,
+ type: K,
+ listener: (ev: HTMLElementEventMap[K]) => unknown,
+ options?: boolean | AddEventListenerOptions,
+): void;
+export function useEventListener(
+ targetValue: EventTarget | RefObject<EventTarget> | null,
+ type: string,
+ listener: (ev: Event) => unknown,
options?: boolean | AddEventListenerOptions,
): void {
const savedListener = useRef(listener);
diff --git a/frontend/src/hooks/useHotkey.ts b/frontend/src/hooks/useHotkey.ts
index 42ab5bf50b..54042196c5 100644
--- a/frontend/src/hooks/useHotkey.ts
+++ b/frontend/src/hooks/useHotkey.ts
@@ -57,7 +57,7 @@ export function useHotkey(shortcut: HotkeyAction, callback: HotkeyHandler) {
* Registers a hotkey listener on a given element or ref to an element.
*/
export function useHotkeysOnElement<T extends HotkeyAction>(
- element: HTMLElement | RefObject<HTMLElement> | null,
+ element: RefObject<HTMLElement> | null,
handlers: Record<T, HotkeyHandler>,
) {
const hotkeys = useAtomValue(hotkeysAtom);
@@ -81,7 +81,7 @@ export function useHotkeysOnElement<T extends HotkeyAction>(
* Registers a hotkey listener on a given element or ref to an element.
*/
export function useKeydownOnElement(
- element: HTMLElement | RefObject<HTMLElement> | null,
+ element: RefObject<HTMLElement> | null,
handlers: Record<string, HotkeyHandler>,
) {
useEventListener(element, "keydown", (e) => {
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index caf836b408..317a803812 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -41,7 +41,10 @@ import useEvent from "react-use-event-hook";
import { Functions } from "@/utils/functions";
import { StyleNamespace } from "@/theme/namespace";
import { UIElementRegistry } from "@/core/dom/uiregistry";
-import { useEventListener } from "@/hooks/useEventListener";
+import {
+ type HTMLElementNotDerivedFromRef,
+ useEventListener,
+} from "@/hooks/useEventListener";
import { shallowCompare } from "@/utils/shallow-compare";
export interface PluginSlotHandle {
@@ -99,11 +102,15 @@ function PluginSlotInternal<T>(
}));
// Listen to value updates
- useEventListener(hostElement, MarimoValueUpdateEvent.TYPE, (e) => {
- if (e.detail.element === hostElement) {
- setValue(e.detail.value as T);
- }
- });
+ useEventListener(
+ hostElement as HTMLElementNotDerivedFromRef,
+ MarimoValueUpdateEvent.TYPE,
+ (e) => {
+ if (e.detail.element === hostElement) {
+ setValue(e.detail.value as T);
+ }
+ },
+ );
// We create a mutation observer to listen for changes to the host element's attributes
// and update the plugin's data accordingly
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index d3c3457d9b..70e9d961b2 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -13,7 +13,10 @@ import { createPlugin } from "@/plugins/core/builder";
import { rpc } from "@/plugins/core/rpc";
import type { AnyModel, AnyWidget, EventHandler, Experimental } from "./types";
import { Logger } from "@/utils/Logger";
-import { useEventListener } from "@/hooks/useEventListener";
+import {
+ type HTMLElementNotDerivedFromRef,
+ useEventListener,
+} from "@/hooks/useEventListener";
import { MarimoIncomingMessageEvent } from "@/core/dom/events";
import { updateBufferPaths } from "@/utils/date-views";
@@ -148,9 +151,13 @@ const LoadedSlot = ({
);
// Listen to incoming messages
- useEventListener(host, MarimoIncomingMessageEvent.TYPE, (e) => {
- model.current.receiveCustomMessage(e.detail.message, e.detail.buffers);
- });
+ useEventListener(
+ host as HTMLElementNotDerivedFromRef,
+ MarimoIncomingMessageEvent.TYPE,
+ (e) => {
+ model.current.receiveCustomMessage(e.detail.message, e.detail.buffers);
+ },
+ );
useOnMount(() => {
if (!ref.current) {
diff --git a/frontend/src/plugins/impl/panel/PanelPlugin.tsx b/frontend/src/plugins/impl/panel/PanelPlugin.tsx
index 3cb5843905..8616af59d1 100644
--- a/frontend/src/plugins/impl/panel/PanelPlugin.tsx
+++ b/frontend/src/plugins/impl/panel/PanelPlugin.tsx
@@ -6,7 +6,10 @@ import type { IPluginProps } from "@/plugins/types";
import { useEffect, useRef, useState } from "react";
import { createPlugin } from "@/plugins/core/builder";
import { rpc } from "@/plugins/core/rpc";
-import { useEventListener } from "@/hooks/useEventListener";
+import {
+ type HTMLElementNotDerivedFromRef,
+ useEventListener,
+} from "@/hooks/useEventListener";
import { MarimoIncomingMessageEvent } from "@/core/dom/events";
import { MessageSchema, extractBuffers, EventBuffer } from "./utils";
import { useEvent } from "@dnd-kit/utilities";
@@ -163,47 +166,51 @@ const PanelSlot = (props: Props) => {
}, [extension, setLoaded]);
// Listen for incoming messages
- useEventListener(host, MarimoIncomingMessageEvent.TYPE, (e) => {
- if (e.detail.message == null) {
- return;
- }
+ useEventListener(
+ host as HTMLElementNotDerivedFromRef,
+ MarimoIncomingMessageEvent.TYPE,
+ (e) => {
+ if (e.detail.message == null) {
+ return;
+ }
- const message = MessageSchema.parse(e.detail.message);
- const buffers = e.detail.buffers;
- const receiver = receiverRef.current;
- const doc = docRef.current;
+ const message = MessageSchema.parse(e.detail.message);
+ const buffers = e.detail.buffers;
+ const receiver = receiverRef.current;
+ const doc = docRef.current;
- if (!receiver || !doc) {
- return;
- }
+ if (!receiver || !doc) {
+ return;
+ }
- const content = message.content;
- if (content !== null && typeof message.content !== "string") {
- // Handle ACK messages
- if (eventBufferRef.current && eventBufferRef.current.size() > 0) {
- processEvents();
+ const content = message.content;
+ if (content !== null && typeof message.content !== "string") {
+ // Handle ACK messages
+ if (eventBufferRef.current && eventBufferRef.current.size() > 0) {
+ processEvents();
+ }
+ return;
}
- return;
- }
- if (buffers && buffers.length > 0) {
- receiver.consume(buffers[0].buffer);
- } else if (content && typeof content === "string") {
- receiver.consume(content);
- } else {
- return;
- }
+ if (buffers && buffers.length > 0) {
+ receiver.consume(buffers[0].buffer);
+ } else if (content && typeof content === "string") {
+ receiver.consume(content);
+ } else {
+ return;
+ }
- const commMessage = receiver.message;
- if (commMessage != null && Object.keys(commMessage.content).length > 0) {
- if (commMessage.content.events !== undefined) {
- commMessage.content.events = commMessage.content.events.filter(
- (e: any) => doc._all_models.has(e.model.id),
- );
+ const commMessage = receiver.message;
+ if (commMessage != null && Object.keys(commMessage.content).length > 0) {
+ if (commMessage.content.events !== undefined) {
+ commMessage.content.events = commMessage.content.events.filter(
+ (e: any) => doc._all_models.has(e.model.id),
+ );
+ }
+ doc.apply_json_patch(commMessage.content, commMessage.buffers);
}
- doc.apply_json_patch(commMessage.content, commMessage.buffers);
- }
- });
+ },
+ );
// Embed the items on the first render
useEffect(() => {