mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-29 00:06:05 +00:00
Merge pull request #1076 from 555aaditya/fix/ai-editors-use-click-outside
feat: close the textarea AI edit and caret menus through useClickOutside like every other floating layer
This commit is contained in:
@@ -9,6 +9,7 @@
|
||||
// the two are naturally exclusive: this renders only for a collapsed caret.
|
||||
|
||||
import React from "react";
|
||||
import useClickOutside from "@/hooks/useClickOutside";
|
||||
import { createPortal } from "react-dom";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import {
|
||||
@@ -210,29 +211,8 @@ export default function TextareaAICaret({
|
||||
};
|
||||
}, [caret, measure]);
|
||||
|
||||
// Click-away and Escape while open.
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (e: MouseEvent | TouchEvent) => {
|
||||
const t = e.target as Node | null;
|
||||
if (rootRef.current?.contains(t)) return;
|
||||
closeAll();
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
e.stopPropagation();
|
||||
closeAll();
|
||||
}
|
||||
};
|
||||
document.addEventListener("mousedown", onDown, true);
|
||||
document.addEventListener("touchstart", onDown, true);
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", onDown, true);
|
||||
document.removeEventListener("touchstart", onDown, true);
|
||||
document.removeEventListener("keydown", onKey, true);
|
||||
};
|
||||
}, [open, closeAll]);
|
||||
// Click-away and Escape while open; a press in the textarea closes it too.
|
||||
useClickOutside(open, () => closeAll(), rootRef);
|
||||
|
||||
// External edits while open (typing, draft bar) close the menu.
|
||||
React.useEffect(() => {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
// click-outside handlers treat it as part of the floating layer.
|
||||
|
||||
import React from "react";
|
||||
import useClickOutside from "@/hooks/useClickOutside";
|
||||
import { createPortal } from "react-dom";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { SparklesIcon } from "lucide-react";
|
||||
@@ -194,23 +195,8 @@ export default function TextareaAIEdit({
|
||||
};
|
||||
}, [sel, syncRects]);
|
||||
|
||||
// Dismiss when the user clicks anywhere outside the floating layer and
|
||||
// the textarea (like useClickOutside, plus the textarea exception).
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (e: MouseEvent | TouchEvent) => {
|
||||
const t = e.target as Node | null;
|
||||
if (rootRef.current?.contains(t)) return;
|
||||
if (textareaRef.current?.contains(t)) return;
|
||||
closeAll();
|
||||
};
|
||||
document.addEventListener("mousedown", onDown, true);
|
||||
document.addEventListener("touchstart", onDown, true);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", onDown, true);
|
||||
document.removeEventListener("touchstart", onDown, true);
|
||||
};
|
||||
}, [open, closeAll, textareaRef]);
|
||||
// Click-away (the textarea counts as inside) and Escape while open.
|
||||
useClickOutside(open, () => closeAll(), [textareaRef, rootRef]);
|
||||
|
||||
// External edits (typing, template insert, discard) while open: bail out
|
||||
// rather than rewriting stale ranges.
|
||||
@@ -219,18 +205,6 @@ export default function TextareaAIEdit({
|
||||
if (expectedValue.current !== null && value !== expectedValue.current) closeAll();
|
||||
}, [value, open, closeAll]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
e.stopPropagation();
|
||||
closeAll();
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
return () => document.removeEventListener("keydown", onKey, true);
|
||||
}, [open, closeAll]);
|
||||
|
||||
const applyResult = React.useCallback(
|
||||
(
|
||||
target: Selection,
|
||||
|
||||
@@ -5,11 +5,14 @@
|
||||
|
||||
import React from "react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, act, fireEvent } from "@testing-library/react";
|
||||
import { render, screen, act, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
let reply = { text: "", charged_usd: 0.01, tokens_used: 10 };
|
||||
let sent: { text: string; instruction: string } | null = null;
|
||||
// When set, the rewrite stays in flight until the test answers it.
|
||||
let holdReply = false;
|
||||
let answer: (() => void) | null = null;
|
||||
vi.mock("@/lib/api/hooks/app/generation/useGenerateEdit", () => ({
|
||||
default: () => ({
|
||||
isPending: false,
|
||||
@@ -18,10 +21,16 @@ vi.mock("@/lib/api/hooks/app/generation/useGenerateEdit", () => ({
|
||||
opts?: { onSuccess?: (res: unknown) => void },
|
||||
) => {
|
||||
sent = vars;
|
||||
opts?.onSuccess?.(reply);
|
||||
if (holdReply) answer = () => opts?.onSuccess?.(reply);
|
||||
else opts?.onSuccess?.(reply);
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("@/lib/api/hooks/app/generation/useGenerateWrite", () => ({
|
||||
default: () => ({ isPending: false, mutate: () => {} }),
|
||||
}));
|
||||
vi.mock("@/hooks/usePermission", () => ({ usePermission: () => true }));
|
||||
vi.mock("@/hooks/useAiMetered", () => ({ default: () => false }));
|
||||
// The typewriter animates the rewrite in; the test wants its end state.
|
||||
vi.mock("./useTypewriter", () => ({
|
||||
default: () => ({
|
||||
@@ -41,6 +50,7 @@ vi.mock("./textareaRange", () => ({
|
||||
}));
|
||||
|
||||
import TextareaAIEdit from "./TextareaAIEdit";
|
||||
import TextareaAICaret from "./TextareaAICaret";
|
||||
|
||||
const MAX = 20;
|
||||
|
||||
@@ -180,3 +190,106 @@ describe("TextareaAIEdit against the composer's length cap", () => {
|
||||
expect(sent?.text).toBe("two");
|
||||
});
|
||||
});
|
||||
|
||||
describe("TextareaAIEdit closes like every floating layer", () => {
|
||||
async function openPopover() {
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<Host initial="one two three" />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
const ta = container.querySelector("textarea")!;
|
||||
await act(async () => {
|
||||
ta.focus();
|
||||
ta.setSelectionRange(4, 7);
|
||||
document.dispatchEvent(new Event("selectionchange"));
|
||||
});
|
||||
await act(async () => {
|
||||
fireEvent.mouseDown(await screen.findByText("Edit with AI"));
|
||||
});
|
||||
await screen.findByPlaceholderText("Tell AI how to change it…");
|
||||
return ta;
|
||||
}
|
||||
const isOpen = () => screen.queryByPlaceholderText("Tell AI how to change it…") !== null;
|
||||
|
||||
it("stays open on a press in the textarea and closes on a press anywhere else", async () => {
|
||||
const ta = await openPopover();
|
||||
await act(async () => {
|
||||
fireEvent.pointerDown(ta);
|
||||
});
|
||||
expect(isOpen()).toBe(true);
|
||||
await act(async () => {
|
||||
fireEvent.pointerDown(document.body);
|
||||
});
|
||||
await waitFor(() => expect(isOpen()).toBe(false));
|
||||
});
|
||||
|
||||
it("closes on Escape", async () => {
|
||||
await openPopover();
|
||||
await act(async () => {
|
||||
fireEvent.keyDown(document.activeElement ?? document.body, { key: "Escape" });
|
||||
});
|
||||
await waitFor(() => expect(isOpen()).toBe(false));
|
||||
});
|
||||
});
|
||||
|
||||
describe("TextareaAIEdit beside the caret menu", () => {
|
||||
beforeEach(() => {
|
||||
holdReply = false;
|
||||
answer = null;
|
||||
});
|
||||
|
||||
it("closes, and drops its pending rewrite, when the caret menu opens after the selection collapses", async () => {
|
||||
function Both() {
|
||||
const ref = React.useRef<HTMLTextAreaElement>(null);
|
||||
const [value, setValue] = React.useState("one two three");
|
||||
return (
|
||||
<>
|
||||
<textarea ref={ref} value={value} onChange={(e) => setValue(e.target.value)} />
|
||||
<TextareaAIEdit textareaRef={ref} value={value} onChange={setValue} />
|
||||
<TextareaAICaret textareaRef={ref} value={value} onChange={setValue} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<Both />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
const ta = container.querySelector("textarea")!;
|
||||
await act(async () => {
|
||||
ta.focus();
|
||||
ta.setSelectionRange(4, 7);
|
||||
document.dispatchEvent(new Event("selectionchange"));
|
||||
});
|
||||
await act(async () => {
|
||||
fireEvent.mouseDown(await screen.findByText("Edit with AI"));
|
||||
});
|
||||
const input = await screen.findByPlaceholderText("Tell AI how to change it…");
|
||||
holdReply = true;
|
||||
reply = { text: "TWO", charged_usd: 0.01, tokens_used: 10 };
|
||||
await act(async () => {
|
||||
fireEvent.change(input, { target: { value: "shout" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
});
|
||||
expect(answer).not.toBeNull();
|
||||
|
||||
// Collapse the selection in the textarea, then open the caret menu.
|
||||
await act(async () => {
|
||||
fireEvent.pointerDown(ta);
|
||||
ta.focus();
|
||||
ta.setSelectionRange(2, 2);
|
||||
document.dispatchEvent(new Event("selectionchange"));
|
||||
});
|
||||
await act(async () => {
|
||||
fireEvent.keyDown(ta, { key: "j", ctrlKey: true });
|
||||
});
|
||||
await screen.findByPlaceholderText("Ask AI to write…");
|
||||
await waitFor(() => expect(screen.queryByPlaceholderText("Tell AI how to change it…")).toBeNull());
|
||||
|
||||
await act(async () => {
|
||||
answer?.();
|
||||
});
|
||||
expect(ta.value).toBe("one two three");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -178,6 +178,43 @@ describe("useClickOutside", () => {
|
||||
expect([isOpen("A"), isOpen("B")]).toEqual([false, true]);
|
||||
});
|
||||
|
||||
it("closes a sibling floating root when another one opens, and keeps one opened inside a floating panel", () => {
|
||||
// A layer rooted on its own portaled [data-floating] panel, opened from
|
||||
// the keyboard like the textarea AI menus.
|
||||
function Floating({ name }: { name: string }) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const ref = React.useRef<HTMLDivElement>(null);
|
||||
useClickOutside(open, () => setOpen(false), ref);
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>
|
||||
{name}
|
||||
</button>
|
||||
{createPortal(
|
||||
<div ref={ref} data-floating="">
|
||||
{open && <div data-testid={`${name}-panel`} />}
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
render(
|
||||
<>
|
||||
<Floating name="A" />
|
||||
<Floating name="B" />
|
||||
<div data-floating="">
|
||||
<Drop name="C" />
|
||||
</div>
|
||||
</>,
|
||||
);
|
||||
toggle("A");
|
||||
toggle("B");
|
||||
expect([isOpen("A"), isOpen("B")]).toEqual([false, true]);
|
||||
toggle("C");
|
||||
expect([isOpen("B"), isOpen("C")]).toEqual([true, true]);
|
||||
});
|
||||
|
||||
it("closes on a press inside an iframe, which only blurs the window", async () => {
|
||||
render(
|
||||
<>
|
||||
|
||||
@@ -48,7 +48,8 @@ export default function useClickOutside(open: boolean, onClose: Dismiss, inside:
|
||||
const origin = refs.current[0]?.current ?? document.activeElement;
|
||||
let parent = layers.length - 1;
|
||||
while (parent >= 0 && !(origin && layers[parent].contains(origin))) parent--;
|
||||
const nested = parent < 0 && !!origin?.closest?.("[data-floating]");
|
||||
// A layer's own [data-floating] root is not a panel it was opened from.
|
||||
const nested = parent < 0 && !!origin?.parentElement?.closest("[data-floating]");
|
||||
if (!nested) for (const other of layers.slice(parent + 1)) other.close("outside");
|
||||
layers.push(self);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user