Friday, January 19, 2007

A TextField Highlighter Class for Flex

One of the features I've always felt was missing from Flash TextFields is the ability to highlight a range of characters with a color. What I did in the past was highlight words by changing their color, which is not nearly as satisifying. So, I was really happy to learn that TextFields in Flash 9 have a new method, getCharBoundaries, which returns the bounding rectangle of the specified character. With this method, we can create a rectangle of color to place behind the TextField, highlighting the specified character or characters.

Keith Peters of BIT-101 and Betaruce both have released demos of this exact functionality. However, their demos lack support for word wrapping, or resizing and scrolling of the TextField. Since text highlighting is on the wishlist for an app I'm developing, I figured I'd Flex it up a bit.

My Highlighter class supports word wrapping, resizing, scrolling, and more. You can highlight all instances of a string, or highlight the next and previous instances of the string. You can also use multiple Highlighters on the same TextField for combinations of colors and functionality.

Try out the demo. You may have to wait a few seconds for the sample text and fonts to load. I'm using embedded fonts and a StyleSheet here just to test that it will handle them, but TextFields in general seem to perform better without them. Oh, and you can right-click and view source too (love that about Flex!).

Here's how it works: when you pass the Highlighter a string to highlight, it finds the instances of that string in the TextField and stores the indexes of each character separately in an array. When the TextField is scrolled or resized, the Highlighter determines which of those characters are visible on the screen and draws a Bitmap rectangle behind them. On every SCROLL or RESIZE event, the Bitmap is cleared and highlights are calculated and redrawn.

This could get to be a pretty processor-intensive system, especially when you have a lot of characters being highlighted. This is where I was really pleasantly surprised by Flash Player 9. When I first started the project, I thought "this will never work - it'll be too slow". But Player 9 handles it like a champ. Unbelievably fast.

There are some things that can screw up TextField.getCharBoundaries, such as newline, carriage return, and other whitespace characters (see my last post). Using condenseWhite on your TextField will take care of that. In my case, I have to preserve whitespace, so some pre-processing of the text is necessary to strip out the offending characters.

Also, in my demo I have padding on my TextArea. This throws off getCharBoundaries, and I compensate by passing an xOffset and yOffset value into the Highlighter class.

Speaking of TextAreas... In the Flex components that use a TextField, there is a property called textField, which would be ideal for my Highlighter class to make use of. But, no. It is protected. Am I really going to extend every component in the Flex framework that I want to use my Highlighter class with? Please. For now, I iterate through the children of the TextArea until I find a TextField. It seems to work fine, but I'd prefer to not resort to such hackery. Anyone else got an alternative?

I'm really happy with the Highlighter class so far, but I'm no architect. I could really use some feedback on what should be public, private, protected, etc... and just architectural advice in general, I guess. How can I make this thing fit in better with the Flex framework? Are there changes I could make that would simplify things, or improve performance? Looking forward to your comments.

Was this post helpful to you? If so, please consider making a small donation to keep this blog going.

39 Comments:

Anonymous majordan said...

Nicely done.

In a similar vein, here is a link to a class that extends mx.controls.Text, mx.controls.LinkButton, and mx.skins.halo.HaloFocusRect to make inline anchor links keyboard and screenreader accessible:

http://www.majordan.net/test/inlinelinksapp/

Cheers.

2:38 PM  
Anonymous Dimitrios Gianninas said...

really interesting, but can I pass an array of strings for it to hightlight? if yes, then I could use it in my new spell checker :)

2:59 PM  
Blogger tom said...

@ majordan - Nice stuff! When I get some time, I want to see how you handled the word wrap. My class treats each character individually, which may be a place I could improve performance.

dimitrios - I was considering that option, it should be pretty easy to do. It's really just a matter of modifying the search functions (which could probably use some optimization anyway).

5:36 PM  
Anonymous Tink said...

Good stuff.

To extend this it would be nice if there were some options to search for whole words.

i.e. if you search for 'the', the 'the' in 'their' wouldn't get selected.

6:19 AM  
Blogger tom said...

Tink, I'm working on improving the search functions, although at present they do find strings within words as you describe. However, they are case-sensitive, and I don't trim white space from the inputs, so sometimes you can accidentally get a space at the end of your word that screws things up.

Also, I'm working on some performance optimizations, so check back!

7:34 AM  
Blogger tom said...

Oh, I misread your comment Tink - I thought you DIDN'T want whole word search. :)

Whole word search would definitely be a nice addition - and String.match with a regex should be just the thing to get it done. I also want to add a case-insensitve option.

7:38 AM  
Blogger David Heacock said...

Hi Tom,

