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.

improvement: markdown code to be completely hidden upon 'Hide Code' (#2974)

Shahmir Varqha41a050061bdc
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5f13eb0dcf..80d5cdad38 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -213,6 +213,8 @@ dependencies; follow those instructions.)
For best practices on writing end-to-end tests, check out the [Best Practices
doc](https://playwright.dev/docs/best-practices).
+For frontend tests, you want to build the frontend first with `make fe` so that Playwright works on your latest changes.
+
**Run end-to-end tests.**
In the root directory, run:
diff --git a/frontend/e2e-tests/helper.ts b/frontend/e2e-tests/helper.ts
index bc774fa984..647129d06b 100644
--- a/frontend/e2e-tests/helper.ts
+++ b/frontend/e2e-tests/helper.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { type Page, expect } from "@playwright/test";
+import { type Locator, type Page, expect } from "@playwright/test";
import { HotkeyProvider, type HotkeyAction } from "../src/core/hotkeys/hotkeys";
import path from "node:path";
@@ -35,6 +35,15 @@ export async function createCellBelow(opts: {
}
}
+export async function openCellActions(page: Page, element: Locator) {
+ await element.hover();
+ await page
+ .getByTestId("cell-actions-button")
+ .locator(":visible")
+ .first()
+ .click();
+}
+
export async function runCell(opts: { page: Page; cellSelector: string }) {
const { page, cellSelector } = opts;
diff --git a/frontend/e2e-tests/toggle-cell-language.spec.ts b/frontend/e2e-tests/toggle-cell-language.spec.ts
new file mode 100644
index 0000000000..f8964896e4
--- /dev/null
+++ b/frontend/e2e-tests/toggle-cell-language.spec.ts
@@ -0,0 +1,51 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { test, expect } from "@playwright/test";
+import { getAppUrl, resetFile } from "../playwright.config";
+import { openCellActions } from "./helper";
+
+const appUrl = getAppUrl("title.py");
+
+test.beforeEach(async ({ page }, info) => {
+ await page.goto(appUrl);
+ if (info.retry) {
+ await page.reload();
+ }
+});
+
+test.afterEach(async () => {
+ // Need to reset the file because this test modifies it
+ await resetFile("title.py");
+});
+
+test("change the cell to a markdown cell and toggle hide code", async ({
+ page,
+}) => {
+ const title = page.getByText("Hello Marimo!", { exact: true });
+ await expect(title).toBeVisible();
+
+ // Convert to Markdown
+ await openCellActions(page, title);
+ await page.getByText("Convert to Markdown").click();
+ await expect(title).toBeVisible();
+
+ // Verify markdown content
+ const markdown = page.getByText("import marimo as mo");
+ await expect(markdown).toBeVisible();
+
+ // Hide code
+ await openCellActions(page, title);
+ await page.getByText("Hide code").click();
+ await expect(title).toBeVisible();
+
+ // Verify code editor is hidden
+ const cellEditor = page.getByTestId("cell-editor");
+ await expect(cellEditor).toBeHidden();
+
+ // Unhide code
+ await openCellActions(page, title);
+ await page.getByText("Show code").click();
+ await expect(title).toBeVisible();
+
+ // Verify code editor is visible
+ await expect(cellEditor).toBeVisible();
+});
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 55c3c78089..6792a2abd2 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -55,6 +55,9 @@ import { Toolbar, ToolbarItem } from "@/components/editor/cell/toolbar";
import { cn } from "@/utils/cn";
import { isErrorMime } from "@/core/mime";
import { getCurrentLanguageAdapter } from "@/core/codemirror/language/commands";
+import { HideCodeButton } from "./code/readonly-python-code";
+import { useResizeObserver } from "@/hooks/useResizeObserver";
+import type { LanguageAdapterType } from "@/core/codemirror/language/types";
/**
* Imperative interface of the cell.
@@ -183,6 +186,8 @@ const CellComponent = (
const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
const [temporarilyVisible, setTemporarilyVisible] = useState(false);
+ const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();
+
const disabledOrAncestorDisabled =
cellConfig.disabled || status === "disabled-transitively";
@@ -311,10 +316,84 @@ const CellComponent = (
[cellRef, editorView],
);
+ const isCellCodeShown = !cellConfig.hide_code || temporarilyVisible;
+ const isMarkdown = languageAdapter === "markdown";
+ const isMarkdownCodeHidden = isMarkdown && !isCellCodeShown;
+
+ const cellContainerRef = useRef<HTMLDivElement>(null);
+ const canCollapse = canCollapseOutline(outline);
+
+ // If the cell is too short, we need to position some icons inline to prevent overlaps.
+ // This can only happen to markdown cells when the code is hidden completely
+ const [isCellStatusInline, setIsCellStatusInline] = useState(false);
+ const [isCellButtonsInline, setIsCellButtonsInline] = useState(false);
+
+ useResizeObserver({
+ ref: cellContainerRef,
+ skip: !isMarkdown,
+ onResize: (size) => {
+ const shouldBeInline =
+ (size.height && size.height < 68 && hasOutput) || false;
+ setIsCellStatusInline(shouldBeInline);
+
+ if (canCollapse && shouldBeInline) {
+ setIsCellButtonsInline(shouldBeInline);
+ } else if (isCellButtonsInline) {
+ setIsCellButtonsInline(false);
+ }
+ },
+ });
+
+ // DOM node where the editorView will be mounted
+ const editorViewParentRef = useRef<HTMLDivElement>(null);
+
+ // if the cell is hidden, show the code editor temporarily
+ const temporarilyShowCode = useCallback(() => {
+ if (!isCellCodeShown) {
+ setTemporarilyVisible(true);
+ editorView.current?.focus();
+ // Reach one parent up
+ const parent = editorViewParentRef.current?.parentElement;
+
+ const handleFocusOut = () => {
+ requestAnimationFrame(() => {
+ if (!parent?.contains(document.activeElement)) {
+ // Hide the code editor
+ setTemporarilyVisible(false);
+ editorView.current?.dom.blur();
+ parent?.removeEventListener("focusout", handleFocusOut);
+ }
+ });
+ };
+ parent?.addEventListener("focusout", handleFocusOut);
+ }
+ }, [isCellCodeShown, editorView]);
+
+ const showHiddenMarkdownCode = () => {
+ if (isMarkdownCodeHidden) {
+ temporarilyShowCode();
+ }
+ };
+
const hasOutput = !isOutputEmpty(output);
+ const unhideCode = useEvent(() => {
+ // Fire-and-forget save
+ void saveCellConfig({ configs: { [cellId]: { hide_code: false } } });
+ updateCellConfig({ cellId, config: { hide_code: false } });
+
+ // focus the editor
+ editorView.current?.focus();
+ return false;
+ });
+
+ // When markdown cell is hidden & output is cleared, show the code editor
+ if (isMarkdownCodeHidden && !hasOutput) {
+ unhideCode();
+ }
+
const outputArea = hasOutput && (
- <div className="relative">
+ <div className="relative" onDoubleClick={showHiddenMarkdownCode}>
<div className="absolute top-5 -left-8 z-10 print:hidden">
<CollapseToggle
isCollapsed={isCollapsed}
@@ -325,7 +404,7 @@ const CellComponent = (
collapseCell({ cellId });
}
}}
- canCollapse={canCollapseOutline(outline)}
+ canCollapse={canCollapse}
/>
</div>
<OutputArea
@@ -335,6 +414,12 @@ const CellComponent = (
cellId={cellId}
stale={outputStale}
/>
+ {isMarkdownCodeHidden && (
+ <HideCodeButton
+ className="z-20 relative -top-3"
+ onClick={temporarilyShowCode}
+ />
+ )}
</div>
);
@@ -350,8 +435,6 @@ const CellComponent = (
const HTMLId = HTMLCellId.create(cellId);
- const isCellCodeShown = !cellConfig.hide_code || temporarilyVisible;
-
// Register hotkeys on the cell instead of the code editor
// This is in case the code editor is hidden
useHotkeysOnElement(editing ? cellRef : null, {
@@ -416,6 +499,10 @@ const CellComponent = (
moveToNextCell({ cellId, before: true, noCreate: true });
return true;
},
+ Enter: () => {
+ showHiddenMarkdownCode();
+ return false;
+ },
// only register j/k movement if the cell is hidden, so as to not
// interfere with editing
...(userConfig.keymap.preset === "vim" && !isCellCodeShown
@@ -462,6 +549,21 @@ const CellComponent = (
setAiCompletionCell({ cellId, initialPrompt: opts.prompt });
};
+ const cellStatusComponent = (
+ <CellStatusComponent
+ status={status}
+ staleInputs={staleInputs}
+ interrupted={interrupted}
+ editing={editing}
+ edited={edited}
+ disabled={cellConfig.disabled ?? false}
+ elapsedTime={runElapsedTimeMs}
+ runStartTimestamp={runStartTimestamp}
+ uninstantiated={uninstantiated}
+ lastRunStartTimestamp={lastRunStartTimestamp}
+ />
+ );
+
return (
<CellActionsContextMenu
cellId={cellId}
@@ -481,9 +583,9 @@ const CellComponent = (
canMoveX={canMoveX}
title={cellTitle()}
>
- <div className={className} id={HTMLId}>
+ <div className={className} id={HTMLId} ref={cellContainerRef}>
{userConfig.display.cell_output === "above" && outputArea}
- <div className="tray">
+ <div className={cn("tray", isMarkdownCodeHidden && "!border-t-0")}>
<div className="absolute right-2 -top-4 z-10">
<CellToolbar
edited={edited}
@@ -499,7 +601,13 @@ const CellComponent = (
onRun={handleRun}
/>
</div>
- <div className="absolute flex flex-col gap-[2px] justify-center h-full left-[-34px] z-20">
+ <div
+ className={cn(
+ "absolute flex flex-col gap-[2px] justify-center h-full left-[-34px] z-20",
+ isMarkdownCodeHidden && "-top-7",
+ isMarkdownCodeHidden && isCellButtonsInline && "-left-[3.8rem]",
+ )}
+ >
<CreateCellButton
tooltipContent={renderShortcut("cell.createAbove")}
appClosed={appClosed}
@@ -532,24 +640,17 @@ const CellComponent = (
clearSerializedEditorState={clearSerializedEditorState}
userConfig={userConfig}
editorViewRef={editorView}
+ editorViewParentRef={editorViewParentRef}
hidden={!isCellCodeShown}
- setTemporarilyVisible={setTemporarilyVisible}
+ temporarilyShowCode={temporarilyShowCode}
+ languageAdapter={languageAdapter}
+ setLanguageAdapter={setLanguageAdapter}
/>
- <div className="shoulder-right z-20">
- <CellStatusComponent
- status={status}
- staleInputs={staleInputs}
- interrupted={interrupted}
- editing={editing}
- edited={edited}
- disabled={cellConfig.disabled ?? false}
- elapsedTime={runElapsedTimeMs}
- runStartTimestamp={runStartTimestamp}
- uninstantiated={uninstantiated}
- lastRunStartTimestamp={lastRunStartTimestamp}
- />
+ <div className="shoulder-right">
+ {!isCellStatusInline && cellStatusComponent}
<div className="flex gap-2 items-end">
<CellDragHandle />
+ {isCellStatusInline && cellStatusComponent}
</div>
</div>
<div className="shoulder-bottom hover-action">
@@ -644,7 +745,11 @@ const CellToolbar = ({
config={cellConfig}
hasOutput={hasOutput}
>
- <ToolbarItem variant={"green"} tooltip={null}>
+ <ToolbarItem
+ variant={"green"}
+ tooltip={null}
+ data-testid="cell-actions-button"
+ >
<MoreHorizontalIcon strokeWidth={1.5} />
</ToolbarItem>
</CellActionsDropdown>
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index ecb1f93cb1..47954db1ea 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -2,14 +2,7 @@
import { historyField } from "@codemirror/commands";
import { EditorState, StateEffect } from "@codemirror/state";
import { EditorView, ViewPlugin } from "@codemirror/view";
-import React, {
- memo,
- useCallback,
- useEffect,
- useRef,
- useState,
- useMemo,
-} from "react";
+import React, { memo, useCallback, useEffect, useRef, useMemo } from "react";
import { setupCodeMirror } from "@/core/codemirror/cm";
import useEvent from "react-use-event-hook";
@@ -67,10 +60,14 @@ export interface CellEditorProps
* This is different from cellConfig.hide_code, since it may be temporarily shown.
*/
hidden?: boolean;
- /**
- * Not used by scratchpad.
- */
- setTemporarilyVisible?: (value: boolean) => void;
+ languageAdapter: LanguageAdapterType | undefined;
+ setLanguageAdapter: React.Dispatch<
+ React.SetStateAction<LanguageAdapterType | undefined>
+ >;
+ // Props below are not used by scratchpad.
+ // DOM node where the editorView will be mounted
+ editorViewParentRef?: React.MutableRefObject<HTMLDivElement | null>;
+ temporarilyShowCode: () => void;
}
const CellEditorInternal = ({
@@ -93,19 +90,21 @@ const CellEditorInternal = ({
clearSerializedEditorState,
userConfig,
editorViewRef,
+ editorViewParentRef,
hidden,
- setTemporarilyVisible,
+ temporarilyShowCode,
+ languageAdapter,
+ setLanguageAdapter,
}: CellEditorProps) => {
const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom);
- const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();
const setLastFocusedCellId = useSetLastFocusedCellId();
- // DOM node where the editorView will be mounted
- const editorViewParentRef = useRef<HTMLDivElement>(null);
const loading = status === "running" || status === "queued";
const { sendToTop, sendToBottom } = useCellActions();
const splitCell = useSplitCellCallback();
+ const isMarkdown = languageAdapter === "markdown";
+
const handleDelete = useEvent(() => {
// Cannot delete running cells, since we're waiting for their output.
if (loading) {
@@ -240,6 +239,7 @@ const CellEditorInternal = ({
runCell,
setAiCompletionCell,
afterToggleMarkdown,
+ setLanguageAdapter,
]);
useEffect(() => {
@@ -298,6 +298,7 @@ const CellEditorInternal = ({
if (
editorViewRef.current !== null &&
+ editorViewParentRef &&
editorViewParentRef.current !== null
) {
// Always replace the children in case the editor view was re-created.
@@ -336,33 +337,6 @@ const CellEditorInternal = ({
};
}, [editorViewRef]);
- const temporarilyShowCode = useCallback(async () => {
- if (hidden && setTemporarilyVisible !== undefined) {
- setTemporarilyVisible(true);
- editorViewRef.current?.focus();
- // Reach one parent up
- const parent = editorViewParentRef.current?.parentElement;
- const abortController = new AbortController();
- parent?.addEventListener(
- "focusout",
- () => {
- requestAnimationFrame(() => {
- // Skip closing if the focus is still in the parent element
- const focusedElement = document.activeElement;
- if (parent?.contains(focusedElement)) {
- return;
- }
- // Hide the code editor
- setTemporarilyVisible(false);
- editorViewRef.current?.dom.blur();
- abortController.abort();
- });
- },
- { signal: abortController.signal },
- );
- }
- }, [hidden, setTemporarilyVisible, editorViewRef, editorViewParentRef]);
-
return (
<AiCompletionEditor
enabled={aiCompletionCell?.cellId === cellId}
@@ -398,9 +372,19 @@ const CellEditorInternal = ({
className="relative w-full"
onFocus={() => setLastFocusedCellId(cellId)}
>
- {hidden && <HideCodeButton onClick={temporarilyShowCode} />}
+ {/* Completely hide the editor and icons when markdown is hidden. If just hidden, display. */}
+ {!isMarkdown && hidden && (
+ <HideCodeButton
+ className="absolute inset-0 z-10"
+ onClick={temporarilyShowCode}
+ />
+ )}
<CellCodeMirrorEditor
- className={cn(hidden && "opacity-20 h-8 overflow-hidden")}
+ className={cn(
+ isMarkdown && hidden
+ ? "h-0 overflow-hidden"
+ : hidden && "opacity-20 h-8 overflow-hidden",
+ )}
editorView={editorViewRef.current}
ref={editorViewParentRef}
/>
@@ -425,7 +409,7 @@ const CellCodeMirrorEditor = React.forwardRef(
className?: string;
editorView: EditorView | null;
},
- ref: React.Ref<HTMLDivElement>,
+ ref?: React.Ref<HTMLDivElement>,
) => {
const { className, editorView } = props;
const internalRef = useRef<HTMLDivElement>(null);
@@ -447,7 +431,7 @@ const CellCodeMirrorEditor = React.forwardRef(
return (
<div
className={cn("cm", className)}
- ref={mergeRefs(ref, internalRef)}
+ ref={(ref && mergeRefs(ref, internalRef)) || internalRef}
data-testid="cell-editor"
/>
);
diff --git a/frontend/src/components/editor/code/readonly-python-code.tsx b/frontend/src/components/editor/code/readonly-python-code.tsx
index c911141146..11a416e01d 100644
--- a/frontend/src/components/editor/code/readonly-python-code.tsx
+++ b/frontend/src/components/editor/code/readonly-python-code.tsx
@@ -95,9 +95,12 @@ const EyeCloseButton = (props: { onClick: () => void }) => {
);
};
-export const HideCodeButton = (props: { onClick: () => void }) => {
+export const HideCodeButton = (props: {
+ className?: string;
+ onClick: () => void;
+}) => {
return (
- <div className="absolute inset-0 z-10" onClick={props.onClick}>
+ <div className={props.className} onClick={props.onClick}>
<EyeIcon className="hover-action w-5 h-5 text-muted-foreground cursor-pointer absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 opacity-80 hover:opacity-100" />
</div>
);
diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsx
index bda357cb28..a4b4494230 100644
--- a/frontend/src/components/scratchpad/scratchpad.tsx
+++ b/frontend/src/components/scratchpad/scratchpad.tsx
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type React from "react";
import { useUserConfig } from "@/core/config/config";
-import { useRef } from "react";
+import { useRef, useState } from "react";
import { useTheme } from "@/theme/useTheme";
import { CellEditor } from "../editor/cell/code/cell-editor";
import { HTMLCellId } from "@/core/cells/ids";
@@ -38,6 +38,7 @@ import {
import { cn } from "@/utils/cn";
import type { CellConfig } from "@/core/network/types";
import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";
+import type { LanguageAdapterType } from "@/core/codemirror/language/types";
const scratchpadCellConfig: CellConfig = {
hide_code: false,
@@ -118,6 +119,8 @@ export const ScratchPad: React.FC = () => {
}
});
+ const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();
+
const renderBody = () => {
// We overlay the history on top of the body, instead of removing it,
// so we don't have to re-render the entire editor and outputs.
@@ -145,6 +148,9 @@ export const ScratchPad: React.FC = () => {
userConfig={userConfig}
editorViewRef={ref}
hidden={false}
+ temporarilyShowCode={Functions.NOOP}
+ languageAdapter={languageAdapter}
+ setLanguageAdapter={setLanguageAdapter}
/>
</div>
<div className="flex-1 overflow-auto flex-shrink-0">
diff --git a/frontend/src/hooks/__tests__/useResizeObserver.test.tsx b/frontend/src/hooks/__tests__/useResizeObserver.test.tsx
new file mode 100644
index 0000000000..cd6efc2ca0
--- /dev/null
+++ b/frontend/src/hooks/__tests__/useResizeObserver.test.tsx
@@ -0,0 +1,85 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, beforeEach, vi, expect, it, afterAll } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { useResizeObserver } from "../useResizeObserver";
+
+describe("useResizeObserver", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterAll(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("should call observe when ref is provided", () => {
+ const observeSpy = vi.fn();
+ global.ResizeObserver = class MockedResizeObserver {
+ observe = observeSpy;
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+ };
+
+ renderHook(() =>
+ useResizeObserver({
+ ref: { current: document.createElement("div") },
+ }),
+ );
+
+ expect(observeSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("should not call observe when ref is not provided", () => {
+ const observeSpy = vi.fn();
+ global.ResizeObserver = class MockedResizeObserver {
+ observe = observeSpy;
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+ };
+
+ renderHook(() =>
+ useResizeObserver({
+ ref: { current: null },
+ }),
+ );
+
+ expect(observeSpy).not.toHaveBeenCalled();
+ });
+
+ it("should not call observe when skipped", () => {
+ const observeSpy = vi.fn();
+ global.ResizeObserver = class MockedResizeObserver {
+ observe = observeSpy;
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+ };
+
+ renderHook(() =>
+ useResizeObserver({
+ ref: { current: document.createElement("div") },
+ skip: true,
+ }),
+ );
+
+ expect(observeSpy).not.toHaveBeenCalled();
+ });
+
+ it("disconnect should be called once unmounted", () => {
+ const disconnectSpy = vi.fn();
+ global.ResizeObserver = class MockedResizeObserver {
+ observe = vi.fn();
+ unobserve = vi.fn();
+ disconnect = disconnectSpy;
+ };
+
+ const { unmount } = renderHook(() =>
+ useResizeObserver({
+ ref: { current: document.createElement("div") },
+ }),
+ );
+
+ unmount();
+
+ expect(disconnectSpy).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/src/hooks/useResizeObserver.ts b/frontend/src/hooks/useResizeObserver.ts
new file mode 100644
index 0000000000..9a848f4897
--- /dev/null
+++ b/frontend/src/hooks/useResizeObserver.ts
@@ -0,0 +1,102 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/*
+ * Simplified version of useResizeObserver from https://usehooks-ts.com/react-hook/use-resize-observer
+ * Use this when you want to attach a resize observer conditionally using the `skip` option.
+ */
+
+import { useEffect, useRef } from "react";
+
+import type { RefObject } from "react";
+
+interface Size {
+ width: number | undefined;
+ height: number | undefined;
+}
+
+interface UseResizeObserverOptions<T extends HTMLElement = HTMLElement> {
+ ref: RefObject<T>;
+ skip?: boolean;
+ onResize?: (size: Size) => void;
+ box?: "border-box" | "content-box" | "device-pixel-content-box";
+}
+
+const initialSize: Size = {
+ width: undefined,
+ height: undefined,
+};
+
+export function useResizeObserver<T extends HTMLElement = HTMLElement>(
+ options: UseResizeObserverOptions<T>,
+): void {
+ const { ref, box = "content-box", skip } = options;
+ // eslint-disable-next-line react/hook-use-state
+ const previousSize = useRef<Size>({ ...initialSize });
+ const onResize = useRef<((size: Size) => void) | undefined>(undefined);
+ // eslint-disable-next-line react-compiler/react-compiler
+ onResize.current = options.onResize;
+
+ useEffect(() => {
+ if (!ref.current || skip) {
+ return;
+ }
+
+ if (typeof window === "undefined" || !("ResizeObserver" in window)) {
+ return;
+ }
+
+ const observer = new ResizeObserver(([entry]) => {
+ const boxProp =
+ box === "border-box"
+ ? "borderBoxSize"
+ : box === "device-pixel-content-box"
+ ? "devicePixelContentBoxSize"
+ : "contentBoxSize";
+
+ const newWidth = extractSize(entry, boxProp, "inlineSize");
+ const newHeight = extractSize(entry, boxProp, "blockSize");
+
+ const hasChanged =
+ previousSize.current.width !== newWidth ||
+ previousSize.current.height !== newHeight;
+
+ if (hasChanged) {
+ const newSize: Size = { width: newWidth, height: newHeight };
+ previousSize.current.width = newWidth;
+ previousSize.current.height = newHeight;
+
+ if (onResize.current) {
+ onResize.current(newSize);
+ }
+ }
+ });
+
+ observer.observe(ref.current, { box });
+
+ return () => {
+ observer.disconnect();
+ };
+ }, [box, ref, skip]);
+}
+
+type BoxSizesKey = keyof Pick<
+ ResizeObserverEntry,
+ "borderBoxSize" | "contentBoxSize" | "devicePixelContentBoxSize"
+>;
+
+function extractSize(
+ entry: ResizeObserverEntry,
+ box: BoxSizesKey,
+ sizeType: keyof ResizeObserverSize,
+): number | undefined {
+ if (!entry[box]) {
+ if (box === "contentBoxSize") {
+ return entry.contentRect[sizeType === "inlineSize" ? "width" : "height"];
+ }
+ return undefined;
+ }
+
+ return Array.isArray(entry[box])
+ ? entry[box][0][sizeType]
+ : // @ts-expect-error Support Firefox's non-standard behavior
+ (entry[box][sizeType] as number);
+}