mcpField
S
syncfusion-javascript-block-editor

syncfusion-javascript-block-editor

github.com/syncfusion设计与 UI060 次安装1 周前更新
代码仓库

关于 syncfusion-javascript-block-editor

Syncfusion JavaScript BlockEditor 是面向开发者的区块式编辑器,用于构建结构化内容编辑体验。它支持自定义编辑工具、HTML 与 JSON 数据交换,以及可选的 Yjs 协作功能。

主要功能

  1. 0114 种内置区块类型
  2. 02拖放调整区块顺序
  3. 03斜杠命令和行内工具栏
  4. 04导入和导出 HTML 与 JSON
  5. 05Yjs 协作和版本历史
  6. 06自定义区块、命令和模板

适用场景

  1. 01构建结构化内容编辑器
  2. 02调整文档区块顺序并设置格式
  3. 03与协作者实时编辑文档
  4. 04以 HTML 或 JSON 存储和交换编辑内容

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/syncfusion/javascript-ui-controls-skills --skill syncfusion-javascript-block-editor

安装后在 Claude Code 中输入/syncfusion-javascript-block-editor确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
blocks-and-content-models.md
built-in-block-types.md
collaborative-editing.md
customization-and-appearance.md
drag-drop-and-selection.md
editor-menus-and-toolbars.md
events-reference.md
getting-started.md
methods-reference.md
paste-undo-redo-keyboard.md
security-and-sanitization.md

详细介绍

Syncfusion JavaScript BlockEditor

概述

Syncfusion JavaScript BlockEditor 是一款现代化的块式文本编辑器,支持用户使用各种块类型创建、设置格式并组织内容。它提供直观的编辑体验,具备拖放排序、斜杠命令、内联工具栏和丰富的自定义选项等功能。BlockEditor 控件采用块式架构构建,内容按独立的块进行组织。每个块都有特定类型(段落、标题、列表、图像等),并可包含格式化内容。主要特点:

  • 块类型:内置 14 种块类型,包括排版、列表、表格、图像、代码和可折叠部分
  • 内容模型:使用 BlockModel 和 ContentModel 组织结构化内容,支持以编程方式操作
  • 直观的用户体验:斜杠命令(/)、拖动手柄、内联工具栏和上下文菜单
  • 协作编辑:由 Yjs 提供支持的实时多人编辑,包含在线状态、远程光标和版本历史
  • 可扩展性:自定义块、命令、菜单项和模板
  • 数据格式:支持导入/导出为 HTML 或 JSON,便于灵活存储和交换
  • 无障碍功能:键盘导航、ARIA 属性和屏幕阅读器支持

文档与导航指南

入门

📄 阅读: references/getting-started.md

  • 先决条件和 Node.js 版本要求(24.13.0 或更高版本)
  • 使用 Vite 创建 TypeScript 应用程序
  • 安装和软件包设置(@syncfusion/ej2-blockeditor)
  • CSS 导入和主题配置(Tailwind3、Material、Bootstrap 等)
  • 使用 Vite 初始化 BlockEditor 的基本方法
  • 使用 npm run dev 运行应用程序
块与内容模型

📄 阅读: references/blocks-and-content-models.md

  • 完整的 BlockModel 接口(id、blockType、content、properties、cssClass、indent、parentId、template)
  • BlockType 枚举(Paragraph、Heading、BulletList、NumberedList、Checklist、Table、Image、Code、Quote、Callout、Divider、CollapsibleParagraph、CollapsibleHeading、Template)
  • ContentModel 接口(id、contentType、content、properties)
  • ContentType 枚举(Text、Link、Mention、Label)
  • 块专属属性(HeadingProps、ImageProps、CodeProps、ChecklistProps、CollapsibleProps 等)
  • 内容专属属性(LinkContentProps、MentionContentProps、StyleModel)
  • 用于提及和协作的 UserModel
  • 用于创建块的辅助方法:BlockFactory 类
内置块类型

📄 阅读: references/built-in-block-types.md

  • 排版块:Paragraph、Heading(1-4)、Quote、Callout
  • 文本格式:粗体、斜体、下划线、删除线、大写、小写、下标、上标、内联代码
  • 字体颜色和背景颜色(文本高亮)
  • 列表块:BulletList、NumberedList、Checklist(带有 isChecked)
  • 带配置选项的表格块
  • 媒体块:Image,支持上传、调整大小和约束(imageBlockSettings)
  • 代码块,支持语法高亮和语言选择(codeBlockSettings)
  • 高级块:CollapsibleParagraph、CollapsibleHeading、Divider、Template
  • 具有父子关系的嵌套块结构
编辑器菜单与工具栏

