Skip to content

Commit

Permalink
Allow behavior to remove and select image node (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
LuisNivar authored Jan 16, 2024
1 parent 4082dfa commit b66995e
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 4 deletions.
57 changes: 54 additions & 3 deletions apps/front-end/src/plugins/ImagePlugin/Image.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,61 @@
/* eslint-disable @next/next/no-img-element */
import { ComponentPropsWithoutRef } from "react";
import Tooltip from "@/components/Tooltip";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { useLexicalNodeSelection } from "@lexical/react/useLexicalNodeSelection";
import clsx from "clsx";
import { COMMAND_PRIORITY_HIGH, SELECTION_CHANGE_COMMAND } from "lexical";
import { ComponentPropsWithoutRef, useEffect, useState } from "react";
import { ImageNode } from "./ImageNode";

type ImageProps = ComponentPropsWithoutRef<"img">;
type ImageProps = ComponentPropsWithoutRef<"img"> & {
node: ImageNode;
};

function Image(props: ImageProps) {
return <img loading="lazy" {...props} />;
const { node, alt, ...rest } = props;
const [hasFocus, setFocus] = useState(false);
const [editor] = useLexicalComposerContext();
const [isSelected, _setSelected, _celearSelection] = useLexicalNodeSelection(
node.__key,
);

useEffect(() => {
return editor.registerCommand(
SELECTION_CHANGE_COMMAND,
() => {
setFocus(false);
return false;
},
COMMAND_PRIORITY_HIGH,
);
}, [editor]);

const handleClick = () => {
setFocus(true);
};

const handleDelete = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === "Delete" || e.key === "Backspace") {
editor.update(() => node.remove());
}
};

return (
<Tooltip title={alt ?? ""}>
<img
tabIndex={-1}
loading="lazy"
onClick={handleClick}
onKeyUp={handleDelete}
className={clsx(
"rounded-lg",
(isSelected || hasFocus) &&
"outline outline-2 outline-offset-2 outline-cyan-600 ",
)}
{...rest}
/>
</Tooltip>
);
}

export default Image;
2 changes: 1 addition & 1 deletion apps/front-end/src/plugins/ImagePlugin/ImageNode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class ImageNode extends DecoratorNode<ReactNode> {
}

decorate(): ReactNode {
return <Image src={this.src} alt={this.alt} />;
return <Image node={this} src={this.src} alt={this.alt} />;
}
}

Expand Down

0 comments on commit b66995e

Please sign in to comment.