You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VRichTextArea.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import java.util.ArrayList;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.Map.Entry;
  22. import java.util.function.Consumer;
  23. import com.google.gwt.core.client.Scheduler;
  24. import com.google.gwt.dom.client.BodyElement;
  25. import com.google.gwt.dom.client.Element;
  26. import com.google.gwt.dom.client.IFrameElement;
  27. import com.google.gwt.dom.client.NativeEvent;
  28. import com.google.gwt.event.dom.client.BlurHandler;
  29. import com.google.gwt.event.dom.client.KeyDownEvent;
  30. import com.google.gwt.event.dom.client.KeyDownHandler;
  31. import com.google.gwt.event.dom.client.KeyPressEvent;
  32. import com.google.gwt.event.dom.client.KeyPressHandler;
  33. import com.google.gwt.event.shared.HandlerRegistration;
  34. import com.google.gwt.user.client.Command;
  35. import com.google.gwt.user.client.Timer;
  36. import com.google.gwt.user.client.ui.Composite;
  37. import com.google.gwt.user.client.ui.FlowPanel;
  38. import com.google.gwt.user.client.ui.Focusable;
  39. import com.google.gwt.user.client.ui.HTML;
  40. import com.google.gwt.user.client.ui.HasEnabled;
  41. import com.google.gwt.user.client.ui.RichTextArea;
  42. import com.google.gwt.user.client.ui.Widget;
  43. import com.vaadin.client.ApplicationConnection;
  44. import com.vaadin.client.BrowserInfo;
  45. import com.vaadin.client.ConnectorMap;
  46. import com.vaadin.client.ui.ShortcutActionHandler.ShortcutActionHandlerOwner;
  47. import com.vaadin.client.ui.richtextarea.VRichTextToolbar;
  48. /**
  49. * This class implements a basic client side rich text editor component.
  50. *
  51. * @author Vaadin Ltd.
  52. *
  53. */
  54. public class VRichTextArea extends Composite implements Field, KeyPressHandler,
  55. KeyDownHandler, Focusable, HasEnabled {
  56. /**
  57. * The input node CSS classname.
  58. */
  59. public static final String CLASSNAME = "v-richtextarea";
  60. /** For internal use only. May be removed or replaced in the future. */
  61. public String id;
  62. /** For internal use only. May be removed or replaced in the future. */
  63. public ApplicationConnection client;
  64. /** For internal use only. May be removed or replaced in the future. */
  65. public boolean immediate = false;
  66. /** For internal use only. May be removed or replaced in the future. */
  67. public RichTextArea rta;
  68. /** For internal use only. May be removed or replaced in the future. */
  69. public VRichTextToolbar formatter;
  70. /** For internal use only. May be removed or replaced in the future. */
  71. public HTML html = new HTML();
  72. private final FlowPanel fp = new FlowPanel();
  73. private boolean enabled = true;
  74. /** For internal use only. May be removed or replaced in the future. */
  75. public int maxLength = -1;
  76. private int toolbarNaturalWidth = 500;
  77. /** For internal use only. May be removed or replaced in the future. */
  78. public HandlerRegistration keyPressHandler;
  79. private ShortcutActionHandlerOwner hasShortcutActionHandler;
  80. private boolean readOnly = false;
  81. private final Map<BlurHandler, HandlerRegistration> blurHandlers = new HashMap<BlurHandler, HandlerRegistration>();
  82. private List<Command> inputHandlers = new ArrayList<>();
  83. public VRichTextArea() {
  84. createRTAComponents();
  85. fp.add(formatter);
  86. fp.add(rta);
  87. initWidget(fp);
  88. setStyleName(CLASSNAME);
  89. TouchScrollDelegate.enableTouchScrolling(html, html.getElement());
  90. }
  91. private void createRTAComponents() {
  92. rta = new RichTextArea();
  93. rta.setWidth("100%");
  94. rta.addKeyDownHandler(this);
  95. rta.addInitializeHandler(e -> {
  96. // Must wait until iframe is attached to be able to access body
  97. BodyElement rtaBody = IFrameElement.as(rta.getElement())
  98. .getContentDocument().getBody();
  99. addInputListener(rtaBody, event -> {
  100. inputHandlers.forEach(handler -> handler.execute());
  101. });
  102. });
  103. formatter = new VRichTextToolbar(rta);
  104. // Add blur handlers
  105. for (Entry<BlurHandler, HandlerRegistration> handler : blurHandlers
  106. .entrySet()) {
  107. // Remove old registration
  108. handler.getValue().removeHandler();
  109. // Add blur handlers
  110. addBlurHandler(handler.getKey());
  111. }
  112. }
  113. private native void addInputListener(Element element,
  114. Consumer<NativeEvent> listener)
  115. /*-{
  116. element.addEventListener("input", $entry(function(event) {
  117. listener.@java.util.function.Consumer::accept(Ljava/lang/Object;)(event);
  118. }));
  119. }-*/;
  120. public void setMaxLength(int maxLength) {
  121. if (maxLength >= 0) {
  122. if (this.maxLength == -1) {
  123. keyPressHandler = rta.addKeyPressHandler(this);
  124. }
  125. this.maxLength = maxLength;
  126. } else if (this.maxLength != -1) {
  127. this.maxLength = -1;
  128. keyPressHandler.removeHandler();
  129. }
  130. }
  131. @Override
  132. public void setEnabled(boolean enabled) {
  133. if (this.enabled != enabled) {
  134. // rta.setEnabled(enabled);
  135. swapEditableArea();
  136. this.enabled = enabled;
  137. }
  138. }
  139. @Override
  140. public boolean isEnabled() {
  141. return enabled;
  142. }
  143. /**
  144. * Swaps html to rta and visa versa.
  145. */
  146. private void swapEditableArea() {
  147. String value = getValue();
  148. if (html.isAttached()) {
  149. fp.remove(html);
  150. if (BrowserInfo.get().isWebkit()) {
  151. fp.remove(formatter);
  152. createRTAComponents(); // recreate new RTA to bypass #5379
  153. fp.add(formatter);
  154. }
  155. fp.add(rta);
  156. } else {
  157. fp.remove(rta);
  158. fp.add(html);
  159. }
  160. setValue(value);
  161. }
  162. /** For internal use only. May be removed or replaced in the future. */
  163. public void selectAll() {
  164. /*
  165. * There is a timing issue if trying to select all immediately on first
  166. * render. Simple deferred command is not enough. Using Timer with
  167. * moderated timeout. If this appears to fail on many (most likely slow)
  168. * environments, consider increasing the timeout.
  169. *
  170. * FF seems to require the most time to stabilize its RTA. On Vaadin
  171. * tiergarden test machines, 200ms was not enough always (about 50%
  172. * success rate) - 300 ms was 100% successful. This however was not
  173. * enough on a sluggish old non-virtualized XP test machine. A bullet
  174. * proof solution would be nice, GWT 2.1 might however solve these. At
  175. * least setFocus has a workaround for this kind of issue.
  176. */
  177. new Timer() {
  178. @Override
  179. public void run() {
  180. rta.getFormatter().selectAll();
  181. }
  182. }.schedule(320);
  183. }
  184. public void setReadOnly(boolean b) {
  185. if (isReadOnly() != b) {
  186. swapEditableArea();
  187. readOnly = b;
  188. }
  189. // reset visibility in case enabled state changed and the formatter was
  190. // recreated
  191. formatter.setVisible(!readOnly);
  192. }
  193. private boolean isReadOnly() {
  194. return readOnly;
  195. }
  196. @Override
  197. public void setHeight(String height) {
  198. super.setHeight(height);
  199. if (height == null || height.equals("")) {
  200. rta.setHeight("");
  201. }
  202. }
  203. @Override
  204. public void setWidth(String width) {
  205. if (width.equals("")) {
  206. /*
  207. * IE cannot calculate the width of the 100% iframe correctly if
  208. * there is no width specified for the parent. In this case we would
  209. * use the toolbar but IE cannot calculate the width of that one
  210. * correctly either in all cases. So we end up using a default width
  211. * for a RichTextArea with no width definition in all browsers (for
  212. * compatibility).
  213. */
  214. super.setWidth(toolbarNaturalWidth + "px");
  215. } else {
  216. super.setWidth(width);
  217. }
  218. }
  219. @Override
  220. public void onKeyPress(KeyPressEvent event) {
  221. if (maxLength >= 0) {
  222. Scheduler.get().scheduleDeferred(new Command() {
  223. @Override
  224. public void execute() {
  225. if (rta.getHTML().length() > maxLength) {
  226. rta.setHTML(rta.getHTML().substring(0, maxLength));
  227. }
  228. }
  229. });
  230. }
  231. }
  232. @Override
  233. public void onKeyDown(KeyDownEvent event) {
  234. // delegate to closest shortcut action handler
  235. // throw event from the iframe forward to the shortcuthandler
  236. ShortcutActionHandler shortcutHandler = getShortcutHandlerOwner()
  237. .getShortcutActionHandler();
  238. if (shortcutHandler != null) {
  239. shortcutHandler.handleKeyboardEvent(
  240. com.google.gwt.user.client.Event.as(event.getNativeEvent()),
  241. ConnectorMap.get(client).getConnector(this));
  242. }
  243. }
  244. private ShortcutActionHandlerOwner getShortcutHandlerOwner() {
  245. if (hasShortcutActionHandler == null) {
  246. Widget parent = getParent();
  247. while (parent != null) {
  248. if (parent instanceof ShortcutActionHandlerOwner) {
  249. break;
  250. }
  251. parent = parent.getParent();
  252. }
  253. hasShortcutActionHandler = (ShortcutActionHandlerOwner) parent;
  254. }
  255. return hasShortcutActionHandler;
  256. }
  257. @Override
  258. public int getTabIndex() {
  259. return rta.getTabIndex();
  260. }
  261. @Override
  262. public void setAccessKey(char key) {
  263. rta.setAccessKey(key);
  264. }
  265. @Override
  266. public void setFocus(boolean focused) {
  267. /*
  268. * Similar issue as with selectAll. Focusing must happen before possible
  269. * selectall, so keep the timeout here lower.
  270. */
  271. new Timer() {
  272. @Override
  273. public void run() {
  274. rta.setFocus(true);
  275. }
  276. }.schedule(300);
  277. }
  278. @Override
  279. public void setTabIndex(int index) {
  280. rta.setTabIndex(index);
  281. }
  282. /**
  283. * Sets the value of the text area.
  284. *
  285. * @param value
  286. * The text value, as HTML
  287. */
  288. public void setValue(String value) {
  289. if (rta.isAttached()) {
  290. rta.setHTML(value);
  291. } else {
  292. html.setHTML(value);
  293. }
  294. }
  295. /**
  296. * Gets the value of the text area.
  297. *
  298. * @return the value as HTML
  299. */
  300. public String getValue() {
  301. if (rta.isAttached()) {
  302. return rta.getHTML();
  303. } else {
  304. return html.getHTML();
  305. }
  306. }
  307. /**
  308. * Browsers differ in what they return as the content of a visually empty
  309. * rich text area. This method is used to normalize these to an empty
  310. * string. See #8004.
  311. *
  312. * @return cleaned html string
  313. */
  314. public String getSanitizedValue() {
  315. BrowserInfo browser = BrowserInfo.get();
  316. String result = getValue();
  317. if (browser.isFirefox()) {
  318. if ("<br>".equals(result)) {
  319. result = "";
  320. }
  321. } else if (browser.isWebkit() || browser.isEdge()) {
  322. if ("<br>".equals(result) || "<div><br></div>".equals(result)) {
  323. result = "";
  324. }
  325. } else if (browser.isIE()) {
  326. if ("<P>&nbsp;</P>".equals(result)) {
  327. result = "";
  328. }
  329. } else if (browser.isOpera()) {
  330. if ("<br>".equals(result) || "<p><br></p>".equals(result)) {
  331. result = "";
  332. }
  333. }
  334. return result;
  335. }
  336. /**
  337. * Adds a blur handler to the component.
  338. *
  339. * @param blurHandler
  340. * the blur handler to add
  341. */
  342. public void addBlurHandler(BlurHandler blurHandler) {
  343. blurHandlers.put(blurHandler, rta.addBlurHandler(blurHandler));
  344. }
  345. /**
  346. * Removes a blur handler.
  347. *
  348. * @param blurHandler
  349. * the handler to remove
  350. */
  351. public void removeBlurHandler(BlurHandler blurHandler) {
  352. HandlerRegistration registration = blurHandlers.remove(blurHandler);
  353. if (registration != null) {
  354. registration.removeHandler();
  355. }
  356. }
  357. public HandlerRegistration addInputHandler(Command inputHandler) {
  358. inputHandlers.add(inputHandler);
  359. return () -> inputHandlers.remove(inputHandler);
  360. }
  361. }