I really love your component. It is really fast. I'm having some issues getting it to work with plain text. It works great if I use a whole HTML document, but not on a plain string. Any ideas on that? I'm trying to use it to highlight search terms in the item renederer of a datagrid.

Cheers

12:21 AM  
Blogger tom said...

Hi David, glad to hear you're getting some use out of my work. I don't believe there's anything in my code that would prevent it from working with plain text. You mentioned that you're trying to use it with a datagrid. What happens if you do a simple test case with a plain old TextField?

11:17 AM  
Blogger David Heacock said...

Hi Tom,
In your demo code I tried changing the value of the variable 'txt' to "this is some text" and then I get this error:

RangeError: Error #2006: The supplied index is out of bounds.
at flash.text::TextField/getLineOffset()
at tl.text::StringBoundaries/::getLineEndOffset()
at tl.text::StringBoundaries/get isVisible()
at tl.text::Highlighter/::highlightVisibleBoundaries()
at tl.text::Highlighter/highlightWordInstances()
at HighlighterDemo/globalHighlight()
at HighlighterDemo/__HighlightButton_click()

I have found that it only works as a full html page. Any advice you can provide me would be great. I finally convinced a client to do this project in Flex, rather than HTML, but now they want text highlighting :-)

Cheers

4:55 PM  
Blogger tom said...

Hi David,

This looks like a classic example of me overlooking the simple fact that someone might want to hilight a word in a body of text that one occupies one line. In other words, I was focused on large amounts of text, and forgot to put in checks to handle scenarios for just a few words. How embarrassing. :) I promise to fix the issue soon.

6:13 PM  
Blogger tom said...

Hey David - I fixed the issue, and updated the source code. I never imagined this being used with a datagrid. Let me know how it works out!

9:04 PM  
Blogger David Heacock said...

Tom, love your work ;-) Now I just have to work out how to make it run inside the item renderer. I'll post you the code if I get it going.

Cheers

7:30 AM  
Anonymous free ps3 said...

Thanks for the nice post!

6:55 AM  
Blogger Andrew said...

Tom,
I noticed if the word to be highlighted extends to the second line it doesn't highlight the first line. How can I fix this ?

2:59 PM  
Blogger bdins said...

A word of warning to everyone: make sure you call canvas.dispose() once you are finished with this class as the "canvas" object is grabbing 4 bytes of memory per pixel.

At 2000 by 2000 pixels, this can get very expensive if the memory is never freed up.

11:53 AM  
Blogger hjkl said...

Youth is not wow gold a time of life;world of warcraft gold it is a state of mind; cheap wow gold it is not a Maple Story Accounts matter of rosy cheeks, red lips and supple knees;mesos it is a matter of the will, a quality of the imagination,wow gold kaufen a vigor of the emotions; it is the freshness wow geld of the deep springs of life.maple story mesos Youth means a tempera-mental predominance of courage over timidity, of the appetite for adventure over the love of ease. This often exists in a man of 60 more than a boy of 20.wow gold farmen Nobody grows old merely by a number of years.maple story money We grow old by deserting our ideals.ms mesos Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul. Worry, fear, self-distrust bows the heart and turns the spring back to dust. Whether 60 or 16, there is in every human being’wow powerleveling s heart the lure of wonder, the unfailing childlike appetite of what’s maple story money next and the joy of the game of living.powerlevel In the center of your heart and my heart there is a wireless station: so long as it receives messages maplestory powerleveling of beauty, hope, cheer,world of warcraft power leveling courage and power from men and from the Infinite, so long are you young. When the aerials are down, and your spirit is covered with snows of cynicism and the ice of pessimism, then you are grown old, even at 20, but as long as your aerials are up, to catch waves of optimism, there is hope you may die young at 80!

12:49 AM  
Blogger miyuki said...

ed hardy clothing Online Store - We wholesale and retail cheap ed hardy shirts
g including Ed Hardy Men's Clothing,ed hardy clothing Clothing,Ed Hardy Kids Clothing, ed hardy womens Sunglasses, Ed Hardy Swimwear and more.

1:44 AM  
Blogger miyuki said...

chaussures pumaquelle paire de chaussures pour hommes choisir?!? La réponse est toute simple:chaussures nike une paire de baskets en partie vernies. du 17ème au 5ème rang, qui lui offre une place dans un top 5 largement tn requindominé par les sites de vente de produits high-tech. Le site de réservation d'hôtels Bookings.com gagne pour sa part 47 places et atteint le 8ème rang.

1:44 AM  
Blogger miyuki said...

puma basketBlack is lubricious, can match, but young people don't want to match with brunetpuma femmes, can try even cardigan knitting coat will appear lively cap. Boys and girls, puma CATcan choose to choose self-cultivation

1:44 AM  
Blogger miyuki said...

mens clothing men's sweate, cheap columbia jackets, lacoste sweater, ralph lauren polo shirts,ski clothing. Free Shipping, PayPal Payment. Enjoy your shopping experience on mensclothingstore.Us
nike max shoes, one of the world's three major brands of Puma shoes, will build its factory in Lanshan county next year, Hunan province. Taiwan Diamond Group of Footwear production chooses its base in Lanshan county, which is one of top 500 companies in the world.

1:44 AM  
Blogger miyuki said...

Paypal payment. Free shipping. cheap ugg boots ,UGG Online Store,australian cheap ugg boots ,ugg boots australia,UGG Online Store,black ugg boots,ugg boots on sale,cheap uggs. Very Cheap!Vente en ligne de discount chaussure sport : chaussure puma, chaussure nike, chaussure tn, nike tn,nike requin, puma future cat, nike shox torch, ugg boots et plus.

1:44 AM  
Blogger miyuki said...

ralph Lauren polo shirts , Lacoste Polo Shirts, Burberry Polo Shirts.wholesale Lacoste polo shirts and polo ralph laurenwith great price. clothingol.com offers lot of 10 lacoste polo shirts and lot of 20 cheap polo shirts. clothingol.com offers classic fit polo shirts. polo clothingnike air max ltd is divided into sports life and NIKE NIKENIKE air shoes sports mark for a big hook (swoosh)NIKE life (NSW) mark is a hook NIKE swoosh (English) +Sometimes life will sell NIKE sports channel,cheap puma mens shoes , enjoy shopping!

1:44 AM  
Blogger miyuki said...

ralph lauren polo shirtssport shoes
18boots
clothes sportspolos shirtgilletteclothes sportspolos shirtgillettetrade chinaHAIR STRAIGHTENERS
wedding dresses
英文推广men's jacketpoloshirtsstortKTO

1:45 AM  
Blogger j said...

ralph lauren poloburberry polo shirtthe north face jacketcolumbia jacketspyder jacketed hardy clothing ed hardy clothesed hardy shirts ed hardy t-shirts ed hardy sunglasses ed hardy mensed hardy womens Wholesale HandbagsCheap HandbagsWomens HandbagsCheap PursesDesigner HandbagsTennis RacquetTennis Racket
cheap tennis racquet
tennis racquet discount
cheap tennis racket
discount Tennis Rackethead junior tennis racketwilson tennis racquet
wilson tennis racket
head tennis racketbabolat tennis racket

1:57 AM  
Blogger polo shirt said...

Thank you so much!!polo shirt men'ssweate,cheap polo shirts cheap columbia jackets, lacoste sweater, ralph lauren polo shirts,ski clothing. Free Shipping, PayPal Payment. Enjoy your shopping experience on mensclothingus.com.We have mens polo shirts.

2:58 AM  
Blogger polo shirt said...

God bless you!I really agree with your opinions.Also,there are some new fashion things here,gillette razor blades.gillette mach3 razor bladesfor men.As for ladies,gillette venus razor blades must the best gift for you in summer,gillette fusion blades are all the best choice for you.

2:59 AM  
Blogger polo shirt said...

Awesome!!!Best wishes for you !!wholesale polo shirts is the father of the summer should be prepared to most commonly used item, it has both style and shape of polo clothing, and vest with a random function, so that in the short-sleeved apply to both on many occasions, the pink and black color men's polo shirts brought into effect, lightweight cotton, linen texture to demonstrate masculine temperament and sense of fashion exhaustively. polo shirts for sale

3:00 AM  
Blogger polo shirt said...

fantastic!God bless you!Meanwhile,you can visit my China Wholesale,we have the highest quality but the lowest price fashion products wholesale from China.Here are the most popular China Wholesale products for all of you.Also the polo clothing is a great choice for you.

3:01 AM  
Anonymous lljj said...

Wonderful!!You can find the father who desire fashionable, intellectual cheap polos simultaneously, you can find a psychologist to study the most harmonious of families should be pink mens clothing, so do not want to take the mature route for the father, buy cheap polos, the learn from such a walk in between the formal and casual styling, refined style to create a sense of mild authority.

3:02 AM  
Anonymous lljj said...

Men's polo shirts was the shirt of choice for diverse groups of teenagers
Brightly coloured polo shirts can make you look like a Day-glo dirigible.
Wonderful!You can find the father who desire fashionable eg,uggs fashion,you can enjoy uggs online here, intellectual polo shirt simultaneously

3:04 AM  
Anonymous lljj said...

Do not mean bad.Thank you so much!I just want to show some fashion things to all of you.I like ugg boots.black ugg boots,Loose T-shirt or super-size clothing are the best partners, it allows you to exercise in relax.The classic style cheap uggs may fit someone.You should never design yourself into a monster of no golden section point because beautiful cheap ugg boots.Also,for ladies, in winter sheepskin boots are the excellent choice.ugg boots on sale

