单行/单块限制

Files
components/single-block-demo.tsx
'use client';

import * as React from 'react';

import { SingleBlockPlugin, SingleLinePlugin } from 'platejs';
import { Plate, usePlateEditor } from 'platejs/react';

import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { EditorKit } from '@/components/editor/editor-kit';
import { Editor, EditorContainer } from '@/components/ui/editor';

export default function SingleBlockDemo() {
  const [isSingleBlock, setIsSingleBlock] = React.useState(true);

  const editor = usePlateEditor(
    {
      plugins: [
        ...EditorKit,
        isSingleBlock ? SingleBlockPlugin : SingleLinePlugin,
      ],
      value: [
        {
          children: [
            {
              text: `Try typing or pasting text with multiple lines. ${
                isSingleBlock
                  ? String.raw`With Single Block mode, line breaks become soft breaks (\n).`
                  : 'With Single Line mode, all line breaks are removed.'
              }`,
            },
          ],
          type: 'p',
        },
      ],
    },
    [isSingleBlock]
  );

  return (
    <div className="space-y-4">
      <Plate editor={editor}>
        <div className="flex items-center space-x-2 p-2">
          <Checkbox
            id="single-block-mode"
            checked={isSingleBlock}
            onCheckedChange={(checked) =>
              setIsSingleBlock(checked === 'indeterminate' ? false : checked)
            }
          />
          <Label htmlFor="single-block-mode">
            {String.raw`Single Block Mode (allows line breaks as \n)`}
          </Label>
        </div>

        <EditorContainer variant="demo">
          <Editor />
        </EditorContainer>
      </Plate>
    </div>
  );
}
Restrict the editor to a single block.
single-block-demo
single-block-demo

功能特性

  • SingleLinePlugin: 将编辑器限制为单行文本,自动移除所有换行符
  • SingleBlockPlugin: 将编辑器限制为单个块,换行符转为软换行
  • 通过标准化处理防止创建多个块
  • 过滤粘贴内容中的换行字符
  • 适用于标题、标签、评论或受限文本输入场景

手动使用

添加插件

import { SingleLinePlugin, SingleBlockPlugin } from 'platejs';
import { createPlateEditor } from 'platejs/react';
 
const editor = createPlateEditor({
  plugins: [
    // ...其他插件,
    SingleLinePlugin, // 用于单行文本
    // 或
    SingleBlockPlugin, // 用于支持软换行的单块文本
  ],
});

插件说明

SingleLinePlugin

通过移除所有换行符并合并多个块,将编辑器内容限制为单行文本的插件。

核心行为:

  • 阻止insertBreakinsertSoftBreak操作
  • 过滤换行字符
  • 将多个块合并到首个块中(无分隔符)

SingleBlockPlugin

在保留换行符的同时,将编辑器内容限制为单个块的插件。

核心行为:

  • insertBreak转换为insertSoftBreak
  • \n分隔符合并多个块到首个块
  • 保留文本内容中现有的换行字符