2 * Plugin that highlights matched word partials in a given element.
3 * TODO: Add a function for restoring the previous text.
4 * TODO: Accept mappings for converting shortcuts like WP: to Wikipedia:.
10 // Split our pattern string at spaces and run our highlight function on the results
11 splitAndHighlight: function ( node
, pat
) {
13 patArray
= pat
.split( ' ' );
14 for ( i
= 0; i
< patArray
.length
; i
++ ) {
15 if ( patArray
[ i
].length
=== 0 ) {
18 $.highlightText
.innerHighlight( node
, patArray
[ i
] );
23 // scans a node looking for the pattern and wraps a span around each match
24 innerHighlight: function ( node
, pat
) {
25 var i
, match
, pos
, spannode
, middlebit
, middleclone
;
26 if ( node
.nodeType
=== Node
.TEXT_NODE
) {
27 // TODO - need to be smarter about the character matching here.
28 // non latin characters can make regex think a new word has begun: do not use \b
29 // http://stackoverflow.com/questions/3787072/regex-wordwrap-with-utf8-characters-in-js
30 // look for an occurrence of our pattern and store the starting position
31 match
= node
.data
.match( new RegExp( '(^|\\s)' + mw
.RegExp
.escape( pat
), 'i' ) );
33 pos
= match
.index
+ match
[ 1 ].length
; // include length of any matched spaces
34 // create the span wrapper for the matched text
35 spannode
= document
.createElement( 'span' );
36 spannode
.className
= 'highlight';
37 // shave off the characters preceding the matched text
38 middlebit
= node
.splitText( pos
);
39 // shave off any unmatched text off the end
40 middlebit
.splitText( pat
.length
);
41 // clone for appending to our span
42 middleclone
= middlebit
.cloneNode( true );
43 // append the matched text node to the span
44 spannode
.appendChild( middleclone
);
45 // replace the matched node, with our span-wrapped clone of the matched node
46 middlebit
.parentNode
.replaceChild( spannode
, middlebit
);
49 node
.nodeType
=== Node
.ELEMENT_NODE
&&
50 // element with childnodes, and not a script, style or an element we created
52 !/(script|style)/i.test( node
.tagName
) &&
54 node
.tagName
.toLowerCase() === 'span' &&
55 node
.className
.match( /\bhighlight/ )
58 for ( i
= 0; i
< node
.childNodes
.length
; ++i
) {
59 // call the highlight function for each child node
60 $.highlightText
.innerHighlight( node
.childNodes
[ i
], pat
);
66 $.fn
.highlightText = function ( matchString
) {
67 return this.each( function () {
69 $el
.data( 'highlightText', { originalText
: $el
.text() } );
70 $.highlightText
.splitAndHighlight( this, matchString
);
74 }( jQuery
, mediaWiki
) );