001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (https://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software, please see the
018 * company website: https://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: https://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.gwt.client.ui.input;
029
030import org.opencms.gwt.client.I_CmsHasInit;
031import org.opencms.gwt.client.I_CmsHasResizeOnShow;
032import org.opencms.gwt.client.ui.CmsScrollPanel;
033import org.opencms.gwt.client.ui.I_CmsAutoHider;
034import org.opencms.gwt.client.ui.css.I_CmsInputLayoutBundle;
035import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle;
036import org.opencms.gwt.client.ui.input.form.CmsWidgetFactoryRegistry;
037import org.opencms.gwt.client.ui.input.form.I_CmsFormWidgetFactory;
038import org.opencms.gwt.client.ui.input.form.I_CmsHasPlaceholder;
039import org.opencms.gwt.client.util.CmsDomUtil;
040import org.opencms.util.CmsStringUtil;
041
042import java.util.Map;
043
044import com.google.common.base.Objects;
045import com.google.common.base.Optional;
046import com.google.gwt.core.client.GWT;
047import com.google.gwt.core.client.Scheduler;
048import com.google.gwt.core.client.Scheduler.ScheduledCommand;
049import com.google.gwt.dom.client.Element;
050import com.google.gwt.event.dom.client.BlurEvent;
051import com.google.gwt.event.dom.client.BlurHandler;
052import com.google.gwt.event.dom.client.ClickEvent;
053import com.google.gwt.event.dom.client.ClickHandler;
054import com.google.gwt.event.dom.client.FocusEvent;
055import com.google.gwt.event.dom.client.FocusHandler;
056import com.google.gwt.event.dom.client.HasFocusHandlers;
057import com.google.gwt.event.dom.client.KeyUpEvent;
058import com.google.gwt.event.dom.client.KeyUpHandler;
059import com.google.gwt.event.logical.shared.HasResizeHandlers;
060import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
061import com.google.gwt.event.logical.shared.ResizeHandler;
062import com.google.gwt.event.logical.shared.ValueChangeEvent;
063import com.google.gwt.event.logical.shared.ValueChangeHandler;
064import com.google.gwt.event.shared.HandlerRegistration;
065import com.google.gwt.user.client.DOM;
066import com.google.gwt.user.client.Timer;
067import com.google.gwt.user.client.ui.Composite;
068import com.google.gwt.user.client.ui.FlowPanel;
069import com.google.gwt.user.client.ui.Panel;
070import com.google.gwt.user.client.ui.SimplePanel;
071import com.google.gwt.user.client.ui.TextArea;
072
073import elemental2.dom.HTMLInputElement;
074import elemental2.dom.HTMLTextAreaElement;
075import jsinterop.base.Js;
076
077/**
078 * Basic text area widget for forms.<p>
079 *
080 * @since 8.0.0
081 *
082 */
083public class CmsTextArea extends Composite
084implements I_CmsFormWidget, I_CmsHasInit, HasValueChangeHandlers<String>, HasResizeHandlers, HasFocusHandlers,
085I_CmsHasResizeOnShow, I_CmsHasGhostValue, I_CmsHasPlaceholder {
086
087    /** The widget type identifier for this widget. */
088    private static final String WIDGET_TYPE = "textarea";
089
090    /** The default rows set. */
091    int m_defaultRows;
092
093    /** The fade panel. */
094    Panel m_fadePanel = new SimplePanel();
095
096    /** The root panel containing the other components of this widget. */
097    Panel m_panel = new FlowPanel();
098
099    /** The internal text area widget used by this widget. */
100    TextArea m_textArea = new TextArea();
101
102    /** The container for the text area. */
103    CmsScrollPanel m_textAreaContainer = GWT.create(CmsScrollPanel.class);
104
105    /** Overlay to disable the text area. */
106    private Element m_disabledOverlay;
107
108    /** The error display for this widget. */
109    private CmsErrorWidget m_error = new CmsErrorWidget();
110
111    /** True if we are currently focused. */
112    private boolean m_focus;
113
114    /** The 'ghost value' to display when no value is set. */
115    private String m_ghostValue;
116
117    /** The real, logical value which might be different from the value displayed in the internal textarea. */
118    private String m_realValue = "";
119
120    /** A timer to schedule the widget size recalculation. */
121    private Timer m_updateSizeTimer;
122
123    /**
124     * Text area widgets for ADE forms.<p>
125     */
126    public CmsTextArea() {
127
128        super();
129        initWidget(m_panel);
130        m_panel.setStyleName(I_CmsInputLayoutBundle.INSTANCE.inputCss().textArea());
131        m_textAreaContainer.addStyleName(I_CmsInputLayoutBundle.INSTANCE.inputCss().textAreaBoxPanel());
132        m_textArea.setStyleName(I_CmsInputLayoutBundle.INSTANCE.inputCss().textAreaBox());
133        m_fadePanel.addStyleName(I_CmsInputLayoutBundle.INSTANCE.inputCss().fader());
134        m_panel.add(m_textAreaContainer);
135        m_textAreaContainer.setResizable(true);
136        m_textAreaContainer.add(m_textArea);
137        m_fadePanel.addDomHandler(new ClickHandler() {
138
139            public void onClick(ClickEvent event) {
140
141                m_textArea.setFocus(true);
142            }
143        }, ClickEvent.getType());
144
145        m_textArea.addKeyUpHandler(new KeyUpHandler() {
146
147            @SuppressWarnings("synthetic-access")
148            public void onKeyUp(KeyUpEvent event) {
149
150                scheduleResize();
151                actionChangeTextareaValue(m_textArea.getValue());
152            }
153
154        });
155
156        m_textArea.addValueChangeHandler(new ValueChangeHandler<String>() {
157
158            @SuppressWarnings("synthetic-access")
159            public void onValueChange(ValueChangeEvent<String> event) {
160
161                actionChangeTextareaValue(event.getValue());
162            }
163        });
164
165        m_panel.add(m_error);
166        m_textAreaContainer.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().cornerAll());
167
168        m_textArea.addFocusHandler(new FocusHandler() {
169
170            @SuppressWarnings("synthetic-access")
171            public void onFocus(FocusEvent event) {
172
173                m_panel.remove(m_fadePanel);
174                CmsDomUtil.fireFocusEvent(CmsTextArea.this);
175                m_focus = true;
176                updateGhostStyle();
177            }
178        });
179        m_textArea.addBlurHandler(new BlurHandler() {
180
181            @SuppressWarnings("synthetic-access")
182            public void onBlur(BlurEvent event) {
183
184                showFadePanelIfNeeded();
185                m_textAreaContainer.scrollToTop();
186                m_focus = false;
187                updateGhostStyle();
188            }
189        });
190    }
191
192    /**
193     * Initializes this class.<p>
194     */
195    public static void initClass() {
196
197        // registers a factory for creating new instances of this widget
198        CmsWidgetFactoryRegistry.instance().registerFactory(WIDGET_TYPE, new I_CmsFormWidgetFactory() {
199
200            public I_CmsFormWidget createWidget(Map<String, String> widgetParams, Optional<String> defaultValue) {
201
202                return new CmsTextArea();
203            }
204        });
205    }
206
207    /**
208     * @see com.google.gwt.event.dom.client.HasFocusHandlers#addFocusHandler(com.google.gwt.event.dom.client.FocusHandler)
209     */
210    public HandlerRegistration addFocusHandler(FocusHandler handler) {
211
212        return addDomHandler(handler, FocusEvent.getType());
213    }
214
215    /**
216     * @see com.google.gwt.event.logical.shared.HasResizeHandlers#addResizeHandler(com.google.gwt.event.logical.shared.ResizeHandler)
217     */
218    public HandlerRegistration addResizeHandler(ResizeHandler handler) {
219
220        return m_textAreaContainer.addResizeHandler(handler);
221    }
222
223    /**
224     * @see com.google.gwt.event.logical.shared.HasValueChangeHandlers#addValueChangeHandler(com.google.gwt.event.logical.shared.ValueChangeHandler)
225     */
226    public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) {
227
228        return addHandler(handler, ValueChangeEvent.getType());
229    }
230
231    /**
232     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#getApparentValue()
233     */
234    public String getApparentValue() {
235
236        return getFormValueAsString();
237    }
238
239    /**
240     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#getFieldType()
241     */
242    public FieldType getFieldType() {
243
244        return I_CmsFormWidget.FieldType.STRING;
245    }
246
247    /**
248     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#getFormValue()
249     */
250    public Object getFormValue() {
251
252        return nullToEmpty(m_realValue);
253    }
254
255    /**
256     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#getFormValueAsString()
257     */
258    public String getFormValueAsString() {
259
260        return (String)getFormValue();
261    }
262
263    /**
264     * Gets the cursor position.
265     *
266     * @return the cursor position
267     */
268    public int getPosition() {
269
270        HTMLInputElement elem = Js.uncheckedCast(m_textArea.getElement()); // wrong class, but works
271        return elem.selectionStart;
272    }
273
274    /**
275     * Returns the text contained in the text area.<p>
276     *
277     * @return the text in the text area
278     */
279    public String getText() {
280
281        return m_textArea.getText();
282    }
283
284    /**
285     * Returns the textarea of this widget.<p>
286     *
287     * @return the textarea
288     */
289    public TextArea getTextArea() {
290
291        return m_textArea;
292    }
293
294    /**
295     * Returns the text area container of this widget.<p>
296     *
297     * @return the text area container
298     */
299    public CmsScrollPanel getTextAreaContainer() {
300
301        return m_textAreaContainer;
302    }
303
304    /**
305     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#isEnabled()
306     */
307    public boolean isEnabled() {
308
309        return m_textArea.isEnabled();
310    }
311
312    /**
313     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#reset()
314     */
315    public void reset() {
316
317        m_textArea.setText("");
318    }
319
320    /**
321     * @see org.opencms.gwt.client.I_CmsHasResizeOnShow#resizeOnShow()
322     */
323    public void resizeOnShow() {
324
325        m_textAreaContainer.onResizeDescendant();
326        updateContentSize();
327        showFadePanelIfNeeded();
328    }
329
330    /**
331     * Selects all content.<p>
332     */
333    public void selectAll() {
334
335        m_textArea.selectAll();
336    }
337
338    /**
339     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#setAutoHideParent(org.opencms.gwt.client.ui.I_CmsAutoHider)
340     */
341    public void setAutoHideParent(I_CmsAutoHider autoHideParent) {
342
343        // nothing to do
344    }
345
346    /**
347     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#setEnabled(boolean)
348     */
349    public void setEnabled(boolean enabled) {
350
351        m_textArea.setEnabled(enabled);
352        // hide / show resize handle
353        m_textAreaContainer.setResizable(enabled);
354        if (enabled) {
355            if (m_disabledOverlay != null) {
356                m_disabledOverlay.removeFromParent();
357                m_disabledOverlay = null;
358            }
359            m_textAreaContainer.onResizeDescendant();
360        } else {
361            if (m_disabledOverlay == null) {
362                m_disabledOverlay = DOM.createDiv();
363                m_disabledOverlay.setClassName(I_CmsInputLayoutBundle.INSTANCE.inputCss().disableTextArea());
364                m_panel.getElement().appendChild(m_disabledOverlay);
365            }
366        }
367    }
368
369    /**
370     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#setErrorMessage(java.lang.String)
371     */
372    public void setErrorMessage(String errorMessage) {
373
374        m_error.setText(errorMessage);
375    }
376
377    /**
378     * Sets or removes focus.<p>
379     *
380     * @param b true if the text area should be focused
381     */
382    public void setFocus(boolean b) {
383
384        m_textArea.setFocus(b);
385
386    }
387
388    /**
389     * Sets the value of the widget.<p>
390     *
391     * @param value the new value
392     */
393    public void setFormValue(Object value) {
394
395        setRealValue((String)value);
396        updateGhostStyle();
397
398    }
399
400    /**
401     * @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#setFormValueAsString(java.lang.String)
402     */
403    public void setFormValueAsString(String newValue) {
404
405        setFormValue(newValue);
406    }
407
408    /**
409     * Not used.<p>
410     *
411     * This widget automatically decides whether it's in ghost mode depending on the real value and ghost value set.<p>
412     *
413     * @param ghostMode not used
414     */
415    public void setGhostMode(boolean ghostMode) {
416        // do nothing
417
418    }
419
420    /**
421     * Enables or disables the 'ghost mode' style.<p>
422     *
423     * @param enabled true if 'ghost mode' style should be enabled
424     */
425    public void setGhostStyleEnabled(boolean enabled) {
426
427        String styleName = I_CmsInputLayoutBundle.INSTANCE.inputCss().textAreaGhostMode();
428        if (enabled) {
429            addStyleName(styleName);
430        } else {
431            removeStyleName(styleName);
432        }
433    }
434
435    /**
436     * @see org.opencms.gwt.client.ui.input.I_CmsHasGhostValue#setGhostValue(java.lang.String, boolean)
437     */
438    public void setGhostValue(String value, boolean ghostMode) {
439
440        m_ghostValue = value;
441        updateGhostStyle();
442    }
443
444    /**
445     * Sets the name of the input field.<p>
446     *
447     * @param name of the input field
448     *
449     */
450    public void setName(String name) {
451
452        m_textArea.setName(name);
453
454    }
455
456    /**
457     * @see org.opencms.gwt.client.ui.input.form.I_CmsHasPlaceholder#setPlaceholder(java.lang.String)
458     */
459    public void setPlaceholder(String placeholder) {
460
461        if (placeholder == null) {
462            placeholder = "";
463        }
464        HTMLTextAreaElement textareaElem = Js.cast(m_textArea.getElement());
465        textareaElem.placeholder = placeholder;
466
467    }
468
469    /**
470     * Sets the cursor position.
471     *
472     * @param position the cursor position
473     */
474    public void setPosition(int position) {
475
476        HTMLInputElement elem = Js.uncheckedCast(m_textArea.getElement()); // wrong class, but works
477        elem.setSelectionRange(position, position);
478    }
479
480    /**
481     * Sets the text area to use a proportional font.<p>
482     *
483     * @param proportional <code>true</code> to use a proportional font
484     */
485    public void setProportionalStyle(boolean proportional) {
486
487        if (proportional) {
488            m_panel.addStyleName(I_CmsInputLayoutBundle.INSTANCE.inputCss().textAreaProportional());
489        } else {
490            m_panel.removeStyleName(I_CmsInputLayoutBundle.INSTANCE.inputCss().textAreaProportional());
491        }
492    }
493
494    /**
495     * Sets the height of this textarea.<p>
496     *
497     * @param rows the value of rows should be shown
498     */
499    public void setRows(int rows) {
500
501        m_defaultRows = rows;
502        double height_scroll = (rows * 17.95) + 8;
503        m_textArea.setVisibleLines(rows);
504        m_textAreaContainer.setHeight(height_scroll + "px");
505        m_textAreaContainer.setDefaultHeight(height_scroll);
506        m_textAreaContainer.onResizeDescendant();
507    }
508
509    /**
510     * Sets the height of this textarea. Especial for the image Gallery.<p>
511     *
512     * @param rows the value of rows should be shown
513     */
514    public void setRowsGallery(int rows) {
515
516        m_defaultRows = rows;
517        double height_scroll = (rows * 17.95) + 8 + 5;
518        m_textArea.setVisibleLines(rows);
519        m_textAreaContainer.setHeight(height_scroll + "px");
520        m_textAreaContainer.setDefaultHeight(height_scroll);
521        m_textAreaContainer.onResizeDescendant();
522    }
523
524    /**
525     * Sets the text in the text area.<p>
526     *
527     * @param text the new text
528     */
529    public void setText(String text) {
530
531        m_textArea.setText(text);
532    }
533
534    /**
535     * @see com.google.gwt.user.client.ui.Composite#onAttach()
536     */
537    @Override
538    protected void onAttach() {
539
540        super.onAttach();
541        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
542
543            public void execute() {
544
545                resizeOnShow();
546            }
547        });
548    }
549
550    /**
551     * Schedules resizing the widget.<p>
552     */
553    protected void scheduleResize() {
554
555        if (m_updateSizeTimer != null) {
556            m_updateSizeTimer.cancel();
557        }
558        m_updateSizeTimer = new Timer() {
559
560            @Override
561            public void run() {
562
563                updateContentSize();
564            }
565        };
566        m_updateSizeTimer.schedule(300);
567    }
568
569    /**
570     * Shows the fade panel if the text area content exceeds the visible area.<p>
571     */
572    protected void showFadePanelIfNeeded() {
573
574        if (m_defaultRows < m_textArea.getVisibleLines()) {
575            m_panel.add(m_fadePanel);
576        }
577    }
578
579    /**
580     * Updates the text area height according to the current text content.<p>
581     */
582    protected void updateContentSize() {
583
584        // The scrolling should be done by the CmsScrollPanel and not by the text area,
585        // so we try to make the text area itself as big as its content here.
586
587        int offsetHeight = m_textArea.getOffsetHeight();
588        int origRows = m_textArea.getVisibleLines();
589        // sanity check: don't do anything, if the measured height doesn't make any sense, e.g. if element is not attached
590        if (offsetHeight > 5) {
591            int scrollPosition = m_textAreaContainer.getVerticalScrollPosition();
592            Element textareaElem = m_textArea.getElement();
593            int rows = Math.max(0, m_defaultRows - 1); // we add 1 to it later, and the sum should be at least 1 and at least the default row number
594            int scrollHeight;
595            int prevOffsetHeight = -1;
596            do {
597                rows += 1;
598                m_textArea.setVisibleLines(rows);
599                scrollHeight = textareaElem.getScrollHeight();
600                offsetHeight = textareaElem.getOffsetHeight();
601                if (offsetHeight <= prevOffsetHeight) {
602                    // Increasing the number of rows should normally increase the offset height.
603                    // If it doesn't, e.g. because of CSS rules limiting the text area height, there is no point in continuing with the loop
604                    break;
605                }
606                prevOffsetHeight = offsetHeight;
607            } while (offsetHeight < scrollHeight);
608            m_textAreaContainer.setVerticalScrollPosition(scrollPosition);
609            if (origRows != rows) {
610                m_textAreaContainer.onResizeDescendant();
611            }
612        }
613    }
614
615    /**
616     * This method is called when the value of the internal textarea changes.<p>
617     *
618     * @param value the textarea value
619     */
620    private void actionChangeTextareaValue(String value) {
621
622        if (m_focus) {
623            setRealValue(value);
624            updateGhostStyle();
625        }
626    }
627
628    /**
629     * Converts null to an empty string, leaves other strings unchanged.<p>
630     *
631     * @param s the input string
632     * @return the input string if it was not null, otherwise the empty string
633     */
634    private String nullToEmpty(String s) {
635
636        if (s == null) {
637            return "";
638        }
639        return s;
640    }
641
642    /**
643     * Sets the 'real' (logical) value.<p>
644     *
645     * @param value the real value
646     */
647    private void setRealValue(String value) {
648
649        if (!Objects.equal(value, m_realValue)) {
650            m_realValue = value;
651            ValueChangeEvent.fire(this, value);
652        }
653    }
654
655    /**
656     * Updates the styling and content of the internal text area based on the real value, the ghost value, and whether
657     * it has focus.
658     */
659    private void updateGhostStyle() {
660
661        if (CmsStringUtil.isEmpty(m_realValue)) {
662            if (CmsStringUtil.isEmpty(m_ghostValue)) {
663                updateTextArea(m_realValue);
664                return;
665            }
666            if (!m_focus) {
667                setGhostStyleEnabled(true);
668                updateTextArea(m_ghostValue);
669            } else {
670                // don't show ghost mode while focused
671                setGhostStyleEnabled(false);
672            }
673        } else {
674            setGhostStyleEnabled(false);
675            updateTextArea(m_realValue);
676        }
677    }
678
679    /**
680     * Updates the content of the internal textarea.<p>
681     *
682     * @param value the new content
683     */
684    private void updateTextArea(String value) {
685
686        String oldValue = m_textArea.getValue();
687        if (!oldValue.equals(value)) {
688            int l1 = oldValue.split("\n").length;
689            int l2 = value.split("\n").length;
690            m_textArea.setValue(value);
691            if (l1 != l2) {
692                scheduleResize();
693            }
694        }
695    }
696}