Search code examples
gwtsmartgwtrichtext

Modify rich text in GWT or smartGWT widget or area


I am trying to create an area with HTML text, a DIV equivalent in GWT or SmartGWT.

Initially some plain text is displayed. User can highlight text and with a press of a button have that text have a line through and turn red in color. Also user can click anywhere in the text and type in new text which would appear underlined and green.

I need to get caret position for each modification as well as newly typed text and so on.

Is there a widget in GWT or SmartGWT that can provide me with such functionality ? currently I have an all javascript solution using DIV and inserting SPANs on click, but I want to move away from it.


Solution

  • This is a demo of a RichTextArea and RichTextToolbar widgets:

    http://samples.gwtproject.org/samples/Showcase/Showcase.html#!CwRichText

    RichTextArea exposes a formatter that can do the things that you need. So if you already have the buttons, you can simply use the formatter to do the work when each button is clicked.

    UPDATE:

    For example, if you want to strikeout a selected text or change its color, it can be done very easily:

    formatter.toggleStrikethrough();
    formatter.setForeColor("#F00");
    

    If you need to get the selected text, you can use something like this:

    private static native String getSelection(Element elem) /*-{
        var txt = "";
        var range;
        var parentElement;
        var container;
    
    if (elem.contentWindow.getSelection) {
            txt = elem.contentWindow.getSelection();
    } else if (elem.contentWindow.document.getSelection) {
            txt = elem.contentWindow.document.getSelection();
    } else if (elem.contentWindow.document.selection) {
            range = elem.contentWindow.document.selection.createRange();
            txt = range.text;
    }
    return "" + txt;
    }-*/;