RichText.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <template>
  2. <div class="rich-wrapper">
  3. <Editor
  4. v-bind="$attrs"
  5. :id="id"
  6. ref="richText"
  7. model-events="change keyup undo redo setContent"
  8. :value="value"
  9. :class="['rich-text', isBorder ? 'is-border' : '']"
  10. :init="init"
  11. v-on="$listeners"
  12. @onBlur="handleRichTextBlur"
  13. />
  14. <div v-show="isShow" :style="contentmenu" class="contentmenu">
  15. <SvgIcon icon-class="slice" size="16" @click="setFill" />
  16. <span class="button" @click="setFill">设为填空</span>
  17. <span class="line"></span>
  18. <SvgIcon icon-class="close-circle" size="16" @click="deleteFill" />
  19. <span class="button" @click="deleteFill">删除填空</span>
  20. </div>
  21. </div>
  22. </template>
  23. <script>
  24. import tinymce from 'tinymce/tinymce';
  25. import Editor from '@tinymce/tinymce-vue';
  26. import 'tinymce/icons/default/icons';
  27. import 'tinymce/themes/silver';
  28. // 引入富文本编辑器主题的js和css
  29. import 'tinymce/themes/silver/theme.min';
  30. import 'tinymce/skins/ui/oxide/skin.min.css';
  31. // 扩展插件
  32. import 'tinymce/plugins/image';
  33. import 'tinymce/plugins/link';
  34. // import 'tinymce/plugins/code';
  35. // import 'tinymce/plugins/table';
  36. import 'tinymce/plugins/lists';
  37. // import 'tinymce/plugins/wordcount'; // 字数统计插件
  38. import 'tinymce/plugins/media'; // 插入视频插件
  39. // import 'tinymce/plugins/template'; // 模板插件
  40. // import 'tinymce/plugins/fullscreen'; // 全屏插件
  41. import 'tinymce/plugins/paste'; // 粘贴插件
  42. // import 'tinymce/plugins/preview'; // 预览插件
  43. import 'tinymce/plugins/hr';
  44. import 'tinymce/plugins/autoresize'; // 自动调整大小插件
  45. import 'tinymce/plugins/ax_wordlimit'; // 字数限制插件
  46. import { getRandomNumber } from '@/utils';
  47. import { isNodeType } from '@/utils/validate';
  48. import { fileUpload } from '@/api/app';
  49. import { addTone, handleToneValue } from '@/views/exercise_questions/data/common';
  50. export default {
  51. name: 'RichText',
  52. components: {
  53. Editor,
  54. },
  55. inheritAttrs: false,
  56. props: {
  57. inline: {
  58. type: Boolean,
  59. default: false,
  60. },
  61. placeholder: {
  62. type: String,
  63. default: '输入内容',
  64. },
  65. value: {
  66. type: String,
  67. required: true,
  68. },
  69. height: {
  70. type: [Number, String],
  71. default: 52,
  72. },
  73. isBorder: {
  74. type: Boolean,
  75. default: false,
  76. },
  77. toolbar: {
  78. type: [String, Boolean],
  79. /* eslint-disable max-len */
  80. default:
  81. 'fontselect fontsizeselect forecolor backcolor | underline | bold italic strikethrough alignleft aligncenter alignright | bullist numlist | image media | link blockquote hr',
  82. },
  83. wordlimitNum: {
  84. type: [Number, Boolean],
  85. default: 1000,
  86. },
  87. isFill: {
  88. type: Boolean,
  89. default: false,
  90. },
  91. fontSize: {
  92. type: Number,
  93. default: 16,
  94. },
  95. isHasSpace: {
  96. type: Boolean,
  97. default: false,
  98. },
  99. },
  100. data() {
  101. return {
  102. isShow: false,
  103. contentmenu: {
  104. top: 0,
  105. left: 0,
  106. },
  107. id: getRandomNumber(),
  108. init: {
  109. inline: this.inline,
  110. font_size: this.fontSize,
  111. language_url: `${process.env.BASE_URL}tinymce/langs/zh_CN.js`,
  112. placeholder: this.placeholder,
  113. language: 'zh_CN',
  114. skin_url: `${process.env.BASE_URL}tinymce/skins/ui/oxide`,
  115. content_css: `${process.env.BASE_URL}tinymce/skins/content/${this.isHasSpace ? 'index-nospace' : 'index'}.css`,
  116. min_height: this.height,
  117. width: '100%',
  118. autoresize_bottom_margin: 0,
  119. plugins: 'link lists image hr media autoresize ax_wordlimit paste',
  120. toolbar: this.toolbar, // 工具栏
  121. contextmenu: false, // 右键菜单
  122. menubar: false, // 菜单栏
  123. branding: false, // 品牌
  124. statusbar: false, // 状态栏
  125. setup(editor) {
  126. editor.on('init', () => {
  127. editor.getBody().style.fontSize = `${this.font_size}pt`; // 设置默认字体大小
  128. editor.getBody().style.fontFamily = 'Arial'; // 设置默认字体
  129. });
  130. editor.on('click', () => {
  131. if (editor?.queryCommandState('ToggleToolbarDrawer')) {
  132. editor.execCommand('ToggleToolbarDrawer');
  133. }
  134. });
  135. },
  136. font_formats:
  137. '楷体=楷体,微软雅黑;' +
  138. '黑体=黑体,微软雅黑;' +
  139. '宋体=宋体,微软雅黑;' +
  140. 'Arial=arial,helvetica,sans-serif;' +
  141. 'Times New Roman=times new roman,times,serif;' +
  142. '拼音=League;',
  143. // 字数限制
  144. fontsize_formats: '8pt 10pt 11pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 26pt 28pt 30pt 32pt 34pt 36pt',
  145. ax_wordlimit_num: this.wordlimitNum,
  146. ax_wordlimit_callback(editor) {
  147. editor.execCommand('undo');
  148. },
  149. media_filter_html: false,
  150. images_upload_handler: this.imagesUploadHandler,
  151. file_picker_types: 'media', // 文件上传类型
  152. file_picker_callback: this.filePickerCallback,
  153. init_instance_callback: this.isFill ? this.initInstanceCallback : '',
  154. paste_enable_default_filters: false, // 禁用默认的粘贴过滤器
  155. // 粘贴预处理
  156. paste_preprocess(plugin, args) {
  157. let content = args.content;
  158. // 使用正则表达式去掉 style 中的 background 属性
  159. content = content.replace(/background(-color)?:[^;]+;/g, '');
  160. // 去掉 p 标签 style 中的 line-height 属性
  161. content = content.replace(/<p[^>]+>/g, (match) => match.replace(/line-height:[^;]+;/g, ''));
  162. args.content = content;
  163. },
  164. // 指定在 WebKit 中粘贴时要保留的样式
  165. paste_webkit_styles:
  166. 'display gap flex-wrap color min-height font font-size font-family font-weight width height margin-bottom margin padding line-height text-align border border-radius white-space',
  167. },
  168. };
  169. },
  170. created() {
  171. window.addEventListener('click', this.hideToolbarDrawer);
  172. if (this.isFill) {
  173. window.addEventListener('click', this.hideContentmenu);
  174. }
  175. },
  176. beforeDestroy() {
  177. window.removeEventListener('click', this.hideToolbarDrawer);
  178. if (this.isFill) {
  179. window.removeEventListener('click', this.hideContentmenu);
  180. }
  181. },
  182. methods: {
  183. /**
  184. * 图片上传自定义逻辑函数
  185. * @param {object} blobInfo 文件数据
  186. * @param {Function} success 成功回调函数
  187. * @param {Function} fail 失败回调函数
  188. */
  189. imagesUploadHandler(blobInfo, success, fail) {
  190. let file = blobInfo.blob();
  191. const formData = new FormData();
  192. formData.append(file.name, file, file.name);
  193. fileUpload('Mid', formData, { isGlobalprogress: true })
  194. .then(({ file_info_list }) => {
  195. if (file_info_list.length > 0) {
  196. success(file_info_list[0].file_url_open);
  197. } else {
  198. fail('上传失败');
  199. }
  200. })
  201. .catch(() => {
  202. fail('上传失败');
  203. });
  204. },
  205. /**
  206. * 文件上传自定义逻辑函数
  207. * @param {Function} callback
  208. * @param {String} value
  209. * @param {object} meta
  210. */
  211. filePickerCallback(callback, value, meta) {
  212. if (meta.filetype === 'media') {
  213. let filetype = '.mp3, .mp4';
  214. let input = document.createElement('input');
  215. input.setAttribute('type', 'file');
  216. input.setAttribute('accept', filetype);
  217. input.click();
  218. input.addEventListener('change', () => {
  219. let file = input.files[0];
  220. const formData = new FormData();
  221. formData.append(file.name, file, file.name);
  222. fileUpload('Mid', formData, { isGlobalprogress: true })
  223. .then(({ file_info_list }) => {
  224. if (file_info_list.length > 0) {
  225. callback(file_info_list[0].file_url_open);
  226. } else {
  227. callback('');
  228. }
  229. })
  230. .catch(() => {
  231. callback('');
  232. });
  233. });
  234. }
  235. },
  236. /**
  237. * 初始化编辑器实例回调函数
  238. * @param {Editor} editor 编辑器实例
  239. */
  240. initInstanceCallback(editor) {
  241. editor.on('SetContent Undo Redo ViewUpdate keyup mousedown', () => {
  242. this.hideContentmenu();
  243. });
  244. editor.on('click', (e) => {
  245. if (e.target.classList.contains('rich-fill')) {
  246. editor.selection.select(e.target); // 选中填空
  247. let { offsetLeft, offsetTop } = e.target;
  248. this.showContentmenu({
  249. pixelsFromLeft: offsetLeft - 14,
  250. pixelsFromTop: offsetTop,
  251. });
  252. }
  253. });
  254. let mouseX = 0;
  255. editor.on('mousedown', (e) => {
  256. mouseX = e.offsetX;
  257. });
  258. editor.on('mouseup', (e) => {
  259. let start = editor.selection.getStart();
  260. let end = editor.selection.getEnd();
  261. let rng = editor.selection.getRng();
  262. if (start !== end || rng.collapsed) {
  263. this.hideContentmenu();
  264. return;
  265. }
  266. if (e.offsetX < mouseX) {
  267. mouseX = e.offsetX;
  268. }
  269. if (isNodeType(start, 'span')) {
  270. start = start.parentNode;
  271. }
  272. // 获取文本内容和起始偏移位置
  273. let text = start.textContent;
  274. let startOffset = rng.startOffset;
  275. let previousSibling = rng.startContainer.previousSibling;
  276. // 判断是否选中的是 span 标签
  277. let isSpan = isNodeType(rng.startContainer.parentNode, 'span');
  278. if (isSpan) {
  279. previousSibling = rng.startContainer.parentNode.previousSibling;
  280. }
  281. // 计算起始偏移位置
  282. while (previousSibling) {
  283. startOffset += previousSibling.textContent.length;
  284. previousSibling = previousSibling.previousSibling;
  285. }
  286. // 获取起始偏移位置前的文本内容
  287. const textBeforeOffset = text.substring(0, startOffset);
  288. /* 使用 Canvas API测量文本宽度 */
  289. // 获取字体大小和行高
  290. let computedStyle = window.getComputedStyle(start);
  291. const fontSize = parseFloat(computedStyle.fontSize);
  292. const canvas = document.createElement('canvas');
  293. const context = canvas.getContext('2d');
  294. context.font = `${fontSize}pt ${computedStyle.fontFamily}`;
  295. // 计算文字距离左侧的像素位置
  296. const width = context.measureText(textBeforeOffset).width;
  297. const lineHeight = context.measureText('M').fontBoundingBoxAscent + 3.8; // 获取行高
  298. /* 计算偏移位置 */
  299. const computedWidth = computedStyle.width.replace('px', ''); // 获取编辑器宽度
  300. let row = width / computedWidth; // 计算选中文本在第几行
  301. row = row % 1 > 0.8 ? Math.ceil(row) : Math.floor(row);
  302. const offsetTop = start.offsetTop; // 获取选中文本距离顶部的像素位置
  303. let pixelsFromTop = offsetTop + lineHeight * row; // 计算选中文本距离顶部的像素位置
  304. this.showContentmenu({
  305. pixelsFromLeft: mouseX,
  306. pixelsFromTop,
  307. });
  308. });
  309. },
  310. // 删除填空
  311. deleteContent() {
  312. let editor = tinymce.get(this.id);
  313. let start = editor.selection.getStart();
  314. if (isNodeType(start, 'span')) {
  315. let textContent = start.textContent;
  316. let content = editor.selection.getContent();
  317. let str = textContent.split(content);
  318. start.remove();
  319. editor.selection.setContent(str.join(content));
  320. } else {
  321. this.collapse();
  322. }
  323. },
  324. // 设置填空
  325. setContent() {
  326. let editor = tinymce.get(this.id);
  327. let start = editor.selection.getStart();
  328. let content = editor.selection.getContent();
  329. if (isNodeType(start, 'span')) {
  330. let textContent = start.textContent;
  331. let str = textContent.split(content);
  332. start.remove();
  333. editor.selection.setContent(str.join(this.getSpanString(content)));
  334. } else {
  335. let str = this.replaceSpanString(content);
  336. editor.selection.setContent(this.getSpanString(str));
  337. }
  338. },
  339. // 折叠选区
  340. collapse() {
  341. let editor = tinymce.get(this.id);
  342. let rng = editor.selection.getRng();
  343. if (!rng.collapsed) {
  344. this.hideContentmenu();
  345. editor.selection.collapse();
  346. }
  347. },
  348. // 获取 span 标签
  349. getSpanString(str) {
  350. return `<span class="rich-fill" style="text-decoration: underline;cursor: pointer;">${str}</span>`;
  351. },
  352. // 去除 span 标签
  353. replaceSpanString(str) {
  354. return str.replace(/<span\b[^>]*>(.*?)<\/span>/gi, '$1');
  355. },
  356. handleRichTextBlur() {
  357. this.$emit('handleRichTextBlur');
  358. let content = tinymce.get(this.id).getContent();
  359. // 判断富文本中是否有 字母+数字+空格 的组合,如果没有,直接返回
  360. let isHasPinyin = content
  361. .split(/<[^>]+>/g)
  362. .filter((item) => item)
  363. .some((item) => item.match(/[a-zA-Z]+\d(\s|&nbsp;)*/));
  364. if (!isHasPinyin) {
  365. return;
  366. }
  367. // 用标签分割富文本,保留标签
  368. let reg = /(<[^>]+>)/g;
  369. let text = content
  370. .split(reg)
  371. .filter((item) => item)
  372. // 如果是标签,直接返回
  373. // 如果是文本,将文本按空格分割为数组,如果是拼音,将拼音转为带音调的拼音
  374. .map((item) => {
  375. // 重置正则,使用全局匹配 g 时需要重置,否则会出现匹配不到的情况,因为 lastIndex 会一直累加,test 方法会从 lastIndex 开始匹配
  376. reg.lastIndex = 0;
  377. if (reg.test(item)) {
  378. return item;
  379. }
  380. return item.split(/\s+/).map((item) => handleToneValue(item));
  381. })
  382. // 如果是标签,直接返回
  383. // 二维数组,转为拼音,并打平为一维数组
  384. .map((item) => {
  385. if (/<[^>]+>/g.test(item)) return item;
  386. return item
  387. .map((li) =>
  388. li.map(({ number, con }) => (number && con ? addTone(Number(number), con) : number || con || '')),
  389. )
  390. .flat();
  391. })
  392. // 如果是数组,将数组字符串每两个之间加一个空格
  393. .map((item) => {
  394. if (typeof item === 'string') return item;
  395. return item.join(' ');
  396. })
  397. .join('');
  398. // 更新 v-model
  399. this.$emit('input', text);
  400. },
  401. // 设置填空
  402. setFill() {
  403. this.setContent();
  404. this.hideContentmenu();
  405. },
  406. // 删除填空
  407. deleteFill() {
  408. this.deleteContent();
  409. this.hideContentmenu();
  410. },
  411. // 隐藏工具栏抽屉
  412. hideToolbarDrawer() {
  413. let editor = tinymce.get(this.id);
  414. if (editor?.queryCommandState('ToggleToolbarDrawer')) {
  415. editor.execCommand('ToggleToolbarDrawer');
  416. }
  417. },
  418. // 隐藏填空右键菜单
  419. hideContentmenu() {
  420. this.isShow = false;
  421. },
  422. showContentmenu({ pixelsFromLeft, pixelsFromTop }) {
  423. this.isShow = true;
  424. this.contentmenu = {
  425. left: `${pixelsFromLeft + 14}px`,
  426. top: `${pixelsFromTop - 18}px`,
  427. };
  428. },
  429. },
  430. };
  431. </script>
  432. <style lang="scss" scoped>
  433. .rich-text {
  434. :deep + .tox {
  435. .tox-sidebar-wrap {
  436. border: 1px solid $fill-color;
  437. border-radius: 4px;
  438. &:hover {
  439. border-color: #c0c4cc;
  440. }
  441. }
  442. &.tox-tinymce {
  443. border-width: 0;
  444. border-radius: 0;
  445. .tox-edit-area__iframe {
  446. background-color: $fill-color;
  447. }
  448. }
  449. &:not(.tox-tinymce-inline) .tox-editor-header {
  450. box-shadow: none;
  451. }
  452. }
  453. &.is-border {
  454. :deep + .tox.tox-tinymce {
  455. border: $border;
  456. border-radius: 4px;
  457. }
  458. }
  459. }
  460. .contentmenu {
  461. position: absolute;
  462. z-index: 999;
  463. display: flex;
  464. column-gap: 4px;
  465. align-items: center;
  466. padding: 4px 8px;
  467. font-size: 14px;
  468. background-color: #fff;
  469. border-radius: 2px;
  470. box-shadow: 0 1px 10px 0 rgba(0, 0, 0, 10%);
  471. .svg-icon,
  472. .button {
  473. cursor: pointer;
  474. }
  475. .line {
  476. min-height: 16px;
  477. margin: 0 4px;
  478. }
  479. }
  480. </style>