-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Allow behavior to remove and select image node (#65)
- Loading branch information
Showing
2 changed files
with
55 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters