forked from opentiny/tiny-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorigin.html
710 lines (681 loc) · 24.4 KB
/
origin.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>FluentEditor Demo</title>
</head>
<body>
<link href="./dist/style.css" rel="stylesheet" />
<!-- Create the editor container -->
<div id="editor">
<p>Hello World!</p>
<p>富文本编辑器</p>
</div>
<script type="module">
import FluentEditor from '/dist/index.es.js'
// console.log('FluentEditor:', FluentEditor.imports)
const SizeStyle = FluentEditor.imports['formats/size'] // 文字大小
const FontClass = FluentEditor.imports['formats/font'] // 文字字体
const lineheight = FluentEditor.imports['formats/lineheight'] // 行高
const Range = FluentEditor.imports['core/selection/range'];
// 工具栏显示的按钮总览
const container = [
['undo', 'redo', 'clean'],
[
{ font: FontClass.whitelist },
{ size: SizeStyle.whitelist },
{ lineheight: lineheight.whitelist },
{ header: [1, 2, 3, 4, 5, 6, false] },
],
['bold', 'italic', 'underline', 'strike'],
['blockquote', 'code-block'],
[{ header: 1 }, { header: 2 }],
[{ list: 'ordered' }, { list: 'bullet' }],
[{ script: 'sub' }, { script: 'super' }],
[{ indent: '-1' }, { indent: '+1' }],
[{ direction: 'rtl' }],
[{ color: [] }, { background: [] }],
[{ align: [] }],
['link', 'image', 'video', 'file'],
['better-table'],
]
// @提醒
const mentionObj = {
data: [
{
name: 'Jack',
age: 26,
cn: 'Jack杰克',
},
{
name: 'Lucy',
age: 22,
cn: 'Lucy露西',
},
],
searchKey: 'name',
}
// 图片:导入\custom-image\Options.ts DefaultOptions默认参数,也可以自定义对象
const CustomImageSpec = FluentEditor.imports['modules/image-spec']
// 表格
const BetterTable = FluentEditor.imports['modules/better-table']
const modules = {
file: true, // 上传文件需开启
image: {
specs: [CustomImageSpec],
},
// counter: true, // 字符计数器,两种配置方式都可以
counter: {
format: 'html',
count: 102400, // 默认500
errorTemplate:
'<span style="color:red">字数不能超过102400个字符</span>',
},
toolbar: {
container,
handlers: {
undo: function () {
// 如果当前有表格被激活则清除表格工具条
const betterTableModule = EDITOR.getModule('better-table')
if (betterTableModule.table) {
betterTableModule.hideTableTools()
}
EDITOR.history.undo()
},
redo: function () {
// 如果当前有表格被激活则清除表格工具条
const betterTableModule = EDITOR.getModule('better-table')
if (betterTableModule.table) {
betterTableModule.hideTableTools()
}
EDITOR.history.redo()
},
lineheight: function (value) {
EDITOR.format('lineheight', value, FluentEditor.sources.USER)
},
file: function () {
const option = EDITOR.options.uploadOption
const accept = option && option.fileAccept
inputFile.call(this, 'file', accept)
},
image: function () {
const option = EDITOR.options.uploadOption
const accept = option && option.imageAccept
inputFile.call(this, 'image', accept)
},
link: function (value) {
const range = this.quill.getSelection();
const { tooltip } = this.quill.theme;
const insertDefaultLink = () => {
const linkPlaceholder = '链接';
this.quill.insertText(range.index, linkPlaceholder, FluentEditor.sources.USER);
this.quill.setSelection(range.index, linkPlaceholder.length, FluentEditor.sources.USER);
const newRange = this.quill.getSelection();
if (newRange) {
// 初次生成blot时,如果值为空,不会走blot的create()方法
this.quill.formatText(newRange, 'link', ' ', FluentEditor.sources.USER);
this.quill.formatText(newRange, 'link', '', FluentEditor.sources.USER);
tooltip.edit('link', '', newRange);
}
};
if (value) {
if (isNullOrUndefined(range) || range.length === 0) {
// 直接插入超链接
insertDefaultLink();
} else {
// 选中文本插入超链接
this.quill.formatText(range, 'link', ' ', Emitter.sources.USER);
this.quill.formatText(range, 'link', '', Emitter.sources.USER);
tooltip.edit('link', '', range);
}
} else {
const [link, offset] = this.quill.scroll.descendant(LinkBlot, range.index);
if (isNullOrUndefined(link)) {
// 在超链接后面插入超链接
insertDefaultLink();
} else {
// 取消超链接
const fullRange = new Range(range.index - offset, link.length());
this.quill.formatText(fullRange, 'link', false, FluentEditor.sources.USER);
}
}
},
},
},
'better-table': {
operationMenu: {
items: {
copyCells: {
text: '复制',
},
copyTable: {
text: '复制表格',
},
emptyCells: {
text: '清空内容',
},
insertRowUp: {
text: '上插入行',
},
insertRowDown: {
text: '下插入行',
},
insertColumnLeft: {
text: '左插入列',
},
insertColumnRight: {
text: '右插入列',
},
mergeCells: {
text: '合并单元格',
},
unmergeCells: {
text: '拆分单元格',
},
deleteRow: {
text: '删除当前行',
},
deleteColumn: {
text: '删除当前列',
},
deleteTable: {
text: '删除表格',
},
},
color: true,
},
},
mention: {
search: async term => {
const { data, searchKey } = mentionObj
try {
return data.filter(d => {
return d[searchKey] && String(d[searchKey]).includes(term)
})
} catch (e) {
console.warn(e)
return []
}
},
},
keyboard: {
bindings: {
...BetterTable.keyboardBindings,
'list autofill': {
key: ' ',
shiftKey: null,
collapsed: true,
format: {
list: false,
'code-block': false,
blockquote: false,
header: false,
table: true,
},
prefix: /^\s*?(\d+\.|-|\*|\[ ?\]|\[x\])$/,
handler(range, context) {
const formats = EDITOR.getFormat(range)
if (formats['table-cell-line']) {
return true
}
if (isNullOrUndefined(EDITOR.scroll.query('list'))) {
return true
}
const { length } = context.prefix
const [line, offset] = EDITOR.getLine(range.index)
if (offset > length) {
return true
}
let value
switch (context.prefix.trim()) {
case '[]':
case '[ ]':
value = 'unchecked'
break
case '[x]':
value = 'checked'
break
case '-':
case '*':
value = 'bullet'
break
default:
value = 'ordered'
}
EDITOR.insertText(range.index, ' ', FluentEditor.sources.USER)
EDITOR.history.cutoff()
const delta = new Delta()
.retain(range.index - offset)
.delete(length + 1)
.retain(line.length() - 2 - offset)
.retain(1, { list: { value: value } })
EDITOR.updateContents(delta, FluentEditor.sources.USER)
EDITOR.history.cutoff()
EDITOR.setSelection(
range.index - length,
FluentEditor.sources.SILENT,
)
return false
},
},
// fix:在list的offset为0时(即只在最左侧触发)加键盘事件,使其跳过contenteditable=false的span进行移动
'list ignoreRight': {
key: 'ArrowRight',
shiftKey: null,
format: ['list'],
collapsed: true,
offset: 0,
handler(range) {
EDITOR.setSelection(
range.index + 1,
FluentEditor.sources.SILENT,
)
},
},
'list ignoreLeft': {
key: 'ArrowLeft',
shiftKey: null,
format: ['list'],
collapsed: true,
offset: 0,
handler(range) {
EDITOR.setSelection(
range.index - 1,
FluentEditor.sources.SILENT,
)
},
},
'list softBreak': {
key: 'Enter',
format: ['list'],
shiftKey: true,
collapsed: true,
handler(range) {
const [line, offset] = EDITOR.getLine(range.index)
const length = line.length()
// li的末尾不能添加软回车
if (length > offset + 1) {
EDITOR.insertEmbed(
range.index,
'soft-break',
true,
FluentEditor.sources.USER,
)
}
},
},
},
},
}
// 上传:图片、视频和文件
const { DEFAULTS: UploaderDfls } = FluentEditor.imports['modules/uploader']
UploaderDfls.enableMultiUpload = { file: true, image: false }
UploaderDfls.handler = (range, files, fileFlags, rejectFlags) => {
const fileArr = []
const imgArr = []
files.forEach((file, index) =>
fileFlags[index] ? fileArr.push(file) : imgArr.push(file),
)
if (modules.file && (fileArr.length || rejectFlags.file)) {
handleUploadFile(range, fileArr, rejectFlags.file)
}
if (imgArr.length || rejectFlags.image) {
handleUploadImage(
range,
{ file: imgArr[0], files: imgArr },
rejectFlags.image,
)
}
}
// 构建一个富文本框的实例,以方便我们的操作
var EDITOR = new FluentEditor('#editor', {
theme: 'snow',
modules,
// 上传:图片、视频和文件,相关配置
uploadOption: {
fileAccept: '.mp4,.xls,.doc,.docx,.ppt,.pptx',
imageAccept: '.gif,.png,.tiff,image/jpeg',
isVideoPlay: true,
imageUploadToServer: false, // 是否需要上传到服务器
},
})
// 点击工具栏插入表格 ql-better-table
var insertButton = document.querySelector('.ql-better-table')
const tableModule = EDITOR.getModule('better-table')
EDITOR.emitter.on(
'file-change',
fileOperationToSev
);
var insertTableHandler = function (event, row = 3, col = 3) {
tableModule.insertTable(row, col)
}
insertButton.addEventListener('click', insertTableHandler)
// 上传:图片、视频和文件,相关配置
// 触发上传
function inputFile(type, accept) {
const defaultMIMETypes = EDITOR.uploader.options[type].join(', ')
const mimeTypes = accept || defaultMIMETypes
let fileInput = this.container.querySelector(
`input.ql-${type}[type=file]`,
)
if (isNullOrUndefined(fileInput)) {
fileInput = document.createElement('input')
fileInput.classList.add(`ql-${type}`)
fileInput.setAttribute('type', 'file')
fileInput.setAttribute('style','display:none');
fileInput.setAttribute('accept', mimeTypes)
if (
UploaderDfls.enableMultiUpload === true ||
(UploaderDfls.enableMultiUpload['file'] && type === 'file') ||
(UploaderDfls.enableMultiUpload['image'] && type === 'image')
) {
fileInput.setAttribute('multiple', '')
}
fileInput.addEventListener('change', () => {
const range = EDITOR.getSelection(true)
EDITOR.uploader.upload(range, fileInput.files, type === 'file')
fileInput.value = ''
})
this.container.appendChild(fileInput)
}
fileInput.click()
}
function isNullOrUndefined(param) {
return param === null || param === undefined
}
const Delta = FluentEditor.imports['delta']
const popoverComponentRef = []
// 处理上传图片
function handleUploadImage(range, { file, files }, hasRejectedImage) {
if (EDITOR.options.uploadOption.imageUploadToServer) {
const imageEnableMultiUpload =
UploaderDfls.enableMultiUpload === true ||
UploaderDfls.enableMultiUpload['image']
const target = document.querySelector('.ql-image')
if (files.length) {
// showUploadingTips('image', target)
console.log('showUploadingTips')
}
const result = {
file,
data: { files: [file] },
hasRejectedImage: hasRejectedImage,
callback: res => {
// closeUploadingTips('image')
console.log('closeUploadingTips')
if (!res) {
return
}
if (imageEnableMultiUpload && Array.isArray(res)) {
res.forEach(value => insertImageToEditor(range, value))
} else {
insertImageToEditor(range, res)
}
},
}
if (imageEnableMultiUpload) {
result['data'] = { files }
}
uploadImageToSev(result)
} else {
const promises = files.map(fileItem => {
return new Promise(resolve => {
const reader = new FileReader()
reader.onload = e => {
resolve(e.target.result)
}
reader.readAsDataURL(fileItem)
})
})
Promise.all(promises).then(images => {
const update = images.reduce((delta, image) => {
return delta.insert({ image })
}, new Delta().retain(range.index).delete(range.length))
EDITOR.updateContents(update, FluentEditor.sources.USER)
EDITOR.setSelection(
range.index + images.length,
FluentEditor.sources.SILENT,
)
})
}
}
// 处理上传文件
function handleUploadFile(range, files, hasRejectedFile) {
const fileEnableMultiUpload =
UploaderDfls.enableMultiUpload === true ||
UploaderDfls.enableMultiUpload['file']
const target = document.querySelector('.ql-file')
if (files.length) {
// showUploadingTips('files', target)
console.log('showUploadingTips')
}
fileOperationToSev({
operation: 'upload',
data: fileEnableMultiUpload ? { files } : { file: files[0] },
hasRejectedFile: hasRejectedFile,
callback: res => {
// this.closeUploadingTips('file')
console.log('closeUploadingTips')
if (!res) {
return
}
console.log('fileEnableMultiUpload')
console.log(fileEnableMultiUpload)
if (fileEnableMultiUpload && Array.isArray(res)) {
res.forEach((value, index) =>
insertFileToEditor(range, files[index], value),
)
} else {
insertFileToEditor(range, files[0], res)
}
},
})
}
// 图片上传到服务器,需要将示例中的上传接口替换成真实的后台接口才能正确运行。
function uploadImageToSev(event) {
const {
file,
hasRejectedImage,
data: { files},
callback,
} = event
if (hasRejectedImage) {
this.msgs = [
{
severity: 'error',
summary: '上传图片失败',
detail: `只支持上传以下类型:\n${EDITOR.options.uploadOption.imageAccept}`,
},
]
}
if (file || files) {
/* 使用时取消注释,填写您的上传接口 */
/* setTimeout用于模拟接口延迟,演示上传提示,使用时请移除 */
// const formData = new FormData()
// formData.append('file', file)
// this.http.post('url/to/your/api', formData).subscribe(res => {
let res
const imageUrl = './src/assets/image1.png' /* 后台返回的图片URL */
if (UploaderDfls.enableMultiUpload.image) {
res = files.map(fileItem => {
return {
code: 0,
message: 'Upload image successfully!',
data: { imageId: 100, imageUrl },
}
})
} else {
res = {
code: 0,
message: 'Upload image successfully!',
data: { imageId: 100, imageUrl },
}
}
setTimeout(() => callback(res), 500)
// })
}
}
// 文件上传到服务器,需要将示例中的上传接口替换成真实的后台接口才能正确运行。
function fileOperationToSev(event) {
const {
operation,
hasRejectedFile,
data: { fileId, file, files, fileDownloadUrl },
callback,
} = event
switch (operation) {
case 'upload':
if (hasRejectedFile) {
this.msgs = [
{
severity: 'error',
summary: '上传文件失败',
detail: `只支持上传以下类型:\n${EDITOR.options.uploadOption.fileAccept}`,
},
]
}
if (file || files) {
/* 使用时取消注释,填写您的上传接口 */
/* setTimeout用于模拟接口延迟,演示上传提示,使用时请移除 */
/* const formData = new FormData();
formData.append('file', file);
this.http.post('url/to/your/api', formData)
.subscribe(res => { */
let res
if (UploaderDfls.enableMultiUpload.file) {
res = files.map(fileItem => {
return {
code: 0,
message: 'Upload file successfully!',
data: {
id: 'faf40644468b497d90cbaf4304c39e1a',
title: fileItem.name,
size: fileItem.size,
lastModified: fileItem.lastModified,
src: 'http://www.baidu.com',
},
}
})
} else {
res = {
code: 0,
message: 'Upload file successfully!',
data: {
id: 'faf40644468b497d90cbaf4304c39e1a',
title: file.name,
size: file.size,
lastModified: file.lastModified,
src: '已上传视频地址',
},
}
}
setTimeout(() => callback(res), 500)
/* }); */
}
break
case 'download':
console.log('download file:' + fileId)
break
case 'delete':
this.http.post(fileDownloadUrl, { id: fileId })
break
}
}
// 将图片插入编辑器
function insertImageToEditor(range, { code, message, data }) {
if (code === 0) {
const { imageId, imageUrl } = data
// 粘贴截图或者从外源直接拷贝的单图时,需要将编辑器中已选中的内容删除
const oldContent = new Delta()
.retain(range.index)
.delete(range.length)
const currentContent = new Delta([
{
insert: { image: imageUrl },
attributes: { 'image-id': imageId },
},
])
const newContent = oldContent.concat(currentContent)
EDITOR.updateContents(newContent, FluentEditor.sources.USER)
} else {
console.error('error message:', message)
}
}
// 将文件插入编辑器
function insertFileToEditor(range, file, { code, message, data }) {
if (code === 0) {
const oldContent = new Delta()
.retain(range.index)
.delete(range.length)
const videoFlag =
EDITOR.options.uploadOption &&
EDITOR.options.uploadOption.isVideoPlay &&
/^video\/[-\w.]+$/.test(file.type)
const insertObj = videoFlag ? { video: data } : { file: data }
const currentContent = new Delta([{ insert: insertObj }])
const newContent = oldContent.concat(currentContent)
EDITOR.updateContents(newContent, FluentEditor.sources.USER)
} else {
console.error('error message:', message)
}
}
// 显示上传中提示
// function showUploadingTips(type, target) {
// popoverComponentRef[type] = this.overlayContainerRef.createComponent(
// this.componentFactoryResolver.resolveComponentFactory(
// PopoverComponent,
// ),
// )
// Object.assign(popoverComponentRef[type].instance, {
// content: LANG_CONF['uploading'],
// triggerElementRef: { nativeElement: target },
// position: 'top',
// popType: 'default',
// popMaxWidth: 200,
// appendToBody: true,
// zIndex: 1060,
// })
// }
// 移除上传中提示
// function closeUploadingTips(type) {
// if (popoverComponentRef[type]) {
// popoverComponentRef[type].destroy()
// }
// if (popoverComponentRef.length === 1) {
// popoverComponentRef = []
// }
// }
function onPaste({ files, callback }) {
const _this = this
function uploadImage(file) {
return new Promise((resolve, reject) => {
const formData = new FormData()
formData.append('file', file)
_this.http.post('url/to/your/api', formData).subscribe(res => {
const imageUrl = 'url/image.png' /* 后台返回的图片URL */
resolve(imageUrl)
})
})
}
;(async () => {
try {
const imageUrls = []
for (let i = 0; i < files.length; i++) {
imageUrls.push(await uploadImage(files[i]))
}
callback({
code: 0,
message: 'Upload all images successfully!',
data: {
imageUrls: imageUrls,
},
})
} catch (e) {
throw new Error('Upload failed.')
}
})()
}
</script>
</body>
</html>