UNPKG

cross-text-highlight

Version:

``` npm i cross-text-highlight ``` # 基于vue-search-highlight 的跨标签可标注序号的文本高亮插件

2 lines 9.38 kB
(function(t,e){"object"===typeof exports&&"object"===typeof module?module.exports=e():"function"===typeof define&&define.amd?define([],e):"object"===typeof exports?exports["cross-text-highlight"]=e():t["cross-text-highlight"]=e()})("undefined"!==typeof self?self:this,(function(){return function(){"use strict";var t={};!function(){t.d=function(e,n){for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})}}(),function(){t.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)}}(),function(){t.r=function(t){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}}(),function(){t.p=""}();var e={};if(t.r(e),t.d(e,{default:function(){return g}}),"undefined"!==typeof window){var n=window.document.currentScript,o=n&&n.src.match(/(.+\/)[^/]+\.js(\?.*)?$/);o&&(t.p=o[1])}var i=function(){var t=this,e=t._self._c;return e("div",{staticClass:"content-main",on:{contextmenu:function(e){return e.preventDefault(),e.stopPropagation(),t.openContextMenu.apply(null,arguments)},mouseup:t.handleMouseUp}},[t.showContentMenu?e("div",{style:{left:t.left+"px",top:t.top+"px"},attrs:{id:"contentMenu"}},[e("ul",[e("li",{on:{click:t.copy}},[e("i",{staticClass:"el-icon-copy-document"}),e("span",[t._v("复制")])])])]):t._e(),e("div",{staticClass:"highlight",attrs:{id:"highlight"},domProps:{innerHTML:t._s(t.contentShow)}})])},r=[];const s="cross-text-hightlight";var l={name:"CrossTextHighLight",props:{content:{type:String,default:""},moveBehavior:{type:Boolean,default:!1},keyword:{type:String,default:""},highlightStyle:{type:String,default:"background: #ffff00"},currentStyle:{type:String,default:"background: #ff9632"},regExp:{type:Boolean,default:!1},markWidth:{type:String,default:"32px"},markHeight:{type:String,default:"32px"},startColor:{type:String,default:"#ff9632"},endColor:{type:String,default:"#ffff00"},textColor:{type:String,default:"#fff"},borderColor:{type:String,default:"#ff9632"},markLeft:{type:String,default:"-30px"},markTop:{type:String,default:"-16px"},markWeight:{type:String,default:"700"},markFontSize:{type:String,default:"22px"},markZoom:{type:String,default:".65"},isNeedMark:{type:Boolean,default:!1},pEle:{type:String,default:"htmlContent"},isContextMenu:{type:Boolean,default:!1}},data(){return{left:0,top:0,showContentMenu:!1,lightIndex:0,matchCount:0,contentShow:"",copyText:"",random:`${Math.random()}`.slice(2)}},computed:{watchString(){return[this.content,this.keyword]},watchStyle(){return[this.lightIndex,this.highlightStyle,this.currentStyle]},flag(){return`${s}${this.random}`},styleSelector(){return`style[${this.flag}]`}},watch:{watchString:{immediate:!0,handler(){this.replaceKeywords()}},watchStyle:{immediate:!0,handler(){this.setStyle()}},lightIndex:{immediate:!0,handler(){this.$emit("current-change",this.lightIndex)}},matchCount:{immediate:!0,handler(){this.$emit("match-count-change",this.matchCount)}}},mounted(){this.isNeedMark&&this.$nextTick((()=>{this.markNumber(0)})),document.onclick=t=>{console.log(t),this.showContentMenu&&this.checkIn(document.getElementById("contentMenu"))||(this.showContentMenu=!1)}},beforeDestroy(){this.clearStyle()},methods:{handleMouseUp(){if(!this.isContextMenu)return;let t="";t=window.getSelection().toString(),t&&(this.copyText=t),!this.showContentMenu&&this.checkIn(document.getElementById("highlight"))&&(this.left=event.offsetX,this.top=event.offsetY),this.$emit("selection-change",t,event.offsetX,event.offsetY)},copy(){this.$copyText(this.copyText).then((t=>{this.$message({message:"复制成功",type:"success"}),console.log(t)}),(t=>{this.$message({message:"复制失败",type:"error"}),console.log(t)}))},openContextMenu(){this.isContextMenu&&window.getSelection().toString()&&(console.log(window.getSelection().toString()),this.showContentMenu=!0)},checkIn(t){var e=Number(window.event.clientX),n=Number(window.event.clientY),o=Number(t.getBoundingClientRect().left),i=Number(t.getBoundingClientRect().left+t.clientWidth),r=Number(t.getBoundingClientRect().top),s=Number(t.getBoundingClientRect().top+t.clientHeight);return e>o&&e<i&&n>r&&n<s},getTextNodeList(t){const e=[...t.childNodes],n=[];while(e.length){const t=e.shift();t.nodeType===t.TEXT_NODE?t.wholeText&&n.push(t):e.unshift(...t.childNodes)}return n},getTextInfoList(t){let e=0;return t.map((t=>{let n=e,o=e+t.wholeText.length;return e=o,{text:t.wholeText,startIdx:n,endIdx:o}}))},getMatchList(t,e){if(!this.regExp){const t=[..."\\[](){}?.+*^$:|"].reduce(((t,e)=>(t[e]=!0,t)),{});e=e.split("").map((e=>t[e]?`\\${e}`:e)).join("[\\s\\n]*")}const n=new RegExp(e,"gmi"),o=[];let i=n.exec(t);while(i)o.push(i),i=n.exec(t);return o},replaceMatchResult(t,e,n){for(let o=n.length-1;o>=0;o--){const i=n[o],r=i.index,s=r+i[0].length;for(let n=0;n<e.length;n++){const{text:i,startIdx:l,endIdx:h}=e[n];if(h<r)continue;if(l>=s)break;let c=t[n];const a=Math.max(0,r-l),d=Math.min(h,s)-l-a;a>0&&(c=c.splitText(a)),d<c.wholeText.length&&c.splitText(d);const u=document.createElement("font");u.setAttribute(this.flag,o+1),u.innerText=i.substr(a,d),c.parentNode.replaceChild(u,c)}}},replaceKeywords(){let t=!1;if(this.regExp)try{const e=new RegExp(this.keyword);e.test("")&&(t=!0)}catch(s){t=!0}if(t||!this.keyword)return this.matchCount=0,this.lightIndex=0,void(this.contentShow=this.content);const e=document.createElement("div");e.innerHTML=this.content;const n=this.getTextNodeList(e),o=this.getTextInfoList(n),i=o.map((({text:t})=>t)).join(""),r=this.getMatchList(i,this.keyword);this.matchCount=r.length,this.lightIndex=this.matchCount?1:0,this.replaceMatchResult(n,o,r),this.contentShow=e.innerHTML},scrollToOrder(t,e){this.$nextTick((()=>{let n=this.$el.querySelector(`font[${this.flag}='${t}']`);if(n){this.lightIndex=t,this.isNeedMark&&this.markNumber(t-1,this.pEle);const o=document.getElementById(this.pEle);setTimeout((()=>{const t=e;if(t){const e=t.$el.getBoundingClientRect(),i=n.getBoundingClientRect(),r=i.top-e.top;o.scrollTo({top:r-200,behavior:"smooth"})}}),100)}else console.log("未找到该节点")}))},scrollTo(t){this.$nextTick((()=>{let e=this.$el.querySelector(`font[${this.flag}='${t}']`);e&&(this.lightIndex=t,e.scrollIntoView())}))},markNumber(t){let e=document.getElementById(this.pEle),n=[],o=e.getElementsByTagName("font");for(let h=0;h<o.length;h++)o[h].attributes.length>0&&-1!=o[h].attributes[0].name.search("cross-text-hightlight")&&n.push(o[h]);if(!n[t])return void console.log("未找到该节点");let i=document.createElement("canvas");i.width=200,i.height=200;let r=i.getContext("2d");r.clearRect(0,0,i.width,i.height),r.font="150px Arial",r.fillStyle="white",r.textAlign="center",r.textBaseline="middle",r.fillText(t+1,95,110);let s=new Image;s.src=i.toDataURL();let l=document.createElement("img");l.src=s.src,l.className="common-marker",l.style.setProperty("width",`${this.markWidth}`),l.style.setProperty("height",`${this.markHeight}`),l.style.setProperty("border-radius","50%"),l.style.setProperty("background",`linear-gradient(to right, ${this.startColor}, ${this.endColor})`),l.style.setProperty("color",`${this.textColor}`),l.style.setProperty("border",`1px solid ${this.borderColor}`),l.style.setProperty("line-height",`${this.markHeight}`),l.style.setProperty("font-weight",`${this.markWeight}`),l.style.setProperty("position","absolute"),l.style.setProperty("left",`${this.markLeft}`),l.style.setProperty("top",`${this.markTop}`),l.style.setProperty("font-size",`${this.markFontSize}`),l.style.setProperty("zoom",`${this.markZoom}`),l.style.setProperty("text-align","center"),l.style.setProperty("user-select","none"),l.style.setProperty("z-index","999"),l.style.setProperty("max-width","none","!important"),document.querySelectorAll(".common-marker").forEach((t=>{t.remove()})),n[t].insertBefore(l,n[t].firstChild)},searchNext(){this.$nextTick((()=>{let t=this.lightIndex>=this.matchCount?1:this.lightIndex+1;this.scrollToOrder(t)}))},searchLast(){this.$nextTick((()=>{let t=this.lightIndex<=1?this.matchCount:this.lightIndex-1;this.scrollToOrder(t)}))},setStyle(){let t=document.head.querySelector(this.styleSelector);t||(t=document.createElement("style"),t.setAttribute(this.flag,1)),t.innerText=`font[${this.flag}]{${this.highlightStyle};position:relative}font[${this.flag}='${this.lightIndex}']{${this.currentStyle};position:relative}`,document.head.appendChild(t)},clearStyle(){let t=document.head.querySelector(this.styleSelector);t&&document.head.removeChild(t)}}},h=l;function c(t,e,n,o,i,r,s,l){var h,c="function"===typeof t?t.options:t;if(e&&(c.render=e,c.staticRenderFns=n,c._compiled=!0),o&&(c.functional=!0),r&&(c._scopeId="data-v-"+r),s?(h=function(t){t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,t||"undefined"===typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),i&&i.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(s)},c._ssrRegister=h):i&&(h=l?function(){i.call(this,(c.functional?this.parent:this).$root.$options.shadowRoot)}:i),h)if(c.functional){c._injectStyles=h;var a=c.render;c.render=function(t,e){return h.call(e),a(t,e)}}else{var d=c.beforeCreate;c.beforeCreate=d?[].concat(d,h):[h]}return{exports:t,options:c}}var a=c(h,i,r,!1,null,"6579304a",null),d=a.exports,u=d,g=u;return e}()})); //# sourceMappingURL=cross-text-highlight.umd.min.js.map