kyle-editor 0.0.0-stage → 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +194 -2
- package/dist/keditor-vue.cjs +120 -0
- package/dist/keditor-vue.es.js +118 -0
- package/dist/keditor-vue.umd.js +122 -0
- package/dist/keditor.cjs +4116 -0
- package/dist/keditor.es.js +4116 -0
- package/dist/keditor.umd.js +4120 -0
- package/docs/api.md +223 -0
- package/docs/index.md +8 -0
- package/docs/integration.md +296 -0
- package/docs/npm-publish.md +412 -0
- package/docs/upload-adapter.md +186 -0
- package/package.json +77 -4
- package/src/core/commands.js +311 -0
- package/src/core/editor.js +795 -0
- package/src/core/format.js +64 -0
- package/src/core/history.js +92 -0
- package/src/core/icons.js +49 -0
- package/src/core/paste.js +140 -0
- package/src/core/sanitize.js +182 -0
- package/src/core/selection.js +129 -0
- package/src/core/toolbar.js +465 -0
- package/src/core/utils.js +95 -0
- package/src/index.js +33 -0
- package/src/media/media.js +331 -0
- package/src/ui/bubble.js +270 -0
- package/src/ui/popover.js +507 -0
- package/src/ui/preview.js +59 -0
- package/src/ui/source.js +97 -0
- package/src/ui/styles.js +447 -0
- package/src/ui/toast.js +56 -0
- package/src/upload/adapters.js +206 -0
- package/src/upload/chunk-uploader.js +193 -0
- package/src/upload/fingerprint.js +38 -0
- package/src/vue/index.js +104 -0
- package/types/index.d.ts +345 -0
- package/types/vue.d.ts +73 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 上传适配器集合
|
|
3
|
+
* - mockAdapter:零后端,浏览器内模拟分片传输,产出 blob: 预览地址(开发/演示默认)
|
|
4
|
+
* - httpAdapter:标准分片接口参考实现(init / chunk / complete / abort),对接真实后端只需给 URL
|
|
5
|
+
* - simpleAdapter:单次直传接口包装
|
|
6
|
+
* 自定义 adapter 只要实现 init?/put/complete? 三个方法即可,见 docs/upload-adapter.md
|
|
7
|
+
*/
|
|
8
|
+
import { ChunkUploader, simpleAdapter } from './chunk-uploader.js'
|
|
9
|
+
|
|
10
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
11
|
+
const jitter = (base, ratio = 0.4) => base * (1 - ratio + Math.random() * ratio * 2)
|
|
12
|
+
|
|
13
|
+
/** 默认演示用:不请求任何服务,把文件切片“传完”后生成 objectURL */
|
|
14
|
+
export function mockAdapter(options = {}) {
|
|
15
|
+
const {
|
|
16
|
+
latency = 160, // 每个分片的固定网络往返(ms)
|
|
17
|
+
speed = 12, // 模拟带宽 MB/s
|
|
18
|
+
onEvent = null, // (type, payload) => void,演示面板可打印日志
|
|
19
|
+
reuseObjectUrl = true,
|
|
20
|
+
failFirstChunk = false, // 打开后可直观看到自动重试效果
|
|
21
|
+
} = options
|
|
22
|
+
/** fingerprint -> { url, name, size, type } */
|
|
23
|
+
const finished = new Map()
|
|
24
|
+
/** uploadId -> Set<index> */
|
|
25
|
+
const sessions = new Map()
|
|
26
|
+
const objectUrls = new Map()
|
|
27
|
+
let failOnce = failFirstChunk
|
|
28
|
+
|
|
29
|
+
const emit = (type, payload) => onEvent?.(type, { ...payload, at: Date.now() })
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
name: 'mock',
|
|
33
|
+
async init(meta) {
|
|
34
|
+
emit('init', meta)
|
|
35
|
+
await sleep(120)
|
|
36
|
+
const hit = finished.get(meta.fingerprint)
|
|
37
|
+
if (hit) {
|
|
38
|
+
emit('instant', { name: meta.name, url: hit.url })
|
|
39
|
+
return { url: hit.url, key: meta.fingerprint, instant: true }
|
|
40
|
+
}
|
|
41
|
+
const session = sessions.get(meta.fingerprint) || new Set()
|
|
42
|
+
sessions.set(meta.fingerprint, session)
|
|
43
|
+
return { uploadId: meta.fingerprint, uploadedChunks: [...session] }
|
|
44
|
+
},
|
|
45
|
+
async put({ uploadId, index, total, size, blob }) {
|
|
46
|
+
if (failOnce && index === 0) {
|
|
47
|
+
failOnce = false
|
|
48
|
+
emit('chunk-error', { index, total, message: 'mock: 模拟首个分片网络异常' })
|
|
49
|
+
const error = new Error('mock: 模拟首个分片网络异常')
|
|
50
|
+
error.retryable = true
|
|
51
|
+
throw error
|
|
52
|
+
}
|
|
53
|
+
const cost = Math.max(40, jitter(latency + (size / (speed * 1024 / 8) / 8), 0.35))
|
|
54
|
+
await sleep(cost)
|
|
55
|
+
const session = sessions.get(uploadId) || new Set()
|
|
56
|
+
session.add(index)
|
|
57
|
+
sessions.set(uploadId, session)
|
|
58
|
+
emit('chunk', { index, total, size, blobSize: blob?.size })
|
|
59
|
+
return { etag: `${uploadId}-${index}` }
|
|
60
|
+
},
|
|
61
|
+
async complete({ uploadId, meta, file }) {
|
|
62
|
+
await sleep(140)
|
|
63
|
+
let url = objectUrls.get(meta.fingerprint)
|
|
64
|
+
if (!url || !reuseObjectUrl) {
|
|
65
|
+
// 生成与业务无关的本地地址,编辑器直接可预览
|
|
66
|
+
const blob = file instanceof File ? file : new File([file], meta.name, { type: meta.type })
|
|
67
|
+
url = URL.createObjectURL(blob)
|
|
68
|
+
objectUrls.set(meta.fingerprint, url)
|
|
69
|
+
}
|
|
70
|
+
finished.set(meta.fingerprint, { url, name: meta.name, size: meta.size, type: meta.type })
|
|
71
|
+
sessions.delete(uploadId)
|
|
72
|
+
emit('complete', { name: meta.name, url, chunks: meta.totalChunks, size: meta.size })
|
|
73
|
+
return { url, key: meta.fingerprint }
|
|
74
|
+
},
|
|
75
|
+
async abort({ uploadId }) {
|
|
76
|
+
emit('abort', { uploadId })
|
|
77
|
+
},
|
|
78
|
+
/** 已完成的上传记录(演示用) */
|
|
79
|
+
list: () => [...finished.entries()].map(([key, value]) => ({ key, ...value })),
|
|
80
|
+
reset: () => {
|
|
81
|
+
finished.clear()
|
|
82
|
+
sessions.clear()
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 真实后端参考实现
|
|
89
|
+
* config = {
|
|
90
|
+
* initUrl, chunkUrl, completeUrl, abortUrl,
|
|
91
|
+
* mode: 'raw' | 'formdata', // 分片是裸 body 还是 multipart
|
|
92
|
+
* headers: () => ({}) | object, // 鉴权
|
|
93
|
+
* withCredentials, fieldName, parse: (json) => ({url, ...})
|
|
94
|
+
* }
|
|
95
|
+
*/
|
|
96
|
+
export function httpAdapter(config = {}) {
|
|
97
|
+
const {
|
|
98
|
+
initUrl,
|
|
99
|
+
chunkUrl,
|
|
100
|
+
completeUrl,
|
|
101
|
+
abortUrl,
|
|
102
|
+
mode = 'raw',
|
|
103
|
+
fieldName = 'file',
|
|
104
|
+
headers = {},
|
|
105
|
+
withCredentials = false,
|
|
106
|
+
parse = (json) => json?.data || json || {},
|
|
107
|
+
chunkUrlFor,
|
|
108
|
+
} = config
|
|
109
|
+
|
|
110
|
+
const headerOf = () => (typeof headers === 'function' ? headers() || {} : headers || {})
|
|
111
|
+
const request = async (url, init = {}) => {
|
|
112
|
+
const res = await fetch(url, { credentials: withCredentials ? 'include' : 'same-origin', ...init })
|
|
113
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`)
|
|
114
|
+
const text = await res.text()
|
|
115
|
+
if (!text) return {}
|
|
116
|
+
try {
|
|
117
|
+
return parse(JSON.parse(text))
|
|
118
|
+
} catch {
|
|
119
|
+
throw new Error(`服务端返回非 JSON 数据:${text.slice(0, 80)}`)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
name: 'http',
|
|
125
|
+
async init(meta, { signal }) {
|
|
126
|
+
if (!initUrl) throw new Error('[KEditor] httpAdapter 缺少 initUrl')
|
|
127
|
+
return request(
|
|
128
|
+
initUrl,
|
|
129
|
+
{
|
|
130
|
+
method: 'POST',
|
|
131
|
+
signal,
|
|
132
|
+
headers: { 'Content-Type': 'application/json', ...headerOf() },
|
|
133
|
+
body: JSON.stringify({
|
|
134
|
+
fileName: meta.name,
|
|
135
|
+
fileSize: meta.size,
|
|
136
|
+
fileType: meta.type,
|
|
137
|
+
lastModified: meta.lastModified,
|
|
138
|
+
identifier: meta.fingerprint,
|
|
139
|
+
chunkSize: meta.chunkSize,
|
|
140
|
+
totalChunks: meta.totalChunks,
|
|
141
|
+
}),
|
|
142
|
+
},
|
|
143
|
+
)
|
|
144
|
+
},
|
|
145
|
+
async put({ uploadId, index, total, blob, meta, signal }) {
|
|
146
|
+
if (!chunkUrl) throw new Error('[KEditor] httpAdapter 缺少 chunkUrl')
|
|
147
|
+
const url = typeof chunkUrlFor === 'function' ? chunkUrlFor({ uploadId, index }) : chunkUrl
|
|
148
|
+
if (mode === 'formdata') {
|
|
149
|
+
const form = new FormData()
|
|
150
|
+
form.append(fieldName, blob, `${meta.name}.part${index}`)
|
|
151
|
+
form.append('uploadId', uploadId)
|
|
152
|
+
form.append('identifier', meta.fingerprint)
|
|
153
|
+
form.append('index', String(index))
|
|
154
|
+
form.append('total', String(total))
|
|
155
|
+
form.append('filename', meta.name)
|
|
156
|
+
return request(url, { method: 'POST', body: form, signal, headers: headerOf() })
|
|
157
|
+
}
|
|
158
|
+
// 裸 body:服务端按 uploadId + index 落盘
|
|
159
|
+
const joiner = url.includes('?') ? '&' : '?'
|
|
160
|
+
const target = `${url}${joiner}uploadId=${encodeURIComponent(uploadId)}&index=${index}&total=${total}&filename=${encodeURIComponent(meta.name)}`
|
|
161
|
+
return request(target, {
|
|
162
|
+
method: 'PUT',
|
|
163
|
+
body: blob,
|
|
164
|
+
signal,
|
|
165
|
+
headers: { 'Content-Type': 'application/octet-stream', 'X-Chunk-Index': String(index), ...headerOf() },
|
|
166
|
+
})
|
|
167
|
+
},
|
|
168
|
+
async complete({ uploadId, meta, total }) {
|
|
169
|
+
if (!completeUrl) throw new Error('[KEditor] httpAdapter 缺少 completeUrl')
|
|
170
|
+
return request(
|
|
171
|
+
completeUrl,
|
|
172
|
+
{
|
|
173
|
+
method: 'POST',
|
|
174
|
+
headers: { 'Content-Type': 'application/json', ...headerOf() },
|
|
175
|
+
body: JSON.stringify({ uploadId, identifier: meta.fingerprint, fileName: meta.name, fileSize: meta.size, fileType: meta.type, chunkSize: meta.chunkSize, totalChunks: total }),
|
|
176
|
+
},
|
|
177
|
+
)
|
|
178
|
+
},
|
|
179
|
+
async abort({ uploadId }) {
|
|
180
|
+
if (!abortUrl) return
|
|
181
|
+
await request(abortUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headerOf() }, body: JSON.stringify({ uploadId }) }).catch(() => {})
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* 归一化用户传入的 uploader 配置,返回 ChunkUploader 实例
|
|
188
|
+
* 支持:undefined('mock') | 'mock' | {type:'mock'|'http', ...} | adapter 对象 | (file)=>url 函数 | ChunkUploader
|
|
189
|
+
*/
|
|
190
|
+
export function createUploader(option = 'mock', config = {}) {
|
|
191
|
+
if (option instanceof ChunkUploader) return option
|
|
192
|
+
if (typeof option === 'function' && !option.put) return new ChunkUploader(simpleAdapter(option), config)
|
|
193
|
+
if (option && typeof option === 'object' && !(option instanceof ChunkUploader)) {
|
|
194
|
+
if (typeof option.put === 'function' || typeof option.upload === 'function') return new ChunkUploader(option, { ...config, ...pick(option) })
|
|
195
|
+
if (option.type === 'http') return new ChunkUploader(httpAdapter(option), { ...config, ...pick(option) })
|
|
196
|
+
}
|
|
197
|
+
return new ChunkUploader(mockAdapter(typeof option === 'object' ? option : {}), config)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const pick = (obj) => {
|
|
201
|
+
const out = {}
|
|
202
|
+
for (const key of ['chunkSize', 'concurrency', 'retries', 'fingerprint']) if (obj[key] !== undefined) out[key] = obj[key]
|
|
203
|
+
return out
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export { ChunkUploader, simpleAdapter }
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 分片上传调度器
|
|
3
|
+
* 职责:切片 → 并发上传 → 失败重试 → 进度回调 → 合并通知
|
|
4
|
+
* 与具体服务端解耦,只需实现 adapter 的三个方法
|
|
5
|
+
*/
|
|
6
|
+
import { createFingerprint } from './fingerprint.js'
|
|
7
|
+
|
|
8
|
+
export const MB = 1024 * 1024
|
|
9
|
+
|
|
10
|
+
export class ChunkUploader {
|
|
11
|
+
constructor(adapter, options = {}) {
|
|
12
|
+
if (!adapter || typeof adapter.put !== 'function') {
|
|
13
|
+
throw new Error('[KEditor] uploader 需要提供 put() 方法,参见 docs/upload-adapter.md')
|
|
14
|
+
}
|
|
15
|
+
this.adapter = adapter
|
|
16
|
+
this.chunkSize = Math.max(64 * 1024, options.chunkSize || MB)
|
|
17
|
+
this.concurrency = Math.max(1, options.concurrency || 3)
|
|
18
|
+
this.retries = options.retries === undefined ? 2 : Math.max(0, options.retries)
|
|
19
|
+
this.retryDelay = options.retryDelay ?? 600
|
|
20
|
+
this.fingerprint = createFingerprint(options.fingerprint || 'fast')
|
|
21
|
+
this.slice = options.slice
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {File|Blob} file
|
|
26
|
+
* @param {{onProgress?,onChunk?,onInfo?,signal?}} handlers
|
|
27
|
+
* @returns {Promise<{url:string, instant?:boolean, chunks:number, size:number, name:string}>}
|
|
28
|
+
*/
|
|
29
|
+
async upload(file, handlers = {}) {
|
|
30
|
+
const { onProgress, onChunk, signal } = handlers
|
|
31
|
+
if (this.adapter.simple) return this.uploadSimple(file, handlers)
|
|
32
|
+
const total = Math.max(1, Math.ceil(file.size / this.chunkSize))
|
|
33
|
+
const meta = {
|
|
34
|
+
name: file.name || 'blob',
|
|
35
|
+
size: file.size,
|
|
36
|
+
type: file.type || guessType(file.name),
|
|
37
|
+
lastModified: file.lastModified || 0,
|
|
38
|
+
fingerprint: await this.fingerprint(file),
|
|
39
|
+
chunkSize: this.chunkSize,
|
|
40
|
+
totalChunks: total,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// 1. 初始化:服务端可返回 uploadId / 已传分片(断点续传)/ 秒传 url
|
|
44
|
+
const init = (await this.adapter.init?.(meta, { signal })) || {}
|
|
45
|
+
if (init.url) {
|
|
46
|
+
onProgress?.(1, { percent: 100, loaded: file.size, total: file.size, chunks: total, instant: true })
|
|
47
|
+
return { url: init.url, instant: true, chunks: 0, size: file.size, name: meta.name, key: init.key }
|
|
48
|
+
}
|
|
49
|
+
const uploadId = init.uploadId || meta.fingerprint
|
|
50
|
+
const uploaded = new Set((init.uploadedChunks || init.uploaded || []).map(Number))
|
|
51
|
+
|
|
52
|
+
// 2. 并发上传未完成的分片
|
|
53
|
+
let loadedBytes = 0
|
|
54
|
+
for (const index of uploaded) loadedBytes += Math.min(this.chunkSize, file.size - index * this.chunkSize)
|
|
55
|
+
const queue = []
|
|
56
|
+
for (let i = 0; i < total; i += 1) if (!uploaded.has(i)) queue.push(i)
|
|
57
|
+
|
|
58
|
+
const chunkResults = new Array(total)
|
|
59
|
+
let doneChunks = uploaded.size
|
|
60
|
+
const startedAt = Date.now()
|
|
61
|
+
const report = () => {
|
|
62
|
+
const elapsed = (Date.now() - startedAt) / 1000
|
|
63
|
+
onProgress?.(file.size ? loadedBytes / file.size : 1, {
|
|
64
|
+
percent: Math.min(100, Math.round((loadedBytes / Math.max(1, file.size)) * 100)),
|
|
65
|
+
loaded: loadedBytes,
|
|
66
|
+
total: file.size,
|
|
67
|
+
chunks: total,
|
|
68
|
+
uploadedChunks: doneChunks,
|
|
69
|
+
speed: elapsed > 0 ? loadedBytes / elapsed : 0,
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
report()
|
|
73
|
+
|
|
74
|
+
let cursor = 0
|
|
75
|
+
let firstError = null
|
|
76
|
+
const worker = async () => {
|
|
77
|
+
while (cursor < queue.length) {
|
|
78
|
+
if (signal?.aborted) throw new DOMException('已取消上传', 'AbortError')
|
|
79
|
+
const index = queue[cursor++]
|
|
80
|
+
const blob = this.slice ? this.slice(file, index, this.chunkSize) : file.slice(index * this.chunkSize, (index + 1) * this.chunkSize)
|
|
81
|
+
let attempt = 0
|
|
82
|
+
for (;;) {
|
|
83
|
+
try {
|
|
84
|
+
const res = await this.adapter.put({
|
|
85
|
+
uploadId,
|
|
86
|
+
index,
|
|
87
|
+
total,
|
|
88
|
+
chunkSize: this.chunkSize,
|
|
89
|
+
blob,
|
|
90
|
+
file,
|
|
91
|
+
meta,
|
|
92
|
+
signal,
|
|
93
|
+
size: blob.size,
|
|
94
|
+
})
|
|
95
|
+
if (res?.url) chunkResults[index] = res
|
|
96
|
+
loadedBytes += blob.size
|
|
97
|
+
doneChunks += 1
|
|
98
|
+
onChunk?.({ index, total, size: blob.size })
|
|
99
|
+
report()
|
|
100
|
+
break
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error?.name === 'AbortError') throw error
|
|
103
|
+
attempt += 1
|
|
104
|
+
if (attempt > this.retries) {
|
|
105
|
+
firstError = error
|
|
106
|
+
throw new Error(`分片 ${index + 1}/${total} 上传失败:${error?.message || error}`)
|
|
107
|
+
}
|
|
108
|
+
await sleep(this.retryDelay * attempt, signal)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const workers = Array.from({ length: Math.max(1, Math.min(this.concurrency, queue.length)) }, worker)
|
|
115
|
+
try {
|
|
116
|
+
await Promise.all(workers)
|
|
117
|
+
} catch (error) {
|
|
118
|
+
await this.adapter.abort?.({ uploadId, meta, error }).catch(() => {})
|
|
119
|
+
throw error
|
|
120
|
+
}
|
|
121
|
+
if (firstError) throw firstError
|
|
122
|
+
|
|
123
|
+
// 3. 通知服务端合并(或本地生成可访问地址)
|
|
124
|
+
const done = (await this.adapter.complete?.({ uploadId, meta, total, uploaded: doneChunks, chunkResults, file })) || {}
|
|
125
|
+
const url = done.url
|
|
126
|
+
if (!url) throw new Error('[KEditor] uploader.complete() 未返回 url')
|
|
127
|
+
return { url, chunks: total, size: file.size, name: meta.name, key: done.key, poster: done.poster, duration: done.duration, raw: done }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 单请求直传(不切片),供对接已有单次上传接口时使用 */
|
|
131
|
+
async uploadSimple(file, handlers = {}) {
|
|
132
|
+
const { onProgress, signal } = handlers
|
|
133
|
+
const startedAt = Date.now()
|
|
134
|
+
const result = await this.adapter.upload(file, {
|
|
135
|
+
signal,
|
|
136
|
+
onProgress: (loaded, total) => {
|
|
137
|
+
const ratio = total ? loaded / total : 0
|
|
138
|
+
const elapsed = (Date.now() - startedAt) / 1000
|
|
139
|
+
onProgress?.(ratio, { percent: Math.round(ratio * 100), loaded, total: total || file.size, chunks: 1, uploadedChunks: ratio >= 1 ? 1 : 0, speed: elapsed > 0 ? loaded / elapsed : 0 })
|
|
140
|
+
},
|
|
141
|
+
})
|
|
142
|
+
const url = typeof result === 'string' ? result : result?.url
|
|
143
|
+
if (!url) throw new Error('[KEditor] uploader.upload() 未返回 url')
|
|
144
|
+
return { url, chunks: 1, size: file.size, name: file.name, key: typeof result === 'object' ? result.key : undefined, raw: result }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
destroy() {
|
|
148
|
+
this.adapter.destroy?.()
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const sleep = (ms, signal) =>
|
|
153
|
+
new Promise((resolve, reject) => {
|
|
154
|
+
const timer = setTimeout(() => {
|
|
155
|
+
signal?.removeEventListener('abort', onAbort)
|
|
156
|
+
resolve()
|
|
157
|
+
}, ms)
|
|
158
|
+
const onAbort = () => {
|
|
159
|
+
clearTimeout(timer)
|
|
160
|
+
reject(new DOMException('已取消上传', 'AbortError'))
|
|
161
|
+
}
|
|
162
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
/** 供 adapter 内部使用的进度上报辅助 */
|
|
166
|
+
export function reportProgress(handler, loaded, total) {
|
|
167
|
+
handler?.(total ? loaded / total : 1, { loaded, total })
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function guessType(name = '') {
|
|
171
|
+
const ext = String(name).split('.').pop()?.toLowerCase()
|
|
172
|
+
const map = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', mp4: 'video/mp4', mov: 'video/quicktime', webm: 'video/webm', m4v: 'video/x-m4v' }
|
|
173
|
+
return map[ext] || 'application/octet-stream'
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 把「一个文件一次请求」的上传函数包装成 adapter(不切片,直传)
|
|
178
|
+
* fn(file, {signal, onProgress}) => Promise<string | {url}>
|
|
179
|
+
*/
|
|
180
|
+
export function simpleAdapter(fn) {
|
|
181
|
+
return {
|
|
182
|
+
simple: true,
|
|
183
|
+
async upload(file, ctx = {}) {
|
|
184
|
+
const res = await fn(toFile(file), ctx)
|
|
185
|
+
return typeof res === 'string' ? { url: res } : res
|
|
186
|
+
},
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function toFile(blob, name = 'blob', type = blob.type) {
|
|
191
|
+
if (blob instanceof File) return blob
|
|
192
|
+
return new File([blob], name, { type })
|
|
193
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** 文件指纹:用于秒传 / 断点续传的任务标识 */
|
|
2
|
+
|
|
3
|
+
export function fastFingerprint(file) {
|
|
4
|
+
return `${sizeHex(file.size)}-${stampHex(file.lastModified)}-${safeName(file.name)}`
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 强指纹:对首尾各 256KB + 文件大小做 SHA-256(大文件也只需读取极少量数据)
|
|
9
|
+
* 需要 crypto.subtle(HTTPS 或 localhost 环境)
|
|
10
|
+
*/
|
|
11
|
+
export async function strongFingerprint(file) {
|
|
12
|
+
if (!globalThis.crypto?.subtle) return fastFingerprint(file)
|
|
13
|
+
const span = 256 * 1024
|
|
14
|
+
const parts = [file.slice(0, span)]
|
|
15
|
+
if (file.size > span) parts.push(file.slice(file.size - span))
|
|
16
|
+
const buf = new Uint8Array(parts.reduce((sum, blob) => sum + blob.size, 0))
|
|
17
|
+
let offset = 0
|
|
18
|
+
for (const blob of parts) {
|
|
19
|
+
const chunk = new Uint8Array(await blob.arrayBuffer())
|
|
20
|
+
buf.set(chunk, offset)
|
|
21
|
+
offset += chunk.length
|
|
22
|
+
}
|
|
23
|
+
const digest = await crypto.subtle.digest('SHA-256', buf)
|
|
24
|
+
const hex = Array.from(new Uint8Array(digest))
|
|
25
|
+
.map((b) => b.toString(16).padStart(2, '0'))
|
|
26
|
+
.join('')
|
|
27
|
+
return `${hex.slice(0, 24)}-${sizeHex(file.size)}`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const sizeHex = (size) => Number(size).toString(16)
|
|
31
|
+
const stampHex = (ts) => Number(ts || 0).toString(16)
|
|
32
|
+
const safeName = (name) => String(name).replace(/[^\w.-]/g, '').slice(0, 24)
|
|
33
|
+
|
|
34
|
+
export function createFingerprint(mode = 'fast') {
|
|
35
|
+
if (mode === 'strong' || mode === 'sha256') return strongFingerprint
|
|
36
|
+
if (typeof mode === 'function') return mode
|
|
37
|
+
return async (file) => fastFingerprint(file)
|
|
38
|
+
}
|
package/src/vue/index.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vue 3 集成:<k-editor v-model="html" :options="{...}" />
|
|
3
|
+
* 组件用 render 函数实现,无需 SFC 编译器,可直接被 Vite / Webpack / CDN 使用
|
|
4
|
+
*/
|
|
5
|
+
import { h, ref, watch, onMounted, onBeforeUnmount, shallowRef } from 'vue'
|
|
6
|
+
import { KEditor, defaults } from 'kyle-editor'
|
|
7
|
+
|
|
8
|
+
export const KEditorVue = {
|
|
9
|
+
name: 'KEditor',
|
|
10
|
+
props: {
|
|
11
|
+
modelValue: { type: String, default: '' },
|
|
12
|
+
options: { type: Object, default: () => ({}) },
|
|
13
|
+
disabled: { type: Boolean, default: false },
|
|
14
|
+
height: { type: Number, default: null },
|
|
15
|
+
},
|
|
16
|
+
emits: ['update:modelValue', 'ready', 'change', 'upload', 'error', 'save', 'blur', 'focus'],
|
|
17
|
+
setup(props, { emit, expose }) {
|
|
18
|
+
const host = ref(null)
|
|
19
|
+
const instance = shallowRef(null)
|
|
20
|
+
|
|
21
|
+
const buildOptions = () => {
|
|
22
|
+
const opts = { ...defaults, ...props.options, value: props.modelValue || '' }
|
|
23
|
+
if (props.height) opts.height = props.height
|
|
24
|
+
opts.onChange = (html) => {
|
|
25
|
+
emit('update:modelValue', html)
|
|
26
|
+
emit('change', html)
|
|
27
|
+
}
|
|
28
|
+
opts.onReady = (editor) => emit('ready', editor)
|
|
29
|
+
opts.onError = (error) => emit('error', error)
|
|
30
|
+
opts.onUpload = (payload) => emit('upload', payload)
|
|
31
|
+
return opts
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// expose 必须在 setup 同步阶段调用,实例字段用 getter 惰读取
|
|
35
|
+
expose({
|
|
36
|
+
get editor() {
|
|
37
|
+
return instance.value
|
|
38
|
+
},
|
|
39
|
+
getHTML: () => instance.value?.getHTML() || '',
|
|
40
|
+
getText: () => instance.value?.getText() || '',
|
|
41
|
+
counts: () => instance.value?.counts() || null,
|
|
42
|
+
focus: () => instance.value?.focus(),
|
|
43
|
+
setContent: (html) => instance.value?.setContent(html),
|
|
44
|
+
enterSource: () => instance.value?.enterSource(),
|
|
45
|
+
openPreview: () => instance.value?.openPreview(),
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
onMounted(() => {
|
|
49
|
+
instance.value = new KEditor(host.value, buildOptions())
|
|
50
|
+
instance.value.on('save', (payload) => emit('save', payload))
|
|
51
|
+
instance.value.on('blur', () => emit('blur'))
|
|
52
|
+
instance.value.on('focus', () => emit('focus'))
|
|
53
|
+
host.value.__keditor__ = instance.value
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
onBeforeUnmount(() => {
|
|
57
|
+
host.value.__keditor__ = null
|
|
58
|
+
instance.value?.destroy()
|
|
59
|
+
instance.value = null
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
watch(
|
|
63
|
+
() => props.modelValue,
|
|
64
|
+
(value) => {
|
|
65
|
+
const editor = instance.value
|
|
66
|
+
if (!editor || editor.sourceMode) return
|
|
67
|
+
if (value === editor.getHTML()) return
|
|
68
|
+
editor.setContent(value || '', { silent: true })
|
|
69
|
+
},
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
watch(
|
|
73
|
+
() => props.disabled,
|
|
74
|
+
(value) => instance.value?.setReadOnly(value),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
return () => h('div', { ref: host, class: 'ke-vue-host' })
|
|
78
|
+
},
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export const KEditorPlugin = {
|
|
82
|
+
install(app, { name = 'KEditor' } = {}) {
|
|
83
|
+
app.component(name, KEditorVue)
|
|
84
|
+
app.config.globalProperties.$keditor = { KEditor, defaults }
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 组合式用法:const { el, editor } = useKEditor(options) */
|
|
89
|
+
export function useKEditor(options = {}) {
|
|
90
|
+
const host = ref(null)
|
|
91
|
+
const instance = shallowRef(null)
|
|
92
|
+
onMounted(() => {
|
|
93
|
+
instance.value = new KEditor(host.value, options)
|
|
94
|
+
})
|
|
95
|
+
onBeforeUnmount(() => instance.value?.destroy())
|
|
96
|
+
return { host, editor: instance }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// 组件自带 install:`app.use(KEditorVue)` 与 `<KEditorVue />` 两种写法都可用,
|
|
100
|
+
// 避免把默认导出当组件却渲染出空白(无任何报错)的陷阱
|
|
101
|
+
KEditorVue.install = (app, options) => KEditorPlugin.install(app, options)
|
|
102
|
+
|
|
103
|
+
export default KEditorVue
|
|
104
|
+
export { KEditor }
|