📄 阅读: references/editor-menus-and-toolbars.md

  • 斜杠菜单(/)- commandMenuSettings 和 CommandItemModel
  • 块操作菜单(⋮ 手柄)- blockActionMenuSettings 和 BlockActionItemModel
  • 上下文菜单(右键单击)- contextMenuSettings 和 ContextMenuItemModel
  • 内联格式工具栏 - inlineToolbarSettings、ToolbarItemModel 和 BuiltInToolbar 枚举
  • 转换菜单 - 用于块类型转换的 transformSettings
  • 自定义命令和菜单项
  • 菜单事件:筛选、itemSelect、beforeOpen、beforeClose
  • 完整的自定义示例
方法参考

📄 阅读: references/methods-reference.md

  • 块管理:addBlock、removeBlock、moveBlock、updateBlock
  • 块查询:getBlock、getBlockCount、getSelectedBlocks
  • 选择:selectBlock、selectAllBlocks、selectRange、setSelection、getRange、setCursorPosition
  • 数据操作:getDataAsHtml、getDataAsJson、parseHtmlToBlocks、renderBlocksFromJson
  • 工具栏控制:enableToolbarItems、disableToolbarItems、executeToolbarAction
  • 焦点管理:focusIn、focusOut
  • 实用工具:print、refresh、dataBind
  • 生命周期:appendTo、destroy、addEventListener、removeEventListener
事件参考

📄 阅读: references/events-reference.md

  • 生命周期:created
  • 内容:blockChanged(包含 BlockChangedEventArgs)、selectionChanged
  • 焦点:focus(FocusEventArgs)、blur(BlurEventArgs)
  • 拖放:blockDragStart、blockDragging、blockDropped(包含 BlockDragEventArgs、BlockDropEventArgs)
  • 粘贴:beforePasteCleanup、afterPasteCleanup(包含 PasteCleanupEventArgs)
  • 文件上传:beforeFileUpload、fileUploading、fileUploadSuccess、fileUploadFailed
  • 完整的事件参数接口
  • 用于跟踪撤销/重做的 ActionType 枚举
拖放和选择

📄 阅读: references/drag-drop-and-selection.md

  • 拖放配置(enableDragAndDrop 属性)
  • 单个块和多个块的拖动
  • 拖放事件和视觉指示器
  • 选择管理方法
  • 以编程方式控制选择
  • NodeSelection 类
  • 光标定位
粘贴、撤销/重做和键盘

📄 阅读: references/paste-undo-redo-keyboard.md

  • 粘贴清理配置(pasteCleanupSettings,包含 keepFormat、plainText、deniedTags)
  • 用于拦截和修改内容的粘贴事件
  • 撤销/重做堆栈配置(undoRedoStack 属性)
  • 键盘快捷键(用于自定义快捷键的 keyConfig 属性)
  • 默认键盘命令
  • 提及(@user),使用 users 属性和 UserModel
  • 标签($label),使用 labelSettings 属性和 LabelItemModel
自定义和外观

