huangyinfeng
6 天以前 a9a03d64cf190188d3db04d14970fc0908b03491
提交 | 用户 | age
00fe0e 1 <template>
H 2   <div :class="prefixCls" :style="{ width: containerWidth }">
3     <textarea
4       :id="tinymceId"
2c1249 5       ref="elPwRef"
00fe0e 6       :style="{ visibility: 'hidden' }"
H 7       v-if="!initOptions.inline"
8     ></textarea>
9     <slot v-else></slot>
ccfd07 10     <!-- <div class="p-2 tox-statusbar">
2c1249 11       <a-upload
H 12         v-if="isElse"
13         v-model:file-list="fileListTemp"
14         action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
15         list-type="picture"
16         class="upload-list-inline"
17       >
18         <a-button type="text" size="small" style="margin: 0 auto">
19           <upload-outlined></upload-outlined>
20           附件
21         </a-button>
22         <template #iconRender><PaperClipOutlined /></template>
23         <template #itemRender="{ file, fileList, actions }">
24           <a-space class="ant-upload-list-picture-card">
25             <span style="display: flex; flex-wrap: wrap">
26               <PaperClipOutlined style="margin-right: 4px" />
27               <span v-if="!file.editor" :style="file.status === 'error' ? 'color: red' : ''">{{
28                 file.name
29               }}</span>
30               <span v-else>
31                 <a-input size="small" v-model:value="file.tempName"></a-input>
32               </span>
33             </span>
34             <span v-if="!file.editor">
35               <a href="javascript:;" @click="actions.preview">预览</a>
36               <a href="javascript:;" @click="fnRename(file, fileList)">重命名</a>
37               <a href="javascript:;" @click="actions.remove">删除</a>
38             </span>
39             <span v-else>
40               <a href="javascript:;" @click="fnSaveRename(file, fileList)">保存</a>
41               <a href="javascript:;" @click="fnOffRename(file, fileList)">取消</a>
42             </span>
43           </a-space>
44         </template>
45       </a-upload>
46       <div :class="fileListTemp.length > 0 ? 'my-upload-list' : ''">
47         <div style="display: flex">
48           <ImgUpload
49             :fullscreen="fullscreen"
50             @uploading="handleImageUploading"
51             @done="handleDone"
52             v-if="isImg"
53             v-show="editorRef"
54             :title="'图片'"
55             :disabled="disabled"
56             :accept="'.jpg,.jpeg,.gif,.png,.webp'"
57           />
58           <a-button v-if="isText" type="text" size="small">
59             <SnippetsOutlined />
60             快速文本</a-button
61           >
62         </div>
63       </div>
ccfd07 64     </div> -->
00fe0e 65   </div>
H 66 </template>
67
68 <script lang="ts" setup>
69   import type { Editor, RawEditorSettings } from 'tinymce';
2c1249 70   import { PaperClipOutlined, UploadOutlined, SnippetsOutlined } from '@ant-design/icons-vue';
00fe0e 71   import tinymce from 'tinymce/tinymce';
H 72   import 'tinymce/themes/silver';
73   import 'tinymce/icons/default/icons';
74   import 'tinymce/plugins/advlist';
75   import 'tinymce/plugins/anchor';
76   import 'tinymce/plugins/autolink';
77   import 'tinymce/plugins/autosave';
78   import 'tinymce/plugins/code';
79   import 'tinymce/plugins/codesample';
80   import 'tinymce/plugins/directionality';
81   import 'tinymce/plugins/fullscreen';
82   import 'tinymce/plugins/hr';
83   import 'tinymce/plugins/insertdatetime';
84   import 'tinymce/plugins/link';
85   import 'tinymce/plugins/lists';
86   import 'tinymce/plugins/media';
87   import 'tinymce/plugins/nonbreaking';
88   import 'tinymce/plugins/noneditable';
89   import 'tinymce/plugins/pagebreak';
90   import 'tinymce/plugins/paste';
91   import 'tinymce/plugins/preview';
92   import 'tinymce/plugins/print';
93   import 'tinymce/plugins/save';
94   import 'tinymce/plugins/searchreplace';
95   import 'tinymce/plugins/spellchecker';
96   import 'tinymce/plugins/tabfocus';
97   // import 'tinymce/plugins/table';
98   import 'tinymce/plugins/template';
99   import 'tinymce/plugins/textpattern';
100   import 'tinymce/plugins/visualblocks';
101   import 'tinymce/plugins/visualchars';
102   import 'tinymce/plugins/wordcount';
103
104   import 'tinymce/plugins/image';
105   import 'tinymce/plugins/table';
106   import 'tinymce/plugins/charmap';
a9a03d 107   // import 'tinymce/plugins/imagetools';
00fe0e 108   import 'tinymce/plugins/help';
H 109   import 'tinymce/plugins/emoticons';
110   import 'tinymce/plugins/emoticons/js/emojis';
111   // import 'tinymce/plugins/bdmap';
112   // import 'tinymce/plugins/indent2em';
113   import 'tinymce/plugins/autoresize';
114   // import 'tinymce/plugins/formatpainter';
115   // import 'tinymce/plugins/axupimgs';
116
117   // import 'tinymce/plugins/powerpaste';
118   // import 'tinymce/plugins/casechange';
119   import 'tinymce/plugins/importcss';
120   // import 'tinymce/plugins/tinyddrive';
121   // import 'tinymce/plugins/advcode';
122   // import 'tinymce/plugins/mediaembed';
a9a03d 123   // import 'tinymce/plugins/toc';
00fe0e 124   // import 'tinymce/plugins/checklist';
H 125   // import 'tinymce/plugins/tinycespellchecker';
126   // import 'tinymce/plugins/a11ychecker';
127   // import 'tinymce/plugins/permanentpen';
128   // import 'tinymce/plugins/pageembed';
129   // import 'tinymce/plugins/tinycomments';
130   // import 'tinymce/plugins/mentions';
131   import 'tinymce/plugins/quickbars';
132   // import 'tinymce/plugins/linkchecker';
133   // import 'tinymce/plugins/advtable';
134   // import 'tinymce/plugins/export';
135
136   import {
137     computed,
138     nextTick,
139     ref,
140     unref,
141     watch,
142     onDeactivated,
143     onBeforeUnmount,
144     PropType,
145     useAttrs,
146   } from 'vue';
2c1249 147   import ImgUpload from './ImgUpload.vue';
00fe0e 148   import {
H 149     plugins as defaultPlugins,
150     toolbar as defaultToolbar,
151     toolbar_groups as defaultStyleFormats,
152   } from './tinymce';
153   import { buildShortUUID } from '@/utils/uuid';
2c1249 154   import { bindHandlers } from './helper';
00fe0e 155   import { onMountedOrActivated } from '@vben/hooks';
H 156   import { useDesign } from '@/hooks/web/useDesign';
157   import { isNumber } from '@/utils/is';
158   import { useLocale } from '@/locales/useLocale';
159   import { useAppStore } from '@/store/modules/app';
160
161   defineOptions({ name: 'Tinymce', inheritAttrs: false });
162
163   const props = defineProps({
164     options: {
165       type: Object as PropType<Partial<RawEditorSettings>>,
166       default: () => ({}),
167     },
168     value: {
169       type: String,
170     },
171
172     toolbar: {
173       type: Array as PropType<string[]>,
174       default: defaultToolbar,
175     },
176     plugins: {
177       type: Array as PropType<string[]>,
178       default: defaultPlugins,
179     },
180     toolbar_groups: {
181       type: Object as PropType<{}>,
182       default: defaultStyleFormats,
183     },
184     modelValue: {
185       type: String,
186     },
187     height: {
188       type: [Number, String] as PropType<string | number>,
189       required: false,
2c1249 190       default: 400,
00fe0e 191     },
H 192     width: {
193       type: [Number, String] as PropType<string | number>,
194       required: false,
195       default: 'auto',
196     },
197     showImageUpload: {
198       type: Boolean,
199       default: true,
200     },
201     fontsize: {
202       type: String,
203     },
2c1249 204     isElse: {
H 205       type: Boolean,
206       default: true,
207     },
208     isText: {
209       type: Boolean,
210       default: true,
211     },
212     isImg: {
213       type: Boolean,
214       default: true,
215     },
00fe0e 216   });
H 217
218   const emit = defineEmits(['change', 'update:modelValue', 'inited', 'init-error']);
219
220   const attrs = useAttrs();
221   const editorRef = ref<Editor | null>(null);
2c1249 222   const fullscreen = ref(false);
H 223   const tinymceId = ref<string>(buildShortUUID('tiny-vue-pw'));
224   const elPwRef = ref<HTMLElement | null>(null);
00fe0e 225
H 226   const { prefixCls } = useDesign('tinymce-container');
227
228   const appStore = useAppStore();
229
230   const containerWidth = computed(() => {
231     const width = props.width;
232     if (isNumber(width)) {
233       return `${width}px`;
234     }
235     return width;
236   });
237
238   const skinName = computed(() => {
239     return appStore.getDarkMode === 'light' ? 'oxide' : 'oxide-dark';
240   });
241
242   const langName = computed(() => {
243     const lang = useLocale().getLocale.value;
244     return ['zh_CN', ''].includes(lang) ? lang : 'zh_CN';
245   });
246
247   const initOptions = computed((): RawEditorSettings => {
248     const { height, options, toolbar, plugins, toolbar_groups } = props;
249
250     const publicPath = import.meta.env.VITE_PUBLIC_PATH || '/';
251     return {
252       selector: `#${unref(tinymceId)}`,
253       height,
254       min_height: 450,
255       font_formats:
256         '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats',
257       fontsize_formats: '10px 11px 12px 14px 16px 18px 24px 36px 48px 48px 56px 72px',
258       image_advtab: true,
259       importcss_append: true, // 允许样式生效
260       menubar: false,
261       branding: false,
262       elementpath: false,
74a35f 263       toolbar: [],
00fe0e 264       // quickbars_selection_toolbar: 'bold italic | quicklink h2 h3 blockquote quickimage quicktable',
H 265       plugins,
266       language_url: publicPath + 'resource/tinymce/langs/' + langName.value + '.js',
267       language: langName.value,
268       default_link_target: '_blank',
269       link_title: false,
270       statusbar: false,
271       object_resizing: false,
272       auto_focus: true, //让编辑器加载完成后自动获得光标焦点
273       autosave_ask_before_unload: true,
274       autosave_interval: '30s',
275       skin: skinName.value,
276       skin_url: publicPath + 'resource/tinymce/skins/ui/' + skinName.value,
277       content_css: publicPath + 'resource/tinymce/skins/ui/' + skinName.value + '/content.min.css',
278       ...options,
74a35f 279       readonly: true,
00fe0e 280       setup: (editor: Editor) => {
H 281         editorRef.value = editor;
2c1249 282         editor.on('init', (e) => initSetup(e));
00fe0e 283       },
H 284     };
2c1249 285   });
H 286
287   const disabled = computed(() => {
288     const { options } = props;
289     const getdDisabled = options && Reflect.get(options, 'readonly');
290     const editor = unref(editorRef);
291     if (editor) {
292       editor.setMode(getdDisabled ? 'readonly' : 'design');
293     }
294     return getdDisabled ?? false;
00fe0e 295   });
H 296
297   watch(
298     () => attrs.disabled,
299     () => {
300       const editor = unref(editorRef);
301       if (!editor) {
302         return;
303       }
304       editor.setMode(attrs.disabled ? 'readonly' : 'design');
305     },
306   );
307
308   onMountedOrActivated(() => {
309     if (!initOptions.value.inline) {
310       tinymceId.value = buildShortUUID('tiny-vue');
311     }
312     nextTick(() => {
313       setTimeout(() => {
314         initEditor();
315       }, 30);
316     });
317   });
318
319   onBeforeUnmount(() => {
320     destory();
321   });
322
323   onDeactivated(() => {
324     destory();
325   });
326
327   function destory() {
328     if (tinymce !== null) {
329       tinymce?.remove?.(unref(initOptions).selector!);
330     }
331   }
332
333   function initEditor() {
2c1249 334     const el = unref(elPwRef);
00fe0e 335     if (el) {
H 336       el.style.visibility = '';
337     }
338     tinymce
339       .init(unref(initOptions))
340       .then((editor) => {
341         emit('inited', editor);
342       })
343       .catch((err) => {
344         emit('init-error', err);
345       });
346   }
347
2c1249 348   function initSetup(e) {
H 349     const editor = unref(editorRef);
350     if (!editor) {
351       return;
352     }
353     const value = props.modelValue || '';
354
355     editor.setContent(value);
356     bindModelHandlers(editor);
357     bindHandlers(e, attrs, unref(editorRef));
358   }
359
74a35f 360   function setValue(editor: Record<string, any>, val?: string, prevVal?: string) {    
H 361     if (!val) {
362       editor.setContent('');
363     }
00fe0e 364     if (
H 365       editor &&
366       typeof val === 'string' &&
367       val !== prevVal &&
368       val !== editor.getContent({ format: attrs.outputFormat })
369     ) {
370       editor.setContent(val);
371     }
74a35f 372
00fe0e 373   }
2c1249 374
H 375   function bindModelHandlers(editor: any) {
376     const modelEvents = attrs.modelEvents ? attrs.modelEvents : null;
377     const normalizedEvents = Array.isArray(modelEvents) ? modelEvents.join(' ') : modelEvents;
378
379     watch(
380       () => props.modelValue,
381       (val, prevVal) => {
74a35f 382         if(val){
H 383           setValue(editor, val, prevVal);
384         }
2c1249 385       },
H 386     );
387
388     watch(
389       () => props.value,
390       (val, prevVal) => {
391         setValue(editor, val, prevVal);
392       },
393       {
394         immediate: true,
395       },
396     );
397
398     editor.on(normalizedEvents ? normalizedEvents : 'change keyup undo redo', () => {
399       const content = editor.getContent({ format: attrs.outputFormat });
400       emit('update:modelValue', content);
401       const data = {
402         content,
403         fileUNID: fileListTemp.value,
404       };
405       emit('change', data);
406     });
407
408     editor.on('FullscreenStateChanged', (e) => {
409       fullscreen.value = e.state;
410     });
411   }
412
413   function handleImageUploading(name: string) {
414     const editor = unref(editorRef);
415     if (!editor) {
416       return;
417     }
418     editor.execCommand('mceInsertContent', false, getUploadingImgName(name));
419     const content = editor?.getContent() ?? '';
420     setValue(editor, content);
421   }
422
423   function handleDone(name: string, url: string) {
424     const editor = unref(editorRef);
425     if (!editor) {
426       return;
427     }
428     const content = editor?.getContent() ?? '';
429     const val = content?.replace(getUploadingImgName(name), `<img src="${url}"/>`) ?? '';
430     setValue(editor, val);
431   }
432
433   function getUploadingImgName(name: string) {
434     return `[uploading:${name}]`;
435   }
436
437   // 附件
438   const fileListTemp = ref<UploadProps['fileList']>([
439     // {
440     //   uid: '-1',
441     //   name: 'xxx.png',
442     //   tempName: 'xxx',
443     //   status: 'done',
444     //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
445     //   thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
446     //   editor: false,
447     // },
448     // {
449     //   uid: '-2',
450     //   name: 'yyy.png',
451     //   tempName: 'yyy',
452     //   status: 'done',
453     //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
454     //   thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
455     //   editor: false,
456     // },
457   ]);
458   function fnRename(file, fileList) {
459     console.log(file, fileList);
460     fileListTemp.value = fileList.map((item) => {
461       // item.tempName = item.name.split('.').slice(0,-1)
462       if (file.uid == item.uid) {
463         item.editor = true;
464       } else {
465         item.editor = false;
466       }
467       return item;
468     });
469   }
470   function fnSaveRename(file, fileList) {
471     fileListTemp.value = fileList.map((item) => {
472       if (file.uid == item.uid) {
473         item.name = item.tempName;
474         item.editor = false;
475       }
476       return item;
477     });
478   }
479   function fnOffRename(file, fileList) {
480     fileListTemp.value = fileList.map((item) => {
481       if (file.uid == item.uid) {
482         item.editor = false;
483       }
484       return item;
485     });
486   }
00fe0e 487 </script>
H 488 <style lang="less" scope>
489   @prefix-cls: ~'@{namespace}-tinymce-container';
490
491   .@{prefix-cls} {
492     position: relative;
493     line-height: normal;
494
495     textarea {
496       visibility: hidden;
497       z-index: -1;
498     }
499   }
500
2c1249 501   .my-upload-list {
H 502     // 过渡
503     position: absolute;
504     left: 78px;
505     transition: all 0.3s;
506   }
507
00fe0e 508   .tox-statusbar {
H 509     display: flex;
510     // position: absolute;
2c1249 511     min-height: 40px;
00fe0e 512     border-bottom-right-radius: 8px;
H 513     border-bottom-left-radius: 8px;
514     background: #f0f2f5;
515   }
516
517   .icon-text {
518     margin-right: 10px;
519     font-size: 14px;
520   }
521
522   .ant-upload-list-picture {
523     display: flex;
524     flex-wrap: wrap;
525   }
526
527   .ant-upload-list-picture-card {
528     display: flex;
529     justify-content: space-between;
530     width: 24vw;
531     margin-right: 10px;
532     padding: 5px 10px;
533     background-color: #edf3f9;
534
535     a {
536       padding: 0 5px;
537       font-size: 12px;
538     }
539   }
540 </style>