Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWT Browser focus on next and previous highlight text

I am developing a small application with SWT Browser widget. I am highlighting a search text word with

<a id="xyz" href=''><mark>test</mark></a>

in a HTML document. and replace all the search words in HTML Text in this way so we get all the search words highlighted.

    htmltext.replaceAll("(?i)"+Pattern.quote(searchword), "\\<a id='xyz' href=''> <mark>$0\\</mark></a>

I want to implement functionality that if I click on next button, next highlighted word should get focus and if I click on previous button previous highlighted text should get focus. how can I accomplish Next and Previous Hit using Javascript in Eclipse RCP application.

like image 259
Abhit Avatar asked Sep 26 '14 06:09

Abhit


1 Answers

This is best solved by combining JavaScript with Java code. It depends what kind of HTML content are you going to handle, if it's stateful (e.g. cannot reload), dynamic with lot of JS code, or plain static. In most cases, the best solution would involve most of logic to be written in JS and just minimal code in Java to bind JS actions to SWT GUI.

There's several things you need to implement:

  1. keyword searching
  2. toggling highlighting
  3. toggling highlight from one word to another

1. Search: you realise that you won't be able to search for words that span through many HTML elements, like W<span>o</span>rd? If that's ok then you can just search and replace from Java as you do now. I'd go for individually tagging each word match with id: <span id="match1"> and remembering how many matches in total were found.

You could likely do such search on JS side as well by adding a function that iterates through DOM and searches for specific text and wraps it with another DOM object.

2. Toggling highlighting: It's best done in JavaScript. Append to your HTML a JS code fragment that toggles DOM element style. Something like: `

function highlight(id) {
  document.getElementById(id).className = 'highlighted'
}

You'll be able to call this JS from SWT by invoking swtBrowser.execute("highlight('match1')") Further you should implement function that takes off highlighting.

3. Toggling highlighting between elements: This can be done both on Java side and on JS side. I would probably go with JS and add two more functions: highlightNext() and highlightPrev() that would just call highlight() function with proper ids. Then in Java you could make SWT buttons that call JS functions through SWTBrowser.execute().

like image 135
Jacek Pospychala Avatar answered Nov 17 '22 06:11

Jacek Pospychala