📄 阅读: references/customization-and-appearance.md

  • 尺寸:width、height 属性
  • 自定义样式:cssClass 属性
  • 字体颜色自定义:fontColorSettings(FontColorSettingsModel,支持调色板/拾色器模式)
  • 背景颜色自定义:backgroundColorSettings(BackgroundColorSettingsModel)
  • ColorModeType 枚举(Palette、Picker)
  • 只读模式:readOnly 属性
  • RTL 支持:enableRtl 属性
  • 本地化:locale 属性
  • 自定义块模板
  • 通过 CSS 变量(--color-sf-*,采用 --sf 命名约定)自定义主题
  • Block Editor CSS 类和 ID(.e-blockeditor、.e-active、.e-selected、.e-list-item、.e-dropdownbase、.e-table-element、#blockeditor_contextmenu、#blockeditor_code-ddl_popup)
  • 使用 CSS 变量覆盖项切换多主题的示例(Slate Light、Sage Green、Dark Pro)
  • 使用 Syncfusion Theme Studio 创建完全自定义的主题(Material 3、Fluent 2、Bootstrap 5.3、Tailwind 3)
  • 主题集成
安全和清理

📄 阅读: references/security-and-sanitization.md

  • HTML 清理
  • HTML 编码(enableHtmlEncode 属性)
  • XSS 防护策略
  • 用于仅查看内容的只读模式
  • 使用 deniedTags 确保粘贴安全
  • 安全处理内容的最佳实践
  • 合规性注意事项
协作编辑

📄 阅读: references/collaborative-editing.md

  • 快速入门指南:使用 Vite、Yjs 和 WebSocket,在几分钟内设置协作功能
  • 创建 collaboration.ts 文件,其中包含 Yjs 文档、适配器、提供程序和房间分配逻辑
  • 使用 y-websocket 设置 WebSocket 服务,以用于生产部署
  • 安装并配置 Yjs 和 WebSocket 提供程序,实现实时同步
  • 由 Yjs 提供支持的实时协作编辑(基于 CRDT 的同步和冲突解决)
  • 注入 Collaboration 和 VersionHistory 模块
  • collaborationSettings 属性(provider、adapter、enableAwareness、versionHistory)
  • 选择 Yjs 提供程序(y-websocket、y-webrtc、y-indexeddb、Hocuspocus、Liveblocks、PartyKit)
  • 用户状态、远程光标和文本选择覆盖层(enableAwareness)
  • 通过 users 和 currentUserId 配置当前用户
  • 使用 IndexedDBVersionStorage 实现进行版本历史记录
  • 版本历史记录 UI,包含快照面板、恢复/删除按钮和自动刷新
  • 版本历史记录方法:创建、列出、重命名、恢复、比较、导出和导入快照
  • 版本历史记录事件:snapshotCreated、snapshotRestored
  • 协作设置的最佳实践和故障排除

快速入门示例

import { BlockEditor, BlockType, ContentType } from '@syncfusion/ej2-blockeditor';

// Initialize BlockEditor with sample content
const editor = new BlockEditor({
    width: '100%',
    height: '600px',
    blocks: [
        {
            id: 'heading-1',
            blockType: BlockType.Heading,
            properties: { level: 1 },
            content: [
                {
                    contentType: ContentType.Text,
                    content: 'Welcome to BlockEditor'
                }
            ]
        },
        {
            id: 'intro-para',
            blockType: BlockType.Paragraph,
            content: [
                {
                    contentType: ContentType.Text,
                    content: 'Start typing or press "/" to open the command menu.'
                }
            ]
        },
        {
            id: 'bullet-list',
            blockType: BlockType.BulletList,
            content: [
                {
                    contentType: ContentType.Text,
                    content: 'Drag blocks to reorder'
                }
            ]
        }
    ],
    enableDragAndDrop: true,
    enableHtmlSanitizer: true
});

// Render the editor
editor.appendTo('#blockeditor');
<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.syncfusion.com/ej2/32.1.19/tailwind.css" rel="stylesheet" />
</head>
<body>
    <div id="blockeditor"></div>
</body>
</html>

常见模式

以编程方式添加块
// Add a new paragraph block after a target block
const newBlock = {
    id: 'new-para',
    blockType: BlockType.Paragraph,
    content: [
        {
            contentType: ContentType.Text,
            content: 'This is a new paragraph.'
        }
    ]
};

editor.addBlock(newBlock, 'target-block-id', true); // true = after
获取 HTML/JSON 格式的内容
// Get all content as HTML
const htmlContent = editor.getDataAsHtml();

// Get all content as JSON
const jsonContent = editor.getDataAsJson();

// Get specific block content
const blockHtml = editor.getDataAsHtml('block-id');
const blockJson = editor.getDataAsJson('block-id');
处理块变更
const editor = new BlockEditor({
    blockChanged: (args) => {
        console.log('Blocks changed:', args.changes);
        // Auto-save functionality
        saveContent(editor.getDataAsJson());
    }
});
自定义斜杠命令
const editor = new BlockEditor({
    commandMenuSettings: {
        popupWidth: '350px',
        commands: [
            {
                id: 'custom-quote',
                type: BlockType.Quote,
                label: 'Quote Block',
                iconCss: 'e-icons e-quote',
                groupBy: 'Basic'
            },
            {
                id: 'timestamp',
                label: 'Insert Timestamp',
                iconCss: 'e-icons e-schedule',
                groupBy: 'Actions'
            }
        ],
        itemSelect: (args) => {
            if (args.command.id === 'timestamp') {
                // Custom action: insert current timestamp
                const timestamp = new Date().toLocaleString();
                // Insert logic here
            }
        }
    }
});
启用实时协作编辑
import { BlockEditor, Collaboration, YjsAdapter } from '@syncfusion/ej2-blockeditor';
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';

BlockEditor.Inject(Collaboration);

const yDoc = new Y.Doc();
const yFragment = yDoc.getXmlFragment('blockeditor');
const adapter: YjsAdapter = { yRuntime: Y, yXmlFragment: yFragment };
const provider = new WebsocketProvider('wss://your-server-url', 'document-room-id', yDoc);

const editor = new BlockEditor({
    users: [{ id: 'user-1', user: 'John Doe', avatarBgColor: '#e74c3c' }],
    currentUserId: 'user-1',
    collaborationSettings: {
        provider: provider,
        adapter: adapter,
        enableAwareness: true,
    }
});

editor.appendTo('#blockeditor');
图像上传配置
const editor = new BlockEditor({
    imageBlockSettings: {
        saveUrl: 'https://your-server.com/api/upload',
        path: '/images/',
        allowedTypes: ['.jpg', '.jpeg', '.png', '.gif'],
        maxFileSize: 5000000, // 5MB
        maxWidth: 1200,
        maxHeight: 800,
        enableResize: true,
        saveFormat: 'Blob' // or 'Base64'
    },
    fileUploadSuccess: (args) => {
        console.log('File uploaded:', args.fileUrl);
    }
});
通过 CSS 变量自定义主题

覆盖 .e-blockeditor(或任意祖先元素)上的 --color-sf-* CSS 变量,即可更换编辑器皮肤,而无需修改组件配置:

const blockEditor = new BlockEditor({
    blocks: blocksData,
    width: '100%',
    height: '600px'
});
blockEditor.appendTo('#blockeditor');

// Switch theme by toggling a body class
function applyTheme(themeName: 'slateLightTheme' | 'sageGreenTheme' | 'darkProTheme') {
    document.body.classList.remove('slateLightTheme', 'sageGreenTheme', 'darkProTheme');
    document.body.classList.add(themeName);
}
/* CSS variables follow the unified --sf naming convention */
.darkProTheme .e-blockeditor {
    --color-sf-content-bg-color: #0d1117;
    --color-sf-content-bg-color-hover: #161b22;
    --color-sf-content-bg-color-selected: #21262d;
    --color-sf-content-text-color: #e6edf3;
    --color-sf-placeholder-text-color: #7d8590;
    --color-sf-border: #30363d;
    --color-sf-border-hover: #58a6ff;
    --color-sf-primary: #1f6feb;
    --color-sf-primary-text-color: #ffffff;
    --color-sf-icon-color: #8b949e;

    background: #0d1117 !important;
    border: 1px solid #30363d;
    border-radius: 20px;
}

若要为所有 Syncfusion 组件全面自定义主题,请使用 Syncfusion Theme Studio,并选择 Material 3、Fluent 2、Bootstrap 5.3 或 Tailwind 3 作为基础。

关键配置选项

基本属性
  • blocks:BlockModel[] - 初始内容块
  • width:string | number - 编辑器宽度(默认值:'100%')
  • height:string | number - 编辑器高度(默认值:'auto')
  • readOnly:boolean - 只读模式(默认值:false)
  • enableDragAndDrop:boolean - 拖放块(默认值:true)
  • enableHtmlSanitizer:boolean - 清理 HTML(默认值:true)
  • undoRedoStack:number - 最大撤消/重做操作次数(默认值:30)
  • cssClass:string - 用于设置样式的自定义 CSS 类
菜单和工具栏设置
  • commandMenuSettings:CommandMenuSettingsModel - 斜杠命令菜单(/)
  • blockActionMenuSettings:BlockActionMenuSettingsModel - 块操作菜单(⋮)
  • contextMenuSettings:ContextMenuSettingsModel - 右键上下文菜单
  • inlineToolbarSettings:InlineToolbarSettingsModel - 文本格式工具栏
  • transformSettings:TransformSettingsModel - 块转换菜单
功能设置
  • imageBlockSettings:ImageBlockSettingsModel - 图像上传和配置
  • codeBlockSettings:CodeBlockSettingsModel - 代码语法高亮
  • pasteCleanupSettings:PasteCleanupSettingsModel - 粘贴格式控制
  • labelSettings:LabelSettingsModel - 标签配置($label)
  • users:UserModel[] - 用于提及的用户(@user)
  • keyConfig:{ [key: string]: string } - 自定义键盘快捷键
颜色设置
  • fontColorSettings:FontColorSettingsModel - 文本颜色调色板
  • backgroundColorSettings:BackgroundColorSettingsModel - 背景/高亮颜色调色板
主题自定义
  • CSS 变量(--color-sf-*):在 .e-blockeditor(或任意祖先元素)上覆盖这些变量,即可自定义颜色、边框、占位符、主色调和图标,而无需修改组件属性
  • CSS 类/ID:.e-blockeditor、.e-active、.e-selected、.e-list-item、.e-dropdownbase、.e-table-element、#blockeditor_contextmenu、#blockeditor_code-ddl_popup
  • Syncfusion Theme Studio:以 Material 3、Fluent 2、Bootstrap 5.3 或 Tailwind 3 为基础,为 Block Editor 和其他 EJ2 组件构建完全自定义的主题
协作设置
  • collaborationSettings:CollaborationSettingsModel - 实时协作配置(提供方、适配器、enableAwareness、versionHistory)
  • users:UserModel[] - 已连接的用户,也用于提及和状态显示
  • currentUserId:string - 标识本地用户,以显示在线状态和光标高亮
  • 需要通过 BlockEditor.Inject(...) 注入 Collaboration 模块(支持快照还需注入 VersionHistory)
本地化和 RTL
  • locale:string - 本地化代码(默认值:'en-US')
  • enableRtl:boolean - 支持从右向左显示(默认值:false)
  • enablePersistence:boolean - 在重新加载后保留状态(默认值:false)

评论

支持 Markdown