Skip to content
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
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions examples/06-custom-schema/05-equation/.bnexample.json
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"
}
}
90 changes: 90 additions & 0 deletions examples/06-custom-schema/05-equation/App.tsx
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>
);
}
250 changes: 250 additions & 0 deletions examples/06-custom-schema/05-equation/Equation.tsx
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) => {
Copy link
Collaborator

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?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

copy of image clipboard should be c = \pm\sqrt{a^2 + b^2}

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}
/>
);
},
}
);
11 changes: 11 additions & 0 deletions examples/06-custom-schema/05-equation/README.md
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)
14 changes: 14 additions & 0 deletions examples/06-custom-schema/05-equation/index.html
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>
11 changes: 11 additions & 0 deletions examples/06-custom-schema/05-equation/main.tsx
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>
);
Loading
Loading