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

simple latex block #818

Closed
wants to merge 14 commits into from
Prev Previous commit
Next Next commit
latex
  • Loading branch information
jkcs committed Jun 6, 2024
commit d11317dd91281102ba75c36fdffb8c08471f7ff8
8 changes: 2 additions & 6 deletions examples/05-custom-schema/05-latex-block/.bnexample.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
{
"playground": true,
"docs": true,
"docs": false,
"author": "matthewlipski",
"tags": ["Intermediate", "Blocks", "Custom Schemas"],
"dependencies": {
"@mantine/core": "^7.7.1",
"react-icons": "^5.2.1"
}
"tags": ["Intermediate", "LaTex", "Custom Schemas"]
}
33 changes: 17 additions & 16 deletions examples/05-custom-schema/05-latex-block/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
BlockNoteSchema,
defaultBlockSpecs,
defaultInlineContentSpecs,
filterSuggestionItems,
insertOrUpdateBlock,
} from "@blocknote/core";
Expand All @@ -19,8 +18,8 @@ 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,
blockSpecs: {
...defaultBlockSpecs,
latex: LaTex,
},
});
Expand All @@ -34,17 +33,11 @@ const insertLaTex = (editor: typeof schema.BlockNoteEditor) => ({
group: "Other",
onItemClick: () => {
insertOrUpdateBlock(editor, {
type: "paragraph",
content: [
{
type: "latex",
props: {
latex: "",
open: true,
},
content: 'c = \\pm\\sqrt{a^2 + b^2}'
},
],
type: "latex",
props: {
open: true
},
content: '\\sqrt{a^2 + b^2}'
});
},
});
Expand All @@ -57,7 +50,7 @@ export default function App() {
{
type: "paragraph",
content: [
"I enjoy working with ",
"latex text editor ",
{
type: "latex",
content: "c = \\pm\\sqrt{a^2 + b^2}",
Expand All @@ -66,7 +59,15 @@ export default function App() {
},
{
type: "paragraph",
content: "Press the '/' key to open the Slash Menu and add another",
},
{
type: "paragraph",
content: [
{
type: "latex",
content: "\\int \\frac{1}{\\sqrt{1-x^{2}}}\\mathrm{d}x= \\arcsin x +C"
},
],
},
{
type: "paragraph",
Expand Down
143 changes: 81 additions & 62 deletions examples/05-custom-schema/05-latex-block/LaTex.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
useComponentsContext,
} from "@blocknote/react";
import { NodeView } from "prosemirror-view";
import { BlockNoteEditor } from "@blocknote/core";
import { BlockNoteEditor, propsToAttributes } from "@blocknote/core";
import {
NodeViewProps,
NodeViewRenderer,
Expand All @@ -12,53 +12,47 @@ import {
import "./styles.css";
import { createStronglyTypedTiptapNode, createInternalBlockSpec } from "@blocknote/core";
import { mergeAttributes } from "@tiptap/core";
import { ChangeEvent, useEffect, useState } from "react";
import { ChangeEvent, useEffect, useState, useRef } from "react";

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 katexScript = document.getElementById("katex-script");
const katexLink = document.getElementById("katex-link");
let scriptLoaded = !!katexScript;
let linkLoaded = !!katexLink;
const Window = window as any;
if (Window.katex) {
return callback();
}

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

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

delete Window._katexCallbacks;
}
};

if (!katexScript) {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js";
script.integrity =
"sha384-hIoBPJpTUs74ddyc4bFZSM1TVlQDA60VBbJS0oA934VSz82sBx1X7kSx2ATBDIyd";
script.crossOrigin = "anonymous";
script.id = "katex-script";
// script.defer = true;
script.onload = () => {
scriptLoaded = true;
handleCallback();
};
document.head.appendChild(script);
}
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js";
script.integrity =
"sha384-hIoBPJpTUs74ddyc4bFZSM1TVlQDA60VBbJS0oA934VSz82sBx1X7kSx2ATBDIyd";
script.crossOrigin = "anonymous";
script.id = "katex-script";
script.onload = () => {
handleCallback();
};
document.head.appendChild(script);

if (!katexLink) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = "https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css";
link.integrity =
"sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww";
link.crossOrigin = "anonymous";
link.id = "katex-link";
link.onload = () => {
linkLoaded = true;
handleCallback();
};
document.head.appendChild(link);
}

if (scriptLoaded && linkLoaded) {
setTimeout(callback);
}
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = "https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css";
link.integrity =
"sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww";
link.crossOrigin = "anonymous";
link.id = "katex-link";
document.head.appendChild(link);
}

function LaTexView() {
Expand All @@ -75,45 +69,61 @@ function LaTexView() {
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.katex.renderToString(content, {
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,
},
view.state.schema.text(val)
));
.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"}>
<span className={"latex"} ref={contentRef}>
{loading ? (
<span className={"latex-loading"}>latex loading...</span>
) : (
Expand All @@ -124,7 +134,7 @@ function LaTexView() {
<Components.Generic.Popover.Content
className={"bn-popover-content bn-form-popover"}
variant={"form-popover"}>
<textarea className={"latex-textarea"} value={content} onChange={handleChange} />
<textarea ref={textareaRef} className={"latex-textarea"} value={content} onChange={handleChange} />
</Components.Generic.Popover.Content>
</Components.Generic.Popover.Root>
</NodeViewWrapper>
Expand Down Expand Up @@ -169,13 +179,25 @@ function LaTexView() {
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 [
{
Expand All @@ -186,8 +208,14 @@ const node = createStronglyTypedTiptapNode({
];
},

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

addNodeView: LaTexView(),
Expand All @@ -197,16 +225,7 @@ export const LaTex = createInternalBlockSpec(
{
content: "inline",
type: "latex",
propSchema: {
language: {
type: "string",
default: "typescript",
},
storage: {
type: "string",
default: "",
},
},
propSchema: propSchema,
},
{
node,
Expand Down
4 changes: 1 addition & 3 deletions examples/05-custom-schema/05-latex-block/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@
"@blocknote/mantine": "^0.13.0",
"@blocknote/shadcn": "^0.13.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"@mantine/core": "^7.7.1",
"react-icons": "^5.2.1"
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.0.25",
Expand Down
1 change: 1 addition & 0 deletions examples/05-custom-schema/05-latex-block/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@
width: 100%;
min-height: 120px;
padding: 8px;
font-size: 16px;
}