Skip to content

simple latex block #818

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

Closed
wants to merge 14 commits into from
Closed
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
6 changes: 6 additions & 0 deletions examples/05-custom-schema/05-latex-block/.bnexample.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"playground": true,
"docs": false,
"author": "jkcs",
"tags": ["Intermediate", "LaTex", "Custom Schemas"]
}
97 changes: 97 additions & 0 deletions examples/05-custom-schema/05-latex-block/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
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 "./LaTex";

// 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) =>
filterSuggestionItems(
[...getDefaultReactSlashMenuItems(editor), insertLaTex(editor)],
query
)
}
/>
</BlockNoteView>
);
}
233 changes: 233 additions & 0 deletions examples/05-custom-schema/05-latex-block/LaTex.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
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 "./styles.css";

function loadKaTex(callback: () => void) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I'd prefer to just have this as a dependency of the package, that makes the code a lot cleaner imo

const Window = window as any;
if (Window.katex) {
return callback();
}

Window._katexCallbacks = Window._katexCallbacks || [];
Window._katexCallbacks.push(callback);

const handleCallback = () => {
if (Window.katex && Window._katexCallbacks) {
Window._katexCallbacks.forEach((callback: () => void) => {
callback();
});

delete Window._katexCallbacks;
}
};

const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js";
script.integrity =
"sha384-hIoBPJpTUs74ddyc4bFZSM1TVlQDA60VBbJS0oA934VSz82sBx1X7kSx2ATBDIyd";
script.crossOrigin = "anonymous";
script.id = "katex-script";
script.onload = () => {
handleCallback();
};
document.head.appendChild(script);


const link = document.createElement("link");
link.rel = "stylesheet";
link.href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css";
link.integrity =
"sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww";
link.crossOrigin = "anonymous";
link.id = "katex-link";
document.head.appendChild(link);
}

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);
loadKaTex(() => {
const html = (window as any).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 = {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't think open should be part of the blockschema. It's a state of the UI, not of the document.

For example, this will mean that the open state will be stored in databases or synced over collaboration, I don't think that's what we want

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/05-custom-schema/05-latex-block/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# LaTex Block

In this example, we create a custom `LaTex` block.

**Try it out:** Press the "/" key to open the Slash Menu and insert an `LaTex` 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/05-custom-schema/05-latex-block/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>Latex Block</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
11 changes: 11 additions & 0 deletions examples/05-custom-schema/05-latex-block/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