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/equation #953

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
test equation
  • Loading branch information
jkcs committed Jul 18, 2024
commit f102c8033b89f96abe5f9049b6a0066f3c5cf01b
11 changes: 11 additions & 0 deletions examples/03-ui-components/13-equation/.bnexample.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"playground": true,
"docs": false,
"author": "matthewlipski",
"tags": ["Intermediate", "Blocks", "Custom Schemas", "Suggestion Menus", "Slash Menu"],
"dependencies": {
"katex": "^0.16.11",
"@types/katex": "^0.16.7",
"react-icons": "^5.2.1"
}
}
98 changes: 98 additions & 0 deletions examples/03-ui-components/13-equation/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {
BlockNoteSchema,
defaultInlineContentSpecs,
filterSuggestionItems,
insertOrUpdateBlock,
} from "@blocknote/core";
import "@blocknote/core/fonts/inter.css";
import {
SuggestionMenuController,
getDefaultReactSlashMenuItems,
useCreateBlockNote,
} from "@blocknote/react";
import { BlockNoteView } from "@blocknote/mantine";
import "@blocknote/mantine/style.css";

import { LaTex } 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,
latex: LaTex,
},
});

// Slash menu item to insert an Alert block
const insertLaTex = (editor: typeof schema.BlockNoteEditor) => ({
title: "latex",
key: "latex",
subtext: "Used for a top-level heading",
aliases: ["latex", "heading1", "h1"],
group: "Other",
onItemClick: () => {
insertOrUpdateBlock(editor, {
type: "paragraph",
content: [
{
type: "latex",
props: {
open: true,
},
content: "\\sqrt{a^2 + b^2}",
},
],
});
},
});

export default function App() {
// Creates a new editor instance.
const editor = useCreateBlockNote({
schema,
initialContent: [
{
type: "paragraph",
content: [
"latex text editor ",
{
type: "latex",
content: "c = \\pm\\sqrt{a^2 + b^2}",
},
],
},
{
type: "paragraph",
},
{
type: "paragraph",
content: [
{
type: "latex",
content:
"\\int \\frac{1}{\\sqrt{1-x^{2}}}\\mathrm{d}x= \\arcsin x +C",
},
],
},
{
type: "paragraph",
},
],
});

// Renders the editor instance.
return (
<BlockNoteView editor={editor} slashMenu={false}>
<SuggestionMenuController
triggerCharacter={"/"}
getItems={async (query: any) =>
filterSuggestionItems(
[...getDefaultReactSlashMenuItems(editor), insertLaTex(editor)],
query
)
}
/>
</BlockNoteView>
);
}
206 changes: 206 additions & 0 deletions examples/03-ui-components/13-equation/Equation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import { useComponentsContext } from "@blocknote/react";
import { NodeView } from "prosemirror-view";
import { BlockNoteEditor, propsToAttributes } from "@blocknote/core";
import {
NodeViewProps,
NodeViewRenderer,
NodeViewWrapper,
ReactNodeViewRenderer,
} from "@tiptap/react";
import {
createStronglyTypedTiptapNode,
createInternalInlineContentSpec,
} from "@blocknote/core";
import { mergeAttributes } from "@tiptap/core";
import { ChangeEvent, useEffect, useState, useRef } from "react";
import katex from "katex";
import "katex/dist/katex.min.css";
import "./styles.css";

