|
| 1 | +import { createBlockSpec, defaultProps } from "@blocknote/core"; |
| 2 | + |
| 3 | +import { macroRegistry } from "./macroRegistry.js"; |
| 4 | + |
| 5 | +// The Macro block — built with the vanilla `createBlockSpec` API. |
| 6 | +// |
| 7 | +// It carries a single `id` prop that is used to look up the HTML that should |
| 8 | +// be rendered in the "before" and "after" slots around the block's editable |
| 9 | +// inline content. This can actually be in any structure, it is in your control |
| 10 | +export const macroBlock = createBlockSpec( |
| 11 | + { |
| 12 | + type: "macro", |
| 13 | + propSchema: { |
| 14 | + textAlignment: defaultProps.textAlignment, |
| 15 | + textColor: defaultProps.textColor, |
| 16 | + id: { |
| 17 | + default: "" as const, |
| 18 | + }, |
| 19 | + }, |
| 20 | + content: "inline", |
| 21 | + }, |
| 22 | + { |
| 23 | + render: (block) => { |
| 24 | + const wrapper = document.createElement("div"); |
| 25 | + wrapper.className = "macro-block"; |
| 26 | + |
| 27 | + // We pull from the "registry" what this block should insert before and after |
| 28 | + const definition = macroRegistry[block.props.id]; |
| 29 | + |
| 30 | + const before = document.createElement("div"); |
| 31 | + before.className = "macro-slot macro-slot-before"; |
| 32 | + before.contentEditable = "false"; |
| 33 | + const beforeContent = definition?.before ?? ""; |
| 34 | + if (typeof beforeContent === "string") { |
| 35 | + before.innerHTML = beforeContent; |
| 36 | + } else { |
| 37 | + before.appendChild(beforeContent); |
| 38 | + } |
| 39 | + |
| 40 | + const content = document.createElement("div"); |
| 41 | + content.className = "macro-content"; |
| 42 | + |
| 43 | + const after = document.createElement("div"); |
| 44 | + after.className = "macro-slot macro-slot-after"; |
| 45 | + after.contentEditable = "false"; |
| 46 | + const afterContent = definition?.after ?? ""; |
| 47 | + if (typeof afterContent === "string") { |
| 48 | + after.innerHTML = afterContent; |
| 49 | + } else { |
| 50 | + after.appendChild(afterContent); |
| 51 | + } |
| 52 | + |
| 53 | + // You have full control over this HTML structure |
| 54 | + // and can inject the rich-text content wherever you want |
| 55 | + wrapper.append(before, content, after); |
| 56 | + |
| 57 | + return { |
| 58 | + dom: wrapper, |
| 59 | + contentDOM: content, |
| 60 | + }; |
| 61 | + }, |
| 62 | + }, |
| 63 | +); |
0 commit comments