You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
memos/web/src/components/MemoEditor/ActionButton/MarkdownMenu.tsx

97 lines
3.0 KiB
TypeScript

import { Dropdown, IconButton, Menu, MenuButton, MenuItem } from "@mui/joy";
import Icon from "@/components/Icon";
import showPreviewMarkdownDialog from "@/components/PreviewMarkdownDialog";
import { EditorRefActions } from "../Editor";
interface Props {
editorRef: React.RefObject<EditorRefActions>;
}
const MarkdownMenu = (props: Props) => {
const { editorRef } = props;
const handleCodeBlockClick = () => {
if (!editorRef.current) {
return;
}
const cursorPosition = editorRef.current.getCursorPosition();
const prevValue = editorRef.current.getContent().slice(0, cursorPosition);
if (prevValue === "" || prevValue.endsWith("\n")) {
editorRef.current.insertText("", "```\n", "\n```");
} else {
editorRef.current.insertText("", "\n```\n", "\n```");
}
setTimeout(() => {
editorRef.current?.scrollToCursor();
editorRef.current?.focus();
});
};
const handleCheckboxClick = () => {
if (!editorRef.current) {
return;
}
const currentPosition = editorRef.current.getCursorPosition();
const currentLineNumber = editorRef.current.getCursorLineNumber();
const currentLine = editorRef.current.getLine(currentLineNumber);
let newLine = "";
let cursorChange = 0;
if (/^- \[( |x|X)\] /.test(currentLine)) {
newLine = currentLine.replace(/^- \[( |x|X)\] /, "");
cursorChange = -6;
} else if (/^\d+\. |- /.test(currentLine)) {
const match = currentLine.match(/^\d+\. |- /) ?? [""];
newLine = currentLine.replace(/^\d+\. |- /, "- [ ] ");
cursorChange = -match[0].length + 6;
} else {
newLine = "- [ ] " + currentLine;
cursorChange = 6;
}
editorRef.current.setLine(currentLineNumber, newLine);
editorRef.current.setCursorPosition(currentPosition + cursorChange);
setTimeout(() => {
editorRef.current?.scrollToCursor();
editorRef.current?.focus();
});
};
const handlePreviewClick = () => {
showPreviewMarkdownDialog(editorRef.current?.getContent() ?? "");
};
return (
<Dropdown>
<MenuButton
slots={{ root: IconButton }}
slotProps={{
root: {
className:
"flex flex-row justify-center items-center p-1 w-auto h-auto mr-1 select-none rounded cursor-pointer text-gray-600 dark:!text-gray-400 hover:bg-gray-300 dark:hover:bg-zinc-800 hover:shadow",
size: "sm",
},
}}
>
<Icon.SquareSlash className="w-5 h-5 mx-auto" />
</MenuButton>
<Menu className="text-sm" size="sm">
<MenuItem onClick={handleCodeBlockClick}>
<Icon.Code2 className="w-4 h-auto" />
<span>Code block</span>
</MenuItem>
<MenuItem onClick={handleCheckboxClick}>
<Icon.CheckSquare className="w-4 h-auto" />
<span>Checkbox</span>
</MenuItem>
<MenuItem onClick={handlePreviewClick}>
<Icon.NotebookText className="w-4 h-auto" />
<span>Preview</span>
</MenuItem>
</Menu>
</Dropdown>
);
};
export default MarkdownMenu;