Skip to content

feat: Toggle blocks #1707

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

Open
wants to merge 9 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
6 changes: 6 additions & 0 deletions examples/06-custom-schema/06-togglable-blocks/.bnexample.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"playground": true,
"docs": true,
"author": "matthewlipski",
"tags": ["Basic"]
}
55 changes: 55 additions & 0 deletions examples/06-custom-schema/06-togglable-blocks/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { BlockNoteSchema, defaultBlockSpecs } from "@blocknote/core";
import "@blocknote/core/fonts/inter.css";
import { BlockNoteView } from "@blocknote/mantine";
import "@blocknote/mantine/style.css";
import { useCreateBlockNote } from "@blocknote/react";

import { ToggleBlock } from "./Toggle.js";

// Our schema with block specs, which contain the configs and implementations for
// blocks that we want our editor to use.
const schema = BlockNoteSchema.create({
blockSpecs: {
// Adds all default blocks.
...defaultBlockSpecs,
// Adds the Alert block.
toggle: ToggleBlock,
},
});

export default function App() {
// Creates a new editor instance.
const editor = useCreateBlockNote({
schema,
initialContent: [
{
type: "paragraph",
content: "Welcome to this demo!",
},
{
type: "toggle",
content: "This is an example toggle",
children: [
{
type: "paragraph",
content: "This is the first child of the toggle block.",
},
{
type: "paragraph",
content: "This is the second child of the toggle block.",
},
],
},
{
type: "paragraph",
content: "Click the '>' icon to show/hide its children",
},
{
type: "paragraph",
},
],
});

// Renders the editor instance.
return <BlockNoteView editor={editor} />;
}
8 changes: 8 additions & 0 deletions examples/06-custom-schema/06-togglable-blocks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Togglable Blocks

This example shows how to create blocks with a toggle button to show/hide their children. This is done using the use the `ToggleWrapper` component from `@blocknote/react`.

**Relevant Docs:**

- [Custom Blocks](/docs/custom-schemas/custom-blocks)
- [Editor Setup](/docs/editor-basics/setup)
19 changes: 19 additions & 0 deletions examples/06-custom-schema/06-togglable-blocks/Toggle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { defaultProps } from "@blocknote/core";
import { createReactBlockSpec, ToggleWrapper } from "@blocknote/react";

export const ToggleBlock = createReactBlockSpec(
{
type: "toggle",
propSchema: {
...defaultProps,
},
content: "inline",
},
{
render: (props) => (
<ToggleWrapper block={props.block} editor={props.editor}>
<p ref={props.contentRef} />
</ToggleWrapper>
),
},
);
14 changes: 14 additions & 0 deletions examples/06-custom-schema/06-togglable-blocks/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>Togglable Blocks</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/06-togglable-blocks/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.jsx";

const root = createRoot(document.getElementById("root")!);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
27 changes: 27 additions & 0 deletions examples/06-custom-schema/06-togglable-blocks/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "@blocknote/example-togglable-blocks",
"description": "AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY",
"private": true,
"version": "0.12.4",
"scripts": {
"start": "vite",
"dev": "vite",
"build:prod": "tsc && vite build",
"preview": "vite preview"
},
"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"
},
"devDependencies": {
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.9",
"@vitejs/plugin-react": "^4.3.1",
"vite": "^5.3.4"
}
}
36 changes: 36 additions & 0 deletions examples/06-custom-schema/06-togglable-blocks/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"__comment": "AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY",
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": [
"DOM",
"DOM.Iterable",
"ESNext"
],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"composite": true
},
"include": [
"."
],
"__ADD_FOR_LOCAL_DEV_references": [
{
"path": "../../../packages/core/"
},
{
"path": "../../../packages/react/"
}
]
}
32 changes: 32 additions & 0 deletions examples/06-custom-schema/06-togglable-blocks/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY
import react from "@vitejs/plugin-react";
import * as fs from "fs";
import * as path from "path";
import { defineConfig } from "vite";
// import eslintPlugin from "vite-plugin-eslint";
// https://vitejs.dev/config/
export default defineConfig((conf) => ({
plugins: [react()],
optimizeDeps: {},
build: {
sourcemap: true,
},
resolve: {
alias:
conf.command === "build" ||
!fs.existsSync(path.resolve(__dirname, "../../packages/core/src"))
? {}
: ({
// Comment out the lines below to load a built version of blocknote
// or, keep as is to load live from sources with live reload working
"@blocknote/core": path.resolve(
__dirname,
"../../packages/core/src/"
),
"@blocknote/react": path.resolve(
__dirname,
"../../packages/react/src/"
),
} as any),
},
}));
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createBlockSpec } from "../../schema/index.js";
import { defaultProps } from "../defaultProps.js";
import { createToggleWrapper } from "../ToggleWrapper/createToggleWrapper.js";

export const ToggleHeading = createBlockSpec(
{
type: "toggleHeading",
propSchema: {
...defaultProps,
level: { default: 1, values: [1, 2, 3] as const },
},
content: "inline",
} as const,
{
render: (block, editor) => {
const contentDOM = document.createElement(`h${block.props.level}`);
const a = createToggleWrapper(block, editor, contentDOM);

return a;
},
},
);
113 changes: 113 additions & 0 deletions packages/core/src/blocks/ToggleWrapper/createToggleWrapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { ViewMutationRecord } from "@tiptap/pm/view";

