Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Editable name refactor #37069

Merged
merged 6 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 212 additions & 0 deletions app/client/src/IDE/Components/EditableName/EditableName.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import React from "react";
import { EditableName } from "./EditableName";
import { render } from "test/testUtils";
import "@testing-library/jest-dom";
import { Icon } from "@appsmith/ads";
import { fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

describe("EditableName", () => {
const mockOnNameSave = jest.fn();
const mockOnExitEditing = jest.fn();

const name = "test_name";
const TabIcon = () => <Icon name="js" />;
const KEY_CONFIG = {
ENTER: { key: "Enter", keyCode: 13 },
ESC: { key: "Esc", keyCode: 27 },
};

const setup = ({ isEditing = false, isLoading = false }) => {
// Define the props
const props = {
name,
icon: <TabIcon />,
isEditing,
onNameSave: mockOnNameSave,
exitEditing: mockOnExitEditing,
isLoading,
};

// Render the component
const utils = render(<EditableName {...props} />);

return {
...props,
...utils,
};
};

test("renders component", () => {
const utils = setup({});
const editableNameElement = utils.getByText(utils.name);

expect(editableNameElement).toBeInTheDocument();
expect(editableNameElement.textContent).toBe(name);
});

test("renders input when editing", () => {
const utils = setup({ isEditing: true });

const editableNameElement = utils.queryByText(utils.name);

expect(editableNameElement).not.toBeInTheDocument();

const inputElement = utils.getByRole("textbox");

expect(inputElement).toBeInTheDocument();
});

describe("valid input actions", () => {
test("submit event", async () => {
const { exitEditing, getByRole, onNameSave } = setup({
isEditing: true,
});

// hit enter
const enterTitle = "enter_title";

fireEvent.change(getByRole("textbox"), {
target: { value: enterTitle },
});
expect(getByRole("textbox")).toHaveValue(enterTitle);

fireEvent.keyUp(getByRole("textbox"), KEY_CONFIG.ENTER);

expect(onNameSave).toHaveBeenCalledWith(enterTitle);
expect(exitEditing).toHaveBeenCalled();
});

test("outside click event", async () => {
const { exitEditing, getByRole, onNameSave } = setup({
isEditing: true,
});

const clickOutsideTitle = "click_outside_title";

fireEvent.change(getByRole("textbox"), {
target: { value: clickOutsideTitle },
});

await userEvent.click(document.body);

expect(onNameSave).toHaveBeenCalledWith(clickOutsideTitle);
expect(exitEditing).toHaveBeenCalled();
});

test("esc key event", async () => {
const escapeTitle = "escape_title";

const { exitEditing, getByRole, onNameSave } = setup({
isEditing: true,
});

fireEvent.change(getByRole("textbox"), {
target: { value: escapeTitle },
});

fireEvent.keyUp(getByRole("textbox"), KEY_CONFIG.ESC);

expect(exitEditing).toHaveBeenCalled();
expect(onNameSave).not.toHaveBeenCalledWith(escapeTitle);
});

test("focus out event", async () => {
const focusOutTitle = "focus_out_title";

const { exitEditing, getByRole, onNameSave } = setup({
isEditing: true,
});

const inputElement = getByRole("textbox");

fireEvent.change(inputElement, {
target: { value: focusOutTitle },
});

fireEvent.keyUp(inputElement, KEY_CONFIG.ESC);
expect(exitEditing).toHaveBeenCalled();
expect(onNameSave).not.toHaveBeenCalledWith(focusOutTitle);
});
});

describe("invalid input actions", () => {
const invalidTitle = "else";
const validationError =
"else is already being used or is a restricted keyword.";

test("click outside", async () => {
const { exitEditing, getByRole, onNameSave } = setup({
isEditing: true,
});
const inputElement = getByRole("textbox");

fireEvent.change(inputElement, {
target: { value: invalidTitle },
});

fireEvent.keyUp(inputElement, KEY_CONFIG.ENTER);

expect(getByRole("tooltip")).toBeInTheDocument();

expect(getByRole("tooltip").textContent).toEqual(validationError);

await userEvent.click(document.body);

expect(getByRole("tooltip").textContent).toEqual("");

expect(exitEditing).toHaveBeenCalled();
expect(onNameSave).not.toHaveBeenCalledWith(invalidTitle);
});

test("esc key", async () => {
const { exitEditing, getByRole, onNameSave } = setup({
isEditing: true,
});
const inputElement = getByRole("textbox");

fireEvent.change(inputElement, {
target: { value: invalidTitle },
});

fireEvent.keyUp(inputElement, KEY_CONFIG.ENTER);
fireEvent.keyUp(inputElement, KEY_CONFIG.ESC);

expect(getByRole("tooltip")).toBeInTheDocument();

expect(getByRole("tooltip").textContent).toEqual("");
expect(exitEditing).toHaveBeenCalled();
expect(onNameSave).not.toHaveBeenCalledWith(invalidTitle);
});

test("focus out event", async () => {
const { exitEditing, getByRole, onNameSave } = setup({
isEditing: true,
});
const inputElement = getByRole("textbox");

fireEvent.change(inputElement, {
target: { value: invalidTitle },
});

fireEvent.keyUp(inputElement, KEY_CONFIG.ENTER);
fireEvent.focusOut(inputElement);
expect(getByRole("tooltip").textContent).toEqual("");
expect(exitEditing).toHaveBeenCalled();
expect(onNameSave).not.toHaveBeenCalledWith(invalidTitle);
});

test("prevents saving empty name", () => {
const { getByRole, onNameSave } = setup({ isEditing: true });
const input = getByRole("textbox");

fireEvent.change(input, { target: { value: "" } });
fireEvent.keyUp(input, KEY_CONFIG.ENTER);

expect(onNameSave).not.toHaveBeenCalledWith("");
expect(getByRole("tooltip")).toHaveTextContent(
"Please enter a valid name",
);
});
});
});
132 changes: 132 additions & 0 deletions app/client/src/IDE/Components/EditableName/EditableName.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Spinner, Text, Tooltip } from "@appsmith/ads";
import { useEventCallback, useEventListener } from "usehooks-ts";
import { usePrevious } from "@mantine/hooks";
import { useNameEditor } from "./useNameEditor";

