index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // 标识必须独一无二 - 标识是为了使用insertText插入标识文本后,查找到标识所在delta位置的索引
  2. export const linkFlag = '#-*=*-*=*-*=*@-link超链接标识link-@*=*-*=*-*=*-#'
  3. export function addLink(editorCtx, attr) {
  4. // 先插入一段文本内容
  5. editorCtx.insertText({
  6. text: linkFlag
  7. })
  8. // 获取全文delta内容
  9. editorCtx.getContents({
  10. success(res) {
  11. let options = res.delta.ops
  12. const findex = options.findIndex(item => {
  13. return item.insert && typeof item.insert !== 'object' && item.insert?.indexOf(linkFlag) !== -1
  14. })
  15. // 根据标识查找到插入的位置
  16. if (findex > -1) {
  17. const findOption = options[findex]
  18. const findAttributes = findOption.attributes
  19. // 将该findOption分成三部分:前内容 要插入的link 后内容
  20. const [prefix, suffix] = findOption.insert.split(linkFlag);
  21. const handleOps = []
  22. // 前内容
  23. if (prefix) {
  24. const prefixOps = findAttributes ? {
  25. insert: prefix,
  26. attributes: findAttributes
  27. } : {
  28. insert: prefix
  29. }
  30. handleOps.push(prefixOps)
  31. }
  32. // 插入的link
  33. const linkOps = {
  34. insert: attr.text,
  35. attributes: {
  36. link: attr.href,
  37. textDecoration: attr.textDecoration || 'none', // 下划线
  38. color: attr.color || '#007aff'
  39. }
  40. }
  41. handleOps.push(linkOps)
  42. // 后内容
  43. if (suffix) {
  44. const suffixOps = findAttributes ? {
  45. insert: suffix,
  46. attributes: findAttributes
  47. } : {
  48. insert: suffix
  49. }
  50. handleOps.push(suffixOps)
  51. }
  52. // 删除原options[findex]并在findex位置插入上述三个ops
  53. options.splice(findex, 1);
  54. options.splice(findex, 0, ...handleOps);
  55. // 最后重新初始化内容,注意该方法会导致光标重置到最开始位置
  56. editorCtx.setContents({
  57. delta: {
  58. ops: options
  59. }
  60. })
  61. // 所以最后建议使富文本光标失焦,让用户手动聚焦光标
  62. editorCtx.blur()
  63. }
  64. }
  65. })
  66. }