import { BlockNoteEditor } from "../../editor/BlockNoteEditor.js";
import { BlockFromConfig } from "../../schema/index.js";

export const createToggleWrapper = (
block: BlockFromConfig<any, any, any>,
editor: BlockNoteEditor<any, any, any>,
contentDOM: HTMLElement,
) => {
const dom = document.createElement("div");

const toggleWrapper = document.createElement("div");
toggleWrapper.className = "bn-toggle-wrapper";
toggleWrapper.setAttribute("data-show-children", "false");

const toggleButton = document.createElement("button");
toggleButton.className = "bn-toggle-button";
toggleButton.innerHTML =
// https://fonts.google.com/icons?selected=Material+Symbols+Rounded:chevron_right:FILL@0;wght@700;GRAD@0;opsz@24&icon.query=chevron&icon.style=Rounded&icon.size=24&icon.color=%23e8eaed
'<svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 -960 960 960" width="1em" fill="currentcolor"><path d="M472-480 332-620q-18-18-18-44t18-44q18-18 44-18t44 18l183 183q9 9 14 21t5 24q0 12-5 24t-14 21L420-252q-18 18-44 18t-44-18q-18-18-18-44t18-44l140-140Z"/></svg>';
const toggleButtonMouseDown = (event: MouseEvent) => event.preventDefault();
toggleButton.addEventListener("mousedown", toggleButtonMouseDown);
const toggleButtonOnClick = () => {
// Toggles visibility of child blocks. Also adds/removes the "add block"
// button if there are no child blocks.
if (toggleWrapper.getAttribute("data-show-children") === "true") {
toggleWrapper.setAttribute("data-show-children", "false");

if (dom.contains(toggleAddBlockButton)) {
dom.removeChild(toggleAddBlockButton);
}
} else {
toggleWrapper.setAttribute("data-show-children", "true");

if (
editor.getBlock(block)?.children.length === 0 &&
!dom.contains(toggleAddBlockButton)
) {
dom.appendChild(toggleAddBlockButton);
}
}
};
toggleButton.addEventListener("click", toggleButtonOnClick);

toggleWrapper.appendChild(toggleButton);
toggleWrapper.appendChild(contentDOM);

const toggleAddBlockButton = document.createElement("button");
toggleAddBlockButton.className = "bn-toggle-add-block-button";
toggleAddBlockButton.textContent = "Empty toggle. Click to add a block.";
const toggleAddBlockButtonMouseDown = (event: MouseEvent) =>
event.preventDefault();
toggleAddBlockButton.addEventListener(
"mousedown",
toggleAddBlockButtonMouseDown,
);
const toggleAddBlockButtonOnClick = () => {
// Adds a single empty child block.
editor.transact(() => {
const updatedBlock = editor.updateBlock(block, {
// Single empty block with default type.
children: [{}],
});
editor.setTextCursorPosition(updatedBlock.children[0].id, "end");
editor.focus();
});
};
toggleAddBlockButton.addEventListener("click", toggleAddBlockButtonOnClick);

dom.appendChild(toggleWrapper);

const onEditorChange = editor.onChange(() => {
// Adds/removes the "add block" button if child blocks are added/removed.
if (
editor.getBlock(block)?.children.length === 0 &&
toggleWrapper.getAttribute("data-show-children") === "true"
) {
dom.appendChild(toggleAddBlockButton);
} else if (dom.contains(toggleAddBlockButton)) {
dom.removeChild(toggleAddBlockButton);
}
});

return {
dom,
contentDOM,
// Prevents re-renders when the toggle button is clicked.
// TODO: Document what this actually does.
ignoreMutation: (mutation: ViewMutationRecord) => {
if (
mutation instanceof MutationRecord &&
(mutation.type === "attributes" || mutation.type === "childList")
) {
return true;
}
return false;
},
destroy: () => {
toggleButton.removeEventListener("mousedown", toggleButtonMouseDown);
toggleButton.removeEventListener("click", toggleButtonOnClick);
toggleAddBlockButton.removeEventListener(
"mousedown",
toggleAddBlockButtonMouseDown,
);
toggleAddBlockButton.removeEventListener(
"click",
toggleAddBlockButtonOnClick,
);
onEditorChange?.();
},
};
};
2 changes: 2 additions & 0 deletions packages/core/src/blocks/defaultBlocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@ import { Paragraph } from "./ParagraphBlockContent/ParagraphBlockContent.js";
import { Quote } from "./QuoteBlockContent/QuoteBlockContent.js";
import { Table } from "./TableBlockContent/TableBlockContent.js";
import { VideoBlock } from "./VideoBlockContent/VideoBlockContent.js";
import { ToggleHeading } from "./ToggleHeadingBlockContent/ToggleHeadingBlockContent.js";

export const defaultBlockSpecs = {
paragraph: Paragraph,
heading: Heading,
toggleHeading: ToggleHeading,
quote: Quote,
codeBlock: CodeBlock,
bulletListItem: BulletListItem,
Expand Down
Loading