RichText.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. args.content = content;
  161. },
  162. // 指定在 WebKit 中粘贴时要保留的样式
  163. paste_webkit_styles:
  164. 'color font font-size font-family font-weight width height margin padding line-height text-align border border-radius',
  165. },
  166. };
  167. },
  168. created() {
  169. window.addEventListener('click', this.hideToolbarDrawer);
  170. if (this.isFill) {
  171. window.addEventListener('click', this.hideContentmenu);
  172. }
  173. },
  174. beforeDestroy() {
  175. window.removeEventListener('click', this.hideToolbarDrawer);
  176. if (this.isFill) {
  177. window.removeEventListener('click', this.hideContentmenu);
  178. }
  179. },
  180. methods: {
  181. /**
  182. * 图片上传自定义逻辑函数
  183. * @param {object} blobInfo 文件数据
  184. * @param {Function} success 成功回调函数
  185. * @param {Function} fail 失败回调函数
  186. */
  187. imagesUploadHandler(blobInfo, success, fail) {
  188. let file = blobInfo.blob();
  189. const formData = new FormData();
  190. formData.append(file.name, file, file.name);
  191. fileUpload('Mid', formData, { isGlobalprogress: true })
  192. .then(({ file_info_list }) => {
  193. if (file_info_list.length > 0) {
  194. success(file_info_list[0].file_url_open);
  195. } else {
  196. fail('上传失败');
  197. }
  198. })
  199. .catch(() => {
  200. fail('上传失败');
  201. });
  202. },
  203. /**
  204. * 文件上传自定义逻辑函数
  205. * @param {Function} callback
  206. * @param {String} value
  207. * @param {object} meta
  208. */
  209. filePickerCallback(callback, value, meta) {
  210. if (meta.filetype === 'media') {
  211. let filetype = '.mp3, .mp4';
  212. let input = document.createElement('input');
  213. input.setAttribute('type', 'file');
  214. input.setAttribute('accept', filetype);
  215. input.click();
  216. input.addEventListener('change', () => {
  217. let file = input.files[0];
  218. const formData = new FormData();
  219. formData.append(file.name, file, file.name);
  220. fileUpload('Mid', formData, { isGlobalprogress: true })
  221. .then(({ file_info_list }) => {
  222. if (file_info_list.length > 0) {
  223. callback(file_info_list[0].file_url_open);
  224. } else {
  225. callback('');
  226. }
  227. })
  228. .catch(() => {
  229. callback('');
  230. });
  231. });
  232. }
  233. },
  234. /**
  235. * 初始化编辑器实例回调函数
  236. * @param {Editor} editor 编辑器实例
  237. */
  238. initInstanceCallback(editor) {
  239. editor.on('SetContent Undo Redo ViewUpdate keyup mousedown', () => {
  240. this.hideContentmenu();
  241. });
  242. editor.on('click', (e) => {
  243. if (e.target.classList.contains('rich-fill')) {
  244. editor.selection.select(e.target); // 选中填空
  245. let { offsetLeft, offsetTop } = e.target;
  246. this.showContentmenu({
  247. pixelsFromLeft: offsetLeft - 14,
  248. pixelsFromTop: offsetTop,
  249. });
  250. }
  251. });
  252. let mouseX = 0;
  253. editor.on('mousedown', (e) => {
  254. mouseX = e.offsetX;
  255. });
  256. editor.on('mouseup', (e) => {
  257. let start = editor.selection.getStart();
  258. let end = editor.selection.getEnd();
  259. let rng = editor.selection.getRng();
  260. if (start !== end || rng.collapsed) {
  261. this.hideContentmenu();
  262. return;
  263. }
  264. if (e.offsetX < mouseX) {
  265. mouseX = e.offsetX;
  266. }
  267. if (isNodeType(start, 'span')) {
  268. start = start.parentNode;
  269. }
  270. // 获取文本内容和起始偏移位置
  271. let text = start.textContent;
  272. let startOffset = rng.startOffset;
  273. let previousSibling = rng.startContainer.previousSibling;
  274. // 判断是否选中的是 span 标签
  275. let isSpan = isNodeType(rng.startContainer.parentNode, 'span');
  276. if (isSpan) {
  277. previousSibling = rng.startContainer.parentNode.previousSibling;
  278. }
  279. // 计算起始偏移位置
  280. while (previousSibling) {
  281. startOffset += previousSibling.textContent.length;
  282. previousSibling = previousSibling.previousSibling;
  283. }
  284. // 获取起始偏移位置前的文本内容
  285. const textBeforeOffset = text.substring(0, startOffset);
  286. /* 使用 Canvas API测量文本宽度 */
  287. // 获取字体大小和行高
  288. let computedStyle = window.getComputedStyle(start);
  289. const fontSize = parseFloat(computedStyle.fontSize);
  290. const canvas = document.createElement('canvas');
  291. const context = canvas.getContext('2d');
  292. context.font = `${fontSize}pt ${computedStyle.fontFamily}`;
  293. // 计算文字距离左侧的像素位置
  294. const width = context.measureText(textBeforeOffset).width;
  295. const lineHeight = context.measureText('M').fontBoundingBoxAscent + 3.8; // 获取行高
  296. /* 计算偏移位置 */
  297. const computedWidth = computedStyle.width.replace('px', ''); // 获取编辑器宽度
  298. let row = width / computedWidth; // 计算选中文本在第几行
  299. row = row % 1 > 0.8 ? Math.ceil(row) : Math.floor(row);
  300. const offsetTop = start.offsetTop; // 获取选中文本距离顶部的像素位置
  301. let pixelsFromTop = offsetTop + lineHeight * row; // 计算选中文本距离顶部的像素位置
  302. this.showContentmenu({
  303. pixelsFromLeft: mouseX,
  304. pixelsFromTop,
  305. });
  306. });
  307. },
  308. // 删除填空
  309. deleteContent() {
  310. let editor = tinymce.get(this.id);
  311. let start = editor.selection.getStart();
  312. if (isNodeType(start, 'span')) {
  313. let textContent = start.textContent;
  314. let content = editor.selection.getContent();
  315. let str = textContent.split(content);
  316. start.remove();
  317. editor.selection.setContent(str.join(content));
  318. } else {
  319. this.collapse();
  320. }
  321. },
  322. // 设置填空
  323. setContent() {
  324. let editor = tinymce.get(this.id);
  325. let start = editor.selection.getStart();
  326. let content = editor.selection.getContent();
  327. if (isNodeType(start, 'span')) {
  328. let textContent = start.textContent;
  329. let str = textContent.split(content);
  330. start.remove();
  331. editor.selection.setContent(str.join(this.getSpanString(content)));
  332. } else {
  333. let str = this.replaceSpanString(content);
  334. editor.selection.setContent(this.getSpanString(str));
  335. }
  336. },
  337. // 折叠选区
  338. collapse() {
  339. let editor = tinymce.get(this.id);
  340. let rng = editor.selection.getRng();
  341. if (!rng.collapsed) {
  342. this.hideContentmenu();
  343. editor.selection.collapse();
  344. }
  345. },
  346. // 获取 span 标签
  347. getSpanString(str) {
  348. return `<span class="rich-fill" style="text-decoration: underline;cursor: pointer;">${str}</span>`;
  349. },
  350. // 去除 span 标签
  351. replaceSpanString(str) {
  352. return str.replace(/<span\b[^>]*>(.*?)<\/span>/gi, '$1');
  353. },
  354. handleRichTextBlur() {
  355. this.$emit('handleRichTextBlur');
  356. let content = tinymce.get(this.id).getContent();
  357. // 判断富文本中是否有 字母+数字+空格 的组合,如果没有,直接返回
  358. if (!content.match(/[a-zA-Z]+\d(\s|&nbsp;)*/)) {
  359. return;
  360. }
  361. // 用标签分割富文本,保留标签
  362. let reg = /(<[^>]+>)/g;
  363. let text = content
  364. .split(reg)
  365. .filter((item) => item)
  366. // 如果是标签,直接返回
  367. // 如果是文本,将文本按空格分割为数组,如果是拼音,将拼音转为带音调的拼音
  368. .map((item) => {
  369. return reg.test(item) ? item : item.split(/\s+/).map((item) => handleToneValue(item));
  370. })
  371. // 如果是标签,直接返回
  372. // 二维数组,转为拼音,并打平为一维数组
  373. .map((item) => {
  374. if (/<[^>]+>/g.test(item)) return item;
  375. return item
  376. .map((li) =>
  377. li.map(({ number, con }) => (number && con ? addTone(Number(number), con) : number || con || '')),
  378. )
  379. .flat();
  380. })
  381. // 如果是数组,将数组字符串每两个之间加一个空格
  382. .map((item) => {
  383. if (typeof item === 'string') return item;
  384. return item.join(' ');
  385. })
  386. .join('');
  387. // 更新 v-model
  388. this.$emit('input', text);
  389. },
  390. // 设置填空
  391. setFill() {
  392. this.setContent();
  393. this.hideContentmenu();
  394. },
  395. // 删除填空
  396. deleteFill() {
  397. this.deleteContent();
  398. this.hideContentmenu();
  399. },
  400. // 隐藏工具栏抽屉
  401. hideToolbarDrawer() {
  402. let editor = tinymce.get(this.id);
  403. if (editor.queryCommandState('ToggleToolbarDrawer')) {
  404. editor.execCommand('ToggleToolbarDrawer');
  405. }
  406. },
  407. // 隐藏填空右键菜单
  408. hideContentmenu() {
  409. this.isShow = false;
  410. },
  411. showContentmenu({ pixelsFromLeft, pixelsFromTop }) {
  412. this.isShow = true;
  413. this.contentmenu = {
  414. left: `${pixelsFromLeft + 14}px`,
  415. top: `${pixelsFromTop - 18}px`,
  416. };
  417. },
  418. },
  419. };
  420. </script>
  421. <style lang="scss" scoped>
  422. .rich-text {
  423. :deep + .tox {
  424. .tox-sidebar-wrap {
  425. border: 1px solid $fill-color;
  426. border-radius: 4px;
  427. &:hover {
  428. border-color: #c0c4cc;
  429. }
  430. }
  431. &.tox-tinymce {
  432. border-width: 0;
  433. border-radius: 0;
  434. .tox-edit-area__iframe {
  435. background-color: $fill-color;
  436. }
  437. }
  438. &:not(.tox-tinymce-inline) .tox-editor-header {
  439. box-shadow: none;
  440. }
  441. }
  442. &.is-border {
  443. :deep + .tox.tox-tinymce {
  444. border: $border;
  445. border-radius: 4px;
  446. }
  447. }
  448. }
  449. .contentmenu {
  450. position: absolute;
  451. z-index: 999;
  452. display: flex;
  453. column-gap: 4px;
  454. align-items: center;
  455. padding: 4px 8px;
  456. font-size: 14px;
  457. background-color: #fff;
  458. border-radius: 2px;
  459. box-shadow: 0 1px 10px 0 rgba(0, 0, 0, 10%);
  460. .svg-icon,
  461. .button {
  462. cursor: pointer;
  463. }
  464. .line {
  465. min-height: 16px;
  466. margin: 0 4px;
  467. }
  468. }
  469. </style>