function LaTexView() {
const nodeView:
| ((this: {
name: string;
options: any;
storage: any;
editor: any;
type: any;
parent: any;
}) => NodeViewRenderer)
| null = function () {
const BlockContent = (props: NodeViewProps & { selectionHack: any }) => {
/* eslint-disable react-hooks/rules-of-hooks */
const editor: BlockNoteEditor<any> = this.options.editor;
const content = props.node.textContent;
const open = props.node.attrs.open;
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const contentRef = useRef<HTMLElement | null>(null);
const [html, setHtml] = useState("");
const [loading, setLoading] = useState(false);
const Components = useComponentsContext()!;

useEffect(() => {
setLoading(true);
const html = katex.renderToString(content, {
throwOnError: false,
});
setHtml(html);
setLoading(false);
}, [content]);

useEffect(() => {
if (open) {
if (contentRef.current) {
contentRef.current.click();
}
setTimeout(() => {
if (textareaRef.current) {
textareaRef.current?.focus();
textareaRef.current?.setSelectionRange(
textareaRef.current.value.length,
textareaRef.current.value.length
);
}
});
}
}, [open]);

const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
const val = e.target.value;
const pos = props.getPos?.();
const node = props.node;
const view = editor._tiptapEditor.view;

const tr = view.state.tr.replaceWith(
pos,
pos + node.nodeSize,
view.state.schema.nodes.latex.create(
{
...node.attrs,
},
val ? view.state.schema.text(val) : null
)
);

view.dispatch(tr);
};

return (
<NodeViewWrapper as={"span"}>
<Components.Generic.Popover.Root>
<Components.Generic.Popover.Trigger>
<span className={"latex"} ref={contentRef}>
{loading ? (
<span className={"latex-loading"}>latex loading...</span>
) : (
<span
className={"latex-content"}
dangerouslySetInnerHTML={{ __html: html }}></span>
)}
</span>
</Components.Generic.Popover.Trigger>
<Components.Generic.Popover.Content
className={"bn-popover-content bn-form-popover"}
variant={"form-popover"}>
<textarea
ref={textareaRef}
className={"latex-textarea"}
value={content}
onChange={handleChange}
/>
</Components.Generic.Popover.Content>
</Components.Generic.Popover.Root>
</NodeViewWrapper>
);
};

return (props) => {
if (!(props.editor as any).contentComponent) {
return {};
}
const ret = ReactNodeViewRenderer(BlockContent, {
stopEvent: () => true,
})(props) as NodeView;
ret.setSelection = (anchor, head) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(ret as any).renderer.updateProps({
selectionHack: { anchor, head },
});
};

(ret as any).contentDOMElement = undefined;

const oldUpdated = ret.update!.bind(ret);
ret.update = (node, outerDeco, innerDeco) => {
const retAsAny = ret as any;
let decorations = retAsAny.decorations;
if (
retAsAny.decorations.decorations !== outerDeco ||
retAsAny.decorations.innerDecorations !== innerDeco
) {
decorations = {
decorations: outerDeco,
innerDecorations: innerDeco,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return oldUpdated(node, decorations, undefined as any);
};
return ret;
};
};
return nodeView;
}

const propSchema = {
open: {
type: "boolean",
default: false,
},
};

const node = createStronglyTypedTiptapNode({
name: "latex",
inline: true,
group: "inline",
content: "inline*",
editable: true,
selectable: false,

addAttributes() {
return propsToAttributes(propSchema);
},

parseHTML() {
return [
{
tag: "latex",
priority: 200,
node: "latex",
},
];
},

renderHTML({ HTMLAttributes }) {
return [
"latex",
mergeAttributes(HTMLAttributes, {
"data-content-type": this.name,
}),
0,
];
},

addNodeView: LaTexView(),
});

export const LaTex = createInternalInlineContentSpec(
{
content: "styled",
type: "latex",
propSchema: propSchema,
},
{
node,
}
);
11 changes: 11 additions & 0 deletions examples/03-ui-components/13-equation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Alert Block

In this example, we create a custom `Alert` block which is used to emphasize text. In addition, we create a Slash Menu item which inserts an `Alert` block.

**Try it out:** Press the "/" key to open the Slash Menu and insert an `Alert` 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/03-ui-components/13-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>Equation</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
11 changes: 11 additions & 0 deletions examples/03-ui-components/13-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>
);
40 changes: 40 additions & 0 deletions examples/03-ui-components/13-equation/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "@blocknote/example-equation",
"description": "AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY",
"private": true,
"version": "0.12.4",
"scripts": {
"start": "vite",
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"lint": "eslint . --max-warnings 0"
},
"dependencies": {
"@blocknote/core": "latest",
"@blocknote/react": "latest",
"@blocknote/ariakit": "latest",
"@blocknote/mantine": "latest",
"@blocknote/shadcn": "latest",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"katex": "^0.16.11",
"@types/katex": "^0.16.7",
"react-icons": "^5.2.1"
},
"devDependencies": {
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.9",
"@vitejs/plugin-react": "^4.0.4",
"eslint": "^8.10.0",
"vite": "^4.4.8"
},
"eslintConfig": {
"extends": [
"../../../.eslintrc.js"
]
},
"eslintIgnore": [
"dist"
]
}
Loading