Merge "show old protection in prop=info, if no new protection exists"
[lhc/web/wiklou.git] / resources / jquery / jquery.highlightText.js
1 /**
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:.
5 */
6 ( function ( $ ) {
7
8 $.highlightText = {
9
10 // Split our pattern string at spaces and run our highlight function on the results
11 splitAndHighlight: function ( node, pat ) {
12 var patArray = pat.split( ' ' );
13 for ( var i = 0; i < patArray.length; i++ ) {
14 if ( patArray[i].length === 0 ) {
15 continue;
16 }
17 $.highlightText.innerHighlight( node, patArray[i] );
18 }
19 return node;
20 },
21
22 // scans a node looking for the pattern and wraps a span around each match
23 innerHighlight: function ( node, pat ) {
24 // if this is a text node
25 if ( node.nodeType === 3 ) {
26 // TODO - need to be smarter about the character matching here.
27 // non latin characters can make regex think a new word has begun: do not use \b
28 // http://stackoverflow.com/questions/3787072/regex-wordwrap-with-utf8-characters-in-js
29 // look for an occurrence of our pattern and store the starting position
30 var match = node.data.match( new RegExp( "(^|\\s)" + $.escapeRE( pat ), "i" ) );
31 if ( match ) {
32 var pos = match.index + match[1].length; // include length of any matched spaces
33 // create the span wrapper for the matched text
34 var spannode = document.createElement( 'span' );
35 spannode.className = 'highlight';
36 // shave off the characters preceding the matched text
37 var middlebit = node.splitText( pos );
38 // shave off any unmatched text off the end
39 middlebit.splitText( pat.length );
40 // clone for appending to our span
41 var middleclone = middlebit.cloneNode( true );
42 // append the matched text node to the span
43 spannode.appendChild( middleclone );
44 // replace the matched node, with our span-wrapped clone of the matched node
45 middlebit.parentNode.replaceChild( spannode, middlebit );
46 }
47 // if this is an element with childnodes, and not a script, style or an element we created
48 } else if ( node.nodeType === 1 && node.childNodes && !/(script|style)/i.test( node.tagName )
49 && !( node.tagName.toLowerCase() === 'span' && node.className.match( /\bhighlight/ ) ) ) {
50 for ( var i = 0; i < node.childNodes.length; ++i ) {
51 // call the highlight function for each child node
52 $.highlightText.innerHighlight( node.childNodes[i], pat );
53 }
54 }
55 }
56 };
57
58 $.fn.highlightText = function ( matchString ) {
59 return $( this ).each( function () {
60 var $el = $( this );
61 $el.data( 'highlightText', { originalText: $el.text() } );
62 $.highlightText.splitAndHighlight( this, matchString );
63 } );
64 };
65
66 }( jQuery ) );
67