TypeCellOS / BlockNote

A React Rich Text Editor that's block-based (Notion style) and extensible. Built on top of Prosemirror and Tiptap.
https://www.blocknotejs.org/
Mozilla Public License 2.0
5.9k stars 384 forks source link

Code formatting with Blocknote? #831

Closed ugeshgupta000 closed 3 weeks ago

ugeshgupta000 commented 3 weeks ago

Describe the bug I see some 'code' styling in the code under defaultBlocks.d.ts file. However, i do not see it anywhere. Is it possible to format a section of text as code with Blocknote.

matthewlipski commented 3 weeks ago

Yes! It's just that the code style button is not included in the formatting toolbar by default, see here how to add it. You can also wrap text in tilde ("`") characters to convert it to code.

ugeshgupta000 commented 3 weeks ago

Thankyou for responding. One more question along the lines:

I am looking to implement a custom block, which can contain code, and when rendered, gets a button on the side to quickly copy the code. In this case, the code is expected to be a multi-line code. For rendering the button, i was thinking of doing similar to https://www.blocknotejs.org/examples/ui-components/formatting-toolbar-block-type-items

As per my understanding, in blocknote, each line becomes a separate block. Is there a way to combine a selection of lines into a single block, and yet still maintain the multi-line content inside it? Please let me know in case you have other suggestions to implement it. Thanks in advance.

matthewlipski commented 3 weeks ago

You can indeed have line breaks inside blocks, allowing you to have multiple lines in a single block (Shift+Enter is the keyboard shortcut for that). If you want to write code in that block, you'll most likely want to also override the Tab and Enter keyboard shortcuts, see how to do that here.

ugeshgupta000 commented 3 weeks ago

Can you help me on:

Sorry, i tried, but i am not getting appropriate examples to achieve the same.

matthewlipski commented 3 weeks ago

There is no API functionality to merge multiple blocks, since that's a pretty niche use case. The best you can do is call editor._tiptapEditor.commands.BNMergeBlocks multiple times but this uses the ProseMirror API.

To get the plain text of a block you have to process its content, which is in the form of InlineContent[]. It contains styled text and links, so you just need to loop over everything and concat the text of each InlineContent object to a string.