From 3a6f446ea4f746de46a5b4786fdc9a52e5c010ff Mon Sep 17 00:00:00 2001 From: erickson Date: Fri, 13 Aug 2010 03:49:35 +0000 Subject: [PATCH] DOM text/pattern highlighter openils.Util.hilightNode( node, [pattern1, pattern2, ...], {classname:foo} ); git-svn-id: svn://svn.open-ils.org/ILS/trunk@17205 dcc99617-32d9-48b4-a31d-7c20da2025e4 --- Open-ILS/web/js/dojo/openils/Util.js | 41 ++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/Open-ILS/web/js/dojo/openils/Util.js b/Open-ILS/web/js/dojo/openils/Util.js index 3e2547ae89..bc402bc04f 100644 --- a/Open-ILS/web/js/dojo/openils/Util.js +++ b/Open-ILS/web/js/dojo/openils/Util.js @@ -319,5 +319,46 @@ if(!dojo._hasResource["openils.Util"]) { return openils.Util.objectProperties(o); } + /** + * Highlight instances of each pattern in the given DOM node + * Inspired by the jquery plugin + * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html + */ + openils.Util.hilightNode = function(node, patterns, args) { + + var hclass = (args && args.classname) ? args.classname : 'oils-hightlight'; + + function _hilightNode(node, pat) { + + if(node.nodeType == 3) { + + pat = pat.toUpperCase(); + var text = node.data.toUpperCase(); + var pos = -1; + + // find each instance of pat in the current node + while( (pos = text.indexOf(pat, pos + 1)) >= 0 ) { + + var wrapper = dojo.create('span', {className : hclass}); + var midnode = node.splitText(pos); + midnode.splitText(pat.length); + wrapper.appendChild(midnode.cloneNode(true)); + midnode.parentNode.replaceChild(wrapper, midnode); + } + + } else if(node.nodeType == 1 && node.childNodes[0]) { + + // not a text node? have you checked the children? + dojo.forEach( + node.childNodes, + function(child) { _hilightNode(child, pat); } + ); + } + } + + // descend the tree for each pattern, since nodes are changed during highlighting + dojo.forEach(patterns, function(pat) { _hilightNode(node, pat); }); + }; + } -- 2.11.0