kyle-editor 1.0.7 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,357 @@
1
+ # 集成指南
2
+
3
+ KEditor 是**纯前端**编辑器,不依赖任何后端接口。三种集成方式任选其一。
4
+
5
+ | 方式 | 适用场景 | 引入文件 |
6
+ |------|----------|----------|
7
+ | Script(UMD) | 静态页、jQuery/Vue2 老项目、快速原型 | `dist/keditor.umd.min.js`(调试可用未压缩的 `keditor.umd.js`) |
8
+ | ESM / 打包器 | Vite、Webpack、Rollup、Next/Nuxt(客户端组件) | `import { KEditor } from 'kyle-editor'` |
9
+ | Vue 3 组件 | Vue 3 项目,`v-model` 双向绑定 | `import KEditorVue from 'kyle-editor/vue'` |
10
+
11
+ 样式随 JS 自动注入(`<style data-keditor-style>`),**无需单独引入 CSS**。
12
+
13
+ ---
14
+
15
+ ## 1. Script 引入(零构建)
16
+
17
+ ```html
18
+ <!DOCTYPE html>
19
+ <html>
20
+ <head>
21
+ <meta charset="utf-8" />
22
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
23
+ </head>
24
+ <body>
25
+ <div id="editor"></div>
26
+
27
+ <!-- 线上用压缩版(192 KB / gzip 61 KB);断点调试换成 dist/keditor.umd.js 即可,API 完全一致 -->
28
+ <script src="dist/keditor.umd.min.js"></script>
29
+ <script>
30
+ const editor = KEditor.create('#editor', {
31
+ placeholder: '开始撰写内容…',
32
+ // 高度默认随内容自动撑开;要固定高度 + 内部滚动就加上 height: 460
33
+ })
34
+
35
+ editor.on('change', ({ html }) => console.log(html))
36
+ document.querySelector('#save').onclick = () => submit(editor.getHTML())
37
+ </script>
38
+ </body></html>
39
+ ```
40
+
41
+ UMD 全局对象 `KEditor` 上的可用成员:
42
+
43
+ ```js
44
+ KEditor.create(target, options) // 返回实例(推荐)
45
+ KEditor.mount(...) // create 的别名
46
+ KEditor.KEditor // 类本体,new KEditor(target, options)
47
+ KEditor.mockAdapter(options) // 无后端演示适配器
48
+ KEditor.httpAdapter(config) // 真实后端适配器
49
+ KEditor.simpleAdapter(fn) // 单次直传接口包装
50
+ KEditor.sanitizeHtml(html) // 独立使用的 HTML 净化
51
+ KEditor.formatHtml(html) // 独立使用的 HTML 格式化
52
+ KEditor.version
53
+ ```
54
+
55
+ > 本地预览:仓库根目录已内置静态服务脚本 `npm run dev`(127.0.0.1:5178),打开 `demo/script.html`。
56
+
57
+ ---
58
+
59
+ ## 2. ESM / 打包工具引入
60
+
61
+ ```bash
62
+ npm i kyle-editor # 或将本仓库 dist/ 拷贝进项目
63
+ ```
64
+
65
+ ```js
66
+ import { KEditor, create, mockAdapter } from 'kyle-editor'
67
+
68
+ const editor = create('#editor', {
69
+ value: '<p>hello</p>',
70
+ uploader: mockAdapter({ speed: 8 }), // 演示:不请求后端(普通上传)
71
+ chunkUploader: mockAdapter({ speed: 8 }), // 演示:分片上传
72
+ upload: { mode: 'auto', chunkSize: 256 * 1024, concurrency: 3 },
73
+ })
74
+
75
+ // 组件卸载时务必销毁
76
+ window.addEventListener('beforeunload', () => editor.destroy())
77
+ ```
78
+
79
+ 按需引入(tree-shaking 友好):
80
+
81
+ ```js
82
+ import { formatHtml } from 'kyle-editor' // 源码格式化
83
+ import { sanitizeHtml } from 'kyle-editor' // 粘贴/回填净化
84
+ import { ChunkUploader, httpAdapter } from 'kyle-editor' // 只用上传能力
85
+ ```
86
+
87
+ ### 在 React 中使用
88
+
89
+ ```jsx
90
+ import { useEffect, useRef } from 'react'
91
+ import { KEditor } from 'kyle-editor'
92
+
93
+ export function Editor({ value, onChange }) {
94
+ const host = useRef(null)
95
+ const editor = useRef(null)
96
+
97
+ useEffect(() => {
98
+ editor.current = new KEditor(host.current, { value, onChange: (html) => onChange(html) })
99
+ return () => editor.current?.destroy()
100
+ }, [])
101
+
102
+ useEffect(() => {
103
+ if (editor.current && value !== editor.current.getHTML()) editor.current.setContent(value)
104
+ }, [value])
105
+
106
+ return <div ref={host} />
107
+ }
108
+ ```
109
+
110
+ ---
111
+
112
+ ## 3. Vue 3 安装集成
113
+
114
+ ### 3.1 全局注册(推荐)
115
+
116
+ ```js
117
+ // main.js
118
+ import { createApp } from 'vue'
119
+ import App from './App.vue'
120
+ import KEditorVue from 'kyle-editor/vue' // 默认导出是组件(自带 install)
121
+
122
+ createApp(App).use(KEditorVue).mount('#app')
123
+ ```
124
+
125
+ ```vue
126
+ <template>
127
+ <k-editor v-model="form.content" :options="editorOptions" :disabled="readonly" @upload="onUpload" @ready="onReady" />
128
+ <button @click="submit">保存</button>
129
+ </template>
130
+
131
+ <script setup>
132
+ import { ref } from 'vue'
133
+
134
+ const form = ref({ content: '<p>初始内容</p>' })
135
+ const readonly = ref(false)
136
+ const editorOptions = {
137
+ placeholder: '支持拖拽 / 粘贴上传…',
138
+ height: 420, // 不写则随内容自动撑开
139
+ // 上传分两条链路,各自配置;小文件走普通上传,大文件自动切片
140
+ uploader: '/api/upload', // 普通上传:整个文件一次请求
141
+ chunkUploader: '/api/chunk-upload', // 分片上传:响应里 url 非空即成功
142
+ upload: { mode: 'auto', chunkThreshold: 5 * 1024 * 1024, chunkSize: 1024 * 1024, concurrency: 3, retries: 2 },
143
+ }
144
+ const onUpload = (payload) => console.log(payload.stage, payload.percent)
145
+ const onReady = (editor) => console.log('编辑器实例', editor)
146
+ </script>
147
+ ```
148
+
149
+ 也可指定注册名:
150
+
151
+ ```js
152
+ app.use(KEditorVue, { name: 'RichEditor' }) // <rich-editor />
153
+ ```
154
+
155
+ ### 3.2 局部引入组件
156
+
157
+ ```vue
158
+ <script setup>
159
+ import { KEditorVue } from 'kyle-editor/vue'
160
+ </script>
161
+
162
+ <template>
163
+ <KEditorVue v-model="html" />
164
+ </template>
165
+ ```
166
+
167
+ > 默认导出与具名导出 `KEditorVue` 是同一个组件(默认导出额外带了 `install`),
168
+ > 所以 `import KEditorVue from 'kyle-editor/vue'` 后直接 `<KEditorVue v-model="html" />` 也能正常渲染。
169
+ > 若只想全局注册,用 `import { KEditorPlugin } from 'kyle-editor/vue'` 语义更清楚。
170
+
171
+ ### 3.3 组合式 API
172
+
173
+ ```js
174
+ import { useKEditor } from 'kyle-editor/vue'
175
+
176
+ const { host, editor } = useKEditor({ height: 400 })
177
+ // <div ref="host"></div>,editor.value 为 KEditor 实例
178
+ ```
179
+
180
+ ### 3.4 组件 Props / Emits
181
+
182
+ | Prop | 类型 | 说明 |
183
+ |------|------|------|
184
+ | `modelValue` | `string` | HTML 字符串,`v-model` 绑定;外部变更会同步进编辑器 |
185
+ | `options` | `object` | 与 `new KEditor(el, options)` 完全一致的配置 |
186
+ | `disabled` | `boolean` | 只读模式 |
187
+ | `height` | `number` | 覆盖 `options.height`(默认自适应内容高度) |
188
+
189
+ | Emit | 载荷 | 说明 |
190
+ |------|------|------|
191
+ | `update:modelValue` | `html: string` | 内容变化(自动去内部属性) |
192
+ | `change` | `{html, text, counts}` | 内容变化(防抖后) |
193
+ | `ready` | `editor` | 实例创建完成 |
194
+ | `upload` | `{state, kind, name, size, progress, result, error, node}` | 上传生命周期,`state` 为 `start/progress/success/error/cancel` |
195
+ | `error` | `{type, error, message}` | 内部异常(上传失败、净化失败、源码解析失败) |
196
+ | `save` | `{html, text, counts}` | 编辑器内按下 ⌘/Ctrl+S |
197
+ | `focus` / `blur` | — | 焦点变化 |
198
+
199
+ 通过 `ref` 拿到原生实例做进阶操作:
200
+
201
+ ```vue
202
+ <k-editor ref="editorRef" v-model="html" />
203
+ <script setup>
204
+ const editorRef = ref()
205
+ editorRef.value.editor.setContent('<p>来自父组件</p>') // KEditor 实例
206
+ editorRef.value.getHTML()
207
+ </script>
208
+ ```
209
+
210
+ ### 3.5 SSR 框架(Nuxt 3 / Next.js)
211
+
212
+ > ❗ 编辑器依赖 `document`、`DOMParser`、`contenteditable`,**只能在浏览器运行**。在服务端渲染阶段引入会报 `document is not defined` / `DOMParser is not defined`,必须做成客户端专属。
213
+
214
+ **Nuxt 3**:插件文件名带 `.client` 后缀即只在客户端加载
215
+
216
+ ```ts
217
+ // plugins/keditor.client.ts
218
+ import KEditorVue from 'kyle-editor/vue'
219
+ export default defineNuxtPlugin((nuxtApp) => nuxtApp.vueApp.use(KEditorVue))
220
+ ```
221
+
222
+ ```vue
223
+ <template>
224
+ <ClientOnly>
225
+ <k-editor v-model="html" />
226
+ </ClientOnly>
227
+ </template>
228
+ ```
229
+
230
+ **Next.js(App Router)**:组件顶部标 `'use client'`,并用 `next/dynamic` 关闭 SSR
231
+
232
+ ```tsx
233
+ // app/editor-page.tsx
234
+ 'use client'
235
+ import dynamic from 'next/dynamic'
236
+
237
+ const KEditor = dynamic(() => import('kyle-editor/vue').then((m) => m.KEditorVue), { ssr: false })
238
+
239
+ export default function Page() {
240
+ return <KEditor modelValue="" />
241
+ }
242
+ ```
243
+
244
+ 若需在服务端做 HTML 消毒(例如入库前过滤),不要直接用本包的 `sanitizeHtml`(依赖 DOM),请改用 `isomorphic-dompurify` 等同构方案;`escapeHtml` / `isSafeUrl` 是纯函数,Node 下可直接用。
245
+
246
+ ---
247
+
248
+ ### 3.6 TypeScript
249
+
250
+ 包内自带声明(`package.json` 的 `types` 与 `exports.types`),无需安装 `@types`:
251
+
252
+ ```ts
253
+ import KEditor, { type KEditorOptions, type UploadAdapter, type UploadResult } from 'kyle-editor'
254
+
255
+ const options: KEditorOptions = {
256
+ height: 480, // 0 / 不写 = 随内容自动撑开
257
+ upload: { mode: 'auto', chunkSize: 2 * 1024 * 1024, concurrency: 4 },
258
+ uploader: myAdapter, // 普通上传(满足 upload() 即可)
259
+ chunkUploader: myChunkAdapter, // 分片上传(满足 put() 即可)
260
+ }
261
+
262
+ const editor = KEditor.create('#editor', options)
263
+ const html: string = editor.getHTML()
264
+ const counts = editor.counts()
265
+ ```
266
+
267
+ Vue 3:`import KEditorVue from 'kyle-editor/vue'` 即带 props/emits 提示;`ref` 取出的实例上 `editor`、`getHTML()`、`focus()` 等均已声明。
268
+
269
+ UMD 方式(无构建)下若需提示,可 `/// <reference types="kyle-editor/types" />` 或直接使用 `KEditor.create`。
270
+
271
+ ---
272
+
273
+ ## 4. 常见问题
274
+
275
+ **Q:不需要后端,怎么让图片真的显示出来?**
276
+ 默认 `uploader` / `chunkUploader` 都是 `'mock'`,在浏览器内完成传输并生成 `blob:` 地址,页面内可直接预览。保存草稿时把 `getHTML()` 存下来即可;正式上线时把两者换成后端接口地址(如 `uploader: '/api/upload'`、`chunkUploader: '/api/chunk-upload'`),接口返回 `url` 就会得到真实(CDN)地址。
277
+
278
+ **Q:只想配一个上传接口,不要分片?**
279
+ 只设 `uploader` 即可 —— 分片链路自动不启用(不会用默认 mock 顶上),所有文件都走整包一次请求。
280
+
281
+ **Q:想让所有文件都走分片上传?**
282
+ 只设 `chunkUploader` 即可(`upload.mode` 自动为 `'chunk'`);想显式写清楚就加 `upload: { mode: 'chunk' }`。
283
+
284
+ **Q:`blob:` 地址提交到服务器会失效,怎么办?**
285
+ 在提交前调用 `editor.getHTML()`,把 `data-k-url` 为 `blob:` 的资源先上传(`beforeUpload` 里做映射),或直接配置真实上传接口。
286
+
287
+ **Q:如何精简工具栏?**
288
+ ```js
289
+ KEditor.create('#editor', { toolbar: ['undo', 'redo', '|', 'bold', 'image', 'video', ':tail', 'source'] })
290
+ ```
291
+
292
+ `'|'` 为分隔符,`':tail'` 之后的按钮靠右对齐(窄屏下吸附在右端不会被滚走),`toolbar: false` 隐藏工具栏。工具栏放不下时可左右滑动,并有滚动条、边缘渐隐、首次引导气泡等提示,详见 [api.md](api.md#工具栏项)。
293
+
294
+ 可用项:`undo` `redo` `heading` `fontsize` `bold` `italic` `underline` `strike` `foreColor` `backColor` `alignLeft` `alignCenter` `alignRight` `alignJustify` `ul` `ol` `quote` `link` `image` `video` `table` `code` `markdown` `hr` `clear` `source` `preview` `fullscreen`,详见 [api.md](api.md#工具栏项)。
295
+
296
+ > `preview` 已从默认工具栏(`KEditor.DEFAULT_TOOLBAR`)里移除,需要它在 `toolbar` 数组里写回,或直接调 `editor.openPreview()`。自定义按钮可用 `position` / `editor.moveButton()` 放到任意位置,包括 `:tail` 吸附区。
297
+
298
+ **Q:怎么往工具栏加自己的按钮(比如下拉选模板、选中后插链接)?**
299
+ 用 `customButtons`,无需改源码。数据可以静态配置,也可以从接口读:
300
+
301
+ ```js
302
+ KEditor.create('#editor', {
303
+ customButtons: [
304
+ { name: 'column', text: '栏目', position: { after: 'link' }, searchable: true, url: '/api/columns', link: true, insert: 'link' },
305
+ {
306
+ name: 'tpl', text: '模板',
307
+ options: [{ value: 'opening', label: '开场白', desc: '问候 + 本期导读' }],
308
+ link: { url: 'https://mp.weixin.qq.com/s/tpl-{value}', text: '【{label}】' },
309
+ },
310
+ ],
311
+ })
312
+ ```
313
+
314
+ 没传 `toolbar` 时会自动追加到工具栏末尾;传了就用名字定位:`toolbar: ['bold', '|', 'tpl']`。
315
+ 位置也能直接写在按钮上,不用重抄整份工具栏:`position: 'start' | 'end' | 'tail' | 索引 | 按钮名 | { before | after }`;
316
+ 运行时还能 `editor.moveButton(name, where)` 移任意按钮(包括内置的)。默认工具栏已不含「预览」,需要时自己写回 `toolbar`。
317
+ 完整字段(缓存/强制刷新/分组/搜索/失败重试/`mode:'open'` 直接开窗/`onSelect` 接管)见 [api.md](api.md#自定义工具栏按钮)。
318
+
319
+ **Vue 里更常见的写法是在组件里自己请求接口,再灌给按钮:**
320
+
321
+ ```vue
322
+ <template>
323
+ <k-editor ref="ed" v-model="html" :options="options" />
324
+ </template>
325
+
326
+ <script setup>
327
+ import { ref, onMounted } from 'vue'
328
+
329
+ const ed = ref(null)
330
+ const html = ref('')
331
+ const options = {
332
+ customButtons: [
333
+ { name: 'column', text: '栏目', options: [], emptyText: '加载中…', link: { url: 'https://x.com/{value}', text: '{label}' } },
334
+ ],
335
+ }
336
+
337
+ onMounted(async () => {
338
+ const list = await fetch('/api/columns').then((r) => r.json())
339
+ ed.value.editor.setButtonOptions('column', list) // 数据就绪后刷新下拉
340
+ })
341
+ </script>
342
+ ```
343
+
344
+ > `k-editor` 组件的 `options` 是普通对象,`customButtons` 里的 `load` / `onSelect` 可以直接闭包引用组件里的 axios 实例、埋点函数等。
345
+
346
+ **Q:不想上传,只想直接贴图片/视频链接?**
347
+ 点工具栏的图片或视频按钮 → 切到「网络链接」页签 → 粘贴地址即可插入(会同时提示该地址能否加载)。代码层面等价于:
348
+ ```js
349
+ editor.insertImage('https://cdn.example.com/a.png', '图注')
350
+ editor.insertVideo('https://cdn.example.com/clip.mp4', '宣传片')
351
+ ```
352
+
353
+ **Q:怎么禁止上传大视频?**
354
+ `maxVideoSize: 100 * 1024 * 1024`,超限会在插入前提示并拦截。
355
+
356
+ **Q:内容里的脚本安全吗?**
357
+ 初始化、粘贴、源码模式回填都会走白名单净化(`sanitize.js`):剔除 `script/iframe/on*/javascript:` 等,`style` 声明逐条过滤。
@@ -0,0 +1,295 @@
1
+ # 上传(普通上传 / 分片上传)
2
+
3
+ 编辑器有两条上传链路,**各自独立配置、互不影响**:
4
+
5
+ | 链路 | 选项 | 过程 | 适用 |
6
+ |------|------|------|------|
7
+ | 普通上传 | `uploader` | 整个文件**一次请求** | 小文件(图片为主) |
8
+ | 分片上传 | `chunkUploader` | 切片 → 并发 → 重试,**只打一个接口** | 大文件(视频为主) |
9
+
10
+ 编辑器按 `upload.mode` 选路:
11
+
12
+ ```js
13
+ KEditor.create('#editor', {
14
+ uploader: '/api/upload', // 普通上传
15
+ chunkUploader: '/api/chunk-upload', // 分片上传
16
+ upload: {
17
+ mode: 'auto', // 'auto'(默认,按体积)| 'normal' | 'chunk'
18
+ chunkThreshold: 5 * 1024 * 1024, // auto:达到该体积才走分片
19
+ chunkSize: 1024 * 1024,
20
+ concurrency: 4,
21
+ retries: 2,
22
+ },
23
+ })
24
+ ```
25
+
26
+ ```
27
+ File ──┬─ size < chunkThreshold ─→ SimpleUploader ─→ POST /api/upload (整包一次)
28
+ └─ size ≥ chunkThreshold ─→ ChunkUploader ─→ POST /api/chunk-upload (每片一次,并发)
29
+ ```
30
+
31
+ | 想做的事 | 怎么写 |
32
+ |----------|--------|
33
+ | 小文件直传、大文件分片 | `uploader` + `chunkUploader` + `mode: 'auto'`(默认) |
34
+ | 全部走普通上传 | 只配 `uploader`(分片自动不启用) |
35
+ | 全部走分片上传 | 只配 `chunkUploader`(`mode` 自动变 `'chunk'`) |
36
+ | 调阈值 | `upload: { chunkThreshold: 2 * 1024 * 1024 }` |
37
+ | 开箱演示(无后端) | 两条都不配,默认两条都是 `'mock'` |
38
+
39
+ > 只配一条链路时,另一条**不会**被默认 `mock` 顶上 —— 否则真实后端只接了一半,另一半会静默产生 `blob:` 假地址。显式写 `upload` 时以你的配置为准。
40
+ >
41
+ > `mode: 'chunk'` 但没配 `chunkUploader`:控制台告警并回退为普通上传,不会静默失败。
42
+
43
+ 进度、已传字节、分片数、实时速度通过 `onProgress(ratio, info)` 回传到编辑区占位块(`info.mode` 为 `'normal'` / `'chunk'`)。
44
+
45
+ ---
46
+
47
+ ## 1. 普通上传(整个文件一次请求)
48
+
49
+ ```js
50
+ KEditor.create('#editor', {
51
+ uploader: '/api/upload',
52
+ // 或:uploader: KEditor.httpAdapter({ url: '/api/upload' })
53
+ // 或:uploader: async (file) => (await myUpload(file)).url
54
+ })
55
+ ```
56
+
57
+ 请求是 `multipart/form-data`,响应里 `url` 非空即成功:
58
+
59
+ ```jsonc
60
+ // POST /api/upload Content-Type: multipart/form-data
61
+ // file 整个文件(字段名可用 fieldName 改)
62
+ // filename 原始文件名
63
+ // fileSize 总字节数
64
+
65
+ { "url": "https://cdn.example.com/a.png" } // ✅ 成功
66
+ { "code": 0, "data": { "url": "https://…/a.png" } } // ✅ 外层包装用 parse 解开
67
+ { "code": 0, "msg": "ok" } // ❌ 没有 url → 判定失败
68
+ ```
69
+
70
+ > 一次请求无法拿到逐字节进度,普通上传只上报「开始 / 结束」两个点。需要精细进度条就用分片上传。
71
+
72
+ ## 2. 分片上传(只配一个地址)
73
+
74
+ ```js
75
+ KEditor.create('#editor', {
76
+ chunkUploader: '/api/chunk-upload', // 就这一个地址
77
+ upload: { mode: 'chunk', chunkSize: 5 * 1024 * 1024, concurrency: 4 },
78
+ })
79
+ ```
80
+
81
+ **约定:只要接口响应里 `url` 不为空,就代表这个文件上传成功。** 每个分片都打到这一个地址,不需要 `init` / `complete`:
82
+
83
+ ```jsonc
84
+ // 请求:POST /api/chunk-upload multipart/form-data
85
+ // file 分片二进制(字段名可用 fieldName 改)
86
+ // identifier 文件指纹,同一文件恒定(用来定位、续传、秒传)
87
+ // index 分片下标,从 0 开始
88
+ // total 总片数
89
+ // filename / fileSize / chunkSize
90
+
91
+ // 响应:
92
+ { "url": "https://cdn.example.com/a.png" } // ✅ 非空 url = 成功
93
+ { "code": 0, "data": { "url": "https://…/a.png" } } // ✅ 外层包装用 parse 解开
94
+ { "code": 0, "msg": "ok" } // ⏳ 还没收齐,继续传
95
+ {}
96
+ ```
97
+
98
+ 拿到 `url` 后:编辑器立即用该地址替换占位块,**剩余未发出的分片不再上传**,上传进度直接置 100%。所以服务端两种实现都支持 ——
99
+
100
+ | 服务端实现 | 行为 |
101
+ |------------|------|
102
+ | 收齐全部分片后返回 url(常见) | 最后一片的响应带回 url,自然成功 |
103
+ | `identifier` 命中已知文件则秒传 | 第一个响应就带 url,后面分片直接不发 |
104
+
105
+ 全程都没有 `url` → 判定为失败,占位块转错误态并给出「重试 / 移除」,**不会静默当成功**。
106
+
107
+ 需要鉴权 / 自定义字段名 / 地址字段不叫 `url` 时(两条链路写法相同):
108
+
109
+ ```js
110
+ KEditor.create('#editor', {
111
+ chunkUploader: {
112
+ type: 'http',
113
+ url: '/api/chunk-upload',
114
+ fieldName: 'chunk', // 默认 'file'
115
+ headers: () => ({ Authorization: `Bearer ${getToken()}` }), // 传函数每次请求实时取值
116
+ withCredentials: true,
117
+ parse: (json) => json.data, // 默认 json.data ?? json
118
+ pickUrl: (json) => json?.payload?.filePath || '', // 默认认 url / fileUrl / src
119
+ mode: 'formdata', // 默认 formdata
120
+ method: 'POST', // 默认:formdata → POST,raw → PUT
121
+ chunkUrlFor: ({ index }) => `/api/chunk-upload?part=${index}`, // 可选:动态分片地址
122
+ },
123
+ })
124
+ ```
125
+
126
+ `mode` 的两种选择:
127
+
128
+ | mode | 请求形式 | 文件与上下文位置 |
129
+ |------|----------|------------------|
130
+ | `'formdata'`(默认) | `POST` multipart | 文件在 `fieldName` 字段,其余在表单字段 |
131
+ | `'raw'` | `PUT`/`POST` 裸 body | 文件是请求体,上下文(`identifier/index/total/filename`)在查询串 |
132
+
133
+ > **已移除三接口模式**:`httpAdapter` 不再接受 `initUrl` / `chunkUrl` / `completeUrl` / `abortUrl`,配了会直接报错并提示迁移。
134
+ > 需要 `init`(断点续传 / 秒传)/ `complete`(自行合并)这类自定义流程时,自己写适配器传给 `chunkUploader`,见第 5 节。
135
+
136
+ ## 3. mock(默认,无需后端)
137
+
138
+ ```js
139
+ KEditor.create('#editor') // uploader / chunkUploader 默认都是 'mock'
140
+
141
+ // 可调参数
142
+ KEditor.create('#editor', {
143
+ chunkUploader: KEditor.mockAdapter({
144
+ speed: 8, // 模拟带宽 MB/s
145
+ latency: 160, // 每片固定往返 ms
146
+ failFirstChunk: true, // 演示「分片失败 → 自动重试」
147
+ onEvent: (type, payload) => console.log(type, payload), // init/chunk/complete/upload/instant/abort
148
+ }),
149
+ upload: { mode: 'chunk', chunkSize: 256 * 1024 },
150
+ })
151
+ ```
152
+
153
+ 特点:真实切片与限速;完成后用 `URL.createObjectURL` 生成本地地址,可直接预览;同一文件重复上传命中「秒传」,不再重复传输。普通上传链路同样可用(`adapter.upload()`,按体积分步上报进度)。
154
+
155
+ ## 4. 后端接口约定
156
+
157
+ ### 4.1 普通上传
158
+
159
+ ```
160
+ POST /api/upload Content-Type: multipart/form-data
161
+ ```
162
+
163
+ | 字段 | 说明 |
164
+ |------|------|
165
+ | `file` | 整个文件(`fieldName` 可改) |
166
+ | `filename` / `fileSize` | 原始文件名 / 总字节 |
167
+
168
+ 服务端存好文件后响应 `{ "url": "…" }` 即可。
169
+
170
+ ### 4.2 分片上传(真的只需要这一个)
171
+
172
+ ```
173
+ POST /api/chunk-upload Content-Type: multipart/form-data
174
+ ```
175
+
176
+ | 字段 | 说明 |
177
+ |------|------|
178
+ | `file` | 分片二进制(`fieldName` 可改) |
179
+ | `identifier` | 文件指纹,同一文件所有分片一致 —— 用它定位临时目录、做续传与秒传 |
180
+ | `index` / `total` | 当前分片下标(从 0 起)/ 总分片数 |
181
+ | `filename` / `fileSize` / `chunkSize` | 原始文件名 / 总字节 / 分片大小 |
182
+
183
+ 服务端要做的事:把分片落到 `tmp/{identifier}/{index}.part`;当 `{identifier}` 下已集齐 `total` 片(或 `identifier` 早已上传过)时,按 index 顺序合并 → 传对象存储 → 响应 `{ "url": "…" }`。其他情况响应 `{}` 即可(不要返回空 `url` 字段)。
184
+
185
+ > 要注意的是分片并发到达,`index === total - 1` 并不意味着"前面都到了",判定"集齐"要按磁盘上实际存在的分片数。
186
+ >
187
+ > 服务端只需要处理「一段二进制 + 几个上下文参数」,不需要 session、不需要 uploadId —— 分片并发到达也不会乱序落盘(文件名就是 index)。
188
+
189
+ ## 5. 自定义适配器
190
+
191
+ **普通上传**只需实现 `upload()`:
192
+
193
+ ```js
194
+ const normalAdapter = {
195
+ async upload(file, { signal, onProgress }) {
196
+ const form = new FormData()
197
+ form.append('file', file)
198
+ const res = await fetch('/api/upload', { method: 'POST', body: form, signal })
199
+ onProgress?.(file.size, file.size) // 可选:(已传字节, 总字节)
200
+ return (await res.json()).url // 返回字符串或 { url }
201
+ },
202
+ }
203
+
204
+ KEditor.create('#editor', { uploader: normalAdapter })
205
+ ```
206
+
207
+ **分片上传**实现 `put()` 即可,`init` / `complete` 可选:
208
+
209
+ ```js
210
+ const chunkAdapter = {
211
+ // 「响应里带 url 就是整份文件成功了」,拿到就收工、不再等 complete
212
+ // 不用这个字段时,最终地址必须由 complete() 返回
213
+ completeOnUrl: true,
214
+ async put({ uploadId, index, total, blob, file, meta, size, signal }) {
215
+ const res = await myClient.send(blob, { index, signal })
216
+ return { url: res?.url } // 配合 completeOnUrl 使用:非空即当成功
217
+ },
218
+ // 可选:秒传 / 断点续传
219
+ async init(meta, { signal }) {
220
+ // meta: {name,size,type,lastModified,fingerprint,chunkSize,totalChunks}
221
+ return { uploadId: meta.fingerprint, uploadedChunks: [] } // 或 { url } 表示秒传
222
+ },
223
+ // 可选:自己合并并返回地址(没有 completeOnUrl 时必须实现)
224
+ async complete({ uploadId, meta, total, uploaded, chunkResults, file }) {
225
+ return { url: 'https://…' }
226
+ },
227
+ }
228
+
229
+ KEditor.create('#editor', {
230
+ chunkUploader: chunkAdapter,
231
+ upload: { mode: 'chunk', chunkSize: 2 * 1024 * 1024, concurrency: 2 },
232
+ })
233
+ ```
234
+
235
+ `completeOnUrl` 也可以由调用方给定,优先级高于适配器:
236
+
237
+ ```js
238
+ new ChunkUploader(adapter, { completeOnUrl: true })
239
+ KEditor.create('#editor', { chunkUploader: adapter, upload: { completeOnUrl: true } })
240
+ ```
241
+
242
+ > 只实现了 `upload()` 的适配器传给 `chunkUploader` 也不会出错:分片链路会**自动退化为整包直传**(等价普通上传)。
243
+
244
+ ### 断点续传 / 秒传的判定依据
245
+
246
+ `meta.fingerprint` 默认由 `size + lastModified + 文件名` 组成(`upload.fingerprint: 'fast'`)。
247
+ 改为 `'strong'` 时读取文件首尾各 256KB 计算 SHA-256(HTTPS / localhost 下可用),也允许传函数:
248
+
249
+ ```js
250
+ upload: { fingerprint: async (file) => `${file.name}-${file.size}` }
251
+ ```
252
+
253
+ 服务端把 `identifier → 最终 url` 建索引即可实现秒传;把已落盘分片 index 列表返回即可续传(需适配器实现 `init`)。
254
+
255
+ ---
256
+
257
+ ## 6. 独立使用(不依赖编辑器)
258
+
259
+ ```js
260
+ import { SimpleUploader, ChunkUploader, httpAdapter, createSimpleUploader, createChunkUploader } from 'kyle-editor'
261
+
262
+ // 普通上传
263
+ const simple = createSimpleUploader('/api/upload')
264
+ const one = await simple.upload(file)
265
+
266
+ // 分片上传
267
+ const uploader = new ChunkUploader(httpAdapter({ url: '/api/chunk-upload' }), { chunkSize: 4 * 1024 * 1024, concurrency: 5, retries: 3 })
268
+
269
+ const ctrl = new AbortController()
270
+ const { url, chunks, mode } = await uploader.upload(bigFile, {
271
+ signal: ctrl.signal,
272
+ onProgress: (ratio, info) => bar.style.width = `${info.percent}%`,
273
+ onChunk: ({ index, total }) => console.log(`${index + 1}/${total}`),
274
+ })
275
+ ```
276
+
277
+ 选路器也可以单独用(`editor.uploader` 就是它):
278
+
279
+ ```js
280
+ const pipeline = new UploadPipeline(simple, uploader, { mode: 'auto', chunkThreshold: 5 * 1024 * 1024 })
281
+ pipeline.pick(file) // 'normal' | 'chunk'
282
+ await pipeline.upload(file, { onProgress })
283
+ ```
284
+
285
+ ## 7. 编辑器内的交互契约
286
+
287
+ | 场景 | 行为 |
288
+ |------|------|
289
+ | 点击工具栏图片/视频 | 选择文件 → 就地插入占位块(含进度条、分片数、速度、取消按钮) |
290
+ | 拖拽文件到编辑区 | 光标定位到落点后插入占位块 |
291
+ | 粘贴截图 | 自动生成文件名并上传 |
292
+ | 上传成功 | 占位块替换为 `<img>` / `<video>`,地址取接口返回的 `url`;图片支持双击放大、气泡工具条调整对齐/宽度/圆角/替换/删除、**拖拽右下角把手实时缩放** |
293
+ | 分片失败 | 自动重试 `retries` 次;仍失败则占位块转为错误态,提供「重试 / 移除」 |
294
+ | 取消 | `AbortController` 中止全部在传请求(分片链路若有 `abort()` 也会调用),占位块移除 |
295
+ | 同一文件重复插入 | 适配器 `init` 返回 `url` 时直接秒传,不再切片 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kyle-editor",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "轻量、美观的微信公众号风格富文本编辑器(纯前端,支持图片/视频分片上传、HTML 源码模式),可通过 <script> 引入或作为 Vue 3 组件安装。",
5
5
  "type": "module",
6
6
  "main": "./dist/keditor.cjs",
@@ -25,6 +25,7 @@
25
25
  "files": [
26
26
  "dist",
27
27
  "types",
28
+ "docs",
28
29
  "README.md",
29
30
  "LICENSE"
30
31
  ],
@@ -41,7 +42,7 @@
41
42
  "test:types": "node test/check-types.mjs",
42
43
  "test:package": "node test/check-package.mjs",
43
44
  "test:install": "node test/check-install.mjs",
44
- "test:visual": "node test/shoot.mjs rich,uploading,bubble,resize,align,source,preview,color,heading,media,link,custom,customload,customerr,posbtn,wide,widefix,scroll,scroll2,http://127.0.0.1:5178/demo/vue.html",
45
+ "test:visual": "node test/shoot.mjs rich,uploading,bubble,resize,align,source,preview,color,heading,media,link,code,codepanel,markdown,markdownpanel,custom,customload,customerr,posbtn,wide,widefix,scroll,scroll2,http://127.0.0.1:5178/demo/vue.html",
45
46
  "clean": "rm -rf dist",
46
47
  "verify": "npm run build && npm test && npm run test:min && npm run test:pages && npm run test:types && npm run test:package",
47
48
  "pack:check": "npm run build && npm run test:package && npm pack --dry-run",