-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: impl list syntax auto complete to editor
- Loading branch information
Showing
4 changed files
with
135 additions
and
87 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
File renamed without changes.
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 |
---|---|---|
@@ -0,0 +1,3 @@ | ||
import useAutoComplete from "./useAutoComplete"; | ||
|
||
export { useAutoComplete }; |
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 |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { last } from "lodash-es"; | ||
import { useEffect } from "react"; | ||
import { NodeType, OrderedListNode, TaskListNode, UnorderedListNode } from "@/types/node"; | ||
import { EditorRefActions } from "../Editor"; | ||
|
||
const useAutoComplete = (actions: EditorRefActions) => { | ||
useEffect(() => { | ||
const editor = actions.getEditor(); | ||
if (!editor) return; | ||
|
||
editor.addEventListener("keydown", (event) => { | ||
if (event.key === "Enter") { | ||
const cursorPosition = actions.getCursorPosition(); | ||
const prevContent = actions.getContent().substring(0, cursorPosition); | ||
const lastNode = last(window.parse(prevContent)); | ||
if (!lastNode) { | ||
return; | ||
} | ||
|
||
let insertText = ""; | ||
if (lastNode.type === NodeType.TASK_LIST) { | ||
const { complete } = lastNode.value as TaskListNode; | ||
insertText = complete ? "- [x] " : "- [ ] "; | ||
} else if (lastNode.type === NodeType.UNORDERED_LIST) { | ||
const { symbol } = lastNode.value as UnorderedListNode; | ||
insertText = `${symbol} `; | ||
} else if (lastNode.type === NodeType.ORDERED_LIST) { | ||
const { number } = lastNode.value as OrderedListNode; | ||
insertText = `${Number(number) + 1}. `; | ||
} | ||
if (insertText) { | ||
actions.insertText(`\n${insertText}`); | ||
event.preventDefault(); | ||
} | ||
} | ||
}); | ||
}, []); | ||
}; | ||
|
||
export default useAutoComplete; |