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.

VCustomLayout.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Copyright 2000-2021 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.HashMap;
  18. import java.util.Locale;
  19. import java.util.Map;
  20. import com.google.gwt.dom.client.Element;
  21. import com.google.gwt.dom.client.ImageElement;
  22. import com.google.gwt.dom.client.NodeList;
  23. import com.google.gwt.dom.client.Style;
  24. import com.google.gwt.dom.client.Style.BorderStyle;
  25. import com.google.gwt.dom.client.Style.Position;
  26. import com.google.gwt.dom.client.Style.Unit;
  27. import com.google.gwt.user.client.DOM;
  28. import com.google.gwt.user.client.Event;
  29. import com.google.gwt.user.client.ui.ComplexPanel;
  30. import com.google.gwt.user.client.ui.Widget;
  31. import com.vaadin.client.ApplicationConnection;
  32. import com.vaadin.client.BrowserInfo;
  33. import com.vaadin.client.ComponentConnector;
  34. import com.vaadin.client.StyleConstants;
  35. import com.vaadin.client.Util;
  36. import com.vaadin.client.VCaption;
  37. import com.vaadin.client.VCaptionWrapper;
  38. import com.vaadin.client.WidgetUtil;
  39. /**
  40. * Custom Layout implements complex layout defined with HTML template.
  41. *
  42. * @author Vaadin Ltd
  43. *
  44. */
  45. public class VCustomLayout extends ComplexPanel {
  46. /** The default classname for this widget. */
  47. public static final String CLASSNAME = "v-customlayout";
  48. /** Location-name to containing element in DOM map */
  49. private final Map<String, Element> locationToElement = new HashMap<>();
  50. /** Location-name to contained widget map */
  51. final Map<String, Widget> locationToWidget = new HashMap<>();
  52. /** Widget to captionwrapper map */
  53. private final Map<Widget, VCaptionWrapper> childWidgetToCaptionWrapper = new HashMap<>();
  54. /**
  55. * Unexecuted scripts loaded from the template.
  56. * <p>
  57. * For internal use only. May be removed or replaced in the future.
  58. */
  59. public String scripts = "";
  60. /**
  61. * Paintable ID of this paintable.
  62. * <p>
  63. * For internal use only. May be removed or replaced in the future.
  64. */
  65. public String pid;
  66. /** For internal use only. May be removed or replaced in the future. */
  67. public ApplicationConnection client;
  68. private boolean htmlInitialized = false;
  69. private Element elementWithNativeResizeFunction;
  70. private String height = "";
  71. private String width = "";
  72. /**
  73. * Constructs a widget for a custom layout.
  74. */
  75. @SuppressWarnings("deprecation")
  76. public VCustomLayout() {
  77. setElement(DOM.createDiv());
  78. // Clear any unwanted styling
  79. Style style = getElement().getStyle();
  80. style.setBorderStyle(BorderStyle.NONE);
  81. style.setMargin(0, Unit.PX);
  82. style.setPadding(0, Unit.PX);
  83. if (BrowserInfo.get().isIE()) {
  84. style.setPosition(Position.RELATIVE);
  85. }
  86. setStyleName(CLASSNAME);
  87. }
  88. @Override
  89. public void setStyleName(String style) {
  90. super.setStyleName(style);
  91. addStyleName(StyleConstants.UI_LAYOUT);
  92. }
  93. /**
  94. * Sets widget to given location.
  95. *
  96. * If location already contains a widget it will be removed.
  97. *
  98. * @param widget
  99. * Widget to be set into location.
  100. * @param location
  101. * location name where widget will be added
  102. *
  103. * @throws IllegalArgumentException
  104. * if no such location is found in the layout.
  105. */
  106. public void setWidget(Widget widget, String location) {
  107. if (widget == null) {
  108. return;
  109. }
  110. // If no given location is found in the layout, and exception is throws
  111. Element elem = locationToElement.get(location);
  112. if (elem == null && hasTemplate()) {
  113. throw new IllegalArgumentException(
  114. "No location " + location + " found");
  115. }
  116. // Get previous widget
  117. final Widget previous = locationToWidget.get(location);
  118. // NOP if given widget already exists in this location
  119. if (previous == widget) {
  120. return;
  121. }
  122. if (previous != null) {
  123. remove(previous);
  124. }
  125. // if template is missing add element in order
  126. if (!hasTemplate()) {
  127. elem = getElement();
  128. }
  129. // Add widget to location
  130. super.add(widget, elem);
  131. locationToWidget.put(location, widget);
  132. }
  133. /**
  134. * Initialize HTML-layout.
  135. *
  136. * @param template
  137. * original HTML-template
  138. * @param themeUri
  139. * URI to the current theme
  140. */
  141. public void initializeHTML(String template, String themeUri) {
  142. // Connect body of the template to DOM
  143. template = extractBodyAndScriptsFromTemplate(template);
  144. // TODO prefix img src:s here with a regeps, cannot work further with IE
  145. String relImgPrefix = WidgetUtil
  146. .escapeAttribute(themeUri + "/layouts/");
  147. // prefix all relative image elements to point to theme dir with a
  148. // regexp search
  149. template = template.replaceAll(
  150. "<((?:img)|(?:IMG))\\s([^>]*)src=\"((?![a-z]+:)[^/][^\"]+)\"",
  151. "<$1 $2src=\"" + relImgPrefix + "$3\"");
  152. // also support src attributes without quotes
  153. template = template.replaceAll(
  154. "<((?:img)|(?:IMG))\\s([^>]*)src=[^\"]((?![a-z]+:)[^/][^ />]+)[ />]",
  155. "<$1 $2src=\"" + relImgPrefix + "$3\"");
  156. // also prefix relative style="...url(...)..."
  157. template = template.replaceAll(
  158. "(<[^>]+style=\"[^\"]*url\\()((?![a-z]+:)[^/][^\"]+)(\\)[^>]*>)",
  159. "$1 " + relImgPrefix + "$2 $3");
  160. getElement().setInnerHTML(template);
  161. // Remap locations to elements
  162. locationToElement.clear();
  163. scanForLocations(getElement());
  164. initImgElements();
  165. elementWithNativeResizeFunction = DOM.getFirstChild(getElement());
  166. if (elementWithNativeResizeFunction == null) {
  167. elementWithNativeResizeFunction = getElement();
  168. }
  169. publishResizedFunction(elementWithNativeResizeFunction);
  170. htmlInitialized = true;
  171. }
  172. private native boolean uriEndsWithSlash()
  173. /*-{
  174. var path = $wnd.location.pathname;
  175. if (path.charAt(path.length - 1) == "/")
  176. return true;
  177. return false;
  178. }-*/;
  179. /**
  180. * For internal use only. May be removed or replaced in the future.
  181. *
  182. * @return {@code true} if has template contents, {@code false} otherwise
  183. */
  184. public boolean hasTemplate() {
  185. return htmlInitialized;
  186. }
  187. /** Collect locations from template */
  188. private void scanForLocations(Element elem) {
  189. if (elem.hasAttribute("location")) {
  190. final String location = elem.getAttribute("location");
  191. locationToElement.put(location, elem);
  192. elem.setInnerHTML("");
  193. } else if (elem.hasAttribute("data-location")) {
  194. final String location = elem.getAttribute("data-location");
  195. locationToElement.put(location, elem);
  196. elem.setInnerHTML("");
  197. } else {
  198. final int len = DOM.getChildCount(elem);
  199. for (int i = 0; i < len; i++) {
  200. scanForLocations(DOM.getChild(elem, i));
  201. }
  202. }
  203. }
  204. /**
  205. * Evaluate given script in browser document.
  206. * <p>
  207. * For internal use only. May be removed or replaced in the future.
  208. *
  209. * @param script
  210. * the script to evaluate
  211. */
  212. public static native void eval(String script)
  213. /*-{
  214. try {
  215. if (script != null)
  216. eval("{ var document = $doc; var window = $wnd; "+ script + "}");
  217. } catch (e) {
  218. }
  219. }-*/;
  220. /**
  221. * Img elements needs some special handling in custom layout. Img elements
  222. * will get their onload events sunk. This way custom layout can notify
  223. * parent about possible size change.
  224. */
  225. private void initImgElements() {
  226. NodeList<Element> nodeList = getElement().getElementsByTagName("IMG");
  227. for (int i = 0; i < nodeList.getLength(); i++) {
  228. ImageElement img = ImageElement.as(nodeList.getItem(i));
  229. DOM.sinkEvents(img, Event.ONLOAD);
  230. }
  231. }
  232. /**
  233. * Extract body part and script tags from raw html-template.
  234. *
  235. * Saves contents of all script-tags to private property: scripts. Returns
  236. * contents of the body part for the html without script-tags. Also replaces
  237. * all _UID_ tags with an unique id-string.
  238. *
  239. * @param html
  240. * Original HTML-template received from server
  241. * @return html that is used to create the HTMLPanel.
  242. */
  243. private String extractBodyAndScriptsFromTemplate(String html) {
  244. // Replace UID:s
  245. html = html.replaceAll("_UID_", pid + "__");
  246. // Exctract script-tags
  247. scripts = "";
  248. int endOfPrevScript = 0;
  249. int nextPosToCheck = 0;
  250. String lc = html.toLowerCase(Locale.ROOT);
  251. String res = "";
  252. int scriptStart = lc.indexOf("<script", nextPosToCheck);
  253. while (scriptStart > 0) {
  254. res += html.substring(endOfPrevScript, scriptStart);
  255. scriptStart = lc.indexOf(">", scriptStart);
  256. final int j = lc.indexOf("</script>", scriptStart);
  257. scripts += html.substring(scriptStart + 1, j) + ";";
  258. endOfPrevScript = j + "</script>".length();
  259. nextPosToCheck = endOfPrevScript;
  260. scriptStart = lc.indexOf("<script", nextPosToCheck);
  261. }
  262. res += html.substring(endOfPrevScript);
  263. // Extract body
  264. html = res;
  265. lc = html.toLowerCase(Locale.ROOT);
  266. int startOfBody = lc.indexOf("<body");
  267. if (startOfBody < 0) {
  268. res = html;
  269. } else {
  270. res = "";
  271. startOfBody = lc.indexOf(">", startOfBody) + 1;
  272. final int endOfBody = lc.indexOf("</body>", startOfBody);
  273. if (endOfBody > startOfBody) {
  274. res = html.substring(startOfBody, endOfBody);
  275. } else {
  276. res = html.substring(startOfBody);
  277. }
  278. }
  279. return res;
  280. }
  281. /**
  282. * Update caption for the given child connector.
  283. *
  284. * @param childConnector
  285. * the child connector whose caption should be updated
  286. */
  287. public void updateCaption(ComponentConnector childConnector) {
  288. Widget widget = childConnector.getWidget();
  289. if (!widget.isAttached()) {
  290. // Widget has not been added because the location was not found
  291. return;
  292. }
  293. VCaptionWrapper wrapper = childWidgetToCaptionWrapper.get(widget);
  294. if (VCaption.isNeeded(childConnector)) {
  295. if (wrapper == null) {
  296. // Add a wrapper between the layout and the child widget
  297. final String loc = getLocation(widget);
  298. super.remove(widget);
  299. wrapper = new VCaptionWrapper(childConnector, client);
  300. super.add(wrapper, locationToElement.get(loc));
  301. childWidgetToCaptionWrapper.put(widget, wrapper);
  302. }
  303. wrapper.updateCaption();
  304. } else {
  305. if (wrapper != null) {
  306. // Remove the wrapper and add the widget directly to the layout
  307. final String loc = getLocation(widget);
  308. super.remove(wrapper);
  309. super.add(widget, locationToElement.get(loc));
  310. childWidgetToCaptionWrapper.remove(widget);
  311. }
  312. }
  313. }
  314. /**
  315. * Get the location of an widget.
  316. *
  317. * @param w
  318. * the widget whose location to check
  319. * @return location name, or {@code null} if not found
  320. */
  321. public String getLocation(Widget w) {
  322. for (final String location : locationToWidget.keySet()) {
  323. if (locationToWidget.get(location) == w) {
  324. return location;
  325. }
  326. }
  327. return null;
  328. }
  329. /** Removes given widget from the layout. */
  330. @Override
  331. public boolean remove(Widget w) {
  332. final String location = getLocation(w);
  333. if (location != null) {
  334. locationToWidget.remove(location);
  335. }
  336. final VCaptionWrapper cw = childWidgetToCaptionWrapper.get(w);
  337. if (cw != null) {
  338. childWidgetToCaptionWrapper.remove(w);
  339. return super.remove(cw);
  340. } else if (w != null) {
  341. return super.remove(w);
  342. }
  343. return false;
  344. }
  345. /** Adding widget without specifying location is not supported. */
  346. @Override
  347. public void add(Widget w) {
  348. throw new UnsupportedOperationException();
  349. }
  350. /** Clear all widgets from the layout. */
  351. @Override
  352. public void clear() {
  353. super.clear();
  354. locationToWidget.clear();
  355. childWidgetToCaptionWrapper.clear();
  356. }
  357. /**
  358. * This method is published to JS side with the same name into first DOM
  359. * node of custom layout. This way if one implements some resizeable
  360. * containers in custom layout he/she can notify children after resize.
  361. *
  362. * @deprecated this method has done absolutely nothing since Vaadin 7.0 and
  363. * should not be used, before that forced a recursive re-layout
  364. */
  365. @Deprecated
  366. public void notifyChildrenOfSizeChange() {
  367. }
  368. @Override
  369. public void onDetach() {
  370. super.onDetach();
  371. if (elementWithNativeResizeFunction != null) {
  372. detachResizedFunction(elementWithNativeResizeFunction);
  373. }
  374. }
  375. private native void detachResizedFunction(Element element)
  376. /*-{
  377. element.notifyChildrenOfSizeChange = null;
  378. }-*/;
  379. private native void publishResizedFunction(Element element)
  380. /*-{
  381. var self = this;
  382. element.notifyChildrenOfSizeChange = $entry(function() {
  383. self.@com.vaadin.client.ui.VCustomLayout::notifyChildrenOfSizeChange()();
  384. });
  385. }-*/;
  386. /**
  387. * In custom layout one may want to run layout functions made with
  388. * JavaScript. This function tests if one exists (with name "iLayoutJS" in
  389. * layouts first DOM node) and runs it. Return value is used to determine if
  390. * children needs to be notified of size changes.
  391. * <p>
  392. * Note! When implementing a JS layout function you most likely want to call
  393. * notifyChildrenOfSizeChange() function on your custom layouts main
  394. * element. That method is used to control whether child components layout
  395. * functions are to be run.
  396. * <p>
  397. * For internal use only. May be removed or replaced in the future.
  398. *
  399. * @param el
  400. * The first element of the layout
  401. * @return true if layout function exists and was run successfully, else
  402. * false.
  403. */
  404. @SuppressWarnings("deprecation")
  405. public native boolean iLayoutJS(com.google.gwt.user.client.Element el)
  406. /*-{
  407. if (el && el.iLayoutJS) {
  408. try {
  409. el.iLayoutJS();
  410. return true;
  411. } catch (e) {
  412. return false;
  413. }
  414. } else {
  415. return false;
  416. }
  417. }-*/;
  418. @SuppressWarnings("deprecation")
  419. @Override
  420. public void onBrowserEvent(Event event) {
  421. super.onBrowserEvent(event);
  422. if (event.getTypeInt() == Event.ONLOAD) {
  423. Util.notifyParentOfSizeChange(this, true);
  424. event.cancelBubble(true);
  425. }
  426. }
  427. }