lake-rich-text
v0.1.0
Published
基于 Lake 的富文本编辑器 React 组件,语雀风格
Maintainers
Readme
lake-rich-text
基于 Lake 的富文本编辑器 React 组件,语雀风格。参考 Entity-Now/yuque-rich-text 的 Vue 实现移植,底层为阿里 Lake 编辑器(通过 iframe + CDN 加载)。
安装
npm install lake-rich-text
# 或
pnpm add lake-rich-text使用
编辑器运行在 iframe 内,所需样式和脚本已由组件内部加载,无需在项目里再引入任何 CDN 样式或脚本。安装后直接使用即可。
1. 编辑模式示例
import { useRef, useState } from 'react';
import { YuqueRichText, type YuqueRichTextRef } from 'lake-rich-text';
function App() {
const editorRef = useRef<YuqueRichTextRef>(null);
const [content, setContent] = useState('');
return (
<div style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
<div>
<button onClick={() => editorRef.current?.appendContent('<p>追加内容</p>', true)}>
追加
</button>
<button onClick={() => alert(editorRef.current?.getContent('text/html'))}>
获取内容
</button>
<button onClick={() => editorRef.current?.setContent('<p>新内容</p>')}>
设置内容
</button>
</div>
<div style={{ flex: 1, minHeight: 0 }}>
<YuqueRichText
ref={editorRef}
value={content}
onChange={(v) => setContent(v)}
onLoad={() => console.log('编辑器已加载')}
onSave={() => console.log('Ctrl+Enter 保存')}
/>
</div>
</div>
);
}注意:不要在
onChange里直接setState(value)再通过value回传给编辑器,否则可能造成无限循环。用onChange做持久化或同步到别处即可。
2. 只读预览
<YuqueRichText isView value={htmlContent} />3. Ref 方法
| 方法 | 说明 |
|------|------|
| appendContent(html, breakLine?) | 追加 HTML,可选前插换行 |
| setContent(content, type?) | 设置全文内容(lake / text/html) |
| getContent(type) | 获取内容(lake / text/html) |
| isEmpty() | 是否为空 |
| getSummaryContent() | 摘要内容 |
| getOutline() | 大纲预览:返回 { level: 1-6, text: string }[],由文档中的 h1~h6 解析得到,可用来渲染目录/侧栏大纲 |
| wordCount() | 字数 |
| focusToStart(offset?) | 聚焦到开头 |
| insertBreakLine() | 插入换行 |
4. 图片/视频上传
复制/粘贴图片或拖入图片时,编辑器会尝试上传。若不配置上传逻辑,会请求默认地址 /api/upload/image(本地无此接口则会提示「图片上传失败」)。
需要传入 uploadImage(及可选的 uploadVideo)自行处理上传,例如传到 OSS/云存储后返回 URL:
<YuqueRichText
uploadImage={async ({ data }) => {
const formData = new FormData();
formData.append('file', data instanceof File ? data : await fetch(data).then(r => r.blob()));
const res = await fetch('/api/your-upload', { method: 'POST', body: formData });
const json = await res.json();
return { url: json.url, size: json.size ?? 0, filename: json.filename ?? 'image' };
}}
/>接口约定:入参 { data: string | File }(粘贴多为 base64 字符串,选择文件为 File),返回 Promise<{ url: string; size: number; filename: string }>。
免责声明
本项目为第三方实现,非语雀官方出品,依赖阿里 Lake 编辑器 CDN。使用前请阅读语雀服务条款,责任自负。
致谢
- Entity-Now/yuque-rich-text(Vue 版)
- 语雀与 Lake 编辑器
