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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. * Copyright 2000-2018 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 -> inputHandlers
  100. .forEach(handler -> handler.execute()));
  101. });
  102. formatter = new VRichTextToolbar(rta);
  103. // Add blur handlers
  104. for (Entry<BlurHandler, HandlerRegistration> handler : blurHandlers
  105. .entrySet()) {
  106. // Remove old registration
  107. handler.getValue().removeHandler();
  108. // Add blur handlers
  109. addBlurHandler(handler.getKey());
  110. }
  111. }
  112. private native void addInputListener(Element element,
  113. Consumer<NativeEvent> listener)
  114. /*-{
  115. element.addEventListener("input", $entry(function(event) {
  116. listener.@java.util.function.Consumer::accept(Ljava/lang/Object;)(event);
  117. }));
  118. }-*/;
  119. public void setMaxLength(int maxLength) {
  120. if (maxLength >= 0) {
  121. if (this.maxLength == -1) {
  122. keyPressHandler = rta.addKeyPressHandler(this);
  123. }
  124. this.maxLength = maxLength;
  125. } else if (this.maxLength != -1) {
  126. this.maxLength = -1;
  127. keyPressHandler.removeHandler();
  128. }
  129. }
  130. @Override
  131. public void setEnabled(boolean enabled) {
  132. if (this.enabled != enabled) {
  133. // rta.setEnabled(enabled);
  134. this.enabled = enabled;
  135. swapEditableArea();
  136. }
  137. }
  138. @Override
  139. public boolean isEnabled() {
  140. return enabled;
  141. }
  142. /**
  143. * Swaps html to rta and visa versa.
  144. */
  145. private void swapEditableArea() {
  146. String value = getValue();
  147. if (html.isAttached()) {
  148. if (isReadOnly() || !isEnabled()) {
  149. return;
  150. }
  151. fp.remove(html);
  152. if (BrowserInfo.get().isWebkit()) {
  153. fp.remove(formatter);
  154. createRTAComponents(); // recreate new RTA to bypass #5379
  155. fp.add(formatter);
  156. }
  157. fp.add(rta);
  158. } else {
  159. fp.remove(rta);
  160. fp.add(html);
  161. }
  162. setValue(value);
  163. }
  164. /** For internal use only. May be removed or replaced in the future. */
  165. public void selectAll() {
  166. /*
  167. * There is a timing issue if trying to select all immediately on first
  168. * render. Simple deferred command is not enough. Using Timer with
  169. * moderated timeout. If this appears to fail on many (most likely slow)
  170. * environments, consider increasing the timeout.
  171. *
  172. * FF seems to require the most time to stabilize its RTA. On Vaadin
  173. * tiergarden test machines, 200ms was not enough always (about 50%
  174. * success rate) - 300 ms was 100% successful. This however was not
  175. * enough on a sluggish old non-virtualized XP test machine. A bullet
  176. * proof solution would be nice, GWT 2.1 might however solve these. At
  177. * least setFocus has a workaround for this kind of issue.
  178. */
  179. new Timer() {
  180. @Override
  181. public void run() {
  182. rta.getFormatter().selectAll();
  183. }
  184. }.schedule(320);
  185. }
  186. public void setReadOnly(boolean b) {
  187. if (isReadOnly() != b) {
  188. readOnly = b;
  189. swapEditableArea();
  190. }
  191. // reset visibility in case enabled state changed and the formatter was
  192. // recreated
  193. formatter.setVisible(!readOnly);
  194. }
  195. private boolean isReadOnly() {
  196. return readOnly;
  197. }
  198. @Override
  199. public void setHeight(String height) {
  200. super.setHeight(height);
  201. if (height == null || height.isEmpty()) {
  202. rta.setHeight("");
  203. }
  204. }
  205. @Override
  206. public void setWidth(String width) {
  207. if (width.isEmpty()) {
  208. /*
  209. * IE cannot calculate the width of the 100% iframe correctly if
  210. * there is no width specified for the parent. In this case we would
  211. * use the toolbar but IE cannot calculate the width of that one
  212. * correctly either in all cases. So we end up using a default width
  213. * for a RichTextArea with no width definition in all browsers (for
  214. * compatibility).
  215. */
  216. super.setWidth(toolbarNaturalWidth + "px");
  217. } else {
  218. super.setWidth(width);
  219. }
  220. }
  221. @Override
  222. public void onKeyPress(KeyPressEvent event) {
  223. if (maxLength >= 0) {
  224. Scheduler.get().scheduleDeferred(() -> {
  225. if (rta.getHTML().length() > maxLength) {
  226. rta.setHTML(rta.getHTML().substring(0, maxLength));
  227. }
  228. });
  229. }
  230. }
  231. @Override
  232. public void onKeyDown(KeyDownEvent event) {
  233. // delegate to closest shortcut action handler
  234. // throw event from the iframe forward to the shortcuthandler
  235. ShortcutActionHandler shortcutHandler = getShortcutHandlerOwner()
  236. .getShortcutActionHandler();
  237. if (shortcutHandler != null) {
  238. shortcutHandler.handleKeyboardEvent(
  239. com.google.gwt.user.client.Event.as(event.getNativeEvent()),
  240. ConnectorMap.get(client).getConnector(this));
  241. }
  242. }
  243. private ShortcutActionHandlerOwner getShortcutHandlerOwner() {
  244. if (hasShortcutActionHandler == null) {
  245. Widget parent = getParent();
  246. while (parent != null) {
  247. if (parent instanceof ShortcutActionHandlerOwner) {
  248. break;
  249. }
  250. parent = parent.getParent();
  251. }
  252. hasShortcutActionHandler = (ShortcutActionHandlerOwner) parent;
  253. }
  254. return hasShortcutActionHandler;
  255. }
  256. @Override
  257. public int getTabIndex() {
  258. return rta.getTabIndex();
  259. }
  260. @Override
  261. public void setAccessKey(char key) {
  262. rta.setAccessKey(key);
  263. }
  264. @Override
  265. public void setFocus(boolean focused) {
  266. /*
  267. * Similar issue as with selectAll. Focusing must happen before possible
  268. * selectall, so keep the timeout here lower.
  269. */
  270. new Timer() {
  271. @Override
  272. public void run() {
  273. rta.setFocus(true);
  274. }
  275. }.schedule(300);
  276. }
  277. @Override
  278. public void setTabIndex(int index) {
  279. rta.setTabIndex(index);
  280. }
  281. /**
  282. * Sets the value of the text area.
  283. *
  284. * @param value
  285. * The text value, as HTML
  286. */
  287. public void setValue(String value) {
  288. if (rta.isAttached()) {
  289. rta.setHTML(value);
  290. } else {
  291. html.setHTML(value);
  292. }
  293. }
  294. /**
  295. * Gets the value of the text area.
  296. *
  297. * @return the value as HTML
  298. */
  299. public String getValue() {
  300. if (rta.isAttached()) {
  301. return rta.getHTML();
  302. } else {
  303. return html.getHTML();
  304. }
  305. }
  306. /**
  307. * Browsers differ in what they return as the content of a visually empty
  308. * rich text area. This method is used to normalize these to an empty
  309. * string. See #8004.
  310. *
  311. * @return cleaned html string
  312. */
  313. public String getSanitizedValue() {
  314. BrowserInfo browser = BrowserInfo.get();
  315. String result = getValue();
  316. if (browser.isFirefox()) {
  317. if ("<br>".equals(result) || "<div><br></div>".equals(result)) {
  318. result = "";
  319. }
  320. } else if (browser.isWebkit() || browser.isEdge()) {
  321. if ("<br>".equals(result) || "<div><br></div>".equals(result)) {
  322. result = "";
  323. }
  324. } else if (browser.isIE()) {
  325. if ("<P>&nbsp;</P>".equals(result) || "<p><br></p>".equals(result)) {
  326. result = "";
  327. }
  328. } else if (browser.isOpera()) {
  329. if ("<br>".equals(result) || "<p><br></p>".equals(result)) {
  330. result = "";
  331. }
  332. }
  333. return result;
  334. }
  335. /**
  336. * Adds a blur handler to the component.
  337. *
  338. * @param blurHandler
  339. * the blur handler to add
  340. */
  341. public void addBlurHandler(BlurHandler blurHandler) {
  342. blurHandlers.put(blurHandler, rta.addBlurHandler(blurHandler));
  343. }
  344. /**
  345. * Removes a blur handler.
  346. *
  347. * @param blurHandler
  348. * the handler to remove
  349. */
  350. public void removeBlurHandler(BlurHandler blurHandler) {
  351. HandlerRegistration registration = blurHandlers.remove(blurHandler);
  352. if (registration != null) {
  353. registration.removeHandler();
  354. }
  355. }
  356. public HandlerRegistration addInputHandler(Command inputHandler) {
  357. inputHandlers.add(inputHandler);
  358. return () -> inputHandlers.remove(inputHandler);
  359. }
  360. }