interface EditableTextProps {
name: string;
isLoading?: boolean;
onNameSave: (name: string) => void;
isEditing: boolean;
exitEditing: () => void;
icon: React.ReactNode;
inputTestId?: string;
}

export const EditableName = ({
exitEditing,
icon,
inputTestId,
isEditing,
isLoading = false,
name,
onNameSave,
}: EditableTextProps) => {
const previousName = usePrevious(name);
const [editableName, setEditableName] = useState(name);
const [validationError, setValidationError] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);

const { normalizeName, validateName } = useNameEditor({
entityName: name,
});

const handleKeyUp = useEventCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
const nameError = validateName(editableName);

if (nameError === null) {
exitEditing();
onNameSave(editableName);
} else {
setValidationError(nameError);
}
} else if (e.key === "Escape") {
exitEditing();
setEditableName(name);
setValidationError(null);
} else {
setValidationError(null);
}
},
);

const handleTitleChange = useEventCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
setEditableName(normalizeName(e.target.value));
},
);

hetunandu marked this conversation as resolved.
Show resolved Hide resolved
const inputProps = useMemo(
() => ({
["data-testid"]: inputTestId,
onKeyUp: handleKeyUp,
onChange: handleTitleChange,
autoFocus: true,
style: { paddingTop: 0, paddingBottom: 0, left: -1, top: -1 },
}),
[handleKeyUp, handleTitleChange],
);

useEventListener(
"focusout",
function handleFocusOut() {
if (isEditing) {
const nameError = validateName(editableName);

exitEditing();

if (nameError === null) {
onNameSave(editableName);
} else {
setEditableName(name);
setValidationError(null);
}
}
},
inputRef,
);

useEffect(
function syncEditableTitle() {
if (!isEditing && previousName !== name) {
setEditableName(name);
}
},
[name, previousName, isEditing],
);

// TODO: This is a temporary fix to focus the input after context retention applies focus to its target
// this is a nasty hack to re-focus the input after context retention applies focus to its target
// this will be addressed in a future task, likely by a focus retention modification
useEffect(
function recaptureFocusInEventOfFocusRetention() {
const input = inputRef.current;

if (isEditing && input) {
setTimeout(() => {
input.focus();
}, 200);
}
},
[isEditing],
);

return (
<>
{isLoading ? <Spinner size="sm" /> : icon}
<Tooltip content={validationError} visible={Boolean(validationError)}>
<Text
inputProps={inputProps}
isEditable={isEditing}
kind="body-s"
ref={inputRef}
>
{editableName}
</Text>
</Tooltip>
</>
);
};
1 change: 1 addition & 0 deletions app/client/src/IDE/Components/EditableName/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { EditableName } from "./EditableName";
Loading
Loading