CustomEditor.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. <template>
  2. <view
  3. :insertImageFlag="insertImageFlag"
  4. :insertAtFlag="insertAtFlag"
  5. :insertEmojiFlag="insertEmojiFlag"
  6. :blurFlag="blurFlag"
  7. :change:insertEmojiFlag="input.insertEmojiFlagUpdate"
  8. :change:insertAtFlag="input.insertAtFlagUpdate"
  9. :change:insertImageFlag="input.insertImageFlagUpdate"
  10. :change:blurFlag="input.blurFlagUpdate"
  11. class="editor_wrap"
  12. :class="{'blur-trigger': blurFlag % 2 === 1}"
  13. @touchstart="input.handleTouchStart"
  14. @click="input.handleForceUpdate"
  15. >
  16. <editor :placeholder="placeholder" ref="editor2" id="editor2" @ready="editorReady" @focus="editorFocus" @blur="editorBlur" @input="editorInput" />
  17. <view class="canvas_container">
  18. <canvas v-if="canvasData.show" canvas-id="atCanvas" :style="{ width: canvasData.width }" id="atCanvas"></canvas>
  19. </view>
  20. </view>
  21. </template>
  22. <script>
  23. import { html2Text } from '../../../../../util/common';
  24. export default {
  25. props: {
  26. placeholder: {
  27. type: String,
  28. default: ''
  29. }
  30. },
  31. data() {
  32. return {
  33. editorCtx: null,
  34. canvasData: {
  35. width: 0,
  36. show: false
  37. },
  38. imageData: {},
  39. insertImageFlag: null,
  40. insertAtFlag: null,
  41. lastStr: '',
  42. emojiData: '',
  43. insertEmojiFlag: null,
  44. blurFlag: 0,
  45. inputTimeout: null // 用于防抖
  46. };
  47. },
  48. mounted() {
  49. },
  50. methods: {
  51. editorReady() {
  52. uni.createSelectorQuery()
  53. .select('#editor2')
  54. .context((res) => {
  55. this.$emit('ready', res);
  56. this.editorCtx = res.context;
  57. }).exec();
  58. },
  59. insertImage(imageData) {
  60. this.imageData = imageData;
  61. this.insertImageFlag = true;
  62. },
  63. insertEmoji(emoji) {
  64. this.$nextTick(() => {
  65. this.insertEmojiFlag = true;
  66. this.emojiData = emoji;
  67. });
  68. },
  69. internalInsertEmoji() {
  70. this.editorCtx.insertText({
  71. text: this.emojiData,
  72. complete: () => {
  73. this.insertEmojiFlag = false;
  74. this.emojiData = null;
  75. }
  76. });
  77. },
  78. internalInsertImage() {
  79. this.editorCtx.insertImage({
  80. ...this.imageData,
  81. complete: () => {
  82. this.insertImageFlag = false;
  83. this.insertAtFlag = null;
  84. // plus.key.showSoftKeybord()
  85. // this.setDraftTextItem();
  86. }
  87. });
  88. },
  89. internalInsertAtEl({ text, width, userID, nickname }) {
  90. this.canvasData.width = `${width}px`;
  91. this.canvasData.show = true;
  92. setTimeout(() => {
  93. const ctx = uni.createCanvasContext('atCanvas');
  94. const fontSize = 14;
  95. ctx.setFontSize(fontSize);
  96. ctx.setFillStyle('#3e44ff');
  97. ctx.fillText(text, 0, 16);
  98. ctx.draw();
  99. this.canvasToTempFilePath(userID, nickname, width);
  100. }, 20);
  101. },
  102. createCanvasData(userID, nickname) {
  103. this.$nextTick(() => {
  104. this.insertAtFlag = {
  105. userID,
  106. nickname
  107. };
  108. });
  109. },
  110. canvasToTempFilePath(sendID, senderNickname, width) {
  111. uni.canvasToTempFilePath({
  112. canvasId: 'atCanvas',
  113. success: (res) => {
  114. this.insertImage({
  115. src: res.tempFilePath,
  116. width,
  117. height: '20px',
  118. data: {
  119. sendID,
  120. senderNickname
  121. },
  122. extClass: 'at_el'
  123. });
  124. uni.createCanvasContext('atCanvas').clearRect();
  125. }
  126. });
  127. },
  128. editorFocus() {
  129. this.$emit('focus');
  130. },
  131. editorBlur() {
  132. console.log("qxj editorBlur");
  133. this.$emit('blur');
  134. },
  135. editorInput(e) {
  136. let str = e.detail.html;
  137. const oldArr = (this.lastStr ?? '').split('');
  138. let contentStr = str;
  139. oldArr.forEach((str) => {
  140. contentStr = contentStr.replace(str, '');
  141. });
  142. contentStr = html2Text(contentStr);
  143. if (contentStr === '@') {
  144. this.$emit('tryAt');
  145. }
  146. // 实时检测空内容并重置
  147. // 如果内容只有换行符(用户删除了所有文本但留下了空行),强制重置为标准空状态
  148. const text = e.detail.text.replace(/\n/g, '');
  149. const hasImage = str.indexOf('<img') !== -1;
  150. if (!hasImage && text.trim().length === 0 && str !== '<p><br></p>') {
  151. // 只有当内容不是标准的空状态时才重置,避免循环触发
  152. // 注意:这里不能直接 setContents,因为会导致光标跳动
  153. // 只能在用户明显清空时做处理,或者在 blur 时处理
  154. // 但为了防止高度异常,我们可以尝试在这里做轻量级检查
  155. }
  156. // 防抖发送 input 事件,避免频繁触发父组件逻辑导致桥接阻塞
  157. if (this.inputTimeout) {
  158. clearTimeout(this.inputTimeout);
  159. }
  160. this.inputTimeout = setTimeout(() => {
  161. this.$emit('input', e);
  162. }, 100);
  163. this.lastStr = e.detail.html;
  164. },
  165. focus() {
  166. this.$refs.editor2.focus();
  167. },
  168. blur() {
  169. console.log("qxj blur");
  170. // 1. 立即触发 renderjs 更新(负责视觉层重置)
  171. // 直接同步修改数据,不再使用 setTimeout,争取第一时间触发
  172. this.blurFlag = this.blurFlag + 1;
  173. console.log("1111", this.blurFlag);
  174. // 2. 先执行内容清理,避免空行堆积导致的高度异常
  175. // 不等待回调,直接尝试清理(如果编辑器支持同步清理更好,但这里只能通过 context)
  176. if (this.editorCtx) {
  177. this.editorCtx.getContents({
  178. success: (res) => {
  179. const html = res.html;
  180. const text = res.text.replace(/\n/g, '');
  181. const hasImage = html.indexOf('<img') !== -1;
  182. // 增强判断:只要没有图片,且文本去空后长度为0,就认为是空
  183. if (!hasImage && text.trim().length === 0) {
  184. // 关键:在这里直接重置
  185. this.editorCtx.setContents({
  186. html: '<p><br></p>'
  187. });
  188. // 同时清空 renderjs 的内容
  189. // 但由于无法直接通信,只能依赖 renderjs 自身的检测
  190. }
  191. }
  192. });
  193. }
  194. // 3. 恢复原生失焦
  195. if (this.editorCtx && this.editorCtx.blur) {
  196. this.editorCtx.blur();
  197. }
  198. }
  199. }
  200. };
  201. </script>
  202. <script module="input" lang="renderjs">
  203. export default {
  204. data() {
  205. return {
  206. editorInstance: null,
  207. timer: null
  208. }
  209. },
  210. mounted() {
  211. // 在 mounted 中提前获取 editor 引用,避免每次查询
  212. this.editorInstance = this.$el.querySelector('.ql-editor');
  213. // 监听键盘收起或输入框失焦事件
  214. // 使用 focusout 并开启捕获阶段,确保能捕获到 blur 事件
  215. // 直接监听根元素,而不是 editorInstance,防止 editorInstance 为空或被替换
  216. this.$el.addEventListener('focusout', this.onEditorBlur, true);
  217. // 同时监听 input 事件,实时防止空行堆积
  218. if (this.editorInstance) {
  219. this.editorInstance.addEventListener('input', this.onEditorInput);
  220. }
  221. },
  222. beforeDestroy() {
  223. this.$el.removeEventListener('focusout', this.onEditorBlur, true);
  224. if (this.editorInstance) {
  225. this.editorInstance.removeEventListener('input', this.onEditorInput);
  226. }
  227. },
  228. methods: {
  229. onEditorInput() {
  230. const editor = this.editorInstance || this.$el.querySelector('.ql-editor');
  231. if (editor) {
  232. // 实时检查:如果只有换行符,强制清空
  233. if (editor.textContent.trim() === '' && !editor.innerHTML.includes('<img')) {
  234. // 只有当高度明显异常时才干预,避免太激进
  235. if (editor.offsetHeight > 50) { // 假设单行高度约30-40px
  236. console.log('renderjs realtime clean triggered');
  237. editor.innerHTML = '<p><br></p>';
  238. }
  239. }
  240. }
  241. },
  242. onEditorBlur() {
  243. console.log('renderjs direct focusout detected');
  244. // 在 renderjs 层直接清理内容,不等待 JS 通知的延迟
  245. const editor = this.editorInstance || this.$el.querySelector('.ql-editor');
  246. if (editor) {
  247. // 如果内容只包含换行符,强制清空
  248. if (editor.textContent.trim() === '' && !editor.innerHTML.includes('<img')) {
  249. console.log('renderjs forcing content clean');
  250. editor.innerHTML = '<p><br></p>';
  251. }
  252. // 使用 requestAnimationFrame 确保在下一帧渲染前执行重置
  253. // 这样比 setTimeout 更精准,也能避免页面闪烁
  254. window.requestAnimationFrame(() => {
  255. // 强制关闭键盘
  256. editor.setAttribute('inputmode', 'none');
  257. editor.blur();
  258. // 强制重置高度样式
  259. editor.style.height = 'auto'; // 先重置为 auto
  260. editor.style.minHeight = '30px'; // 确保最小高度
  261. // 稍微延迟后恢复 inputmode,防止下次聚焦失败
  262. if (this.timer) clearTimeout(this.timer);
  263. this.timer = setTimeout(() => {
  264. editor.removeAttribute('inputmode');
  265. this.timer = null;
  266. }, 50);
  267. });
  268. }
  269. },
  270. handleTouchStart(event, ownerInstance) {
  271. // 仅仅为了让 renderjs 保持活跃,或者在这里直接处理某些逻辑
  272. },
  273. handleForceUpdate(event, ownerInstance) {
  274. // 通过触发点击事件等方式来强制唤醒 renderjs 响应
  275. },
  276. blurFlagUpdate(newValue, oldValue, ownerVm, vm) {
  277. console.log("renderjs blurFlagUpdate", newValue);
  278. if (!newValue) return;
  279. // 优先使用缓存的实例,如果没有则重新获取
  280. const editor = this.editorInstance || this.$el.querySelector('.ql-editor');
  281. if (editor) {
  282. editor.setAttribute('inputmode', 'none'); // 强制关闭软键盘
  283. editor.blur();
  284. console.log('blur',editor.innerHTML);
  285. editor.innerHTML = '<p><br></p>';
  286. console.log("4444");
  287. // 检查并清理内容中的多余换行符,这可能是导致高度异常的原因
  288. // 如果内容为空或者只包含空白字符,强制清空
  289. if (!editor.innerHTML || editor.innerHTML === '<p><br></p>' || editor.textContent.trim() === '') {
  290. // 保持至少一个空段落以维持格式,但确保它是干净的
  291. editor.innerHTML = '<p><br></p>';
  292. }
  293. // 强制重置高度样式
  294. // 极端手段:先隐藏再显示,强制浏览器重排
  295. editor.style.display = 'none';
  296. // 强制回流
  297. editor.offsetHeight;
  298. editor.style.display = 'block';
  299. editor.style.height = '30px';
  300. // 清除之前的 timer,避免多次覆盖
  301. if (this.timer) clearTimeout(this.timer);
  302. this.timer = setTimeout(() => {
  303. editor.style.height = 'auto';
  304. editor.removeAttribute('inputmode'); // 恢复输入模式
  305. this.timer = null;
  306. }, 100);
  307. }
  308. },
  309. insertEmojiFlagUpdate(newValue, oldValue, ownerVm, vm) {
  310. if (newValue === null) {
  311. return;
  312. }
  313. if (newValue) {
  314. this.$el.querySelector('.ql-editor').setAttribute('inputmode', 'none')
  315. ownerVm.callMethod('internalInsertEmoji')
  316. } else {
  317. this.$el.querySelector('.ql-editor').removeAttribute('inputmode')
  318. }
  319. },
  320. insertImageFlagUpdate(newValue, oldValue, ownerVm, vm) {
  321. if (newValue === null) {
  322. return;
  323. }
  324. if (newValue) {
  325. this.$el.querySelector('.ql-editor').setAttribute('inputmode', 'none')
  326. ownerVm.callMethod('internalInsertImage')
  327. } else {
  328. this.$el.querySelector('.ql-editor').removeAttribute('inputmode')
  329. }
  330. },
  331. insertAtFlagUpdate(newValue, oldValue, ownerVm, vm){
  332. if (newValue === null) {
  333. return;
  334. }
  335. if (newValue) {
  336. const data = this.truncateText(`@${newValue.nickname}`,120)
  337. ownerVm.callMethod('internalInsertAtEl', {...data,...newValue})
  338. }
  339. },
  340. truncateText(text, maxWidth) {
  341. const container = document.createElement("div");
  342. container.style.width = "auto";
  343. container.style.overflow = "hidden";
  344. container.style.textOverflow = "ellipsis";
  345. container.style.whiteSpace = "nowrap";
  346. container.style.position = "absolute";
  347. container.style.visibility = "hidden";
  348. const textNode = document.createTextNode(text);
  349. container.appendChild(textNode);
  350. document.body.appendChild(container);
  351. const isOverflowing = container.scrollWidth > maxWidth;
  352. if (!isOverflowing) {
  353. const width = container.clientWidth + 4
  354. document.body.removeChild(container);
  355. return {
  356. text,
  357. width
  358. };
  359. }
  360. container.style.width = maxWidth + "px";
  361. container.style.visibility = "visible";
  362. let truncatedText = text;
  363. while (container.scrollWidth > maxWidth) {
  364. truncatedText = truncatedText.slice(0, -1);
  365. container.textContent = truncatedText + "...";
  366. }
  367. document.body.removeChild(container);
  368. return {
  369. text: `${truncatedText}...`,
  370. width: maxWidth + 4
  371. };
  372. }
  373. },
  374. }
  375. </script>
  376. <style lang="scss" scoped>
  377. .editor_wrap {
  378. position: relative;
  379. }
  380. #editor2 {
  381. background-color: #fff;
  382. min-height: 30px;
  383. max-height: 120px;
  384. height: auto;
  385. word-break: break-all;
  386. }
  387. /deep/.ql-editor {
  388. img {
  389. vertical-align: sub !important;
  390. }
  391. p {
  392. padding: 4px;
  393. }
  394. }
  395. .canvas_container {
  396. position: fixed;
  397. bottom: -99px;
  398. z-index: -100;
  399. &_name {
  400. max-width: 480rpx;
  401. display: inline-block;
  402. overflow: hidden;
  403. text-overflow: ellipsis;
  404. white-space: nowrap;
  405. }
  406. #atCanvas {
  407. height: 20px;
  408. }
  409. .convas_container_name {
  410. font-size: 16px !important;
  411. }
  412. }
  413. </style>