huangyinfeng
2024-09-18 ccfd07feeaa670a3d56548d7fea0936e299df95b
提交 | 用户 | 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';
107   import 'tinymce/plugins/imagetools';
108   import 'tinymce/plugins/help';
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';
123   import 'tinymce/plugins/toc';
124   // import 'tinymce/plugins/checklist';
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,
2c1249 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,
2c1249 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
00fe0e 360   function setValue(editor: Record<string, any>, val?: string, prevVal?: string) {
H 361     if (
362       editor &&
363       typeof val === 'string' &&
364       val !== prevVal &&
365       val !== editor.getContent({ format: attrs.outputFormat })
366     ) {
367       editor.setContent(val);
2c1249 368     }else{
H 369       editor.setContent('');
370       console.log('-5-5-5555555555');
371       
00fe0e 372     }
H 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) => {
382         setValue(editor, val, prevVal);
383       },
384     );
385
386     watch(
387       () => props.value,
388       (val, prevVal) => {
389         setValue(editor, val, prevVal);
390       },
391       {
392         immediate: true,
393       },
394     );
395
396     editor.on(normalizedEvents ? normalizedEvents : 'change keyup undo redo', () => {
397       const content = editor.getContent({ format: attrs.outputFormat });
398       emit('update:modelValue', content);
399       const data = {
400         content,
401         fileUNID: fileListTemp.value,
402       };
403       emit('change', data);
404     });
405
406     editor.on('FullscreenStateChanged', (e) => {
407       fullscreen.value = e.state;
408     });
409   }
410
411   function handleImageUploading(name: string) {
412     const editor = unref(editorRef);
413     if (!editor) {
414       return;
415     }
416     editor.execCommand('mceInsertContent', false, getUploadingImgName(name));
417     const content = editor?.getContent() ?? '';
418     setValue(editor, content);
419   }
420
421   function handleDone(name: string, url: string) {
422     const editor = unref(editorRef);
423     if (!editor) {
424       return;
425     }
426     const content = editor?.getContent() ?? '';
427     const val = content?.replace(getUploadingImgName(name), `<img src="${url}"/>`) ?? '';
428     setValue(editor, val);
429   }
430
431   function getUploadingImgName(name: string) {
432     return `[uploading:${name}]`;
433   }
434
435   // 附件
436   const fileListTemp = ref<UploadProps['fileList']>([
437     // {
438     //   uid: '-1',
439     //   name: 'xxx.png',
440     //   tempName: 'xxx',
441     //   status: 'done',
442     //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
443     //   thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
444     //   editor: false,
445     // },
446     // {
447     //   uid: '-2',
448     //   name: 'yyy.png',
449     //   tempName: 'yyy',
450     //   status: 'done',
451     //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
452     //   thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
453     //   editor: false,
454     // },
455   ]);
456   function fnRename(file, fileList) {
457     console.log(file, fileList);
458     fileListTemp.value = fileList.map((item) => {
459       // item.tempName = item.name.split('.').slice(0,-1)
460       if (file.uid == item.uid) {
461         item.editor = true;
462       } else {
463         item.editor = false;
464       }
465       return item;
466     });
467   }
468   function fnSaveRename(file, fileList) {
469     fileListTemp.value = fileList.map((item) => {
470       if (file.uid == item.uid) {
471         item.name = item.tempName;
472         item.editor = false;
473       }
474       return item;
475     });
476   }
477   function fnOffRename(file, fileList) {
478     fileListTemp.value = fileList.map((item) => {
479       if (file.uid == item.uid) {
480         item.editor = false;
481       }
482       return item;
483     });
484   }
00fe0e 485 </script>
H 486 <style lang="less" scope>
487   @prefix-cls: ~'@{namespace}-tinymce-container';
488
489   .@{prefix-cls} {
490     position: relative;
491     line-height: normal;
492
493     textarea {
494       visibility: hidden;
495       z-index: -1;
496     }
497   }
498
2c1249 499   .my-upload-list {
H 500     // 过渡
501     position: absolute;
502     left: 78px;
503     transition: all 0.3s;
504   }
505
00fe0e 506   .tox-statusbar {
H 507     display: flex;
508     // position: absolute;
2c1249 509     min-height: 40px;
00fe0e 510     border-bottom-right-radius: 8px;
H 511     border-bottom-left-radius: 8px;
512     background: #f0f2f5;
513   }
514
515   .icon-text {
516     margin-right: 10px;
517     font-size: 14px;
518   }
519
520   .ant-upload-list-picture {
521     display: flex;
522     flex-wrap: wrap;
523   }
524
525   .ant-upload-list-picture-card {
526     display: flex;
527     justify-content: space-between;
528     width: 24vw;
529     margin-right: 10px;
530     padding: 5px 10px;
531     background-color: #edf3f9;
532
533     a {
534       padding: 0 5px;
535       font-size: 12px;
536     }
537   }
538 </style>