3:06 AM  
Anonymous lljj said...

Perfect!!You are a outstanding person!Have you ever wore chaussures puma, puma CAT,Puma shoes store gives some preview of puma speed cat,puma basket, puma speed, puma speed and other puma shoes. These puma sport items are at store recently and available for anyone.

3:07 AM  
Blogger sky22d said...

For the polo shirts, many people loveralphlaurenpoloshirtscheappolos but hate it. This brand is favorite, products like his style; the same is hard not to develop the Lacoste polo shirts brand has been cheap lacoste polos the Asian market. There are stores to buy wholesale polo shirts, However, ralph lauren polo shirts is too many fakes. It will be out of shape cheap ralph lauren polos.

8:41 PM  
Blogger sky22d said...

discount ralph lauren polos are one of the highest in demand cheappolos because along with protecting your skin it also enhances your looks. These polo clothingare the in-thing in today's ralph lauren polo shirts fashion world and among the youngstersdiscount polossummer polospolo shirts whosale.

8:42 PM  
Blogger sky22d said...

It was just a ed hardy clothing with a colourful design of three wolves howling at the moon. Now, it’s a viral sensation with its own ed hardy clothes, videos and an exploding following that has swamped a tiny New ed hardy shirts. Longer arms extend the yoke farther up each side of the babolat pure drive. These arms - or Side Drivers wilson k six- create a stiffer construction and distribute maximum power from the base of the yoke to the middle of the head microgel.

8:43 PM  
Anonymous summer said...

Advanced precision comes from the connection of the Side prince-o3-tour to the cheap tennis racquets at three o'clock and nine o'clock, which results in less torque (or twisting) at polo logopolo shirts in voguepolo women clothinged-hardy shirtsed-hardy sunglassesimpact.

8:44 PM  
Anonymous tree said...

This issue ed hardy t-shirts is of paramount importance as forensic experts ed hardy mens claimed to have discovered in the collar of one of ed hardy womens the fragment of an electronic timer which provided the key link ed hardy sunglasses between the bombing and Libya.They will surely love polo ralph laurenlike this. The styles are so fabulous burberry polos catching the light who would not love lacoste polo shirts like these.

8:46 PM  
Anonymous Anonymous said...

In a womens clothing boutique store, several girls were trying on fashionable new polos men poloswomen polos. In addition to flower dresspolo fashionembroodered polostennis racketsclothing poloclothingedhardyshirtedhardyclothingedhardysummer ed hardy clothingcheap shirtsed hardy brandcheap ed hardypolo shirts cheapcheap tennis racketsdiscount tennis racketsralphlaurenpoloshirtscheappolospolo fashion, flower shirt, flower jacket, even with the scarf pattern is all kinds of flowers.

8:48 PM  
Blogger as said...

I like your blog. Thank you. They are really great . Ermunterung ++ .
Some new style Puma Speed is in fashion this year.
chaussure puma is Puma shoes in french . Many Franzose like seach “chaussure sport” by the internet when they need buy the Puma Shoes Or nike max shoes. The information age is really convenient .




By the way ,the nike max ltd is really good NIKE air shoes ,don’t forget buy the puma mens shoes and nike air max ltd by the internet when you need them . Do you know Nike Air Shoes is a best Air Shoes . another kinds of Nike shoes is better . For example , Nike Air Rift is good and Cheap Nike Shoes .the nike shox shoes is fitting to running.



Spring is coming, Do you think this season is not for Ugg Boots? maybe yes .but this season is best time that can buy the cheap ugg boots. Many sellers are selling discounted. Do not miss . Please view my fc2 blog and hair straighteners blog.
.thank you .


I like orange converse shoes ,I like to buy the cheap converse shoes by the internet shop . the puma shoes and the adidas shoes (or addidas shoes) are more on internet shop .i can buy the cheap nike shoes and cheap puma shoes online. It’s really convenient.
Many persons more like Puma basket shoes than nike air rift shoes . the Puma Cat shoes is a kind of Cheap Puma Shoes .
If you want to buy the Cheap Nike Air shoes ,you can buy them online. They are same as the Nike Air shoes authorized shop. Very high-caliber Air shoes and puma cat shoes . the cheap puma shoes as same as other.




polo shirts

ralph lauren polo shirts
chaussure puma

chaussure sport



chaussures puma

puma CAT

ed hardy clothing

ed hardy clothes



ed hardy womens

ed hardy sunglasses

ugg boots

cheap ugg boots

12:32 AM  

Post a Comment

Links to this post:

Create a Link

<< Home