-
-
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 all commits
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
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", "Katex"], | ||
"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 { BlockNoteView } from "@blocknote/mantine"; | ||
import "@blocknote/mantine/style.css"; | ||
import { | ||
SuggestionMenuController, | ||
getDefaultReactSlashMenuItems, | ||
useCreateBlockNote, | ||
} from "@blocknote/react"; | ||
import { RiFormula } from "react-icons/ri"; | ||
|
||
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,250 @@ | ||
import { InlineContentFromConfig } from "@blocknote/core"; | ||
import { | ||
createReactInlineContentSpec, | ||
useBlockNoteEditor, | ||
useComponentsContext, | ||
} from "@blocknote/react"; | ||
import { Node as TipTapNode } from "@tiptap/pm/model"; | ||
import { NodeViewWrapper } from "@tiptap/react"; | ||
import katex from "katex"; | ||
import "katex/dist/katex.min.css"; | ||
import { | ||
ChangeEvent, | ||
MouseEvent as ReactMouseEvent, | ||
TextareaHTMLAttributes, | ||
forwardRef, | ||
useCallback, | ||
useEffect, | ||
useMemo, | ||
useRef, | ||
} from "react"; | ||
import { AiOutlineEnter } from "react-icons/ai"; | ||
import "./styles.css"; | ||
|
||
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: { | ||
inlineContent: InlineContentFromConfig<typeof InlineEquation.config, any>; | ||
node: TipTapNode; | ||
isSelected: boolean; | ||
}) => { | ||
const content = props.inlineContent.props.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 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]); | ||
|
||
const handleEnter = useCallback( | ||
(event: ReactMouseEvent | React.KeyboardEvent) => { | ||
event.preventDefault(); | ||
const pos = getPos(); | ||
if (!content) { | ||
// TODO: implement BlockNote API to easily delete inline 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 { | ||
// TODO: implement BlockNote API to easily update cursor position | ||
editor._tiptapEditor.commands.setTextSelection(pos + nodeSize); | ||
} | ||
editor.focus(); | ||
}, | ||
[content, editor, getPos, nodeSize, props.node] | ||
); | ||
|
||
const handleMenuNavigationKeys = useCallback( | ||
(event: React.KeyboardEvent) => { | ||
const textareaEdge = getTextareaEdge(); | ||
const pos = getPos(); | ||
|
||
if (event.key === "ArrowLeft") { | ||
if (textareaEdge.isLeftEdge) { | ||
// TODO: implement BlockNote API to set cursor position | ||
event.preventDefault(); | ||
editor.focus(); | ||
editor._tiptapEditor.commands.setTextSelection(pos); | ||
} | ||
return true; | ||
} | ||
|
||
if (event.key === "ArrowRight") { | ||
if (textareaEdge.isRightEdge) { | ||
// TODO: implement BlockNote API to set cursor position | ||
event.preventDefault(); | ||
editor.focus(); | ||
editor._tiptapEditor.commands.setTextSelection(pos + nodeSize); | ||
} | ||
return true; | ||
} | ||
|
||
if (event.key === "Enter" && props.isSelected) { | ||
handleEnter(event); | ||
return true; | ||
} | ||
|
||
return false; | ||
}, | ||
[editor, getPos, handleEnter, nodeSize, props.isSelected] | ||
); | ||
|
||
// TODO: implement BlockNote API to easily update inline content | ||
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); | ||
}; | ||
|
||
return ( | ||
<NodeViewWrapper as={"span"} ref={containerRef}> | ||
<Components.Generic.Popover.Root opened={props.isSelected}> | ||
<Components.Generic.Popover.Trigger> | ||
<span | ||
className={"equation " + (props.isSelected ? "focus" : "")} | ||
ref={contentRef}> | ||
{!content ? ( | ||
<span className={"equation-empty"}>New Equation</span> | ||
) : ( | ||
<span | ||
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} | ||
onKeyDown={handleMenuNavigationKeys} | ||
/> | ||
<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} | ||
inlineContent={props.inlineContent} | ||
isSelected={props.isSelected} | ||
/> | ||
); | ||
}, | ||
} | ||
); |
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 @@ | ||
# Inline Equation | ||
|
||
In this example, we create a custom `Inline Equation` | ||
|
||
**Try it out:** Press the "/" key to open the Slash Menu and insert an `Equation` block! | ||
|
||
**Relevant Docs:** | ||
|
||
- [Custom Blocks](/docs/custom-schemas/custom-blocks) | ||
- [Changing Slash Menu Items](/docs/ui-components/suggestion-menus#changing-slash-menu-items) | ||
- [Editor Setup](/docs/editor-basics/setup) |
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,14 @@ | ||
<html lang="en"> | ||
<head> | ||
<script> | ||
<!-- AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY --> | ||
</script> | ||
<meta charset="UTF-8" /> | ||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | ||
<title>Inline Equation</title> | ||
</head> | ||
<body> | ||
<div id="root"></div> | ||
<script type="module" src="./main.tsx"></script> | ||
</body> | ||
</html> |
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 @@ | ||
// AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY | ||
import React from "react"; | ||
import { createRoot } from "react-dom/client"; | ||
import App from "./App"; | ||
|
||
const root = createRoot(document.getElementById("root")!); | ||
root.render( | ||
<React.StrictMode> | ||
<App /> | ||
</React.StrictMode> | ||
); |
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}