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.

SelectorEngine.java 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. /*
  2. * Copyright 2011, The gwtquery team.
  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.google.gwt.query.client.impl;
  17. import static com.google.gwt.query.client.GQuery.document;
  18. import static com.google.gwt.query.client.GQuery.window;
  19. import com.google.gwt.core.client.GWT;
  20. import com.google.gwt.dom.client.Document;
  21. import com.google.gwt.dom.client.Element;
  22. import com.google.gwt.dom.client.Node;
  23. import com.google.gwt.dom.client.NodeList;
  24. import com.google.gwt.query.client.Predicate;
  25. import com.google.gwt.query.client.js.JsMap;
  26. import com.google.gwt.query.client.js.JsNodeArray;
  27. import com.google.gwt.query.client.js.JsUtils;
  28. import com.google.gwt.regexp.shared.MatchResult;
  29. import com.google.gwt.regexp.shared.RegExp;
  30. import java.util.HashSet;
  31. /**
  32. * Core Selector engine functions, and native JS utility functions.
  33. */
  34. public class SelectorEngine implements HasSelector {
  35. private static DocumentStyleImpl styleImpl;
  36. public static native NodeList<Element> getElementsByClassName(String clazz,
  37. Node ctx) /*-{
  38. return ctx.getElementsByClassName(clazz);
  39. }-*/;
  40. public static native Node getNextSibling(Node n) /*-{
  41. return n.nextSibling || null;
  42. }-*/;
  43. public static native Node getPreviousSibling(Node n) /*-{
  44. return n.previousSibling || null;
  45. }-*/;
  46. public NodeList<Element> querySelectorAll(String selector, Node ctx) {
  47. if (!hasQuerySelector) {
  48. return impl.select(selector, ctx);
  49. }
  50. try {
  51. return querySelectorAllImpl(selector, ctx);
  52. } catch (Exception e) {
  53. return impl.select(selector, ctx);
  54. }
  55. }
  56. public static native NodeList<Element> querySelectorAllImpl(String selector,
  57. Node ctx) /*-{
  58. return ctx.querySelectorAll(selector);
  59. }-*/;
  60. public static native NodeList<Element> elementsByTagName(String selector,
  61. Node ctx) /*-{
  62. return ctx.getElementsByTagName(selector);
  63. }-*/;
  64. public static native NodeList<Element> elementsByClassName(String selector,
  65. Node ctx) /*-{
  66. return ctx.getElementsByClassName(selector);
  67. }-*/;
  68. public static NodeList<Element> veryQuickId(String id, Node ctx) {
  69. Document d = ctx.getNodeType() == Node.DOCUMENT_NODE
  70. ? ctx.<Document> cast() : ctx.getOwnerDocument();
  71. return JsNodeArray.create(d.getElementById(id));
  72. }
  73. public static NodeList<Element> xpathEvaluate(String selector, Node ctx) {
  74. return xpathEvaluate(selector, ctx, JsNodeArray.create());
  75. }
  76. public static native NodeList<Element> xpathEvaluate(String selector,
  77. Node ctx, JsNodeArray r) /*-{
  78. var node;
  79. var ownerDoc = ctx && (ctx.ownerDocument || ctx );
  80. var evalDoc = ownerDoc ? ownerDoc : $doc;
  81. var result = evalDoc.evaluate(selector, ctx, null, 0, null);
  82. while ((node = result.iterateNext())) {
  83. r.push(node);
  84. }
  85. return r;
  86. }-*/;
  87. public final SelectorEngineImpl impl;
  88. /**
  89. * Set it to false if all your elements are attached to the DOM and you want to
  90. * increase filter performance using {@link GQuery#getSelectorEngine()}
  91. * method.
  92. */
  93. public boolean filterDetached = true;
  94. protected Node root = Document.get();
  95. public static final boolean hasQuerySelector = hasQuerySelectorAll();
  96. public static JsMap<String, Predicate> filters;
  97. static {
  98. filters = JsMap.create();
  99. filters.put("visible", new Predicate() {
  100. public boolean f(Element e, int index) {
  101. return (e.getOffsetWidth() + e.getOffsetHeight()) > 0 &&
  102. !"none".equalsIgnoreCase(styleImpl.curCSS(e, "display", true));
  103. }
  104. });
  105. filters.put("hidden", new Predicate() {
  106. public boolean f(Element e, int index) {
  107. return !filters.get("visible").f(e, index);
  108. }
  109. });
  110. filters.put("selected", new Predicate() {
  111. public boolean f(Element e, int index) {
  112. return e.getPropertyBoolean("selected");
  113. }
  114. });
  115. filters.put("input", new Predicate() {
  116. public boolean f(Element e, int index) {
  117. return e.getNodeName().toLowerCase().matches("input|select|textarea|button");
  118. }
  119. });
  120. filters.put("header", new Predicate() {
  121. public boolean f(Element e, int index) {
  122. return e.getNodeName().toLowerCase().matches("h\\d");
  123. }
  124. });
  125. }
  126. public SelectorEngine() {
  127. impl = (SelectorEngineImpl) GWT.create(SelectorEngineImpl.class);
  128. GWT.log("GQuery - Created SelectorEngineImpl: " + impl.getClass().getName());
  129. styleImpl = GWT.create(DocumentStyleImpl.class);
  130. GWT.log("GQuery - Created DocumentStyleImpl: " + styleImpl.getClass().getName());
  131. }
  132. public Node getRoot() {
  133. return root;
  134. }
  135. public NodeList<Element> filter(NodeList<Element> nodes, Predicate p) {
  136. JsNodeArray res = JsNodeArray.create();
  137. for (int i = 0, l = nodes.getLength(), j = 0; i < l; i++) {
  138. Element e = nodes.getItem(i);
  139. if (p.f(e, i)) {
  140. res.addNode(e, j++);
  141. }
  142. }
  143. return res;
  144. }
  145. public NodeList<Element> filter(NodeList<Element> nodes, String selector) {
  146. return filter(nodes, selector, filterDetached);
  147. }
  148. public NodeList<Element> filter(NodeList<Element> nodes, String selector, boolean filterDetached) {
  149. JsNodeArray res = JsNodeArray.create();
  150. if (selector.isEmpty()) {
  151. return res;
  152. }
  153. Element ghostParent = null;
  154. HashSet<Node> parents = new HashSet<>();
  155. HashSet<Node> elmList = new HashSet<>();
  156. for (int i = 0, l = nodes.getLength(); i < l; i++) {
  157. Node e = nodes.getItem(i);
  158. if (e == window || e == document || e.getNodeName() == null
  159. || "html".equalsIgnoreCase(e.getNodeName())) {
  160. continue;
  161. }
  162. elmList.add(e);
  163. if (filterDetached) {
  164. Element p = e.getParentElement();
  165. if (p == null) {
  166. if (ghostParent == null) {
  167. ghostParent = Document.get().createDivElement();
  168. parents.add(ghostParent);
  169. }
  170. p = ghostParent;
  171. p.appendChild(e);
  172. } else if (!parents.contains(p)) {
  173. parents.add(p);
  174. }
  175. } else if (parents.isEmpty()) {
  176. parents.add(document);
  177. }
  178. }
  179. for (Node e : parents) {
  180. NodeList<Element> n = select(selector, e);
  181. for (int i = 0, l = n.getLength(); i < l; i++) {
  182. Element el = n.getItem(i);
  183. if (elmList.remove(el)) {
  184. res.addNode(el);
  185. }
  186. }
  187. }
  188. if (ghostParent != null) {
  189. ghostParent.setInnerHTML(null);
  190. }
  191. return res;
  192. }
  193. // pseudo selectors which are computed by gquery in runtime
  194. RegExp gQueryPseudo =
  195. RegExp.compile(
  196. "(.*):((visible|hidden|selected|input|header)|((button|checkbox|file|hidden|image|password|radio|reset|submit|text)\\s*(,|$)))(.*)", "i");
  197. // pseudo selectors which work in engine
  198. RegExp nativePseudo = RegExp.compile(
  199. "(.*):([\\w]+):(disabled|checked|enabled|empty|focus)\\s*([:,].*|$)", "i");
  200. public NodeList<Element> select(String selector, Node ctx) {
  201. if (nativePseudo.test(selector)) {
  202. // move gQuery filters at the end to improve performance, and deal with issue #220
  203. MatchResult r;
  204. while ((r = nativePseudo.exec(selector)) != null) {
  205. selector = r.getGroup(1) + ":" + r.getGroup(3);
  206. if (!r.getGroup(3).equals(r.getGroup(2))) {
  207. selector += ":" + r.getGroup(2);
  208. }
  209. selector += r.getGroup(4);
  210. }
  211. }
  212. if (gQueryPseudo.test(selector)) {
  213. JsNodeArray res = JsNodeArray.create();
  214. for (String s : selector.trim().split("\\s*,\\s*")) {
  215. NodeList<Element> nodes;
  216. MatchResult a = gQueryPseudo.exec(s);
  217. if (a != null) {
  218. String select = a.getGroup(1).isEmpty() ? "*" : a.getGroup(1);
  219. String pseudo = a.getGroup(2);
  220. Predicate pred = filters.get(pseudo.toLowerCase());
  221. if (pred != null) {
  222. nodes = filter(select(select, ctx), pred);
  223. } else if (nativePseudo.test(pseudo)) {
  224. nodes = select(select, ctx);
  225. } else {
  226. nodes = select(select + "[type=" + pseudo + "]", ctx);
  227. }
  228. } else {
  229. nodes = select(s, ctx);
  230. }
  231. JsUtils.copyNodeList(res, nodes, false);
  232. }
  233. return res.<NodeList<Element>> cast();
  234. } else {
  235. return impl.select(selector, ctx);
  236. }
  237. }
  238. public native boolean contains(Element a, Element b) /*-{
  239. return a.contains ? a != b && a.contains(b) : !!(a.compareDocumentPosition(b) & 16)
  240. }-*/;
  241. public void setRoot(Node root) {
  242. assert root != null;
  243. this.root = root;
  244. }
  245. public String getName() {
  246. return getClass().getName().replaceAll("^.*\\.", "");
  247. }
  248. public boolean isDegradated() {
  249. return !hasQuerySelector;
  250. }
  251. /**
  252. * Check if the browser has native support for css selectors.
  253. */
  254. public static native boolean hasQuerySelectorAll() /*-{
  255. return $doc.location.href.indexOf("_force_no_native") < 0 &&
  256. typeof $doc.querySelectorAll == 'function';
  257. }-*/;
  258. public static native boolean hasXpathEvaluate() /*-{
  259. return !!$doc.evaluate;
  260. }-*/;
  261. /**
  262. * Return the DocumentStyleImpl used by this selector engine.
  263. */
  264. public DocumentStyleImpl getDocumentStyleImpl() {
  265. return styleImpl;
  266. }
  267. }