-
-
Notifications
You must be signed in to change notification settings - Fork 491
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
feat: Custom inline equation using the BlockNote API #1022
Open
jkcs
wants to merge
3
commits into
TypeCellOS:main
Choose a base branch
from
jkcs:feat/blocknote-equtaion
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next
Next commit
inline equation
- Loading branch information
commit 26d5df5b505e2fa7ce344bce02b837c424c49b8c
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 |
---|---|---|
@@ -0,0 +1,11 @@ | ||
{ | ||
"playground": true, | ||
"docs": false, | ||
"author": "jkcs", | ||
"tags": ["Equation", "Inline Equation", "Custom Schemas", "Latex", "Slash Menu"], | ||
"dependencies": { | ||
"katex": "^0.16.11", | ||
"@types/katex": "^0.16.7", | ||
"react-icons": "^5.2.1" | ||
} | ||
} |
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,90 @@ | ||
import { | ||
BlockNoteSchema, | ||
defaultInlineContentSpecs, | ||
filterSuggestionItems, | ||
} from "@blocknote/core"; | ||
import "@blocknote/core/fonts/inter.css"; | ||
import { | ||
SuggestionMenuController, | ||
getDefaultReactSlashMenuItems, | ||
useCreateBlockNote, | ||
} from "@blocknote/react"; | ||
import { BlockNoteView } from "@blocknote/mantine"; | ||
import { RiFormula } from "react-icons/ri"; | ||
import "@blocknote/mantine/style.css"; | ||
|
||
import { InlineEquation } from "./Equation"; | ||
|
||
// Our schema with block specs, which contain the configs and implementations for blocks | ||
// that we want our editor to use. | ||
const schema = BlockNoteSchema.create({ | ||
inlineContentSpecs: { | ||
...defaultInlineContentSpecs, | ||
inlineEquation: InlineEquation, | ||
}, | ||
}); | ||
|
||
const insertInlineEquation = (editor: typeof schema.BlockNoteEditor) => ({ | ||
icon: <RiFormula size={18} />, | ||
title: "Inline Equation", | ||
key: "inlineEquation", | ||
subtext: "Insert mathematical symbols in text.", | ||
aliases: ["equation", "latex", "katex"], | ||
group: "Other", | ||
onItemClick: () => { | ||
editor.insertInlineContent([ | ||
{ | ||
type: "inlineEquation", | ||
}, | ||
" ", // add a space after the mention | ||
]); | ||
}, | ||
}); | ||
|
||
export default function App() { | ||
const editor = useCreateBlockNote({ | ||
schema, | ||
initialContent: [ | ||
{ | ||
type: "paragraph", | ||
content: [ | ||
"This is an example inline equation ", | ||
{ | ||
type: "inlineEquation", | ||
props: { | ||
content: "c = \\pm\\sqrt{a^2 + b^2}", | ||
}, | ||
}, | ||
], | ||
}, | ||
{ | ||
type: "paragraph", | ||
content: "Press the '/' key to open the Slash Menu and add another", | ||
}, | ||
{ | ||
type: "paragraph", | ||
}, | ||
{ | ||
type: "paragraph", | ||
}, | ||
], | ||
}); | ||
|
||
// Renders the editor instance. | ||
return ( | ||
<BlockNoteView editor={editor} slashMenu={false}> | ||
<SuggestionMenuController | ||
triggerCharacter={"/"} | ||
getItems={async (query: any) => | ||
filterSuggestionItems( | ||
[ | ||
...getDefaultReactSlashMenuItems(editor), | ||
insertInlineEquation(editor), | ||
], | ||
query | ||
) | ||
} | ||
/> | ||
</BlockNoteView> | ||
); | ||
} |
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,292 @@ | ||
import { | ||
createReactInlineContentSpec, | ||
useBlockNoteEditor, | ||
useComponentsContext, | ||
useEditorContentOrSelectionChange, | ||
} from "@blocknote/react"; | ||
import { NodeViewWrapper } from "@tiptap/react"; | ||
import { | ||
ChangeEvent, | ||
forwardRef, | ||
MouseEvent as ReactMouseEvent, | ||
TextareaHTMLAttributes, | ||
useCallback, | ||
useEffect, | ||
useMemo, | ||
useRef, | ||
useState, | ||
} from "react"; | ||
import katex from "katex"; | ||
import { AiOutlineEnter } from "react-icons/ai"; | ||
import "katex/dist/katex.min.css"; | ||
import "./styles.css"; | ||
import { Node as TipTapNode } from "@tiptap/pm/model"; | ||
|
||
const TextareaView = forwardRef< | ||
HTMLTextAreaElement, | ||
{ | ||
autofocus?: boolean; | ||
} & TextareaHTMLAttributes<HTMLTextAreaElement> | ||
>((props, ref) => { | ||
const { autofocus, ...rest } = props; | ||
useEffect(() => { | ||
if (autofocus && ref && typeof ref !== "function" && ref.current) { | ||
ref.current.setSelectionRange(0, ref.current.value.length); | ||
ref.current.focus(); | ||
} | ||
}, [autofocus, ref]); | ||
|
||
return ( | ||
<textarea | ||
ref={ref} | ||
className={"equation-textarea"} | ||
value={props.value} | ||
onChange={props.onChange} | ||
{...rest} | ||
/> | ||
); | ||
}); | ||
|
||
export const InlineEquationView = (props: { node: TipTapNode }) => { | ||
const content = props.node.attrs.content; | ||
const nodeSize = props.node.nodeSize; | ||
const textareaRef = useRef<HTMLTextAreaElement | null>(null); | ||
const contentRef = useRef<HTMLElement | null>(null); | ||
const containerRef = useRef<HTMLElement | null>(null); | ||
const [focus, setFocus] = useState(!content); | ||
const [curEdge, setCurEdge] = useState(!content); | ||
const Components = useComponentsContext()!; | ||
const editor = useBlockNoteEditor(); | ||
const html = useMemo( | ||
() => | ||
katex.renderToString(content, { | ||
throwOnError: false, | ||
}), | ||
[content] | ||
); | ||
|
||
const getTextareaEdge = () => { | ||
const $textarea = textareaRef.current; | ||
if (!$textarea) { | ||
return {}; | ||
} | ||
|
||
return { | ||
isLeftEdge: | ||
$textarea.selectionStart === 0 && $textarea.selectionEnd === 0, | ||
isRightEdge: | ||
$textarea.selectionStart === $textarea.value.length && | ||
$textarea.selectionEnd === $textarea.value.length, | ||
}; | ||
}; | ||
|
||
const getPos = useCallback((): number => { | ||
let position = 0; | ||
|
||
editor._tiptapEditor.state.doc.descendants( | ||
(node: TipTapNode, pos: number) => { | ||
if (node === props.node) { | ||
position = pos; | ||
return false; | ||
} | ||
} | ||
); | ||
|
||
return position; | ||
}, [editor, props.node]); | ||
|
||
useEditorContentOrSelectionChange(() => { | ||
const pos = getPos(); | ||
const courPos = editor._tiptapEditor.state.selection.from; | ||
const selection = editor.getSelection(); | ||
|
||
setCurEdge(!selection && (courPos === pos + nodeSize || courPos === pos)); | ||
}); | ||
|
||
useEffect(() => { | ||
if (focus) { | ||
contentRef.current?.click(); | ||
} | ||
}, [focus]); | ||
|
||
const handleEnter = useCallback( | ||
(event: ReactMouseEvent | KeyboardEvent) => { | ||
event.preventDefault(); | ||
const pos = getPos(); | ||
if (!content) { | ||
const node = props.node; | ||
const view = editor._tiptapEditor.view; | ||
|
||
const tr = view.state.tr.delete(pos, pos + node.nodeSize); | ||
|
||
view.dispatch(tr); | ||
editor._tiptapEditor.commands.setTextSelection(pos); | ||
} else { | ||
editor._tiptapEditor.commands.setTextSelection(pos + nodeSize); | ||
} | ||
editor.focus(); | ||
setFocus(false); | ||
setCurEdge(true); | ||
}, | ||
[content, editor, getPos, nodeSize, props.node] | ||
); | ||
|
||
const handleMenuNavigationKeys = useCallback( | ||
(event: KeyboardEvent) => { | ||
const textareaEdge = getTextareaEdge(); | ||
const pos = getPos(); | ||
const courPos = editor._tiptapEditor.state.selection.from; | ||
|
||
if (event.key === "ArrowLeft") { | ||
if (courPos === pos + nodeSize && !focus) { | ||
setFocus(true); | ||
} | ||
if (textareaEdge.isLeftEdge) { | ||
event.preventDefault(); | ||
editor.focus(); | ||
editor._tiptapEditor.commands.setTextSelection(pos); | ||
setFocus(false); | ||
} | ||
return true; | ||
} | ||
|
||
if (event.key === "ArrowRight") { | ||
if (courPos === pos && !focus) { | ||
setFocus(true); | ||
} | ||
if (textareaEdge.isRightEdge) { | ||
event.preventDefault(); | ||
editor.focus(); | ||
editor._tiptapEditor.commands.setTextSelection(pos + nodeSize); | ||
setFocus(false); | ||
} | ||
return true; | ||
} | ||
|
||
if (event.key === "Enter" && focus) { | ||
handleEnter(event); | ||
return true; | ||
} | ||
|
||
return false; | ||
}, | ||
[editor, focus, getPos, handleEnter, nodeSize] | ||
); | ||
|
||
useEffect(() => { | ||
const domEle = editor._tiptapEditor?.view?.dom; | ||
if (focus || curEdge) { | ||
domEle?.addEventListener("keydown", handleMenuNavigationKeys, true); | ||
} | ||
|
||
return () => { | ||
domEle?.removeEventListener("keydown", handleMenuNavigationKeys, true); | ||
}; | ||
}, [editor, focus, handleMenuNavigationKeys, curEdge]); | ||
|
||
const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => { | ||
const val = e.target.value; | ||
const pos = getPos(); | ||
const node = props.node; | ||
const view = editor._tiptapEditor.view; | ||
|
||
const tr = view.state.tr.replaceWith( | ||
pos, | ||
pos + node.nodeSize, | ||
view.state.schema.nodes.inlineEquation.create( | ||
{ | ||
...node.attrs, | ||
content: val || "", | ||
}, | ||
null | ||
) | ||
); | ||
|
||
view.dispatch(tr); | ||
setFocus(true); | ||
}; | ||
|
||
useEffect(() => { | ||
const handleClickOutside = (event: MouseEvent) => { | ||
if ( | ||
containerRef.current && | ||
!containerRef.current.contains(event.target as Node) | ||
) { | ||
setFocus(false); | ||
} | ||
}; | ||
|
||
document.addEventListener("pointerup", handleClickOutside, true); | ||
return () => { | ||
document.removeEventListener("pointerup", handleClickOutside, true); | ||
}; | ||
}, []); | ||
|
||
return ( | ||
<NodeViewWrapper as={"span"} ref={containerRef}> | ||
<Components.Generic.Popover.Root opened={focus}> | ||
<Components.Generic.Popover.Trigger> | ||
<span | ||
className={"equation " + (focus ? "focus" : "")} | ||
ref={contentRef}> | ||
{!content ? ( | ||
<span onClick={() => setFocus(true)} className={"equation-empty"}> | ||
New Equation | ||
</span> | ||
) : ( | ||
<span | ||
onClick={() => setFocus(true)} | ||
className={"equation-content"} | ||
dangerouslySetInnerHTML={{ __html: html }}></span> | ||
)} | ||
</span> | ||
</Components.Generic.Popover.Trigger> | ||
<Components.Generic.Popover.Content | ||
className={"bn-popover-content bn-form-popover"} | ||
variant={"form-popover"}> | ||
<label className={"equation-label"}> | ||
<TextareaView | ||
placeholder={"c^2 = a^2 + b^2"} | ||
ref={textareaRef} | ||
autofocus | ||
value={content} | ||
onChange={handleChange} | ||
/> | ||
<span onClick={handleEnter} className={"equation-enter"}> | ||
<AiOutlineEnter /> | ||
</span> | ||
</label> | ||
</Components.Generic.Popover.Content> | ||
</Components.Generic.Popover.Root> | ||
</NodeViewWrapper> | ||
); | ||
}; | ||
|
||
export const InlineEquation = createReactInlineContentSpec( | ||
{ | ||
type: "inlineEquation", | ||
propSchema: { | ||
content: { | ||
default: "", | ||
}, | ||
}, | ||
content: "none", | ||
// copy content | ||
renderHTML: (props) => { | ||
const { HTMLAttributes, node } = props; | ||
const dom = document.createElement("span"); | ||
dom.setAttribute("data-inline-content-type", "inlineEquation"); | ||
Object.keys(HTMLAttributes).forEach((key) => { | ||
dom.setAttribute(key, HTMLAttributes[key]); | ||
}); | ||
dom.innerText = node.attrs.content; | ||
|
||
return { dom }; | ||
}, | ||
}, | ||
{ | ||
render: (props) => { | ||
return <InlineEquationView node={props.node} />; | ||
}, | ||
} | ||
); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What were the exact issues you were having with copying without the renderHTML?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
copy of clipboard should be
c = \pm\sqrt{a^2 + b^2}