kyle-editor 1.0.0 → 1.0.2
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/README.md +103 -69
- package/dist/keditor.cjs +849 -217
- package/dist/keditor.es.js +849 -217
- package/dist/keditor.umd.js +849 -217
- package/package.json +3 -7
- package/types/index.d.ts +136 -4
- package/docs/api.md +0 -223
- package/docs/index.md +0 -8
- package/docs/integration.md +0 -296
- package/docs/npm-publish.md +0 -412
- package/docs/upload-adapter.md +0 -186
- package/src/core/commands.js +0 -311
- package/src/core/editor.js +0 -795
- package/src/core/format.js +0 -64
- package/src/core/history.js +0 -92
- package/src/core/icons.js +0 -49
- package/src/core/paste.js +0 -140
- package/src/core/sanitize.js +0 -182
- package/src/core/selection.js +0 -129
- package/src/core/toolbar.js +0 -465
- package/src/core/utils.js +0 -95
- package/src/index.js +0 -33
- package/src/media/media.js +0 -331
- package/src/ui/bubble.js +0 -270
- package/src/ui/popover.js +0 -507
- package/src/ui/preview.js +0 -59
- package/src/ui/source.js +0 -97
- package/src/ui/styles.js +0 -447
- package/src/ui/toast.js +0 -56
- package/src/upload/adapters.js +0 -206
- package/src/upload/chunk-uploader.js +0 -193
- package/src/upload/fingerprint.js +0 -38
- package/src/vue/index.js +0 -104
package/src/core/editor.js
DELETED
|
@@ -1,795 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* KEditor 核心:组装 DOM、事件、命令、上传与面板
|
|
3
|
-
*/
|
|
4
|
-
import { injectStyle } from '../ui/styles.js'
|
|
5
|
-
import { Popover } from '../ui/popover.js'
|
|
6
|
-
import { SourcePanel } from '../ui/source.js'
|
|
7
|
-
import { PreviewOverlay } from '../ui/preview.js'
|
|
8
|
-
import { MediaBubble } from '../ui/bubble.js'
|
|
9
|
-
import { Toast, lightbox } from '../ui/toast.js'
|
|
10
|
-
import { Toolbar, DEFAULT_TOOLBAR } from './toolbar.js'
|
|
11
|
-
import { Commands } from './commands.js'
|
|
12
|
-
import { History } from './history.js'
|
|
13
|
-
import { MediaManager } from '../media/media.js'
|
|
14
|
-
import { createUploader } from '../upload/adapters.js'
|
|
15
|
-
import { attachDrop, attachPaste } from './paste.js'
|
|
16
|
-
import { sanitizeHtml, toPlainText } from './sanitize.js'
|
|
17
|
-
import { caretOffset, getRange, closestBlock } from './selection.js'
|
|
18
|
-
import { debounce, h, clamp, getMediaAlign } from './utils.js'
|
|
19
|
-
|
|
20
|
-
const KB = 1024
|
|
21
|
-
const MB = 1024 * KB
|
|
22
|
-
|
|
23
|
-
export const defaults = {
|
|
24
|
-
value: '',
|
|
25
|
-
placeholder: '开始撰写内容,支持拖拽 / 粘贴图片与视频…',
|
|
26
|
-
height: 460, // 编辑区可视高度(px),0 = 自适应
|
|
27
|
-
minHeight: 320,
|
|
28
|
-
primaryColor: '#07c160',
|
|
29
|
-
paperWidth: 677,
|
|
30
|
-
toolbar: DEFAULT_TOOLBAR,
|
|
31
|
-
hideToolbar: false,
|
|
32
|
-
hideStatusbar: false,
|
|
33
|
-
readOnly: false,
|
|
34
|
-
autofocus: false,
|
|
35
|
-
maxLength: 0, // 0 表示不限制
|
|
36
|
-
wordCount: true,
|
|
37
|
-
sanitize: true,
|
|
38
|
-
historyLimit: 60,
|
|
39
|
-
uploader: 'mock', // 'mock' | {type:'http', ...} | adapter | fn | ChunkUploader
|
|
40
|
-
upload: { chunkSize: MB, concurrency: 3, retries: 2, fingerprint: 'fast' },
|
|
41
|
-
image: { compress: { maxWidth: 1440, quality: 0.85, minSize: 300 * KB } },
|
|
42
|
-
maxImageSize: 20 * MB,
|
|
43
|
-
maxVideoSize: 512 * MB,
|
|
44
|
-
imageAccept: 'image/png,image/jpeg,image/gif,image/webp,image/bmp,image/svg+xml,image/avif',
|
|
45
|
-
videoAccept: 'video/mp4,video/quicktime,video/webm,video/x-m4v,video/ogg',
|
|
46
|
-
paste: { enabled: true, clean: true, uploadFiles: true, localizeImages: false },
|
|
47
|
-
onChange: null,
|
|
48
|
-
onReady: null,
|
|
49
|
-
onError: null,
|
|
50
|
-
onUpload: null, // ({stage, file, kind, url, percent, info}) => void
|
|
51
|
-
beforeUpload: null, // (file, kind) => File | false
|
|
52
|
-
toolbarFloat: false,
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
let instanceSeq = 0
|
|
56
|
-
|
|
57
|
-
export class KEditor {
|
|
58
|
-
constructor(target, options = {}) {
|
|
59
|
-
injectStyle()
|
|
60
|
-
this.options = mergeOptions(options)
|
|
61
|
-
this.id = `ke-${(instanceSeq += 1)}`
|
|
62
|
-
this.el = resolveTarget(target, this.id)
|
|
63
|
-
this.emitters = new Map()
|
|
64
|
-
this.domListeners = []
|
|
65
|
-
this.destroyed = false
|
|
66
|
-
this.sourceMode = false
|
|
67
|
-
this.previewMode = false
|
|
68
|
-
this.fullscreen = false
|
|
69
|
-
this.readOnly = false
|
|
70
|
-
|
|
71
|
-
this.buildDOM()
|
|
72
|
-
this.toast = new Toast()
|
|
73
|
-
this.popover = new Popover(this.el)
|
|
74
|
-
this.commands = new Commands(this)
|
|
75
|
-
this.uploader = createUploader(this.options.uploader, this.options.upload)
|
|
76
|
-
this.media = createMedia(this)
|
|
77
|
-
this.history = new History(this.root, { limit: this.options.historyLimit })
|
|
78
|
-
this.toolbar = new Toolbar(this, this.options.toolbar)
|
|
79
|
-
this.source = new SourcePanel(this)
|
|
80
|
-
this.previewPanel = new PreviewOverlay(this)
|
|
81
|
-
this.bubble = new MediaBubble(this)
|
|
82
|
-
this.mainEl.append(this.source.el, this.previewPanel.el)
|
|
83
|
-
|
|
84
|
-
this.applyTheme()
|
|
85
|
-
this.setContent(this.options.value || this.el.innerHTML, { sanitize: this.options.sanitize, silent: true })
|
|
86
|
-
this.bindEvents()
|
|
87
|
-
this.setReadOnly(this.options.readOnly)
|
|
88
|
-
this.refresh()
|
|
89
|
-
this.refreshStatus()
|
|
90
|
-
this.history.reset(this.root.innerHTML)
|
|
91
|
-
|
|
92
|
-
queueMicrotask(() => {
|
|
93
|
-
if (this.destroyed) return
|
|
94
|
-
this.emit('ready', { editor: this })
|
|
95
|
-
this.options.onReady?.(this)
|
|
96
|
-
if (this.options.autofocus) this.focus()
|
|
97
|
-
})
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/* ------------------------------ DOM ------------------------------ */
|
|
101
|
-
|
|
102
|
-
buildDOM() {
|
|
103
|
-
this.el.classList.add('ke')
|
|
104
|
-
this.el.id = this.el.id || this.id
|
|
105
|
-
this.el.innerHTML = ''
|
|
106
|
-
|
|
107
|
-
this.tbEl = h('div.ke-tb', { role: 'toolbar', 'aria-label': '编辑器工具栏' })
|
|
108
|
-
this.scrollEl = h('div.ke-scroll')
|
|
109
|
-
this.paperEl = h('div.ke-paper')
|
|
110
|
-
this.root = h('div.ke-content', {
|
|
111
|
-
contenteditable: this.readOnly ? 'false' : 'true',
|
|
112
|
-
role: 'textbox',
|
|
113
|
-
'aria-multiline': 'true',
|
|
114
|
-
spellcheck: 'false',
|
|
115
|
-
'data-placeholder': this.options.placeholder,
|
|
116
|
-
'data-ke-root': '',
|
|
117
|
-
})
|
|
118
|
-
this.root.style.minHeight = `${this.options.minHeight}px`
|
|
119
|
-
this.paperEl.appendChild(this.root)
|
|
120
|
-
this.scrollEl.appendChild(this.paperEl)
|
|
121
|
-
|
|
122
|
-
this.mainEl = h('div.ke-main', {}, [this.scrollEl])
|
|
123
|
-
this.statusEl = buildStatusbar(this)
|
|
124
|
-
this.dropzoneEl = h('div.ke-dropzone', {}, [h('span', { text: '松开即可上传(分片传输)' })])
|
|
125
|
-
|
|
126
|
-
if (!this.options.hideToolbar) this.el.appendChild(this.tbEl)
|
|
127
|
-
this.el.appendChild(this.mainEl)
|
|
128
|
-
if (!this.options.hideStatusbar) this.el.appendChild(this.statusEl)
|
|
129
|
-
this.el.appendChild(this.dropzoneEl)
|
|
130
|
-
|
|
131
|
-
if (this.options.height) {
|
|
132
|
-
this.scrollEl.style.height = `${this.options.height}px`
|
|
133
|
-
this.scrollEl.style.maxHeight = `${this.options.height}px`
|
|
134
|
-
}
|
|
135
|
-
this.paperEl.style.setProperty('--ke-paper', `${this.options.paperWidth}px`)
|
|
136
|
-
this.paperEl.style.setProperty('--ke-min-height', `${this.options.minHeight}px`)
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
applyTheme() {
|
|
140
|
-
if (this.options.primaryColor) this.el.style.setProperty('--ke-primary', this.options.primaryColor)
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/* ------------------------------ 事件 ------------------------------ */
|
|
144
|
-
|
|
145
|
-
bindEvents() {
|
|
146
|
-
const debouncedChange = debounce(() => this.emitChange(), 160)
|
|
147
|
-
|
|
148
|
-
this.bind(this.root, 'input', () => {
|
|
149
|
-
this.history.snapshot()
|
|
150
|
-
this.refreshStatus()
|
|
151
|
-
this.togglePlaceholder()
|
|
152
|
-
debouncedChange()
|
|
153
|
-
this.enforceMaxLength()
|
|
154
|
-
})
|
|
155
|
-
|
|
156
|
-
this.bind(this.root, 'keydown', (event) => this.handleKeydown(event))
|
|
157
|
-
this.bind(this.root, 'blur', () => {
|
|
158
|
-
this.history.flush()
|
|
159
|
-
this.el.classList.remove('ke-is-focus')
|
|
160
|
-
this.emit('blur')
|
|
161
|
-
})
|
|
162
|
-
this.bind(this.root, 'focus', () => {
|
|
163
|
-
this.el.classList.add('ke-is-focus')
|
|
164
|
-
this.emit('focus')
|
|
165
|
-
})
|
|
166
|
-
this.bind(this.root, 'click', (event) => this.handleContentClick(event))
|
|
167
|
-
this.bind(this.root, 'dblclick', (event) => {
|
|
168
|
-
const img = event.target.closest('img')
|
|
169
|
-
if (img && this.root.contains(img)) lightbox(img.src)
|
|
170
|
-
})
|
|
171
|
-
|
|
172
|
-
attachPaste(this)
|
|
173
|
-
attachDrop(this)
|
|
174
|
-
|
|
175
|
-
this.selectionHandler = () => {
|
|
176
|
-
if (!this.root.contains(document.activeElement) && document.activeElement !== this.root) return
|
|
177
|
-
this.refresh()
|
|
178
|
-
this.syncBubble()
|
|
179
|
-
}
|
|
180
|
-
document.addEventListener('selectionchange', this.selectionHandler)
|
|
181
|
-
|
|
182
|
-
this.scrollHandler = () => this.bubble.position()
|
|
183
|
-
this.bind(this.scrollEl, 'scroll', this.scrollHandler)
|
|
184
|
-
window.addEventListener('resize', this.scrollHandler)
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
/** 内部 DOM 事件登记,便于 destroy 时统一清理 */
|
|
188
|
-
bind(node, type, handler) {
|
|
189
|
-
node.addEventListener(type, handler)
|
|
190
|
-
this.domListeners.push({ node, type, handler })
|
|
191
|
-
return handler
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
handleKeydown(event) {
|
|
195
|
-
const meta = event.metaKey || event.ctrlKey
|
|
196
|
-
const key = event.key.toLowerCase()
|
|
197
|
-
|
|
198
|
-
if (meta && key === 'z') {
|
|
199
|
-
event.preventDefault()
|
|
200
|
-
if (event.shiftKey) this.redo()
|
|
201
|
-
else this.undo()
|
|
202
|
-
return
|
|
203
|
-
}
|
|
204
|
-
if (meta && key === 'y') {
|
|
205
|
-
event.preventDefault()
|
|
206
|
-
this.redo()
|
|
207
|
-
return
|
|
208
|
-
}
|
|
209
|
-
if (meta && ['b', 'i', 'u'].includes(key)) {
|
|
210
|
-
event.preventDefault()
|
|
211
|
-
this.commands.toggleMark({ b: 'bold', i: 'italic', u: 'underline' }[key])
|
|
212
|
-
this.refresh()
|
|
213
|
-
return
|
|
214
|
-
}
|
|
215
|
-
if (meta && event.shiftKey && key === 'k') {
|
|
216
|
-
event.preventDefault()
|
|
217
|
-
this.toggleSource()
|
|
218
|
-
return
|
|
219
|
-
}
|
|
220
|
-
if (meta && key === 'k') {
|
|
221
|
-
event.preventDefault()
|
|
222
|
-
this.toolbar.openLink()
|
|
223
|
-
return
|
|
224
|
-
}
|
|
225
|
-
if (meta && key === 's') {
|
|
226
|
-
event.preventDefault()
|
|
227
|
-
this.emit('save', { html: this.getHTML() })
|
|
228
|
-
return
|
|
229
|
-
}
|
|
230
|
-
if (event.key === 'Escape') {
|
|
231
|
-
this.popover.close()
|
|
232
|
-
this.bubble.hide()
|
|
233
|
-
if (this.previewMode) this.closePreview()
|
|
234
|
-
return
|
|
235
|
-
}
|
|
236
|
-
if (event.key === 'Backspace' || event.key === 'Delete') {
|
|
237
|
-
const selected = this.bubble.node
|
|
238
|
-
if (selected) {
|
|
239
|
-
event.preventDefault()
|
|
240
|
-
this.bubble.remove()
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
handleContentClick(event) {
|
|
246
|
-
const media = event.target.closest('[data-k-media]')
|
|
247
|
-
if (media && this.root.contains(media)) {
|
|
248
|
-
this.selectMedia(media)
|
|
249
|
-
return
|
|
250
|
-
}
|
|
251
|
-
this.clearMediaSelection()
|
|
252
|
-
this.bubble.hide()
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
selectMedia(node) {
|
|
256
|
-
this.clearMediaSelection()
|
|
257
|
-
node.classList.add('ke-is-selected-media')
|
|
258
|
-
this.bubble.show(node)
|
|
259
|
-
// 图片是 contenteditable=false,点击不触发 selectionchange,需手动刷新工具栏高亮
|
|
260
|
-
this.refreshStatus()
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
clearMediaSelection() {
|
|
264
|
-
this.root.querySelectorAll('.ke-is-selected-media').forEach((n) => n.classList.remove('ke-is-selected-media'))
|
|
265
|
-
this.bubble.hide()
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
syncBubble() {
|
|
269
|
-
if (!this.bubble.node || !this.root.contains(this.bubble.node)) this.bubble.hide()
|
|
270
|
-
else this.bubble.position()
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/* ------------------------------ 状态 ------------------------------ */
|
|
274
|
-
|
|
275
|
-
getState() {
|
|
276
|
-
const range = getRange(this.root)
|
|
277
|
-
const block = closestBlock(range?.commonAncestorContainer || this.root, this.root)
|
|
278
|
-
const anchor = range ? findAnchor(range, this.root) : null
|
|
279
|
-
// 选中图片时,工具栏对齐按钮反映图片自身的对齐(margin auto),而非所在段落
|
|
280
|
-
const media = this.bubble?.node
|
|
281
|
-
const mediaImg = media && media.dataset?.kMedia === 'image' ? media.querySelector('img') : null
|
|
282
|
-
const align = mediaImg ? getMediaAlign(mediaImg) : currentAlign(range, block)
|
|
283
|
-
return {
|
|
284
|
-
bold: this.queryState('bold'),
|
|
285
|
-
italic: this.queryState('italic'),
|
|
286
|
-
underline: this.queryState('underline'),
|
|
287
|
-
strikeThrough: this.queryState('strikeThrough'),
|
|
288
|
-
ul: this.queryState('insertUnorderedList'),
|
|
289
|
-
ol: this.queryState('insertOrderedList'),
|
|
290
|
-
align,
|
|
291
|
-
block: block?.tagName?.toLowerCase() || 'p',
|
|
292
|
-
fontSize: this.commands.currentFontSize(),
|
|
293
|
-
linkUrl: anchor ? anchor.getAttribute('href') : '',
|
|
294
|
-
linkTarget: anchor ? anchor.getAttribute('target') === '_blank' : false,
|
|
295
|
-
selectionText: range ? range.toString() : '',
|
|
296
|
-
canUndo: this.history.canUndo(),
|
|
297
|
-
canRedo: this.history.canRedo(),
|
|
298
|
-
source: this.sourceMode,
|
|
299
|
-
preview: this.previewMode,
|
|
300
|
-
fullscreen: this.fullscreen,
|
|
301
|
-
readOnly: this.readOnly,
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
queryState(command) {
|
|
306
|
-
if (!this.root.contains(window.getSelection()?.anchorNode || null)) return false
|
|
307
|
-
try {
|
|
308
|
-
return document.queryCommandState(command)
|
|
309
|
-
} catch {
|
|
310
|
-
return false
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
refresh() {
|
|
315
|
-
if (this.destroyed) return
|
|
316
|
-
try {
|
|
317
|
-
this.toolbar.refresh(this.getState())
|
|
318
|
-
} catch {
|
|
319
|
-
/* 忽略状态刷新异常 */
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
refreshStatus() {
|
|
324
|
-
const api = this.statusApi
|
|
325
|
-
if (api) api.update(this.counts())
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
counts() {
|
|
329
|
-
const text = toPlainText(this.root.innerHTML)
|
|
330
|
-
return {
|
|
331
|
-
chars: text.replace(/\s/g, '').length,
|
|
332
|
-
words: countWords(text),
|
|
333
|
-
images: this.root.querySelectorAll('img').length,
|
|
334
|
-
videos: this.root.querySelectorAll('[data-k-media="video"] video, video').length,
|
|
335
|
-
uploading: this.media ? this.media.tasks.size : 0,
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
togglePlaceholder() {
|
|
340
|
-
const empty = !this.root.textContent.trim() && !this.root.querySelector('img,video,hr,table,iframe')
|
|
341
|
-
this.root.classList.toggle('ke-is-empty', empty)
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
enforceMaxLength() {
|
|
345
|
-
const max = this.options.maxLength
|
|
346
|
-
if (!max) return
|
|
347
|
-
const { chars } = this.counts()
|
|
348
|
-
if (chars > max) {
|
|
349
|
-
this.toast.warn(`已超过建议字数 ${max}`)
|
|
350
|
-
this.statusEl?.classList.add('ke-is-over')
|
|
351
|
-
} else {
|
|
352
|
-
this.statusEl?.classList.remove('ke-is-over')
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/* ------------------------------ 内容 API ------------------------------ */
|
|
357
|
-
|
|
358
|
-
getHTML({ clean = true } = {}) {
|
|
359
|
-
const html = this.root.innerHTML
|
|
360
|
-
if (!clean) return html
|
|
361
|
-
return exportHtml(html)
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
getText() {
|
|
365
|
-
return toPlainText(this.root.innerHTML)
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
getJSON() {
|
|
369
|
-
return { html: this.getHTML(), text: this.getText(), counts: this.counts() }
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
setContent(html, { sanitize = this.options.sanitize, silent = false } = {}) {
|
|
373
|
-
const value = sanitizeHtml(html || '<p><br></p>', { allowEmpty: true })
|
|
374
|
-
this.root.innerHTML = value || '<p><br></p>'
|
|
375
|
-
this.afterEdit({ silent })
|
|
376
|
-
if (!silent) this.history.snapshot(true)
|
|
377
|
-
this.togglePlaceholder()
|
|
378
|
-
return this
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
appendHTML(html) {
|
|
382
|
-
const range = document.createRange()
|
|
383
|
-
range.selectNodeContents(this.root)
|
|
384
|
-
range.collapse(false)
|
|
385
|
-
const sel = window.getSelection()
|
|
386
|
-
sel.removeAllRanges()
|
|
387
|
-
sel.addRange(range)
|
|
388
|
-
this.commands.insertHTML(html)
|
|
389
|
-
return this
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
clear() {
|
|
393
|
-
this.media.cancelAll()
|
|
394
|
-
this.setContent('<p><br></p>')
|
|
395
|
-
this.focus()
|
|
396
|
-
return this
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
afterEdit({ silent = false } = {}) {
|
|
400
|
-
this.history.snapshot()
|
|
401
|
-
this.refreshStatus()
|
|
402
|
-
this.togglePlaceholder()
|
|
403
|
-
if (!silent) this.emitChange()
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
commitHistory() {
|
|
407
|
-
this.history.snapshot(true)
|
|
408
|
-
this.refreshStatus()
|
|
409
|
-
this.emitChange()
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
emitChange() {
|
|
413
|
-
this.emit('change', { html: this.getHTML(), text: this.getText() })
|
|
414
|
-
this.options.onChange?.(this.getHTML(), this)
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
focus() {
|
|
418
|
-
if (this.readOnly || this.sourceMode) {
|
|
419
|
-
if (this.sourceMode) this.source.code.focus()
|
|
420
|
-
return this
|
|
421
|
-
}
|
|
422
|
-
this.root.focus()
|
|
423
|
-
const sel = window.getSelection()
|
|
424
|
-
if (!sel || sel.rangeCount === 0 || !this.root.contains(sel.anchorNode)) {
|
|
425
|
-
const range = document.createRange()
|
|
426
|
-
const first = this.root.firstElementChild || this.root
|
|
427
|
-
range.selectNodeContents(first)
|
|
428
|
-
range.collapse(false)
|
|
429
|
-
sel.removeAllRanges()
|
|
430
|
-
sel.addRange(range)
|
|
431
|
-
}
|
|
432
|
-
return this
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
blur() {
|
|
436
|
-
this.root.blur()
|
|
437
|
-
return this
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
/** 打开面板前记录选区(面板内的输入框会抢走焦点) */
|
|
441
|
-
saveSelection() {
|
|
442
|
-
const range = getRange(this.root)
|
|
443
|
-
this.savedRange = range ? range.cloneRange() : null
|
|
444
|
-
return this
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
/** 执行面板动作前还原选区,无有效选区时退化为 focus() 的兜底 */
|
|
448
|
-
restoreSelection() {
|
|
449
|
-
this.root.focus()
|
|
450
|
-
const sel = window.getSelection()
|
|
451
|
-
if (this.savedRange && this.root.contains(this.savedRange.startContainer) && this.root.contains(this.savedRange.endContainer)) {
|
|
452
|
-
sel.removeAllRanges()
|
|
453
|
-
sel.addRange(this.savedRange)
|
|
454
|
-
return this
|
|
455
|
-
}
|
|
456
|
-
return this.focus()
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
setReadOnly(value) {
|
|
460
|
-
this.readOnly = !!value
|
|
461
|
-
this.root.setAttribute('contenteditable', this.readOnly ? 'false' : 'true')
|
|
462
|
-
this.el.classList.toggle('ke-is-readonly', this.readOnly)
|
|
463
|
-
this.refresh()
|
|
464
|
-
return this
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
undo() {
|
|
468
|
-
this.history.flush()
|
|
469
|
-
if (!this.history.undo()) {
|
|
470
|
-
this.toast.show('没有可撤销的操作')
|
|
471
|
-
return this
|
|
472
|
-
}
|
|
473
|
-
this.afterEdit({ silent: false })
|
|
474
|
-
this.refresh()
|
|
475
|
-
return this
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
redo() {
|
|
479
|
-
if (!this.history.redo()) {
|
|
480
|
-
this.toast.show('没有可重做的操作')
|
|
481
|
-
return this
|
|
482
|
-
}
|
|
483
|
-
this.afterEdit()
|
|
484
|
-
this.refresh()
|
|
485
|
-
return this
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
/* ------------------------------ 媒体快捷入口 ------------------------------ */
|
|
489
|
-
|
|
490
|
-
/** 上传任意文件(自动识别图片/视频),等价于点击工具栏上传 */
|
|
491
|
-
upload(file, kind = this.media.kindOf(file)) {
|
|
492
|
-
if (!kind) throw new Error('[KEditor] 不支持的文件类型')
|
|
493
|
-
return this.media.upload(file, kind)
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
/** 以 URL 插入图片 */
|
|
497
|
-
insertImage(url, alt = '') {
|
|
498
|
-
return this.media.insertImageUrl(url, alt)
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
/** 以 URL 插入视频 */
|
|
502
|
-
insertVideo(url, label = '视频') {
|
|
503
|
-
return this.media.insertVideoUrl(url, label)
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
/** 取消全部进行中的上传 */
|
|
507
|
-
cancelUploads() {
|
|
508
|
-
this.media.cancelAll()
|
|
509
|
-
return this
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
/* ------------------------------ 面板 ------------------------------ */
|
|
513
|
-
|
|
514
|
-
toggleSource() {
|
|
515
|
-
if (this.sourceMode) this.exitSource()
|
|
516
|
-
else this.enterSource()
|
|
517
|
-
return this.sourceMode
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
enterSource() {
|
|
521
|
-
if (this.sourceMode) return
|
|
522
|
-
this.history.flush()
|
|
523
|
-
this.sourceMode = true
|
|
524
|
-
this.el.classList.add('ke-is-source')
|
|
525
|
-
this.clearMediaSelection()
|
|
526
|
-
this.source.show(this.getHTML({ clean: true }))
|
|
527
|
-
this.previewPanel.hide()
|
|
528
|
-
this.previewMode = false
|
|
529
|
-
this.refresh()
|
|
530
|
-
this.emit('sourcechange', { mode: 'source' })
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
exitSource() {
|
|
534
|
-
if (!this.sourceMode) return
|
|
535
|
-
this.source.apply({ silent: true })
|
|
536
|
-
this.sourceMode = false
|
|
537
|
-
this.el.classList.remove('ke-is-source')
|
|
538
|
-
this.source.hide()
|
|
539
|
-
this.focus()
|
|
540
|
-
this.refresh()
|
|
541
|
-
this.emit('sourcechange', { mode: 'visual' })
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
togglePreview() {
|
|
545
|
-
if (this.previewMode) this.closePreview()
|
|
546
|
-
else this.openPreview()
|
|
547
|
-
return this.previewMode
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
openPreview() {
|
|
551
|
-
this.previewMode = true
|
|
552
|
-
this.previewPanel.show(previewHtml(this.getHTML()))
|
|
553
|
-
this.refresh()
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
closePreview() {
|
|
557
|
-
this.previewMode = false
|
|
558
|
-
this.previewPanel.hide()
|
|
559
|
-
this.refresh()
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
toggleFullscreen() {
|
|
563
|
-
this.fullscreen = !this.fullscreen
|
|
564
|
-
this.el.classList.toggle('ke-is-fullscreen', this.fullscreen)
|
|
565
|
-
document.body.style.overflow = this.fullscreen ? 'hidden' : ''
|
|
566
|
-
this.refresh()
|
|
567
|
-
return this.fullscreen
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
/* ------------------------------ 事件总线 ------------------------------ */
|
|
571
|
-
|
|
572
|
-
/** 订阅编辑器事件:ready / change / focus / blur / save / uploadstart / uploaddone / uploaderror / uploadcancel / sourcechange */
|
|
573
|
-
on(type, handler) {
|
|
574
|
-
return this.addListener(type, handler)
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
off(type, handler) {
|
|
578
|
-
return this.removeListener(type, handler)
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
emit(type, payload = {}) {
|
|
582
|
-
const list = this.emitters.get(type) || []
|
|
583
|
-
for (const handler of list) {
|
|
584
|
-
try {
|
|
585
|
-
handler(payload)
|
|
586
|
-
} catch (error) {
|
|
587
|
-
this.options.onError?.(error)
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
if (type.startsWith('upload')) this.options.onUpload?.({ stage: type, ...payload })
|
|
591
|
-
return this
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
addListener(type, handler) {
|
|
595
|
-
if (!this.emitters.has(type)) this.emitters.set(type, [])
|
|
596
|
-
this.emitters.get(type).push(handler)
|
|
597
|
-
return () => this.removeListener(type, handler)
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
removeListener(type, handler) {
|
|
601
|
-
const list = this.emitters.get(type) || []
|
|
602
|
-
const idx = list.indexOf(handler)
|
|
603
|
-
if (idx >= 0) list.splice(idx, 1)
|
|
604
|
-
return this
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
/* 兼容别名 */
|
|
608
|
-
get element() {
|
|
609
|
-
return this.root
|
|
610
|
-
}
|
|
611
|
-
|
|
612
|
-
get editorElement() {
|
|
613
|
-
return this.el
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
destroy() {
|
|
617
|
-
if (this.destroyed) return
|
|
618
|
-
this.destroyed = true
|
|
619
|
-
this.media.destroy()
|
|
620
|
-
this.history.destroy()
|
|
621
|
-
this.popover.destroy()
|
|
622
|
-
this.source.destroy()
|
|
623
|
-
this.previewPanel.destroy()
|
|
624
|
-
this.bubble.destroy()
|
|
625
|
-
this.toolbar.destroy()
|
|
626
|
-
this.toast.destroy()
|
|
627
|
-
for (const { node, type, handler } of this.domListeners) node.removeEventListener(type, handler)
|
|
628
|
-
document.removeEventListener('selectionchange', this.selectionHandler)
|
|
629
|
-
this.scrollEl.removeEventListener('scroll', this.scrollHandler)
|
|
630
|
-
window.removeEventListener('resize', this.scrollHandler)
|
|
631
|
-
if (this.fullscreen) document.body.style.overflow = ''
|
|
632
|
-
this.el.innerHTML = ''
|
|
633
|
-
this.el.classList.remove('ke', 'ke-is-fullscreen', 'ke-is-readonly')
|
|
634
|
-
this.el.removeAttribute('style')
|
|
635
|
-
this.emitters.clear()
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
/** 便捷静态方法 */
|
|
639
|
-
static create(target, options) {
|
|
640
|
-
return new KEditor(target, options)
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
/* ------------------------------ helpers ------------------------------ */
|
|
645
|
-
|
|
646
|
-
function createMedia(editor) {
|
|
647
|
-
const manager = new MediaManager(editor)
|
|
648
|
-
const originalUpload = manager.upload.bind(manager)
|
|
649
|
-
manager.upload = async (file, kind) => {
|
|
650
|
-
const hook = editor.options.beforeUpload
|
|
651
|
-
let target = file
|
|
652
|
-
if (hook) {
|
|
653
|
-
target = await hook(file, kind)
|
|
654
|
-
if (target === false) return null
|
|
655
|
-
}
|
|
656
|
-
return originalUpload(target, kind)
|
|
657
|
-
}
|
|
658
|
-
/** 替换已有媒体节点(气泡工具条「替换」用) */
|
|
659
|
-
manager.replaceNode = async (node, file) => {
|
|
660
|
-
const kind = node.dataset.kMedia === 'video' ? 'video' : 'image'
|
|
661
|
-
const range = document.createRange()
|
|
662
|
-
range.setStartBefore(node)
|
|
663
|
-
range.collapse(true)
|
|
664
|
-
const sel = window.getSelection()
|
|
665
|
-
sel.removeAllRanges()
|
|
666
|
-
sel.addRange(range)
|
|
667
|
-
const result = await manager.upload(file, kind)
|
|
668
|
-
node.remove()
|
|
669
|
-
editor.commitHistory()
|
|
670
|
-
return result
|
|
671
|
-
}
|
|
672
|
-
return manager
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
function resolveTarget(target, id) {
|
|
676
|
-
if (typeof target === 'string') {
|
|
677
|
-
const el = document.querySelector(target)
|
|
678
|
-
if (!el) throw new Error(`[KEditor] 找不到挂载节点:${target}`)
|
|
679
|
-
return el
|
|
680
|
-
}
|
|
681
|
-
if (target instanceof HTMLElement) return target
|
|
682
|
-
if (target?.$el instanceof HTMLElement) return target.$el
|
|
683
|
-
throw new Error(`[KEditor] 无效的挂载目标(${typeof target})`)
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
function mergeOptions(options) {
|
|
687
|
-
const out = { ...defaults, ...options }
|
|
688
|
-
out.image = { ...defaults.image, ...(options.image || {}) }
|
|
689
|
-
out.paste = { ...defaults.paste, ...(options.paste || {}) }
|
|
690
|
-
out.upload = { ...defaults.upload, ...(options.upload || {}) }
|
|
691
|
-
if (Array.isArray(options.toolbar)) out.toolbar = options.toolbar
|
|
692
|
-
if (options.toolbar === false) out.toolbar = []
|
|
693
|
-
if (options.toolbar === true) out.toolbar = DEFAULT_TOOLBAR
|
|
694
|
-
out.height = clamp(out.height ?? 460, 0, 4000)
|
|
695
|
-
return out
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
function buildStatusbar(editor) {
|
|
699
|
-
const chars = h('b', { text: '0' })
|
|
700
|
-
const words = h('b', { text: '0' })
|
|
701
|
-
const images = h('b', { text: '0' })
|
|
702
|
-
const videos = h('b', { text: '0' })
|
|
703
|
-
const chip = h('span.ke-chip', { hidden: true })
|
|
704
|
-
const hint = h('span.ke-status-hint', { text: '支持拖拽 / 粘贴上传,Ctrl/⌘ + S 保存' })
|
|
705
|
-
const tail = h('span.ke-status-tail')
|
|
706
|
-
const el = h(
|
|
707
|
-
'div.ke-status',
|
|
708
|
-
{},
|
|
709
|
-
[
|
|
710
|
-
h('span', {}, ['字数 ', chars, ' · ', words, ' 词']),
|
|
711
|
-
h('span', {}, ['图片 ', images, ' · 视频 ', videos]),
|
|
712
|
-
chip,
|
|
713
|
-
hint,
|
|
714
|
-
tail,
|
|
715
|
-
],
|
|
716
|
-
)
|
|
717
|
-
const api = {
|
|
718
|
-
update: (counts) => {
|
|
719
|
-
chars.textContent = String(counts.chars)
|
|
720
|
-
words.textContent = String(counts.words)
|
|
721
|
-
images.textContent = String(counts.images)
|
|
722
|
-
videos.textContent = String(counts.videos)
|
|
723
|
-
if (counts.uploading > 0) {
|
|
724
|
-
chip.hidden = false
|
|
725
|
-
chip.className = 'ke-chip ke-is-busy'
|
|
726
|
-
chip.textContent = `${counts.uploading} 个上传进行中`
|
|
727
|
-
} else {
|
|
728
|
-
chip.hidden = true
|
|
729
|
-
}
|
|
730
|
-
},
|
|
731
|
-
addExtra: (node) => tail.appendChild(node),
|
|
732
|
-
}
|
|
733
|
-
editor.statusApi = api
|
|
734
|
-
if (!editor.options.wordCount) el.style.display = 'none'
|
|
735
|
-
return el
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
function findAnchor(range, root) {
|
|
739
|
-
let node = range?.commonAncestorContainer
|
|
740
|
-
if (!node || !root.contains(node)) return null
|
|
741
|
-
if (node.nodeType === 3) node = node.parentElement
|
|
742
|
-
const anchor = node?.closest?.('a')
|
|
743
|
-
return anchor && root.contains(anchor) ? anchor : null
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
function currentAlign(range, block) {
|
|
747
|
-
const node = block || range?.commonAncestorContainer
|
|
748
|
-
const styles = [node, node?.parentElement].filter((n) => n && n.nodeType === 1)
|
|
749
|
-
for (const el of styles) {
|
|
750
|
-
const align = el.style?.textAlign
|
|
751
|
-
if (align) return align === '-webkit-justify' ? 'justify' : align
|
|
752
|
-
const cs = el.getAttribute?.('align')
|
|
753
|
-
if (cs) return cs
|
|
754
|
-
}
|
|
755
|
-
try {
|
|
756
|
-
if (document.queryCommandState('justifyCenter')) return 'center'
|
|
757
|
-
if (document.queryCommandState('justifyRight')) return 'right'
|
|
758
|
-
if (document.queryCommandState('justifyFull')) return 'justify'
|
|
759
|
-
} catch {
|
|
760
|
-
/* ignore */
|
|
761
|
-
}
|
|
762
|
-
return 'left'
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
function countWords(text) {
|
|
766
|
-
const cjk = (text.match(/[\u4e00-\u9fa5\u3040-\u30ff]/g) || []).length
|
|
767
|
-
const latin = (text.match(/[a-zA-Z0-9'’-]+/g) || []).length
|
|
768
|
-
return cjk + latin
|
|
769
|
-
}
|
|
770
|
-
|
|
771
|
-
/** 导出用净化:去掉编辑器内部属性,保留业务可读的结构与样式 */
|
|
772
|
-
export function exportHtml(html) {
|
|
773
|
-
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, 'text/html')
|
|
774
|
-
const root = doc.body.firstChild
|
|
775
|
-
root.querySelectorAll('[contenteditable]').forEach((n) => n.removeAttribute('contenteditable'))
|
|
776
|
-
root.querySelectorAll('[data-k-id]').forEach((n) => n.removeAttribute('data-k-id'))
|
|
777
|
-
root.querySelectorAll('[data-k-state]').forEach((n) => n.removeAttribute('data-k-state'))
|
|
778
|
-
root.querySelectorAll('[data-ke-marker]').forEach((n) => n.removeAttribute('data-ke-marker'))
|
|
779
|
-
root.querySelectorAll('[data-placeholder]').forEach((n) => n.removeAttribute('data-placeholder'))
|
|
780
|
-
root.querySelectorAll('.ke-is-selected-media').forEach((n) => n.classList.remove('ke-is-selected-media'))
|
|
781
|
-
// 上传中的占位块不进入导出结果
|
|
782
|
-
root.querySelectorAll('[data-k-state="uploading"], [data-k-state="error"]').forEach((n) => n.remove())
|
|
783
|
-
return root.innerHTML.trim()
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
/** 预览用:把内部占位/属性转成静态展示结构 */
|
|
787
|
-
function previewHtml(html) {
|
|
788
|
-
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, 'text/html')
|
|
789
|
-
const root = doc.body.firstChild
|
|
790
|
-
root.querySelectorAll('[data-k-media]').forEach((n) => {
|
|
791
|
-
n.removeAttribute('data-k-media')
|
|
792
|
-
n.removeAttribute('data-k-url')
|
|
793
|
-
})
|
|
794
|
-
return root.innerHTML
|
|
795
|
-
}
|