+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.google.gwt.query.client;
import com.google.gwt.dom.client.Element;
}
/**
- * Wrap a JSON object
+ * Wrap a JSON object.
*/
public static Properties $$(String properties) {
return GQuery.$$(properties);
}
/**
- * Registers a GQuery plugin
+ * Registers a GQuery plugin.
* @param plugin
* @param pluginFactory
*/
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
import com.google.gwt.dom.client.Node;\r
public interface DeferredGQuery {\r
\r
/**\r
- * The selector which was compiled.\r
- * @return\r
+ * Evaluate the compiled selector with the given DOM node as a context.\r
+ * Returns a NodeList as a result.\r
*/\r
- String getSelector();\r
+ NodeList<Element> array(Node ctx);\r
\r
/**\r
* Evaluate the compiled selector with the given DOM node as a context.\r
* Returns the result as a GQuery object.\r
- * @param ctx\r
- * @return\r
*/\r
- GQuery eval(Node ctx);\r
+ GQuery eval(Node ctx);\r
\r
/**\r
- * Evaluate the compiled selector with the given DOM node as a context.\r
- * Returns a NodeList as a result.\r
- * @param ctx\r
- * @return\r
+ * The selector which was compiled.\r
*/\r
- NodeList<Element> array(Node ctx);\r
+ String getSelector();\r
}\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
import com.google.gwt.animation.client.Animation;\r
import com.google.gwt.dom.client.Element;\r
import com.google.gwt.dom.client.NodeList;\r
\r
+/**\r
+ * Effects plugin for Gwt Query.\r
+ */\r
public class Effects extends GQuery {\r
\r
- static {\r
- GQuery.registerPlugin(Effects.class, new EffectsPlugin());\r
+ /**\r
+ * Used to register the plugin.\r
+ */\r
+ private static class EffectsPlugin implements Plugin<Effects> {\r
+\r
+ public Effects init(GQuery gq) {\r
+ return new Effects(gq.get());\r
+ }\r
}\r
\r
public static final Class<Effects> Effects = Effects.class;\r
\r
+ static {\r
+ GQuery.registerPlugin(Effects.class, new EffectsPlugin());\r
+ }\r
+\r
public Effects(Element element) {\r
super(element);\r
}\r
super(list);\r
}\r
\r
- public Effects hide() {\r
- this.css("display", "none");\r
- return this;\r
- }\r
-\r
- public Effects show() {\r
- this.css("display", "");\r
- return this;\r
- }\r
-\r
- public boolean visible() {\r
- return !"none".equalsIgnoreCase(this.css("display"));\r
- }\r
-\r
- public Effects toggle() {\r
- for (Element e : elements()) {\r
- Effects ef = new Effects(e);\r
- if (ef.visible()) {\r
- ef.hide();\r
- } else {\r
- ef.show();\r
- }\r
- }\r
- return this;\r
- }\r
-\r
- public Effects fadeOut() {\r
+ public Effects fadeIn() {\r
Animation a = new Animation() {\r
\r
public void onCancel() {\r
}\r
\r
public void onComplete() {\r
- for (int i = 0; i < elements.getLength(); i++) {\r
- elements.getItem(i).getStyle().setProperty("opacity", "0");\r
- elements.getItem(i).getStyle().setProperty("display", "none");\r
- }\r
}\r
\r
public void onStart() {\r
public void onUpdate(double progress) {\r
for (int i = 0; i < elements.getLength(); i++) {\r
elements.getItem(i).getStyle()\r
- .setProperty("opacity", String.valueOf(1.0 - progress));\r
+ .setProperty("opacity", String.valueOf(progress));\r
}\r
}\r
};\r
return this;\r
}\r
\r
- public Effects fadeIn() {\r
+ public Effects fadeOut() {\r
Animation a = new Animation() {\r
\r
public void onCancel() {\r
}\r
\r
public void onComplete() {\r
+ for (int i = 0; i < elements.getLength(); i++) {\r
+ elements.getItem(i).getStyle().setProperty("opacity", "0");\r
+ elements.getItem(i).getStyle().setProperty("display", "none");\r
+ }\r
}\r
\r
public void onStart() {\r
public void onUpdate(double progress) {\r
for (int i = 0; i < elements.getLength(); i++) {\r
elements.getItem(i).getStyle()\r
- .setProperty("opacity", String.valueOf(progress));\r
+ .setProperty("opacity", String.valueOf(1.0 - progress));\r
}\r
}\r
};\r
return this;\r
}\r
\r
- public static class EffectsPlugin implements Plugin<Effects> {\r
+ public Effects hide() {\r
+ this.css("display", "none");\r
+ return this;\r
+ }\r
\r
- public Effects init(GQuery gq) {\r
- return new Effects(gq.get());\r
+ public Effects show() {\r
+ this.css("display", "");\r
+ return this;\r
+ }\r
+\r
+ public Effects toggle() {\r
+ for (Element e : elements()) {\r
+ Effects ef = new Effects(e);\r
+ if (ef.visible()) {\r
+ ef.hide();\r
+ } else {\r
+ ef.show();\r
+ }\r
}\r
+ return this;\r
+ }\r
+\r
+ public boolean visible() {\r
+ return !"none".equalsIgnoreCase(this.css("display"));\r
}\r
}\r
+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.google.gwt.query.client;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Event;
/**
- * GQuery Plugin for handling and queuing browser events
+ * GQuery Plugin for handling and queuing browser events.
*/
public class Events extends GQuery {
+ public static final Class<Events> Events = Events.class;
+
static {
GQuery.registerPlugin(Events.class, new Plugin<Events>() {
public Events init(GQuery gq) {
});
}
- public static final Class<Events> Events = Events.class;
-
public Events(Element element) {
super(element);
}
}
/**
- * Just a class with static methods for firing element events on demand
+ * Just a class with static methods for firing element events on demand.
*/
class FireEvents {
- private native static Event createMouseEventImpl(String type) /*-{
- var event = $doc.createEvent('MouseEvents');
- event.initEvent(type, true, true);
- return event;
+ public static void fire(Element element, int eventbits, int... keys) {
+ Event event = null;
+
+ String type = getEventTypeStr(eventbits);
+
+ if ((eventbits & Event.MOUSEEVENTS) != 0
+ || (eventbits | Event.ONCLICK) == Event.ONCLICK) {
+ event = createMouseEventImpl(type);
+ } else if ((eventbits & Event.KEYEVENTS) != 0) {
+ event = createKeyEventImpl(type, keys[0]);
+ } else if ((eventbits & Event.FOCUSEVENTS) != 0) {
+ event = createHtmlEventImpl(type);
+ }
+
+ dispatchEvent(element, event);
+ }
+
+ private static native Event createHtmlEventImpl(String type) /*-{
+ var event = $doc.createEvent('HTMLEvents');
+ event.initEvent( type, true, true);
+ return event;
}-*/;
- private native static Event createKeyEventImpl(String type, int keycode) /*-{
+ private static native Event createKeyEventImpl(String type, int keycode) /*-{
var event;
if( $wnd.KeyEvent ) {
event = $doc.createEvent('KeyEvents');
return event;
}-*/;
- private native static Event createHtmlEventImpl(String type) /*-{
- var event = $doc.createEvent('HTMLEvents');
- event.initEvent( type, true, true);
- return event;
+ private static native Event createMouseEventImpl(String type) /*-{
+ var event = $doc.createEvent('MouseEvents');
+ event.initEvent(type, true, true);
+ return event;
}-*/;
- private native static void dispatchEvent(Element elem, Event event) /*-{
+ private static native void dispatchEvent(Element elem, Event event) /*-{
elem.dispatchEvent(event);
if (event.type == 'focus' && elem.focus)
elem.focus();
return "";
}
}
-
- public static void fire(Element element, int eventbits, int... keys) {
- Event event = null;
-
- String type = getEventTypeStr(eventbits);
-
- if ((eventbits & Event.MOUSEEVENTS) != 0
- || (eventbits | Event.ONCLICK) == Event.ONCLICK) {
- event = createMouseEventImpl(type);
- } else if ((eventbits & Event.KEYEVENTS) != 0) {
- event = createKeyEventImpl(type, keys[0]);
- } else if ((eventbits & Event.FOCUSEVENTS) != 0) {
- event = createHtmlEventImpl(type);
- }
-
- dispatchEvent(element, event);
- }
}
\ No newline at end of file
+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.google.gwt.query.client;
import com.google.gwt.user.client.EventListener;
import java.util.List;
import java.util.ArrayList;
-
/**
- * This class implements an event queue instance for one element.
- * This queue instance is configured as the default event listener in GWT.
- *
- * The reference to this queue is stored as a uniq variable in the element's DOM
- *
- * The class takes care of calling the appropiate functions for each browser event
- * and also calls sinkEvents methods.
- *
+ * This class implements an event queue instance for one element. This queue
+ * instance is configured as the default event listener in GWT.
+ *
+ * The reference to this queue is stored as a uniq variable in the element's
+ * DOM
+ *
+ * The class takes care of calling the appropiate functions for each browser
+ * event and also calls sinkEvents methods.
*/
class EventsListener implements EventListener {
- private class BindFunction {
+ private static class BindFunction {
+
int type;
+
Function function;
+
Object data;
+
int times = -1;
BindFunction(int t, Function f, Object d) {
this.times = times;
}
- public boolean hasEventType(int etype) {
- return (type | etype) == type;
- }
-
public boolean fire(Event event) {
if (times != 0) {
times--;
}
return true;
}
+
+ public boolean hasEventType(int etype) {
+ return (type | etype) == type;
+ }
}
-
- private native static EventsListener getWidgetElementImpl(
- Element elem) /*-{
+
+ public static EventsListener getInstance(Element e) {
+ EventsListener ret = getWidgetElementImpl(e);
+ return ret != null ? ret : new EventsListener(e);
+ }
+
+ private static native EventsListener getWidgetElementImpl(Element elem) /*-{
return elem.__gqueryevent;
}-*/;
- private native static void setWidgetElementImpl(Element elem, EventsListener gqevent) /*-{
- elem.__gqueryevent = gqevent;
+ private static native void setFocusable(Element elem) /*-{
+ elem.tabIndex = 0;
}-*/;
- private native static void setFocusable(Element elem) /*-{
- elem.tabIndex = 0;
+ private static native void setWidgetElementImpl(Element elem,
+ EventsListener gqevent) /*-{
+ elem.__gqueryevent = gqevent;
}-*/;
+ private List<EventsListener.BindFunction> elementEvents
+ = new ArrayList<EventsListener.BindFunction>();
- private List<EventsListener.BindFunction> elementEvents = new ArrayList<EventsListener.BindFunction>();
private Element element;
private EventsListener(Element e) {
DOM.setEventListener((com.google.gwt.user.client.Element) e, this);
}
- public static EventsListener getInstance(Element e) {
- EventsListener ret = getWidgetElementImpl(e);
- return ret != null ? ret : new EventsListener(e);
- }
-
- public void bind(int eventbits, final Object data, final Function function, int times) {
+ public void bind(int eventbits, final Object data, final Function function,
+ int times) {
if (function == null) {
unbind(eventbits);
} else {
- DOM.sinkEvents((com.google.gwt.user.client.Element) element, eventbits
- | DOM.getEventsSunk((com.google.gwt.user.client.Element) element));
+ DOM.sinkEvents((com.google.gwt.user.client.Element) element,
+ eventbits | DOM
+ .getEventsSunk((com.google.gwt.user.client.Element) element));
- if ((eventbits | Event.FOCUSEVENTS) == Event.FOCUSEVENTS)
+ if ((eventbits | Event.FOCUSEVENTS) == Event.FOCUSEVENTS) {
setFocusable(element);
+ }
- elementEvents.add(new EventsListener.BindFunction(eventbits, function, data, times));
+ elementEvents.add(
+ new EventsListener.BindFunction(eventbits, function, data, times));
}
}
}
public void unbind(int eventbits) {
- ArrayList<EventsListener.BindFunction> newList = new ArrayList<EventsListener.BindFunction>();
- for (EventsListener.BindFunction listener : elementEvents)
- if (!listener.hasEventType(eventbits))
+ ArrayList<EventsListener.BindFunction> newList
+ = new ArrayList<EventsListener.BindFunction>();
+ for (EventsListener.BindFunction listener : elementEvents) {
+ if (!listener.hasEventType(eventbits)) {
newList.add(listener);
+ }
+ }
elementEvents = newList;
}
-
}
+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.google.gwt.query.client;
import com.google.gwt.dom.client.Element;
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
import com.google.gwt.core.client.GWT;\r
import java.util.Map;\r
\r
/**\r
- *\r
+ * Gwt Query is a GWT clone of the popular jQuery library.\r
*/\r
public class GQuery {\r
\r
+ /**\r
+ * A POJO used to store the top/left CSS positioning values of an element.\r
+ */\r
public static class Offset {\r
\r
public int top;\r
}\r
\r
public static <T extends GQuery> T $(T gq) {\r
-\r
return gq;\r
}\r
\r
Class<T> plugin) {\r
try {\r
if (plugins != null) {\r
- T gquery = (T) plugins.get(plugin)\r
- .init(new GQuery(select(selector, context)));\r
+ T gquery = (T) plugins.get(plugin).\r
+ init(new GQuery(select(selector, context)));\r
return gquery;\r
}\r
throw new RuntimeException("No plugin for class " + plugin);\r
}\r
\r
/**\r
- * Wrap a JSON object\r
+ * Wrap a JSON object.\r
*/\r
public static Properties $$(String properties) {\r
return Properties.create(properties);\r
}\r
\r
/**\r
- * Copied from UIObject *\r
+ * Copied from UIObject.\r
*/\r
protected static void setStyleName(Element elem, String style, boolean add) {\r
\r
\r
protected NodeList<Element> elements = null;\r
\r
- private String selector;\r
+ private String currentSelector;\r
\r
private GQuery previousObject;\r
\r
* Remove all child nodes from the set of matched elements.\r
*/\r
public GQuery empty() {\r
- //TODO: add memory leak cleanup, remove event handlers, and \r
+ // TODO: add memory leak cleanup, remove event handlers, and \r
// data caches\r
for (Element e : elements()) {\r
while (e.getFirstChild() != null) {\r
result.addNode(e);\r
}\r
}\r
- return pushStack(result, "filter", selector);\r
+ return pushStack(result, "filter", currentSelector);\r
}\r
\r
/**\r
* Return the selector representing the current set of matched elements.\r
*/\r
public String getSelector() {\r
- return selector;\r
+ return currentSelector;\r
}\r
\r
/**\r
* Get the current computed, pixel, height of the first matched element.\r
*/\r
public int height() {\r
- return DOM\r
- .getElementPropertyInt((com.google.gwt.user.client.Element) get(0),\r
+ return DOM.\r
+ getElementPropertyInt((com.google.gwt.user.client.Element) get(0),\r
"offsetHeight");\r
}\r
\r
/**\r
- * Make invisible all matched elements\r
+ * Make invisible all matched elements.\r
*/\r
public GQuery hide() {\r
return $(as(Effects).hide());\r
* function fires.\r
*/\r
public GQuery hover(Function fover, Function fout) {\r
- return bind(Event.ONMOUSEOVER, null, fover)\r
- .bind(Event.ONMOUSEOUT, null, fout);\r
+ return bind(Event.ONMOUSEOVER, null, fover).\r
+ bind(Event.ONMOUSEOUT, null, fout);\r
}\r
\r
/**\r
}\r
\r
/**\r
- * Find the index of the specified Element\r
+ * Find the index of the specified Element.\r
*/\r
public int index(Element element) {\r
for (int i = 0; i < elements.getLength(); i++) {\r
* relative or absolute). This method only works with visible elements.\r
*/\r
public GQuery offsetParent() {\r
- Element offParent = SelectorEngine\r
- .or(elements.getItem(0).getOffsetParent(), Document.get().getBody());\r
+ Element offParent = SelectorEngine.\r
+ or(elements.getItem(0).getOffsetParent(), Document.get().getBody());\r
while (offParent != null && !"body".equalsIgnoreCase(offParent.getTagName())\r
- && !"html".equalsIgnoreCase(offParent.getTagName()) && "static"\r
- .equals(curCSS(offParent, "position"))) {\r
+ && !"html".equalsIgnoreCase(offParent.getTagName()) && "static".\r
+ equals(curCSS(offParent, "position"))) {\r
offParent = offParent.getOffsetParent();\r
}\r
return new GQuery(offParent);\r
*/\r
public GQuery remove() {\r
for (Element e : elements()) {\r
- //TODO: cleanup event bindings\r
+ // TODO: cleanup event bindings\r
removeData(e, null);\r
if (e.getParentNode() != null) {\r
e.getParentNode().removeChild(e);\r
}\r
\r
public void setSelector(String selector) {\r
- this.selector = selector;\r
+ this.currentSelector = selector;\r
}\r
\r
/**\r
* Return the text contained in the first matched element.\r
*/\r
public String text() {\r
- String result="";\r
- for(Element e : elements()) {\r
+ String result = "";\r
+ for (Element e : elements()) {\r
result += e.getInnerText();\r
}\r
return result;\r
}\r
\r
/**\r
- * Produces a string representation of the matched elements\r
+ * Produces a string representation of the matched elements.\r
*/\r
public String toString() {\r
return toString(false);\r
}\r
\r
/**\r
- * Produces a string representation of the matched elements\r
+ * Produces a string representation of the matched elements.\r
*/\r
public String toString(boolean pretty) {\r
String r = "";\r
}\r
\r
/**\r
- * Removes all events that match the eventbits\r
+ * Removes all events that match the eventbits.\r
*/\r
public GQuery unbind(int eventbits) {\r
return as(Events).unbind(eventbits);\r
} else if ("input".equalsIgnoreCase(name)) {\r
InputElement ie = InputElement.as(e);\r
String type = ie.getType();\r
- if ("radio".equalsIgnoreCase((type)) || "checkbox"\r
- .equalsIgnoreCase(type)) {\r
+ if ("radio".equalsIgnoreCase((type)) || "checkbox".\r
+ equalsIgnoreCase(type)) {\r
if ("checkbox".equalsIgnoreCase(type)) {\r
for (String val : values) {\r
if (ie.getValue().equals(val)) {\r
* Get the current computed, pixel, width of the first matched element.\r
*/\r
public int width() {\r
- return DOM\r
- .getElementPropertyInt((com.google.gwt.user.client.Element) get(0),\r
+ return DOM.\r
+ getElementPropertyInt((com.google.gwt.user.client.Element) get(0),\r
"offsetWidth");\r
}\r
\r
preWrap = "<table><tbody></tbody><colgroup>";\r
postWrap = "</colgroup></table>";\r
}\r
- //TODO: fix IE link tag serialization\r
+ // TODO: fix IE link tag serialization\r
Element div = Document.get().createDivElement();\r
div.setInnerHTML(preWrap + elem + postWrap);\r
Node n = div;\r
while (wrapPos-- != 0) {\r
n = n.getLastChild();\r
}\r
- //TODO: add fixes for IE TBODY issue\r
+ // TODO: add fixes for IE TBODY issue\r
return n.getChildNodes().cast();\r
}\r
\r
\r
private void dequeue(Element elem, String type) {\r
Queue<Function> q = queue(elem, type, null);\r
- Function f = q.dequeue();\r
\r
if (q != null) {\r
+ Function f = q.dequeue();\r
+\r
if (SelectorEngine.eq(type, "__FX")) {\r
f = q.peek(0);\r
}\r
for (Element e : elements()) {\r
for (int i = 0; i < nodes.getLength(); i++) {\r
Node n = nodes.getItem(i);\r
- if(size() > 1) n=n.cloneNode(true);\r
- \r
+ if (size() > 1) {\r
+ n = n.cloneNode(true);\r
+ }\r
+\r
switch (func) {\r
case FUNC_PREPEND:\r
e.insertBefore(n, e.getFirstChild());\r
return Integer.parseInt(v);\r
}\r
} catch (NumberFormatException e) {\r
-\r
}\r
return 0;\r
}\r
private void replacequeue(Element elem, String type, Queue data) {\r
if (elem != null) {\r
type = type + "queue";\r
- Object q = (Queue) data(elem, type, null);\r
data(elem, type, data);\r
}\r
}\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
import com.google.gwt.core.client.JavaScriptObject;\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
/**\r
* A GQuery plugin. All GQuery plugins must implement this interface.\r
+ * @param <T> the plugin class\r
*/\r
public interface Plugin<T extends GQuery> {\r
\r
+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.google.gwt.query.client;
import com.google.gwt.dom.client.Element;
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
import com.google.gwt.core.client.JavaScriptObject;\r
*/\r
public class Properties extends JavaScriptObject {\r
\r
- protected Properties() {\r
- }\r
-\r
public static Properties create(String properties) {\r
String s = properties.replaceFirst("^[({]*(.*)[})]*$", "({$1})");\r
return (Properties) createImpl(s);\r
}\r
\r
- public final native static JavaScriptObject createImpl(String properties) /*-{\r
+ public final static native JavaScriptObject createImpl(String properties) /*-{\r
return eval(properties);\r
}-*/;\r
\r
+ protected Properties() {\r
+ }\r
+\r
public final native String get(String name) /*-{\r
return this[name];\r
}-*/;\r
\r
- public final native int getInt(String name) /*-{\r
+ public final native float getFloat(String name) /*-{\r
return this[name];\r
}-*/;\r
\r
- public final native float getFloat(String name) /*-{\r
+ public final native int getInt(String name) /*-{\r
return this[name];\r
}-*/;\r
\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
import com.google.gwt.core.client.JavaScriptObject;\r
*/\r
public class Regexp {\r
\r
+ public static native JavaScriptObject compile(String pat) /*-{\r
+ return new RegExp(pat);\r
+ }-*/;\r
+\r
+ public static native JavaScriptObject compileFlags(String pat, String flags) /*-{\r
+ return new RegExp(pat, flags);\r
+ }-*/;\r
+\r
+ public static JSArray match(String regexp, String flags, String string) {\r
+ return new Regexp(regexp, flags).match(string);\r
+ }\r
+\r
+ private static native JSArray exec0(JavaScriptObject regexp, String str) /*-{\r
+ return regexp.exec(str);\r
+ }-*/;\r
+\r
private final JavaScriptObject regexp;\r
\r
public Regexp(String pattern) {\r
this.regexp = compileFlags(pat, flags);\r
}\r
\r
- public static native JavaScriptObject compile(String pat) /*-{\r
- return new RegExp(pat);\r
- }-*/;\r
- \r
- public static native JavaScriptObject compileFlags(String pat, String flags) /*-{\r
- return new RegExp(pat, flags);\r
- }-*/;\r
- \r
- public JSArray exec(String str) {\r
- return exec0(regexp, str);\r
- }\r
-\r
- \r
- private static native JSArray exec0(JavaScriptObject regexp, String str) /*-{\r
- return regexp.exec(str);\r
- }-*/;\r
+ public JSArray exec(String str) {\r
+ return exec0(regexp, str);\r
+ }\r
\r
public JSArray match(String currentRule) {\r
return match0(regexp, currentRule);\r
}\r
\r
- private native JSArray match0(JavaScriptObject regexp, String currentRule)/*-{\r
- return currentRule.match(regexp);\r
- }-*/;\r
-\r
public boolean test(String rule) {\r
return test0(regexp, rule);\r
}\r
\r
+ private native JSArray match0(JavaScriptObject regexp, String currentRule)/*-{\r
+ return currentRule.match(regexp);\r
+ }-*/;\r
+\r
private native boolean test0(JavaScriptObject regexp, String rule) /*-{\r
return regexp.test(rule);\r
}-*/;\r
-\r
- public static JSArray match(String regexp, String flags, String string) {\r
- return new Regexp(regexp, flags).match(string);\r
- }\r
}\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
import java.lang.annotation.Target;\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
import com.google.gwt.core.client.GWT;\r
import com.google.gwt.dom.client.NodeList;\r
import com.google.gwt.query.client.impl.SelectorEngineImpl;\r
\r
-\r
/**\r
* Core Selector engine functions, and native JS utility functions.\r
*/\r
public class SelectorEngine {\r
\r
- private SelectorEngineImpl impl;\r
-\r
- public SelectorEngine() {\r
- impl = (SelectorEngineImpl) GWT.create(SelectorEngineImpl.class);\r
- }\r
-\r
public static native boolean eq(String s1, String s2) /*-{\r
return s1 == s2;\r
}-*/;\r
return ctx.getElementsByClassName(clazz);\r
}-*/;\r
\r
+ public static native Node getNextSibling(Node n) /*-{\r
+ return n.nextSibling || null; \r
+ }-*/;\r
+\r
+ public static native Node getPreviousSibling(Node n) /*-{\r
+ return n.previousSibling || null; \r
+ }-*/;\r
+\r
public static native <T> T or(T s1, T s2) /*-{\r
return s1 || s2;\r
}-*/;\r
return ctx.querySelectorAll(selector);\r
}-*/;\r
\r
- public NodeList<Element> select(String selector, Node ctx) {\r
- return impl.select(selector, ctx);\r
- }\r
-\r
public static boolean truth(String a) {\r
return GWT.isScript() ? truth0(a) : a != null && !"".equals(a);\r
}\r
return a;\r
}-*/;\r
\r
+ private SelectorEngineImpl impl;\r
+\r
+ public SelectorEngine() {\r
+ impl = (SelectorEngineImpl) GWT.create(SelectorEngineImpl.class);\r
+ }\r
+\r
+ public NodeList<Element> select(String selector, Node ctx) {\r
+ return impl.select(selector, ctx);\r
+ }\r
+\r
protected JSArray veryQuickId(Node context, String id) {\r
JSArray r = JSArray.create();\r
if (context.getNodeType() == Node.DOCUMENT_NODE) {\r
return r;\r
}\r
}\r
-\r
- public static native Node getNextSibling(Node n) /*-{\r
- return n.nextSibling || null; \r
- }-*/;\r
-\r
- public static native Node getPreviousSibling(Node n) /*-{\r
- return n.previousSibling || null; \r
- }-*/;\r
}\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client;\r
\r
/**\r
+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.google.gwt.query.client.impl;
import com.google.gwt.dom.client.Element;
*/
public class DocumentStyleImpl {
+ public String getCurrentStyle(Element elem, String name) {
+ name = hyphenize(name);
+ String propVal = getComputedStyle(elem, name, null);
+ if ("opacity".equals(name)) {
+ propVal = SelectorEngine.or(propVal, "1");
+ }
+ return propVal;
+ }
+
public String getPropertyName(String name) {
if ("float".equals(name)) {
return "cssFloat";
return GQuery.camelize(name);
}
- public String getCurrentStyle(Element elem, String name) {
- name = hyphenize(name);
- String propVal = getComputedStyle(elem, name, null);
- if ("opacity".equals(name)) {
- propVal = SelectorEngine.or(propVal, "1");
- }
- return propVal;
- }
-
protected native String hyphenize(String name) /*-{
return name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
}-*/;
private native String getComputedStyle(Element elem, String name,
String pseudo) /*-{
- var cStyle = $doc.defaultView.getComputedStyle( elem, pseudo );
- return cStyle ? cStyle.getPropertyValue( name ) : null;
+ var cStyle = $doc.defaultView.getComputedStyle( elem, pseudo );
+ return cStyle ? cStyle.getPropertyValue( name ) : null;
}-*/;
}
+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.google.gwt.query.client.impl;
import com.google.gwt.dom.client.Element;
*/
public class DocumentStyleImplIE extends DocumentStyleImpl {
+ public String getCurrentStyle(Element elem, String name) {
+ name = hyphenize(name);
+ String propVal = getComputedStyle(elem, name, null);
+ if ("opacity".equals(name)) {
+ propVal = SelectorEngine.or(propVal, "1");
+ }
+ return propVal;
+ }
+
public String getPropertyName(String name) {
if ("float".equals(name)) {
return "styleFloat";
return name;
}
- public String getCurrentStyle(Element elem, String name) {
- name = hyphenize(name);
- String propVal = getComputedStyle(elem, name, null);
- if ("opacity".equals(name)) {
- propVal = SelectorEngine.or(propVal, "1");
- }
- return propVal;
- }
-
// code lifted from jQuery
private native String getComputedStyle(Element elem, String name,
String pseudo) /*-{
var style = elem.style;
var camelCase = name.replace(/\-(\w)/g, function(all, letter){
- return letter.toUpperCase();
- });
+ return letter.toUpperCase();
+ });
var ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
- // From the awesome hack by Dean Edwards
- // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
- // If we're not dealing with a regular pixel number
- // but a number that has a weird ending, we need to convert it to pixels
- if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
- // Remember the original values
- var left = style.left, rsLeft = elem.runtimeStyle.left;
- // Put in the new values to get a computed value out
- elem.runtimeStyle.left = elem.currentStyle.left;
- style.left = ret || 0;
- ret = style.pixelLeft + "px";
- // Revert the changed values
- style.left = left;
- elem.runtimeStyle.left = rsLeft;
- }
- return ret;
+ // From the awesome hack by Dean Edwards
+ // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+ // If we're not dealing with a regular pixel number
+ // but a number that has a weird ending, we need to convert it to pixels
+ if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
+ // Remember the original values
+ var left = style.left, rsLeft = elem.runtimeStyle.left;
+ // Put in the new values to get a computed value out
+ elem.runtimeStyle.left = elem.currentStyle.left;
+ style.left = ret || 0;
+ ret = style.pixelLeft + "px";
+ // Revert the changed values
+ style.left = left;
+ elem.runtimeStyle.left = rsLeft;
+ }
+ return ret;
}-*/;
}
\ No newline at end of file
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client.impl;\r
\r
import com.google.gwt.dom.client.Element;\r
*/\r
public abstract class SelectorEngineImpl {\r
\r
- public abstract NodeList<Element> select(String selector, Node ctx);\r
+ /**\r
+ * Internal class.\r
+ */\r
+ protected static class Sequence {\r
+\r
+ public int start;\r
+\r
+ public int max;\r
+\r
+ public int add;\r
+\r
+ public int modVal;\r
+ }\r
+\r
+ /**\r
+ * Internal class.\r
+ */\r
+ protected static class SplitRule {\r
+\r
+ public String tag;\r
+\r
+ public String id;\r
+\r
+ public String allClasses;\r
+\r
+ public String allAttr;\r
+\r
+ public String allPseudos;\r
+\r
+ public String tagRelation;\r
+\r
+ public SplitRule(String tag, String id, String allClasses, String allAttr,\r
+ String allPseudos) {\r
+ this.tag = tag;\r
+ this.id = id;\r
+ this.allClasses = allClasses;\r
+ this.allAttr = allAttr;\r
+ this.allPseudos = allPseudos;\r
+ }\r
+\r
+ public SplitRule(String tag, String id, String allClasses, String allAttr,\r
+ String allPseudos, String tagRelation) {\r
+ this.tag = tag;\r
+ this.id = id;\r
+ this.allClasses = allClasses;\r
+ this.allAttr = allAttr;\r
+ this.allPseudos = allPseudos;\r
+ this.tagRelation = tagRelation;\r
+ }\r
+ }\r
\r
protected static Sequence getSequence(String expression) {\r
int start = 0, add = 2, max = -1, modVal = -1;\r
return s;\r
}\r
\r
- public static class Sequence {\r
-\r
- public int start;\r
-\r
- public int max;\r
-\r
- public int add;\r
-\r
- public int modVal;\r
- }\r
-\r
- public static class SplitRule {\r
-\r
- public String tag;\r
-\r
- public String id;\r
-\r
- public String allClasses;\r
-\r
- public String allAttr;\r
-\r
- public String allPseudos;\r
-\r
- public String tagRelation;\r
-\r
- public SplitRule(String tag, String id, String allClasses, String allAttr,\r
- String allPseudos) {\r
- this.tag = tag;\r
- this.id = id;\r
- this.allClasses = allClasses;\r
- this.allAttr = allAttr;\r
- this.allPseudos = allPseudos;\r
- }\r
-\r
- public SplitRule(String tag, String id, String allClasses, String allAttr,\r
- String allPseudos, String tagRelation) {\r
- this.tag = tag;\r
- this.id = id;\r
- this.allClasses = allClasses;\r
- this.allAttr = allAttr;\r
- this.allPseudos = allPseudos;\r
- this.tagRelation = tagRelation;\r
- }\r
- }\r
+ /**\r
+ * Parse and execute a given selector expression given a context.\r
+ * @param selector the CSS selector expression\r
+ * @param ctx the DOM node to use as a context\r
+ * @return a list of matched nodes\r
+ */\r
+ public abstract NodeList<Element> select(String selector, Node ctx);\r
}\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client.impl;\r
\r
import com.google.gwt.dom.client.Document;\r
import com.google.gwt.dom.client.Element;\r
import com.google.gwt.dom.client.Node;\r
import com.google.gwt.dom.client.NodeList;\r
-import com.google.gwt.query.client.SelectorEngine;\r
-import com.google.gwt.query.client.Regexp;\r
import com.google.gwt.query.client.JSArray;\r
+import com.google.gwt.query.client.Regexp;\r
+import com.google.gwt.query.client.SelectorEngine;\r
\r
/**\r
- * Runtime selector engine implementation with no-XPath/native support based\r
- * on DOMAssistant.\r
+ * Runtime selector engine implementation with no-XPath/native support based on\r
+ * DOMAssistant.\r
*/\r
public class SelectorEngineJS extends SelectorEngineImpl {\r
- private Regexp cssSelectorRegExp;\r
- private Regexp selectorSplitRegExp;\r
- private Regexp childOrSiblingRefRegExp;\r
-\r
\r
- public SelectorEngineJS() {\r
- selectorSplitRegExp = new Regexp("[^\\s]+", "g");\r
- childOrSiblingRefRegExp = new Regexp("^(>|\\+|~)$");\r
- cssSelectorRegExp = new Regexp(\r
- "^(\\w+)?(#[\\w\\u00C0-\\uFFFF\\-\\_]+|(\\*))?((\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+)?\\]+)*)?(((:\\w+[\\w\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[\\w\\u00C0-\\uFFFF\\-_]+|((\\w*\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[\\w\\-]*))\\))?)*)?");\r
+ public static void clearAdded(JSArray a) {\r
+ for (int i = 0, len = a.size(); i < len; i++) {\r
+ clearAdded(a.getNode(i));\r
}\r
+ }\r
\r
- public static void clearAdded(JSArray a) {\r
- for (int i = 0, len = a.size(); i < len; i++) {\r
- clearAdded(a.getNode(i));\r
- }\r
- }\r
-\r
- public static native void clearAdded(Node node) /*-{\r
+ public static native void clearAdded(Node node) /*-{\r
node.added = null;\r
}-*/;\r
\r
- public static native NodeList<Element> getElementsByClassName(String clazz,\r
- Node ctx) /*-{\r
+ public static native NodeList<Element> getElementsByClassName(String clazz,\r
+ Node ctx) /*-{\r
return ctx.getElementsByClassName(clazz);\r
}-*/;\r
\r
- public static native boolean isAdded(Node prevRef) /*-{\r
+ public static native boolean isAdded(Node prevRef) /*-{\r
return prevRef.added || false;\r
}-*/;\r
\r
- public static native void setAdded(Node prevRef, boolean added) /*-{\r
+ public static native void setAdded(Node prevRef, boolean added) /*-{\r
prevRef.added = added;\r
}-*/;\r
\r
- public static native void setSkipTag(JSArray prevElem, boolean skip) /*-{\r
+ public static native void setSkipTag(JSArray prevElem, boolean skip) /*-{\r
prevElem.skipTag = skip;\r
}-*/;\r
\r
- private static String attrToRegExp(String attrVal, String op) {\r
- if (SelectorEngine.eq("^", op)) {\r
- return "^" + attrVal;\r
- }\r
- if (SelectorEngine.eq("$", op)) {\r
- return attrVal + "$";\r
- }\r
- if (SelectorEngine.eq("*", op)) {\r
- return attrVal;\r
- }\r
- if (SelectorEngine.eq("|", op)) {\r
- return "(^" + attrVal + "(\\-\\w+)*$)";\r
- }\r
- if (SelectorEngine.eq("~", op)) {\r
- return "\\b" + attrVal + "\\b";\r
- }\r
- return SelectorEngine.truth(attrVal) ? "^" + attrVal + "$" : null;\r
+ private static String attrToRegExp(String attrVal, String op) {\r
+ if (SelectorEngine.eq("^", op)) {\r
+ return "^" + attrVal;\r
}\r
-\r
- private static void clearChildElms(JSArray prevParents) {\r
- for (int n = 0, nl = prevParents.size(); n < nl; n++) {\r
- setHasChildElms(prevParents.getNode(n), false);\r
- }\r
+ if (SelectorEngine.eq("$", op)) {\r
+ return attrVal + "$";\r
}\r
-\r
- protected String getAttr(Element current, String name) {\r
- return current.getAttribute(name);\r
+ if (SelectorEngine.eq("*", op)) {\r
+ return attrVal;\r
}\r
-\r
- private static void getDescendantNodes(JSArray matchingElms,\r
- String nextTagStr, Node prevRef) {\r
- NodeList<Element> children = getElementsByTagName(nextTagStr, prevRef);\r
- for (int k = 0, klen = children.getLength(); k < klen; k++) {\r
- Node child = children.getItem(k);\r
- if (child.getParentNode() == prevRef) {\r
- matchingElms.addNode(child);\r
- }\r
- }\r
+ if (SelectorEngine.eq("|", op)) {\r
+ return "(^" + attrVal + "(\\-\\w+)*$)";\r
}\r
-\r
- private JSArray getElementsByPseudo(JSArray previousMatch, String pseudoClass,\r
- String pseudoValue) {\r
- JSArray prevParents = JSArray.create();\r
- boolean previousDir = pseudoClass.startsWith("first") ? true : false;\r
- JSArray matchingElms = JSArray.create();\r
- Node prev, next, previous;\r
- if (SelectorEngine.eq("first-child", pseudoClass) || SelectorEngine\r
- .eq("last-child", pseudoClass)) {\r
- getFirstChildPseudo(previousMatch, previousDir, matchingElms);\r
- } else if (SelectorEngine.eq("only-child", pseudoClass)) {\r
- getOnlyChildPseudo(previousMatch, matchingElms);\r
- } else if (SelectorEngine.eq("nth-child", pseudoClass)) {\r
- matchingElms = getNthChildPseudo(previousMatch, pseudoValue, prevParents,\r
- matchingElms);\r
- } else if (SelectorEngine.eq("first-of-type", pseudoClass) || SelectorEngine\r
- .eq("last-of-type", pseudoClass)) {\r
- getFirstOfTypePseudo(previousMatch, previousDir, matchingElms);\r
- } else if (SelectorEngine.eq("only-of-type", pseudoClass)) {\r
- getOnlyOfTypePseudo(previousMatch, matchingElms);\r
- } else if (SelectorEngine.eq("nth-of-type", pseudoClass)) {\r
- matchingElms = getNthOfTypePseudo(previousMatch, pseudoValue, prevParents,\r
- matchingElms);\r
- } else if (SelectorEngine.eq("empty", pseudoClass)) {\r
- getEmptyPseudo(previousMatch, matchingElms);\r
- } else if (SelectorEngine.eq("enabled", pseudoClass)) {\r
- getEnabledPseudo(previousMatch, matchingElms);\r
- } else if (SelectorEngine.eq("disabled", pseudoClass)) {\r
- getDisabledPseudo(previousMatch, matchingElms);\r
- } else if (SelectorEngine.eq("checked", pseudoClass)) {\r
- getCheckedPseudo(previousMatch, matchingElms);\r
- } else if (SelectorEngine.eq("contains", pseudoClass)) {\r
- getContainsPseudo(previousMatch, pseudoValue, matchingElms);\r
- } else if (SelectorEngine.eq("not", pseudoClass)) {\r
- matchingElms = getNotPseudo(previousMatch, pseudoValue, matchingElms);\r
- } else {\r
- getDefaultPseudo(previousMatch, pseudoClass, pseudoValue, matchingElms);\r
- }\r
- return matchingElms;\r
+ if (SelectorEngine.eq("~", op)) {\r
+ return "\\b" + attrVal + "\\b";\r
}\r
+ return SelectorEngine.truth(attrVal) ? "^" + attrVal + "$" : null;\r
+ }\r
\r
- private void getDefaultPseudo(JSArray previousMatch, String pseudoClass,\r
- String pseudoValue, JSArray matchingElms) {\r
- Node previous;\r
- for (int w = 0, wlen = previousMatch.size(); w < wlen; w++) {\r
- previous = previousMatch.getElement(w);\r
- if (SelectorEngine\r
- .eq(((Element) previous).getAttribute(pseudoClass), pseudoValue)) {\r
- matchingElms.addNode(previous);\r
- }\r
- }\r
- }\r
+ private static native boolean checked(Node previous) /*-{\r
+ return previous.checked || false;\r
+ }-*/;\r
\r
- private JSArray getNotPseudo(JSArray previousMatch, String pseudoValue,\r
- JSArray matchingElms) {\r
- if (new Regexp("(:\\w+[\\w\\-]*)$").test(pseudoValue)) {\r
- matchingElms = subtractArray(previousMatch,\r
- getElementsByPseudo(previousMatch, pseudoValue.substring(1), ""));\r
- } else {\r
- pseudoValue = pseudoValue\r
- .replace("^\\[#([\\w\\u00C0-\\uFFFF\\-\\_]+)\\]$", "[id=$1]");\r
- JSArray notTag = new Regexp("^(\\w+)").exec(pseudoValue);\r
- JSArray notClass = new Regexp("^\\.([\\w\u00C0-\uFFFF\\-_]+)")\r
- .exec(pseudoValue);\r
- JSArray notAttr = new Regexp(\r
- "\\[(\\w+)(\\^|\\$|\\*|\\||~)?=?([\\w\\u00C0-\\uFFFF\\s\\-_\\.]+)?\\]")\r
- .exec(pseudoValue);\r
- Regexp notRegExp = new Regexp(\r
- "(^|\\s)" + (SelectorEngine.truth(notTag) ? notTag\r
- .getStr(1)\r
- : SelectorEngine.truth(notClass) ? notClass.getStr(1) : "")\r
- + "(\\s|$)", "i");\r
- if (SelectorEngine.truth(notAttr)) {\r
- String notAttribute = SelectorEngine.truth(notAttr.getStr(3)) ? notAttr\r
- .getStr(3)\r
- .replace("\\.", "\\.") : null;\r
- String notMatchingAttrVal = attrToRegExp(notAttribute,\r
- notAttr.getStr(2));\r
- notRegExp = new Regexp(notMatchingAttrVal, "i");\r
- }\r
- for (int v = 0, vlen = previousMatch.size(); v < vlen; v++) {\r
- Element notElm = previousMatch.getElement(v);\r
- Element addElm = null;\r
- if (SelectorEngine.truth(notTag) && !notRegExp\r
- .test(notElm.getNodeName())) {\r
- addElm = notElm;\r
- } else if (SelectorEngine.truth(notClass) && !notRegExp\r
- .test(notElm.getClassName())) {\r
- addElm = notElm;\r
- } else if (SelectorEngine.truth(notAttr)) {\r
- String att = getAttr(notElm, notAttr.getStr(1));\r
- if (!SelectorEngine.truth(att) || !notRegExp.test(att)) {\r
- addElm = notElm;\r
- }\r
- }\r
- if (SelectorEngine.truth(addElm) && !isAdded(addElm)) {\r
- setAdded(addElm, true);\r
- matchingElms.addNode(addElm);\r
- }\r
- }\r
- }\r
- return matchingElms;\r
+ private static void clearChildElms(JSArray prevParents) {\r
+ for (int n = 0, nl = prevParents.size(); n < nl; n++) {\r
+ setHasChildElms(prevParents.getNode(n), false);\r
}\r
+ }\r
\r
- private void getContainsPseudo(JSArray previousMatch, String pseudoValue,\r
- JSArray matchingElms) {\r
- Node previous;\r
- for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
- previous = previousMatch.getNode(q);\r
- if (!isAdded(previous)) {\r
- if (((Element) previous).getInnerText().indexOf(pseudoValue) != -1) {\r
- setAdded(previous, true);\r
- matchingElms.addNode(previous);\r
- }\r
- }\r
- }\r
- }\r
+ private static native boolean enabled(Node node) /*-{\r
+ return !node.disabled;\r
+ }-*/;\r
\r
- private void getCheckedPseudo(JSArray previousMatch, JSArray matchingElms) {\r
- Node previous;\r
- for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
- previous = previousMatch.getNode(q);\r
- if (checked(previous)) {\r
- matchingElms.addNode(previous);\r
- }\r
- }\r
+ private static void getDescendantNodes(JSArray matchingElms,\r
+ String nextTagStr, Node prevRef) {\r
+ NodeList<Element> children = getElementsByTagName(nextTagStr, prevRef);\r
+ for (int k = 0, klen = children.getLength(); k < klen; k++) {\r
+ Node child = children.getItem(k);\r
+ if (child.getParentNode() == prevRef) {\r
+ matchingElms.addNode(child);\r
+ }\r
}\r
-\r
- private void getDisabledPseudo(JSArray previousMatch, JSArray matchingElms) {\r
- Node previous;\r
- for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
- previous = previousMatch.getNode(q);\r
- if (!enabled(previous)) {\r
- matchingElms.addNode(previous);\r
- }\r
- }\r
+ }\r
+\r
+ private static NodeList<Element> getElementsByTagName(String tag, Node ctx) {\r
+ return ((Element) ctx).getElementsByTagName(tag);\r
+ }\r
+\r
+ private static void getGeneralSiblingNodes(JSArray matchingElms,\r
+ JSArray nextTag, Regexp nextRegExp, Node prevRef) {\r
+ while (\r
+ SelectorEngine.truth((prevRef = SelectorEngine.getNextSibling(prevRef)))\r
+ && !isAdded(prevRef)) {\r
+ if (!SelectorEngine.truth(nextTag) || nextRegExp\r
+ .test(prevRef.getNodeName())) {\r
+ setAdded(prevRef, true);\r
+ matchingElms.addNode(prevRef);\r
+ }\r
}\r
+ }\r
\r
- private void getEnabledPseudo(JSArray previousMatch, JSArray matchingElms) {\r
- Node previous;\r
- for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
- previous = previousMatch.getNode(q);\r
- if (enabled(previous)) {\r
- matchingElms.addNode(previous);\r
- }\r
- }\r
+ private static void getSiblingNodes(JSArray matchingElms, JSArray nextTag,\r
+ Regexp nextRegExp, Node prevRef) {\r
+ while (\r
+ SelectorEngine.truth(prevRef = SelectorEngine.getNextSibling(prevRef))\r
+ && prevRef.getNodeType() != Node.ELEMENT_NODE) {\r
}\r
-\r
- private void getEmptyPseudo(JSArray previousMatch, JSArray matchingElms) {\r
- Node previous;\r
- for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
- previous = previousMatch.getNode(q);\r
- if (!previous.hasChildNodes()) {\r
- matchingElms.addNode(previous);\r
- }\r
- }\r
+ if (SelectorEngine.truth(prevRef)) {\r
+ if (!SelectorEngine.truth(nextTag) || nextRegExp\r
+ .test(prevRef.getNodeName())) {\r
+ matchingElms.addNode(prevRef);\r
+ }\r
}\r
+ }\r
\r
- private JSArray getNthOfTypePseudo(JSArray previousMatch, String pseudoValue,\r
- JSArray prevParents, JSArray matchingElms) {\r
- Node previous;\r
- if (pseudoValue.startsWith("n")) {\r
- matchingElms = previousMatch;\r
- } else {\r
- Sequence sequence = getSequence(pseudoValue);\r
- if (sequence != null) {\r
- for (int p = 0, plen = previousMatch.size(); p < plen; p++) {\r
- previous = previousMatch.getNode(p);\r
- Node prevParent = previous.getParentNode();\r
- if (!hasChildElms(prevParent)) {\r
- int iteratorNext = sequence.start;\r
- int childCount = 0;\r
- Node childElm = prevParent.getFirstChild();\r
- while (SelectorEngine.truth(childElm) && (sequence.max < 0\r
- || iteratorNext <= sequence.max)) {\r
- if (SelectorEngine\r
- .eq(childElm.getNodeName(), previous.getNodeName())) {\r
- if (++childCount == iteratorNext) {\r
- matchingElms.addNode(childElm);\r
- iteratorNext += sequence.add;\r
- }\r
- }\r
- childElm = SelectorEngine.getNextSibling(childElm);\r
- }\r
- setHasChildElms(prevParent, true);\r
- prevParents.addNode(prevParent);\r
- }\r
- }\r
- clearChildElms(prevParents);\r
- }\r
- }\r
- return matchingElms;\r
- }\r
+ private static native boolean hasChildElms(Node prevParent) /*-{\r
+ return prevParent.childElms || false;\r
+ }-*/;\r
\r
- private void getOnlyOfTypePseudo(JSArray previousMatch,\r
- JSArray matchingElms) {\r
- Node previous;\r
- Node next;\r
- Node prev;\r
- Node oParent = null;\r
- for (int o = 0, olen = previousMatch.size(); o < olen; o++) {\r
- prev = next = previous = previousMatch.getNode(o);\r
- Node prevParent = previous.getParentNode();\r
- if (prevParent != oParent) {\r
- while (\r
- SelectorEngine.truth(prev = SelectorEngine.getPreviousSibling(prev))\r
- && !SelectorEngine\r
- .eq(prev.getNodeName(), previous.getNodeName())) {\r
- }\r
- while (SelectorEngine.truth(next = SelectorEngine.getNextSibling(next))\r
- && !SelectorEngine.eq(next.getNodeName(), previous.getNodeName())) {\r
- }\r
- if (!SelectorEngine.truth(prev) && !SelectorEngine.truth(next)) {\r
- matchingElms.addNode(previous);\r
- }\r
- oParent = prevParent;\r
- }\r
- }\r
- }\r
+ private static native boolean isSkipped(JSArray prevElem) /*-{\r
+ return prevElem.skipTag || false;\r
+ }-*/;\r
\r
- private void getFirstOfTypePseudo(JSArray previousMatch, boolean previousDir,\r
- JSArray matchingElms) {\r
- Node previous;\r
- Node next;\r
- for (int n = 0, nlen = previousMatch.size(); n < nlen; n++) {\r
- next = previous = previousMatch.getNode(n);\r
-\r
- if (previousDir) {\r
- while (\r
- SelectorEngine.truth(next = SelectorEngine.getPreviousSibling(next))\r
- && !SelectorEngine\r
- .eq(next.getNodeName(), previous.getNodeName())) {\r
- }\r
- } else {\r
- while (SelectorEngine.truth(next = SelectorEngine.getNextSibling(next))\r
- && !SelectorEngine.eq(next.getNodeName(), previous.getNodeName())) {\r
- }\r
- }\r
+ private static native void setHasChildElms(Node prevParent, boolean bool) /*-{\r
+ prevParent.childElms = bool ? bool : null;\r
+ }-*/;\r
\r
- if (!SelectorEngine.truth(next)) {\r
- matchingElms.addNode(previous);\r
- }\r
+ private static native JSArray subtractArray(JSArray previousMatch,\r
+ JSArray elementsByPseudo) /*-{\r
+ for (var i=0, src1; (src1=arr1[i]); i++) {\r
+ var found = false;\r
+ for (var j=0, src2; (src2=arr2[j]); j++) {\r
+ if (src2 === src1) {\r
+ found = true;\r
+ break;\r
+ }\r
}\r
- }\r
+ if (found) {\r
+ arr1.splice(i--, 1);\r
+ }\r
+ }\r
+ return arr;\r
+ }-*/;\r
\r
- private JSArray getNthChildPseudo(JSArray previousMatch, String pseudoValue,\r
- JSArray prevParents, JSArray matchingElms) {\r
- Node previous;\r
- if (SelectorEngine.eq(pseudoValue, "n")) {\r
- matchingElms = previousMatch;\r
- } else {\r
- Sequence sequence = getSequence(pseudoValue);\r
- if (sequence != null) {\r
- for (int l = 0, llen = previousMatch.size(); l < llen; l++) {\r
- previous = previousMatch.getNode(l);\r
- Node prevParent = previous.getParentNode();\r
- if (!hasChildElms(prevParent)) {\r
- int iteratorNext = sequence.start;\r
- int childCount = 0;\r
- Node childElm = prevParent.getFirstChild();\r
- while (childElm != null && (sequence.max < 0\r
- || iteratorNext <= sequence.max)) {\r
- if (childElm.getNodeType() == Node.ELEMENT_NODE) {\r
- if (++childCount == iteratorNext) {\r
- if (SelectorEngine\r
- .eq(childElm.getNodeName(), previous.getNodeName())) {\r
- matchingElms.addNode(childElm);\r
- }\r
- iteratorNext += sequence.add;\r
- }\r
- }\r
- childElm = SelectorEngine.getNextSibling(childElm);\r
- }\r
- setHasChildElms(prevParent, true);\r
- prevParents.addNode(prevParent);\r
- }\r
- }\r
- clearChildElms(prevParents);\r
+ private Regexp cssSelectorRegExp;\r
+\r
+ private Regexp selectorSplitRegExp;\r
+\r
+ private Regexp childOrSiblingRefRegExp;\r
+\r
+ public SelectorEngineJS() {\r
+ selectorSplitRegExp = new Regexp("[^\\s]+", "g");\r
+ childOrSiblingRefRegExp = new Regexp("^(>|\\+|~)$");\r
+ cssSelectorRegExp = new Regexp(\r
+ "^(\\w+)?(#[\\w\\u00C0-\\uFFFF\\-\\_]+|(\\*))?((\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+)?\\]+)*)?(((:\\w+[\\w\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[\\w\\u00C0-\\uFFFF\\-_]+|((\\w*\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[\\w\\-]*))\\))?)*)?");\r
+ }\r
+\r
+ public NodeList<Element> select(String sel, Node ctx) {\r
+ String selectors[] = sel.replace("\\s*(,)\\s*", "$1").split(",");\r
+ boolean identical = false;\r
+ JSArray elm = JSArray.create();\r
+ for (int a = 0, len = selectors.length; a < len; a++) {\r
+ if (a > 0) {\r
+ identical = false;\r
+ for (int b = 0, bl = a; b < bl; b++) {\r
+ if (SelectorEngine.eq(selectors[a], selectors[b])) {\r
+ identical = true;\r
+ break;\r
+ }\r
+ }\r
+ if (identical) {\r
+ continue;\r
+ }\r
+ }\r
+ String currentRule = selectors[a];\r
+ JSArray cssSelectors = selectorSplitRegExp.match(currentRule);\r
+ JSArray prevElem = JSArray.create(ctx);\r
+ for (int i = 0, slen = cssSelectors.size(); i < slen; i++) {\r
+ JSArray matchingElms = JSArray.create();\r
+ String rule = cssSelectors.getStr(i);\r
+ if (i > 0 && childOrSiblingRefRegExp.test(rule)) {\r
+ JSArray childOrSiblingRef = childOrSiblingRefRegExp.exec(rule);\r
+ if (SelectorEngine.truth(childOrSiblingRef)) {\r
+ JSArray nextTag = new Regexp("^\\w+")\r
+ .exec(cssSelectors.getStr(i + 1));\r
+ Regexp nextRegExp = null;\r
+ String nextTagStr = null;\r
+ if (SelectorEngine.truth(nextTag)) {\r
+ nextTagStr = nextTag.getStr(0);\r
+ nextRegExp = new Regexp("(^|\\s)" + nextTagStr + "(\\s|$)", "i");\r
+ }\r
+ for (int j = 0, jlen = prevElem.size(); j < jlen; j++) {\r
+ Node prevRef = prevElem.getNode(j);\r
+ String ref = childOrSiblingRef.getStr(0);\r
+ if (SelectorEngine.eq(">", ref)) {\r
+ getDescendantNodes(matchingElms, nextTagStr, prevRef);\r
+ } else if (SelectorEngine.eq("+", ref)) {\r
+ getSiblingNodes(matchingElms, nextTag, nextRegExp, prevRef);\r
+ } else if (SelectorEngine.eq("~", ref)) {\r
+ getGeneralSiblingNodes(matchingElms, nextTag, nextRegExp,\r
+ prevRef);\r
+ }\r
+ }\r
+ prevElem = matchingElms;\r
+ clearAdded(prevElem);\r
+ rule = cssSelectors.getStr(++i);\r
+ if (new Regexp("^\\w+$").test(rule)) {\r
+ continue;\r
}\r
+ setSkipTag(prevElem, true);\r
+ }\r
}\r
- return matchingElms;\r
- }\r
-\r
- private void getOnlyChildPseudo(JSArray previousMatch, JSArray matchingElms) {\r
- Node previous;\r
- Node next;\r
- Node prev;\r
- Node kParent = null;\r
- for (int k = 0, klen = previousMatch.size(); k < klen; k++) {\r
- prev = next = previous = previousMatch.getNode(k);\r
- Node prevParent = previous.getParentNode();\r
- if (prevParent != kParent) {\r
- while (\r
- SelectorEngine.truth(prev = SelectorEngine.getPreviousSibling(prev))\r
- && prev.getNodeType() != Node.ELEMENT_NODE) {\r
+ JSArray cssSelector = cssSelectorRegExp.exec(rule);\r
+ SplitRule splitRule = new SplitRule(\r
+ !SelectorEngine.truth(cssSelector.getStr(1)) || SelectorEngine\r
+ .eq(cssSelector.getStr(3), "*") ? "*" : cssSelector.getStr(1),\r
+ !SelectorEngine.eq(cssSelector.getStr(3), "*") ? cssSelector\r
+ .getStr(2) : null, cssSelector.getStr(4), cssSelector.getStr(6),\r
+ cssSelector.getStr(10));\r
+ if (SelectorEngine.truth(splitRule.id)) {\r
+ Element domelem = Document.get()\r
+ .getElementById(splitRule.id.substring(1));\r
+ if (SelectorEngine.truth(domelem)) {\r
+ matchingElms = JSArray.create(domelem);\r
+ }\r
+ prevElem = matchingElms;\r
+ } else if (SelectorEngine.truth(splitRule.tag) && !isSkipped(\r
+ prevElem)) {\r
+ if (i == 0 && matchingElms.size() == 0 && prevElem.size() == 1) {\r
+ prevElem = matchingElms = JSArray.create(\r
+ getElementsByTagName(splitRule.tag, prevElem.getNode(0)));\r
+ } else {\r
+ NodeList<Element> tagCollectionMatches;\r
+ for (int l = 0, ll = prevElem.size(); l < ll; l++) {\r
+ tagCollectionMatches = getElementsByTagName(splitRule.tag,\r
+ prevElem.getNode(l));\r
+ for (int m = 0, mlen = tagCollectionMatches.getLength(); m < mlen;\r
+ m++) {\r
+ Node tagMatch = tagCollectionMatches.getItem(m);\r
+\r
+ if (!isAdded(tagMatch)) {\r
+ setAdded(tagMatch, true);\r
+ matchingElms.addNode(tagMatch);\r
}\r
- while (SelectorEngine.truth(next = SelectorEngine.getNextSibling(next))\r
- && next.getNodeType() != Node.ELEMENT_NODE) {\r
+ }\r
+ }\r
+ prevElem = matchingElms;\r
+ clearAdded(prevElem);\r
+ }\r
+ if (matchingElms.size() == 0) {\r
+ break;\r
+ }\r
+ setSkipTag(prevElem, false);\r
+ if (SelectorEngine.truth(splitRule.allClasses)) {\r
+ String[] allClasses = splitRule.allClasses.replaceFirst("^\\.", "")\r
+ .split("\\.");\r
+ Regexp[] regExpClassNames = new Regexp[allClasses.length];\r
+ for (int n = 0, nl = allClasses.length; n < nl; n++) {\r
+ regExpClassNames[n] = new Regexp(\r
+ "(^|\\s)" + allClasses[n] + "(\\s|$)");\r
+ }\r
+ JSArray matchingClassElms = JSArray.create();\r
+ for (int o = 0, olen = prevElem.size(); o < olen; o++) {\r
+ Element current = prevElem.getElement(o);\r
+ String elmClass = current.getClassName();\r
+ boolean addElm = false;\r
+ if (SelectorEngine.truth(elmClass) && !isAdded(current)) {\r
+ for (int p = 0, pl = regExpClassNames.length; p < pl; p++) {\r
+ addElm = regExpClassNames[p].test(elmClass);\r
+ if (!addElm) {\r
+ break;\r
+ }\r
}\r
- if (!SelectorEngine.truth(prev) && !SelectorEngine.truth(next)) {\r
- matchingElms.addNode(previous);\r
+ if (addElm) {\r
+ setAdded(current, true);\r
+ matchingClassElms.addNode(current);\r
}\r
- kParent = prevParent;\r
+ }\r
}\r
- }\r
- }\r
-\r
- private void getFirstChildPseudo(JSArray previousMatch, boolean previousDir,\r
- JSArray matchingElms) {\r
- Node next;\r
- Node previous;\r
- for (int j = 0, jlen = previousMatch.size(); j < jlen; j++) {\r
- previous = next = previousMatch.getElement(j);\r
- if (previousDir) {\r
- while (SelectorEngine\r
- .truth((next = SelectorEngine.getPreviousSibling(next)))\r
- && next.getNodeType() != Node.ELEMENT_NODE) {\r
+ clearAdded(prevElem);\r
+ prevElem = matchingElms = matchingClassElms;\r
+ }\r
+ if (SelectorEngine.truth(splitRule.allAttr)) {\r
+ JSArray allAttr = Regexp\r
+ .match("\\[[^\\]]+\\]", "g", splitRule.allAttr);\r
+ Regexp[] regExpAttributes = new Regexp[allAttr.size()];\r
+ String[] regExpAttributesStr = new String[allAttr.size()];\r
+ Regexp attributeMatchRegExp = new Regexp(\r
+ "(\\w+)(\\^|\\$|\\*|\\||~)?=?([\\w\u00C0-\uFFFF\\s\\-_\\.]+)?");\r
+ for (int q = 0, ql = allAttr.size(); q < ql; q++) {\r
+ JSArray attributeMatch = attributeMatchRegExp\r
+ .exec(allAttr.getStr(q));\r
+ String attributeValue =\r
+ SelectorEngine.truth(attributeMatch.getStr(3))\r
+ ? attributeMatch.getStr(3).replaceAll("\\.", "\\.")\r
+ : null;\r
+ String attrVal = attrToRegExp(attributeValue,\r
+ (SelectorEngine.or(attributeMatch.getStr(2), null)));\r
+ regExpAttributes[q] = (SelectorEngine.truth(attrVal) ? new Regexp(\r
+ attrVal) : null);\r
+ regExpAttributesStr[q] = attributeMatch.getStr(1);\r
+ }\r
+ JSArray matchingAttributeElms = JSArray.create();\r
+\r
+ for (int r = 0, rlen = matchingElms.size(); r < rlen; r++) {\r
+ Element current = matchingElms.getElement(r);\r
+ boolean addElm = false;\r
+ for (int s = 0, sl = regExpAttributes.length, attributeRegExp;\r
+ s < sl; s++) {\r
+ addElm = false;\r
+ Regexp attributeRegExp2 = regExpAttributes[s];\r
+ String currentAttr = getAttr(current, regExpAttributesStr[s]);\r
+ if (SelectorEngine.truth(currentAttr)\r
+ && currentAttr.length() != 0) {\r
+ if (attributeRegExp2 == null || attributeRegExp2\r
+ .test(currentAttr)) {\r
+ addElm = true;\r
+ }\r
}\r
- } else {\r
- while (\r
- SelectorEngine.truth((next = SelectorEngine.getNextSibling(next)))\r
- && next.getNodeType() != Node.ELEMENT_NODE) {\r
+ if (!addElm) {\r
+ break;\r
}\r
+ }\r
+ if (addElm) {\r
+ matchingAttributeElms.addNode(current);\r
+ }\r
}\r
- if (!SelectorEngine.truth(next)) {\r
- matchingElms.addNode(previous);\r
+ prevElem = matchingElms = matchingAttributeElms;\r
+ }\r
+ if (SelectorEngine.truth(splitRule.allPseudos)) {\r
+ Regexp pseudoSplitRegExp = new Regexp(\r
+ ":(\\w[\\w\\-]*)(\\(([^\\)]+)\\))?");\r
+\r
+ JSArray allPseudos = Regexp\r
+ .match("(:\\w+[\\w\\-]*)(\\([^\\)]+\\))?", "g",\r
+ splitRule.allPseudos);\r
+ for (int t = 0, tl = allPseudos.size(); t < tl; t++) {\r
+ JSArray pseudo = pseudoSplitRegExp.match(allPseudos.getStr(t));\r
+ String pseudoClass = SelectorEngine.truth(pseudo.getStr(1))\r
+ ? pseudo.getStr(1).toLowerCase() : null;\r
+ String pseudoValue = SelectorEngine.truth(pseudo.getStr(3))\r
+ ? pseudo.getStr(3) : null;\r
+ matchingElms = getElementsByPseudo(matchingElms, pseudoClass,\r
+ pseudoValue);\r
+ clearAdded(matchingElms);\r
}\r
+ prevElem = matchingElms;\r
+ }\r
}\r
+ }\r
+ elm.pushAll(prevElem);\r
}\r
\r
- private static native boolean checked(Node previous) /*-{\r
- return previous.checked || false;\r
- }-*/;\r
+ return elm;\r
+ }\r
\r
- private static native boolean enabled(Node node) /*-{\r
- return !node.disabled;\r
- }-*/;\r
+ protected String getAttr(Element current, String name) {\r
+ return current.getAttribute(name);\r
+ }\r
\r
- private static NodeList<Element> getElementsByTagName(String tag, Node ctx) {\r
- return ((Element) ctx).getElementsByTagName(tag);\r
+ private void getCheckedPseudo(JSArray previousMatch, JSArray matchingElms) {\r
+ Node previous;\r
+ for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
+ previous = previousMatch.getNode(q);\r
+ if (checked(previous)) {\r
+ matchingElms.addNode(previous);\r
+ }\r
}\r
-\r
- private static void getGeneralSiblingNodes(JSArray matchingElms,\r
- JSArray nextTag, Regexp nextRegExp, Node prevRef) {\r
- while (\r
- SelectorEngine.truth((prevRef = SelectorEngine.getNextSibling(prevRef)))\r
- && !isAdded(prevRef)) {\r
- if (!SelectorEngine.truth(nextTag) || nextRegExp\r
- .test(prevRef.getNodeName())) {\r
- setAdded(prevRef, true);\r
- matchingElms.addNode(prevRef);\r
- }\r
+ }\r
+\r
+ private void getContainsPseudo(JSArray previousMatch, String pseudoValue,\r
+ JSArray matchingElms) {\r
+ Node previous;\r
+ for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
+ previous = previousMatch.getNode(q);\r
+ if (!isAdded(previous)) {\r
+ if (((Element) previous).getInnerText().indexOf(pseudoValue) != -1) {\r
+ setAdded(previous, true);\r
+ matchingElms.addNode(previous);\r
}\r
+ }\r
}\r
-\r
- private static void getSiblingNodes(JSArray matchingElms, JSArray nextTag,\r
- Regexp nextRegExp, Node prevRef) {\r
- while (\r
- SelectorEngine.truth(prevRef = SelectorEngine.getNextSibling(prevRef))\r
- && prevRef.getNodeType() != Node.ELEMENT_NODE) {\r
+ }\r
+\r
+ private void getDefaultPseudo(JSArray previousMatch, String pseudoClass,\r
+ String pseudoValue, JSArray matchingElms) {\r
+ Node previous;\r
+ for (int w = 0, wlen = previousMatch.size(); w < wlen; w++) {\r
+ previous = previousMatch.getElement(w);\r
+ if (SelectorEngine\r
+ .eq(((Element) previous).getAttribute(pseudoClass), pseudoValue)) {\r
+ matchingElms.addNode(previous);\r
+ }\r
+ }\r
+ }\r
+\r
+ private void getDisabledPseudo(JSArray previousMatch, JSArray matchingElms) {\r
+ Node previous;\r
+ for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
+ previous = previousMatch.getNode(q);\r
+ if (!enabled(previous)) {\r
+ matchingElms.addNode(previous);\r
+ }\r
+ }\r
+ }\r
+\r
+ private JSArray getElementsByPseudo(JSArray previousMatch, String pseudoClass,\r
+ String pseudoValue) {\r
+ JSArray prevParents = JSArray.create();\r
+ boolean previousDir = pseudoClass.startsWith("first") ? true : false;\r
+ JSArray matchingElms = JSArray.create();\r
+ Node prev, next, previous;\r
+ if (SelectorEngine.eq("first-child", pseudoClass) || SelectorEngine\r
+ .eq("last-child", pseudoClass)) {\r
+ getFirstChildPseudo(previousMatch, previousDir, matchingElms);\r
+ } else if (SelectorEngine.eq("only-child", pseudoClass)) {\r
+ getOnlyChildPseudo(previousMatch, matchingElms);\r
+ } else if (SelectorEngine.eq("nth-child", pseudoClass)) {\r
+ matchingElms = getNthChildPseudo(previousMatch, pseudoValue, prevParents,\r
+ matchingElms);\r
+ } else if (SelectorEngine.eq("first-of-type", pseudoClass) || SelectorEngine\r
+ .eq("last-of-type", pseudoClass)) {\r
+ getFirstOfTypePseudo(previousMatch, previousDir, matchingElms);\r
+ } else if (SelectorEngine.eq("only-of-type", pseudoClass)) {\r
+ getOnlyOfTypePseudo(previousMatch, matchingElms);\r
+ } else if (SelectorEngine.eq("nth-of-type", pseudoClass)) {\r
+ matchingElms = getNthOfTypePseudo(previousMatch, pseudoValue, prevParents,\r
+ matchingElms);\r
+ } else if (SelectorEngine.eq("empty", pseudoClass)) {\r
+ getEmptyPseudo(previousMatch, matchingElms);\r
+ } else if (SelectorEngine.eq("enabled", pseudoClass)) {\r
+ getEnabledPseudo(previousMatch, matchingElms);\r
+ } else if (SelectorEngine.eq("disabled", pseudoClass)) {\r
+ getDisabledPseudo(previousMatch, matchingElms);\r
+ } else if (SelectorEngine.eq("checked", pseudoClass)) {\r
+ getCheckedPseudo(previousMatch, matchingElms);\r
+ } else if (SelectorEngine.eq("contains", pseudoClass)) {\r
+ getContainsPseudo(previousMatch, pseudoValue, matchingElms);\r
+ } else if (SelectorEngine.eq("not", pseudoClass)) {\r
+ matchingElms = getNotPseudo(previousMatch, pseudoValue, matchingElms);\r
+ } else {\r
+ getDefaultPseudo(previousMatch, pseudoClass, pseudoValue, matchingElms);\r
+ }\r
+ return matchingElms;\r
+ }\r
+\r
+ private void getEmptyPseudo(JSArray previousMatch, JSArray matchingElms) {\r
+ Node previous;\r
+ for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
+ previous = previousMatch.getNode(q);\r
+ if (!previous.hasChildNodes()) {\r
+ matchingElms.addNode(previous);\r
+ }\r
+ }\r
+ }\r
+\r
+ private void getEnabledPseudo(JSArray previousMatch, JSArray matchingElms) {\r
+ Node previous;\r
+ for (int q = 0, qlen = previousMatch.size(); q < qlen; q++) {\r
+ previous = previousMatch.getNode(q);\r
+ if (enabled(previous)) {\r
+ matchingElms.addNode(previous);\r
+ }\r
+ }\r
+ }\r
+\r
+ private void getFirstChildPseudo(JSArray previousMatch, boolean previousDir,\r
+ JSArray matchingElms) {\r
+ Node next;\r
+ Node previous;\r
+ for (int j = 0, jlen = previousMatch.size(); j < jlen; j++) {\r
+ previous = next = previousMatch.getElement(j);\r
+ if (previousDir) {\r
+ while (SelectorEngine\r
+ .truth((next = SelectorEngine.getPreviousSibling(next)))\r
+ && next.getNodeType() != Node.ELEMENT_NODE) {\r
}\r
- if (SelectorEngine.truth(prevRef)) {\r
- if (!SelectorEngine.truth(nextTag) || nextRegExp\r
- .test(prevRef.getNodeName())) {\r
- matchingElms.addNode(prevRef);\r
- }\r
+ } else {\r
+ while (\r
+ SelectorEngine.truth((next = SelectorEngine.getNextSibling(next)))\r
+ && next.getNodeType() != Node.ELEMENT_NODE) {\r
}\r
+ }\r
+ if (!SelectorEngine.truth(next)) {\r
+ matchingElms.addNode(previous);\r
+ }\r
}\r
+ }\r
\r
- private static native boolean hasChildElms(Node prevParent) /*-{\r
- return prevParent.childElms || false;\r
- }-*/;\r
+ private void getFirstOfTypePseudo(JSArray previousMatch, boolean previousDir,\r
+ JSArray matchingElms) {\r
+ Node previous;\r
+ Node next;\r
+ for (int n = 0, nlen = previousMatch.size(); n < nlen; n++) {\r
+ next = previous = previousMatch.getNode(n);\r
\r
- private static native boolean isSkipped(JSArray prevElem) /*-{\r
- return prevElem.skipTag || false;\r
- }-*/;\r
-\r
- private static native void setHasChildElms(Node prevParent, boolean bool) /*-{\r
- prevParent.childElms = bool ? bool : null;\r
- }-*/;\r
+ if (previousDir) {\r
+ while (\r
+ SelectorEngine.truth(next = SelectorEngine.getPreviousSibling(next))\r
+ && !SelectorEngine\r
+ .eq(next.getNodeName(), previous.getNodeName())) {\r
+ }\r
+ } else {\r
+ while (SelectorEngine.truth(next = SelectorEngine.getNextSibling(next))\r
+ && !SelectorEngine.eq(next.getNodeName(), previous.getNodeName())) {\r
+ }\r
+ }\r
\r
- private static native JSArray subtractArray(JSArray previousMatch,\r
- JSArray elementsByPseudo) /*-{\r
- for (var i=0, src1; (src1=arr1[i]); i++) {\r
- var found = false;\r
- for (var j=0, src2; (src2=arr2[j]); j++) {\r
- if (src2 === src1) {\r
- found = true;\r
- break;\r
+ if (!SelectorEngine.truth(next)) {\r
+ matchingElms.addNode(previous);\r
+ }\r
+ }\r
+ }\r
+\r
+ private JSArray getNotPseudo(JSArray previousMatch, String pseudoValue,\r
+ JSArray matchingElms) {\r
+ if (new Regexp("(:\\w+[\\w\\-]*)$").test(pseudoValue)) {\r
+ matchingElms = subtractArray(previousMatch,\r
+ getElementsByPseudo(previousMatch, pseudoValue.substring(1), ""));\r
+ } else {\r
+ pseudoValue = pseudoValue\r
+ .replace("^\\[#([\\w\\u00C0-\\uFFFF\\-\\_]+)\\]$", "[id=$1]");\r
+ JSArray notTag = new Regexp("^(\\w+)").exec(pseudoValue);\r
+ JSArray notClass = new Regexp("^\\.([\\w\u00C0-\uFFFF\\-_]+)")\r
+ .exec(pseudoValue);\r
+ JSArray notAttr = new Regexp(\r
+ "\\[(\\w+)(\\^|\\$|\\*|\\||~)?=?([\\w\\u00C0-\\uFFFF\\s\\-_\\.]+)?\\]")\r
+ .exec(pseudoValue);\r
+ Regexp notRegExp = new Regexp("(^|\\s)"\r
+ + (SelectorEngine.truth(notTag) ? notTag.getStr(1)\r
+ : SelectorEngine.truth(notClass) ? notClass.getStr(1) : "")\r
+ + "(\\s|$)", "i");\r
+ if (SelectorEngine.truth(notAttr)) {\r
+ String notAttribute = SelectorEngine.truth(notAttr.getStr(3)) ? notAttr\r
+ .getStr(3).replace("\\.", "\\.") : null;\r
+ String notMatchingAttrVal = attrToRegExp(notAttribute,\r
+ notAttr.getStr(2));\r
+ notRegExp = new Regexp(notMatchingAttrVal, "i");\r
+ }\r
+ for (int v = 0, vlen = previousMatch.size(); v < vlen; v++) {\r
+ Element notElm = previousMatch.getElement(v);\r
+ Element addElm = null;\r
+ if (SelectorEngine.truth(notTag) && !notRegExp\r
+ .test(notElm.getNodeName())) {\r
+ addElm = notElm;\r
+ } else if (SelectorEngine.truth(notClass) && !notRegExp\r
+ .test(notElm.getClassName())) {\r
+ addElm = notElm;\r
+ } else if (SelectorEngine.truth(notAttr)) {\r
+ String att = getAttr(notElm, notAttr.getStr(1));\r
+ if (!SelectorEngine.truth(att) || !notRegExp.test(att)) {\r
+ addElm = notElm;\r
}\r
}\r
- if (found) {\r
- arr1.splice(i--, 1);\r
+ if (SelectorEngine.truth(addElm) && !isAdded(addElm)) {\r
+ setAdded(addElm, true);\r
+ matchingElms.addNode(addElm);\r
}\r
}\r
- return arr;\r
- }-*/;\r
-\r
- public NodeList<Element> select(String sel, Node ctx) {\r
- String selectors[] = sel.replace("\\s*(,)\\s*", "$1").split(",");\r
- boolean identical = false;\r
- JSArray elm = JSArray.create();\r
- for (int a = 0, len = selectors.length; a < len; a++) {\r
- if (a > 0) {\r
- identical = false;\r
- for (int b = 0, bl = a; b < bl; b++) {\r
- if (SelectorEngine.eq(selectors[a], selectors[b])) {\r
- identical = true;\r
- break;\r
- }\r
- }\r
- if (identical) { \r
- continue;\r
+ }\r
+ return matchingElms;\r
+ }\r
+\r
+ private JSArray getNthChildPseudo(JSArray previousMatch, String pseudoValue,\r
+ JSArray prevParents, JSArray matchingElms) {\r
+ Node previous;\r
+ if (SelectorEngine.eq(pseudoValue, "n")) {\r
+ matchingElms = previousMatch;\r
+ } else {\r
+ Sequence sequence = getSequence(pseudoValue);\r
+ if (sequence != null) {\r
+ for (int l = 0, llen = previousMatch.size(); l < llen; l++) {\r
+ previous = previousMatch.getNode(l);\r
+ Node prevParent = previous.getParentNode();\r
+ if (!hasChildElms(prevParent)) {\r
+ int iteratorNext = sequence.start;\r
+ int childCount = 0;\r
+ Node childElm = prevParent.getFirstChild();\r
+ while (childElm != null && (sequence.max < 0\r
+ || iteratorNext <= sequence.max)) {\r
+ if (childElm.getNodeType() == Node.ELEMENT_NODE) {\r
+ if (++childCount == iteratorNext) {\r
+ if (SelectorEngine\r
+ .eq(childElm.getNodeName(), previous.getNodeName())) {\r
+ matchingElms.addNode(childElm);\r
+ }\r
+ iteratorNext += sequence.add;\r
}\r
+ }\r
+ childElm = SelectorEngine.getNextSibling(childElm);\r
}\r
- String currentRule = selectors[a];\r
- JSArray cssSelectors = selectorSplitRegExp.match(currentRule);\r
- JSArray prevElem = JSArray.create(ctx);\r
- for (int i = 0, slen = cssSelectors.size(); i < slen; i++) {\r
- JSArray matchingElms = JSArray.create();\r
- String rule = cssSelectors.getStr(i);\r
- if (i > 0 && childOrSiblingRefRegExp.test(rule)) {\r
- JSArray childOrSiblingRef = childOrSiblingRefRegExp.exec(rule);\r
- if (SelectorEngine.truth(childOrSiblingRef)) {\r
- JSArray nextTag = new Regexp("^\\w+")\r
- .exec(cssSelectors.getStr(i + 1));\r
- Regexp nextRegExp = null;\r
- String nextTagStr = null;\r
- if (SelectorEngine.truth(nextTag)) {\r
- nextTagStr = nextTag.getStr(0);\r
- nextRegExp = new Regexp("(^|\\s)" + nextTagStr + "(\\s|$)", "i");\r
- }\r
- for (int j = 0, jlen = prevElem.size(); j < jlen; j++) {\r
- Node prevRef = prevElem.getNode(j);\r
- String ref = childOrSiblingRef.getStr(0);\r
- if (SelectorEngine.eq(">", ref)) {\r
- getDescendantNodes(matchingElms, nextTagStr, prevRef);\r
- } else if (SelectorEngine.eq("+", ref)) {\r
- getSiblingNodes(matchingElms, nextTag, nextRegExp, prevRef);\r
- } else if (SelectorEngine.eq("~", ref)) {\r
- getGeneralSiblingNodes(matchingElms, nextTag, nextRegExp,\r
- prevRef);\r
- }\r
- }\r
- prevElem = matchingElms;\r
- clearAdded(prevElem);\r
- rule = cssSelectors.getStr(++i);\r
- if (new Regexp("^\\w+$").test(rule)) {\r
- continue;\r
- }\r
- setSkipTag(prevElem, true);\r
- }\r
- }\r
- JSArray cssSelector = cssSelectorRegExp.exec(rule);\r
- SplitRule splitRule = new SplitRule(\r
- !SelectorEngine.truth(cssSelector.getStr(1)) || SelectorEngine\r
- .eq(cssSelector.getStr(3), "*") ? "*" : cssSelector.getStr(1),\r
- !SelectorEngine.eq(cssSelector.getStr(3), "*") ? cssSelector\r
- .getStr(2) : null, cssSelector.getStr(4), cssSelector.getStr(6),\r
- cssSelector.getStr(10));\r
- if (SelectorEngine.truth(splitRule.id)) {\r
- Element domelem = Document.get()\r
- .getElementById(splitRule.id.substring(1));\r
- if (SelectorEngine.truth(domelem)) {\r
- matchingElms = JSArray.create(domelem);\r
- }\r
- prevElem = matchingElms;\r
- } else if (SelectorEngine.truth(splitRule.tag) && !isSkipped(prevElem)) {\r
- if (i == 0 && matchingElms.size() == 0 && prevElem.size() == 1) {\r
- prevElem = matchingElms = JSArray.create(\r
- getElementsByTagName(splitRule.tag, prevElem.getNode(0)));\r
- } else {\r
- NodeList<Element> tagCollectionMatches;\r
- for (int l = 0, ll = prevElem.size(); l < ll; l++) {\r
- tagCollectionMatches = getElementsByTagName(splitRule.tag,\r
- prevElem.getNode(l));\r
- for (int m = 0, mlen = tagCollectionMatches.getLength(); m < mlen;\r
- m++) {\r
- Node tagMatch = tagCollectionMatches.getItem(m);\r
-\r
- if (!isAdded(tagMatch)) {\r
- setAdded(tagMatch, true);\r
- matchingElms.addNode(tagMatch);\r
- }\r
- }\r
- }\r
- prevElem = matchingElms;\r
- clearAdded(prevElem);\r
- }\r
- if (matchingElms.size() == 0) {\r
- break;\r
- }\r
- setSkipTag(prevElem, false);\r
- if (SelectorEngine.truth(splitRule.allClasses)) {\r
- String[] allClasses = splitRule.allClasses.replaceFirst("^\\.", "")\r
- .split("\\.");\r
- Regexp[] regExpClassNames = new Regexp[allClasses.length];\r
- for (int n = 0, nl = allClasses.length; n < nl; n++) {\r
- regExpClassNames[n] = new Regexp(\r
- "(^|\\s)" + allClasses[n] + "(\\s|$)");\r
- }\r
- JSArray matchingClassElms = JSArray.create();\r
- for (int o = 0, olen = prevElem.size(); o < olen; o++) {\r
- Element current = prevElem.getElement(o);\r
- String elmClass = current.getClassName();\r
- boolean addElm = false;\r
- if (SelectorEngine.truth(elmClass) && !isAdded(current)) {\r
- for (int p = 0, pl = regExpClassNames.length; p < pl; p++) {\r
- addElm = regExpClassNames[p].test(elmClass);\r
- if (!addElm) {\r
- break;\r
- }\r
- }\r
- if (addElm) {\r
- setAdded(current, true);\r
- matchingClassElms.addNode(current);\r
- }\r
- }\r
- }\r
- clearAdded(prevElem);\r
- prevElem = matchingElms = matchingClassElms;\r
- }\r
- if (SelectorEngine.truth(splitRule.allAttr)) {\r
- JSArray allAttr = Regexp\r
- .match("\\[[^\\]]+\\]", "g", splitRule.allAttr);\r
- Regexp[] regExpAttributes = new Regexp[allAttr.size()];\r
- String[] regExpAttributesStr = new String[allAttr.size()];\r
- Regexp attributeMatchRegExp = new Regexp(\r
- "(\\w+)(\\^|\\$|\\*|\\||~)?=?([\\w\u00C0-\uFFFF\\s\\-_\\.]+)?");\r
- for (int q = 0, ql = allAttr.size(); q < ql; q++) {\r
- JSArray attributeMatch = attributeMatchRegExp\r
- .exec(allAttr.getStr(q));\r
- String attributeValue =\r
- SelectorEngine.truth(attributeMatch.getStr(3))\r
- ? attributeMatch.getStr(3).replaceAll("\\.", "\\.")\r
- : null;\r
- String attrVal = attrToRegExp(attributeValue,\r
- (SelectorEngine.or(attributeMatch.getStr(2), null)));\r
- regExpAttributes[q] = (SelectorEngine.truth(attrVal) ? new Regexp(\r
- attrVal) : null);\r
- regExpAttributesStr[q] = attributeMatch.getStr(1); \r
- }\r
- JSArray matchingAttributeElms = JSArray.create();\r
-\r
- for (int r = 0, rlen = matchingElms.size(); r < rlen; r++) {\r
- Element current = matchingElms.getElement(r);\r
- boolean addElm = false;\r
- for (int s = 0, sl = regExpAttributes.length, attributeRegExp;\r
- s < sl; s++) {\r
- addElm = false;\r
- Regexp attributeRegExp2 = regExpAttributes[s];\r
- String currentAttr = getAttr(current, regExpAttributesStr[s]);\r
- if (SelectorEngine.truth(currentAttr)\r
- && currentAttr.length() != 0) {\r
- if (attributeRegExp2 == null || attributeRegExp2\r
- .test(currentAttr)) {\r
- addElm = true;\r
- }\r
- }\r
- if (!addElm) {\r
- break;\r
- }\r
- }\r
- if (addElm) {\r
- matchingAttributeElms.addNode(current);\r
- }\r
- }\r
- prevElem = matchingElms = matchingAttributeElms;\r
- }\r
- if (SelectorEngine.truth(splitRule.allPseudos)) {\r
- Regexp pseudoSplitRegExp = new Regexp(\r
- ":(\\w[\\w\\-]*)(\\(([^\\)]+)\\))?");\r
-\r
- JSArray allPseudos = Regexp.match(\r
- "(:\\w+[\\w\\-]*)(\\([^\\)]+\\))?", "g", splitRule.allPseudos);\r
- for (int t = 0, tl = allPseudos.size(); t < tl; t++) {\r
- JSArray pseudo = pseudoSplitRegExp.match(allPseudos.getStr(t));\r
- String pseudoClass = SelectorEngine.truth(pseudo.getStr(1))\r
- ? pseudo.getStr(1)\r
- .toLowerCase() : null;\r
- String pseudoValue = SelectorEngine.truth(pseudo.getStr(3))\r
- ? pseudo.getStr(3) : null;\r
- matchingElms = getElementsByPseudo(matchingElms, pseudoClass,\r
- pseudoValue);\r
- clearAdded(matchingElms);\r
- }\r
- prevElem = matchingElms;\r
- }\r
+ setHasChildElms(prevParent, true);\r
+ prevParents.addNode(prevParent);\r
+ }\r
+ }\r
+ clearChildElms(prevParents);\r
+ }\r
+ }\r
+ return matchingElms;\r
+ }\r
+\r
+ private JSArray getNthOfTypePseudo(JSArray previousMatch, String pseudoValue,\r
+ JSArray prevParents, JSArray matchingElms) {\r
+ Node previous;\r
+ if (pseudoValue.startsWith("n")) {\r
+ matchingElms = previousMatch;\r
+ } else {\r
+ Sequence sequence = getSequence(pseudoValue);\r
+ if (sequence != null) {\r
+ for (int p = 0, plen = previousMatch.size(); p < plen; p++) {\r
+ previous = previousMatch.getNode(p);\r
+ Node prevParent = previous.getParentNode();\r
+ if (!hasChildElms(prevParent)) {\r
+ int iteratorNext = sequence.start;\r
+ int childCount = 0;\r
+ Node childElm = prevParent.getFirstChild();\r
+ while (SelectorEngine.truth(childElm) && (sequence.max < 0\r
+ || iteratorNext <= sequence.max)) {\r
+ if (SelectorEngine\r
+ .eq(childElm.getNodeName(), previous.getNodeName())) {\r
+ if (++childCount == iteratorNext) {\r
+ matchingElms.addNode(childElm);\r
+ iteratorNext += sequence.add;\r
}\r
+ }\r
+ childElm = SelectorEngine.getNextSibling(childElm);\r
}\r
- elm.pushAll(prevElem);\r
+ setHasChildElms(prevParent, true);\r
+ prevParents.addNode(prevParent);\r
+ }\r
}\r
-\r
- return elm;\r
+ clearChildElms(prevParents);\r
+ }\r
+ }\r
+ return matchingElms;\r
+ }\r
+\r
+ private void getOnlyChildPseudo(JSArray previousMatch, JSArray matchingElms) {\r
+ Node previous;\r
+ Node next;\r
+ Node prev;\r
+ Node kParent = null;\r
+ for (int k = 0, klen = previousMatch.size(); k < klen; k++) {\r
+ prev = next = previous = previousMatch.getNode(k);\r
+ Node prevParent = previous.getParentNode();\r
+ if (prevParent != kParent) {\r
+ while (\r
+ SelectorEngine.truth(prev = SelectorEngine.getPreviousSibling(prev))\r
+ && prev.getNodeType() != Node.ELEMENT_NODE) {\r
+ }\r
+ while (SelectorEngine.truth(next = SelectorEngine.getNextSibling(next))\r
+ && next.getNodeType() != Node.ELEMENT_NODE) {\r
+ }\r
+ if (!SelectorEngine.truth(prev) && !SelectorEngine.truth(next)) {\r
+ matchingElms.addNode(previous);\r
+ }\r
+ kParent = prevParent;\r
+ }\r
+ }\r
+ }\r
+\r
+ private void getOnlyOfTypePseudo(JSArray previousMatch,\r
+ JSArray matchingElms) {\r
+ Node previous;\r
+ Node next;\r
+ Node prev;\r
+ Node oParent = null;\r
+ for (int o = 0, olen = previousMatch.size(); o < olen; o++) {\r
+ prev = next = previous = previousMatch.getNode(o);\r
+ Node prevParent = previous.getParentNode();\r
+ if (prevParent != oParent) {\r
+ while (\r
+ SelectorEngine.truth(prev = SelectorEngine.getPreviousSibling(prev))\r
+ && !SelectorEngine\r
+ .eq(prev.getNodeName(), previous.getNodeName())) {\r
+ }\r
+ while (SelectorEngine.truth(next = SelectorEngine.getNextSibling(next))\r
+ && !SelectorEngine.eq(next.getNodeName(), previous.getNodeName())) {\r
+ }\r
+ if (!SelectorEngine.truth(prev) && !SelectorEngine.truth(next)) {\r
+ matchingElms.addNode(previous);\r
+ }\r
+ oParent = prevParent;\r
+ }\r
}\r
+ }\r
}\r
import com.google.gwt.dom.client.Element;\r
\r
/**\r
- * Runtime implementaton of non-XPath/native for IE that fixes some \r
- * DOM operation incompatibilities.\r
+ * Runtime implementaton of non-XPath/native for IE that fixes some DOM\r
+ * operation incompatibilities.\r
*/\r
public class SelectorEngineJSIE extends SelectorEngineJS {\r
- public native String getAttr(Element elm, String attr) /*-{\r
+\r
+ public native String getAttr(Element elm, String attr) /*-{\r
switch (attr) {\r
- case "id":\r
- return elm.id;\r
- case "for":\r
- return elm.htmlFor;\r
- case "class":\r
- return elm.className;\r
- }\r
- return elm.getAttribute(attr, 2);\r
+ case "id":\r
+ return elm.id;\r
+ case "for":\r
+ return elm.htmlFor;\r
+ case "class":\r
+ return elm.className;\r
+ }\r
+ return elm.getAttribute(attr, 2);\r
}-*/;\r
}\r
+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.google.gwt.query.client.impl;
import com.google.gwt.dom.client.Element;
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.client.impl;\r
\r
import com.google.gwt.core.client.GWT;\r
* and delegates to document.evaluate().\r
*/\r
public class SelectorEngineXPath extends SelectorEngineImpl {\r
- private Regexp cssSelectorRegExp;\r
- private Regexp selectorSplitRegExp;\r
- private Regexp COMBINATOR;\r
\r
- public SelectorEngineXPath() {\r
+ private static String attrToXPath(String match, String p1, String p2,\r
+ String p3) {\r
+ if (eq("^", p2)) {\r
+ return "starts-with(@" + p1 + ", '" + p3 + "')";\r
}\r
-\r
- private void init() {\r
- if (cssSelectorRegExp == null) {\r
- cssSelectorRegExp = new Regexp(\r
- "^(\\w+)?(#[\\w\\u00C0-\\uFFFF\\-\\_]+|(\\*))?((\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+)?\\]+)*)?(((:\\w+[\\w\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[\\w\\u00C0-\\uFFFF\\-_]+|((\\w*\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[\\w\\-]*))\\))?)*)?(>|\\+|~)?");\r
- selectorSplitRegExp = new Regexp("[^\\s]+", "g");\r
- COMBINATOR = new Regexp("(>|\\+|~)");\r
- }\r
+ if (eq("$", p2)) {\r
+ return "substring(@" + p1 + ", (string-length(@" + p1 + ") - "\r
+ + (p3.length() - 1) + "), " + p3.length() + ") = '" + p3 + "'";\r
+ }\r
+ if (eq("*", p2)) {\r
+ return "contains(concat(' ', @" + p1 + ", ' '), '" + p3 + "')";\r
}\r
+ if (eq("|", p2)) {\r
+ return "(@" + p1 + "='" + p3 + "' or starts-with(@" + p1 + ", '" + p3\r
+ + "-'))";\r
+ }\r
+ if (eq("~", p2)) {\r
+ return "contains(concat(' ', @" + p1 + ", ' '), ' " + p3 + " ')";\r
+ }\r
+ return "@" + p1 + (truth(p3) ? "='" + p3 + "'" : "");\r
+ }\r
\r
+ private Regexp cssSelectorRegExp;\r
\r
- public NodeList<Element> select(String sel, Node ctx) {\r
- init();\r
- String selectors[] = sel.replaceAll("\\s*(,)\\s*", "$1").split(",");\r
- boolean identical = false;\r
- JSArray elm = JSArray.create();\r
- for (int a = 0, len = selectors.length; a < len; a++) {\r
- if (a > 0) {\r
- identical = false;\r
- for (int b = 0, bl = a; b < bl; b++) {\r
- if (eq(selectors[a], selectors[b])) {\r
- identical = true;\r
- break;\r
- }\r
- }\r
- if (identical) {\r
- continue;\r
- }\r
- }\r
- String currentRule = selectors[a];\r
- JSArray cssSelectors = selectorSplitRegExp.match(currentRule);\r
- String xPathExpression = ".";\r
- for (int i = 0, slen = cssSelectors.size(); i < slen; i++) {\r
- String rule = cssSelectors.getStr(i);\r
- JSArray cssSelector = cssSelectorRegExp.exec(rule);\r
- SplitRule splitRule = new SplitRule(!truth(cssSelector.getStr(1)) || eq(\r
- cssSelector.getStr(3), "*") ? "*" : cssSelector.getStr(1),\r
- !eq(cssSelector.getStr(3), "*") ? cssSelector.getStr(2) : null,\r
- cssSelector.getStr(4), cssSelector.getStr(6),\r
- cssSelector.getStr(10), cssSelector.getStr(22));\r
- if (truth(splitRule.tagRelation)) {\r
- if (eq(">", splitRule.tagRelation)) {\r
- xPathExpression += "/child::";\r
- } else if (eq("+", splitRule.tagRelation)) {\r
- xPathExpression += "/following-sibling::*[1]/self::";\r
- } else if (eq("~", splitRule.tagRelation)) {\r
- xPathExpression += "/following-sibling::";\r
- }\r
- } else {\r
- xPathExpression +=\r
- (i > 0 && COMBINATOR.test(cssSelectors.getStr(i - 1)))\r
- ? splitRule.tag : ("/descendant::" + splitRule.tag);\r
- }\r
- if (truth(splitRule.id)) {\r
- xPathExpression += "[@id = '" + splitRule.id.replaceAll("^#", "")\r
- + "']";\r
- }\r
- if (truth(splitRule.allClasses)) {\r
- xPathExpression += splitRule.allClasses.replaceAll(\r
- "\\.([\\w\\u00C0-\\uFFFF\\-_]+)",\r
- "[contains(concat(' ', @class, ' '), ' $1 ')]");\r
- }\r
- if (truth(splitRule.allAttr)) {\r
- GWT.log("AllAttr is " + splitRule.allAttr, null);\r
- xPathExpression += replaceAttr(\r
- SelectorEngine.or(splitRule.allAttr, ""));\r
- }\r
- if (truth(splitRule.allPseudos)) {\r
- Regexp pseudoSplitRegExp = new Regexp(\r
- ":(\\w[\\w\\-]*)(\\(([^\\)]+)\\))?");\r
- Regexp pseudoMatchRegExp = new Regexp(\r
- "(:\\w+[\\w\\-]*)(\\([^\\)]+\\))?", "g");\r
- JSArray allPseudos = pseudoMatchRegExp.match(splitRule.allPseudos);\r
- for (int k = 0, kl = allPseudos.size(); k < kl; k++) {\r
- JSArray pseudo = pseudoSplitRegExp.match(allPseudos.getStr(k));\r
- String pseudoClass = truth(pseudo.getStr(1)) ? pseudo.getStr(1)\r
- .toLowerCase() : null;\r
- String pseudoValue = truth(pseudo.getStr(3)) ? pseudo.getStr(3)\r
- : null;\r
- String xpath = pseudoToXPath(splitRule.tag, pseudoClass,\r
- pseudoValue);\r
- if (xpath.length() > 0) {\r
- xPathExpression += "[" + xpath + "]";\r
- }\r
- }\r
- }\r
- }\r
- SelectorEngine.xpathEvaluate(xPathExpression, ctx, elm);\r
- }\r
- return elm;\r
- }\r
+ private Regexp selectorSplitRegExp;\r
\r
- private String pseudoToXPath(String tag, String pseudoClass,\r
- String pseudoValue) {\r
- String xpath = "";\r
- if (eq("first-child", pseudoClass)) {\r
- xpath = "not(preceding-sibling::*)";\r
- } else if (eq("first-of-type", pseudoClass)) {\r
- xpath = "not(preceding-sibling::" + tag + ")";\r
- } else if (eq("last-child", pseudoClass)) {\r
- xpath = "not(following-sibling::*)";\r
- } else if (eq("last-of-type", pseudoClass)) {\r
- xpath = "not(following-sibling::" + tag + ")";\r
- } else if (eq("only-child", pseudoClass)) {\r
- xpath = "not(preceding-sibling::* or following-sibling::*)";\r
- } else if (eq("only-of-type", pseudoClass)) {\r
- xpath = "not(preceding-sibling::" + tag + " or following-sibling::" + tag\r
- + ")";\r
- } else if (eq("nth-child", pseudoClass)) {\r
- if (!eq("n", pseudoClass)) {\r
- Sequence sequence = getSequence(pseudoValue);\r
- if (sequence != null) {\r
- if (sequence.start == sequence.max) {\r
- xpath = "count(preceding-sibling::*) = " + (sequence.start - 1);\r
- } else {\r
- xpath = "(count(preceding-sibling::*) + 1) mod " + sequence.add\r
- + " = " + sequence.modVal + ((sequence.start > 1) ?\r
- " and count(preceding-sibling::*) >= " + (sequence.start - 1)\r
- : "") + ((sequence.max > 0) ?\r
- " and count(preceding-sibling::*) <= " + (sequence.max - 1)\r
- : "");\r
- }\r
- }\r
- }\r
- } else if (eq("nth-of-type", pseudoClass)) {\r
- if (!pseudoValue.startsWith("n")) {\r
- Sequence sequence = getSequence(pseudoValue);\r
- if (sequence != null) {\r
- if (sequence.start == sequence.max) {\r
- xpath = pseudoValue;\r
- } else {\r
- xpath = "position() mod " + sequence.add + " = " + sequence.modVal\r
- + ((sequence.start > 1) ? " and position() >= " + sequence\r
- .start : "") + ((sequence.max > 0) ? " and position() <= "\r
- + sequence.max : "");\r
- }\r
- }\r
- }\r
- } else if (eq("empty", pseudoClass)) {\r
- xpath = "count(child::*) = 0 and string-length(text()) = 0";\r
- } else if (eq("contains", pseudoClass)) {\r
- xpath = "contains(., '" + pseudoValue + "')";\r
- } else if (eq("enabled", pseudoClass)) {\r
- xpath = "not(@disabled)";\r
- } else if (eq("disabled", pseudoClass)) {\r
- xpath = "@disabled";\r
- } else if (eq("checked", pseudoClass)) {\r
- xpath = "@checked='checked'"; // Doesn't work in Opera 9.24\r
- } else if (eq("not", pseudoClass)) {\r
- if (new Regexp("^(:\\w+[\\w\\-]*)$").test(pseudoValue)) {\r
- xpath = "not(" + pseudoToXPath(tag, pseudoValue.substring(1), "") + ")";\r
- } else {\r
+ private Regexp combinator;\r
\r
- pseudoValue = pseudoValue\r
- .replaceFirst("^\\[#([\\w\\u00C0-\\uFFFF\\-\\_]+)\\]$", "[id=$1]");\r
- String notSelector = pseudoValue\r
- .replaceFirst("^(\\w+)", "self::$1");\r
- notSelector = notSelector.replaceAll("^\\.([\\w\\u00C0-\\uFFFF\\-_]+)",\r
- "contains(concat(' ', @class, ' '), ' $1 ')");\r
- notSelector = replaceAttr2(notSelector);\r
- xpath = "not(" + notSelector + ")";\r
- }\r
+ public SelectorEngineXPath() {\r
+ }\r
+\r
+ public NodeList<Element> select(String sel, Node ctx) {\r
+ init();\r
+ String selectors[] = sel.replaceAll("\\s*(,)\\s*", "$1").split(",");\r
+ boolean identical = false;\r
+ JSArray elm = JSArray.create();\r
+ for (int a = 0, len = selectors.length; a < len; a++) {\r
+ if (a > 0) {\r
+ identical = false;\r
+ for (int b = 0, bl = a; b < bl; b++) {\r
+ if (eq(selectors[a], selectors[b])) {\r
+ identical = true;\r
+ break;\r
+ }\r
+ }\r
+ if (identical) {\r
+ continue;\r
+ }\r
+ }\r
+ String currentRule = selectors[a];\r
+ JSArray cssSelectors = selectorSplitRegExp.match(currentRule);\r
+ String xPathExpression = ".";\r
+ for (int i = 0, slen = cssSelectors.size(); i < slen; i++) {\r
+ String rule = cssSelectors.getStr(i);\r
+ JSArray cssSelector = cssSelectorRegExp.exec(rule);\r
+ SplitRule splitRule = new SplitRule(\r
+ !truth(cssSelector.getStr(1)) || eq(cssSelector.getStr(3), "*")\r
+ ? "*" : cssSelector.getStr(1),\r
+ !eq(cssSelector.getStr(3), "*") ? cssSelector.getStr(2) : null,\r
+ cssSelector.getStr(4), cssSelector.getStr(6),\r
+ cssSelector.getStr(10), cssSelector.getStr(22));\r
+ if (truth(splitRule.tagRelation)) {\r
+ if (eq(">", splitRule.tagRelation)) {\r
+ xPathExpression += "/child::";\r
+ } else if (eq("+", splitRule.tagRelation)) {\r
+ xPathExpression += "/following-sibling::*[1]/self::";\r
+ } else if (eq("~", splitRule.tagRelation)) {\r
+ xPathExpression += "/following-sibling::";\r
+ }\r
} else {\r
- xpath = "@" + pseudoClass + "='" + pseudoValue + "'";\r
+ xPathExpression +=\r
+ (i > 0 && combinator.test(cssSelectors.getStr(i - 1)))\r
+ ? splitRule.tag : ("/descendant::" + splitRule.tag);\r
}\r
-\r
- return xpath;\r
- }\r
-\r
- private static String attrToXPath(String match, String p1, String p2,\r
- String p3) {\r
- if (eq("^", p2)) {\r
- return "starts-with(@" + p1 + ", '" + p3 + "')";\r
+ if (truth(splitRule.id)) {\r
+ xPathExpression += "[@id = '" + splitRule.id.replaceAll("^#", "")\r
+ + "']";\r
}\r
- if (eq("$", p2)) {\r
- return "substring(@" + p1 + ", (string-length(@" + p1 + ") - "\r
- + (p3.length() - 1) + "), " + p3.length() + ") = '" + p3 + "'";\r
+ if (truth(splitRule.allClasses)) {\r
+ xPathExpression += splitRule.allClasses\r
+ .replaceAll("\\.([\\w\\u00C0-\\uFFFF\\-_]+)",\r
+ "[contains(concat(' ', @class, ' '), ' $1 ')]");\r
}\r
- if (eq("*", p2)) {\r
- return "contains(concat(' ', @" + p1 + ", ' '), '" + p3 + "')";\r
+ if (truth(splitRule.allAttr)) {\r
+ GWT.log("AllAttr is " + splitRule.allAttr, null);\r
+ xPathExpression += replaceAttr(\r
+ SelectorEngine.or(splitRule.allAttr, ""));\r
}\r
- if (eq("|", p2)) {\r
- return "(@" + p1 + "='" + p3 + "' or starts-with(@" + p1 + ", '" + p3\r
- + "-'))";\r
+ if (truth(splitRule.allPseudos)) {\r
+ Regexp pseudoSplitRegExp = new Regexp(\r
+ ":(\\w[\\w\\-]*)(\\(([^\\)]+)\\))?");\r
+ Regexp pseudoMatchRegExp = new Regexp(\r
+ "(:\\w+[\\w\\-]*)(\\([^\\)]+\\))?", "g");\r
+ JSArray allPseudos = pseudoMatchRegExp.match(splitRule.allPseudos);\r
+ for (int k = 0, kl = allPseudos.size(); k < kl; k++) {\r
+ JSArray pseudo = pseudoSplitRegExp.match(allPseudos.getStr(k));\r
+ String pseudoClass = truth(pseudo.getStr(1)) ? pseudo.getStr(1)\r
+ .toLowerCase() : null;\r
+ String pseudoValue = truth(pseudo.getStr(3)) ? pseudo.getStr(3)\r
+ : null;\r
+ String xpath = pseudoToXPath(splitRule.tag, pseudoClass,\r
+ pseudoValue);\r
+ if (xpath.length() > 0) {\r
+ xPathExpression += "[" + xpath + "]";\r
+ }\r
+ }\r
}\r
- if (eq("~", p2)) {\r
- return "contains(concat(' ', @" + p1 + ", ' '), ' " + p3 + " ')";\r
+ }\r
+ SelectorEngine.xpathEvaluate(xPathExpression, ctx, elm);\r
+ }\r
+ return elm;\r
+ }\r
+\r
+ private void init() {\r
+ if (cssSelectorRegExp == null) {\r
+ cssSelectorRegExp = new Regexp(\r
+ "^(\\w+)?(#[\\w\\u00C0-\\uFFFF\\-\\_]+|(\\*))?((\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+)?\\]+)*)?(((:\\w+[\\w\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[\\w\\u00C0-\\uFFFF\\-_]+|((\\w*\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[\\w\\-]*))\\))?)*)?(>|\\+|~)?");\r
+ selectorSplitRegExp = new Regexp("[^\\s]+", "g");\r
+ combinator = new Regexp("(>|\\+|~)");\r
+ }\r
+ }\r
+\r
+ private String pseudoToXPath(String tag, String pseudoClass,\r
+ String pseudoValue) {\r
+ String xpath = "";\r
+ if (eq("first-child", pseudoClass)) {\r
+ xpath = "not(preceding-sibling::*)";\r
+ } else if (eq("first-of-type", pseudoClass)) {\r
+ xpath = "not(preceding-sibling::" + tag + ")";\r
+ } else if (eq("last-child", pseudoClass)) {\r
+ xpath = "not(following-sibling::*)";\r
+ } else if (eq("last-of-type", pseudoClass)) {\r
+ xpath = "not(following-sibling::" + tag + ")";\r
+ } else if (eq("only-child", pseudoClass)) {\r
+ xpath = "not(preceding-sibling::* or following-sibling::*)";\r
+ } else if (eq("only-of-type", pseudoClass)) {\r
+ xpath = "not(preceding-sibling::" + tag + " or following-sibling::" + tag\r
+ + ")";\r
+ } else if (eq("nth-child", pseudoClass)) {\r
+ if (!eq("n", pseudoClass)) {\r
+ Sequence sequence = getSequence(pseudoValue);\r
+ if (sequence != null) {\r
+ if (sequence.start == sequence.max) {\r
+ xpath = "count(preceding-sibling::*) = " + (sequence.start - 1);\r
+ } else {\r
+ xpath = "(count(preceding-sibling::*) + 1) mod " + sequence.add\r
+ + " = " + sequence.modVal\r
+ + ((sequence.start > 1) ? " and count(preceding-sibling::*) >= "\r
+ + (sequence.start - 1) : "") + ((sequence.max > 0) ?\r
+ " and count(preceding-sibling::*) <= " + (sequence.max - 1)\r
+ : "");\r
+ }\r
}\r
- return "@" + p1 + (truth(p3) ? "='" + p3 + "'" : "");\r
+ }\r
+ } else if (eq("nth-of-type", pseudoClass)) {\r
+ if (!pseudoValue.startsWith("n")) {\r
+ Sequence sequence = getSequence(pseudoValue);\r
+ if (sequence != null) {\r
+ if (sequence.start == sequence.max) {\r
+ xpath = pseudoValue;\r
+ } else {\r
+ xpath = "position() mod " + sequence.add + " = " + sequence.modVal\r
+ + ((sequence.start > 1) ? " and position() >= " + sequence.start\r
+ : "") + ((sequence.max > 0) ? " and position() <= "\r
+ + sequence.max : "");\r
+ }\r
+ }\r
+ }\r
+ } else if (eq("empty", pseudoClass)) {\r
+ xpath = "count(child::*) = 0 and string-length(text()) = 0";\r
+ } else if (eq("contains", pseudoClass)) {\r
+ xpath = "contains(., '" + pseudoValue + "')";\r
+ } else if (eq("enabled", pseudoClass)) {\r
+ xpath = "not(@disabled)";\r
+ } else if (eq("disabled", pseudoClass)) {\r
+ xpath = "@disabled";\r
+ } else if (eq("checked", pseudoClass)) {\r
+ xpath = "@checked='checked'"; // Doesn't work in Opera 9.24\r
+ } else if (eq("not", pseudoClass)) {\r
+ if (new Regexp("^(:\\w+[\\w\\-]*)$").test(pseudoValue)) {\r
+ xpath = "not(" + pseudoToXPath(tag, pseudoValue.substring(1), "") + ")";\r
+ } else {\r
+\r
+ pseudoValue = pseudoValue\r
+ .replaceFirst("^\\[#([\\w\\u00C0-\\uFFFF\\-\\_]+)\\]$", "[id=$1]");\r
+ String notSelector = pseudoValue.replaceFirst("^(\\w+)", "self::$1");\r
+ notSelector = notSelector.replaceAll("^\\.([\\w\\u00C0-\\uFFFF\\-_]+)",\r
+ "contains(concat(' ', @class, ' '), ' $1 ')");\r
+ notSelector = replaceAttr2(notSelector);\r
+ xpath = "not(" + notSelector + ")";\r
+ }\r
+ } else {\r
+ xpath = "@" + pseudoClass + "='" + pseudoValue + "'";\r
}\r
\r
- private native String replaceAttr(String allAttr) /*-{\r
+ return xpath;\r
+ }\r
+\r
+ private native String replaceAttr(String allAttr) /*-{\r
if(!allAttr) return "";\r
return allAttr.replace(/(\w+)(\^|\$|\*|\||~)?=?([\w\u00C0-\uFFFF\s\-_\.]+)?/g, \r
function(a,b,c,d) {\r
\r
}-*/;\r
\r
- private native String replaceAttr2(String allAttr) /*-{\r
+ private native String replaceAttr2(String allAttr) /*-{\r
if(!allAttr) return "";\r
return allAttr.replace(/\[(\w+)(\^|\$|\*|\||~)?=?([\w\u00C0-\uFFFF\s\-_\.]+)?\]/g, @com.google.gwt.query.client.impl.SelectorEngineXPath::attrToXPath(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;));\r
}-*/;\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.rebind;\r
\r
import com.google.gwt.core.ext.Generator;\r
*/\r
public abstract class SelectorGeneratorBase extends Generator {\r
\r
- private TreeLogger treeLogger;\r
+ protected JClassType nodeType = null;\r
\r
- protected JClassType NODE_TYPE = null;\r
+ private TreeLogger treeLogger;\r
\r
public String generate(TreeLogger treeLogger,\r
GeneratorContext generatorContext, String requestedClass)\r
throws UnableToCompleteException {\r
this.treeLogger = treeLogger;\r
TypeOracle oracle = generatorContext.getTypeOracle();\r
- NODE_TYPE = oracle.findType("com.google.gwt.dom.client.Node");\r
+ nodeType = oracle.findType("com.google.gwt.dom.client.Node");\r
\r
JClassType selectorType = oracle.findType(requestedClass);\r
SourceWriter sw = getSourceWriter(treeLogger, generatorContext,\r
+ selectorType.getSimpleSourceName() + getImplSuffix();\r
}\r
\r
- protected String getImplSuffix() {\r
- return "Impl";\r
- }\r
-\r
- // used by benchmark harness\r
- private void genGetAllMethod(SourceWriter sw, JMethod[] methods,\r
- TreeLogger treeLogger) {\r
- sw.println("public DeferredGQuery[] getAllSelectors() {");\r
- sw.indent();\r
- sw.println(\r
- "DeferredGQuery[] dg = new DeferredGQuery[" + (methods.length) + "];");\r
- int i = 0;\r
- for (JMethod m : methods) {\r
- Selector selectorAnnotation = m.getAnnotation(Selector.class);\r
- if(selectorAnnotation == null) continue;\r
- String selector = selectorAnnotation.value();\r
-\r
- sw.println("dg[" + i + "]=new DeferredGQuery() {");\r
- sw.indent();\r
- sw.println(\r
- "public String getSelector() { return \"" + selector + "\"; }");\r
- sw.println("public GQuery eval(Node ctx) { return " + wrapJS(m, m.getName()\r
- + (m.getParameters().length == 0 ? "()" : "(ctx)")+"") + " ;}");\r
- sw.println("public NodeList<Element> array(Node ctx) { return "+("NodeList".equals(m.getReturnType().getSimpleSourceName()) ?\r
- (m.getName()\r
- + (m.getParameters().length == 0 ? "(); " : "(ctx); ")) : \r
- "eval"+(m.getParameters().length == 0 ? "(null).get(); " : "(ctx).get(); "))+"}");\r
- \r
- i++;\r
- sw.outdent();\r
- sw.println("};");\r
- }\r
- sw.println("return dg;");\r
- sw.outdent();\r
- sw.println("}");\r
- }\r
-\r
public void generateMethod(SourceWriter sw, JMethod method, TreeLogger logger)\r
throws UnableToCompleteException {\r
- Selector selectorAnnotation = method.getAnnotation(Selector.class);\r
- if(selectorAnnotation == null) return;\r
+ Selector selectorAnnotation = method.getAnnotation(Selector.class);\r
+ if (selectorAnnotation == null) {\r
+ return;\r
+ }\r
\r
- String selector = selectorAnnotation.value();\r
JParameter[] params = method.getParameters();\r
\r
sw.indent();\r
- String retType = method.getReturnType().getParameterizedQualifiedSourceName();\r
- sw.print("public final "+retType+" "+method.getName());\r
+ String retType = method.getReturnType()\r
+ .getParameterizedQualifiedSourceName();\r
+ sw.print("public final " + retType + " " + method.getName());\r
boolean hasContext = false;\r
if (params.length == 0) {\r
sw.print("()");\r
} else if (params.length == 1) {\r
JClassType type = params[0].getType().isClassOrInterface();\r
- if (type != null && type.isAssignableTo(NODE_TYPE)) {\r
+ if (type != null && type.isAssignableTo(nodeType)) {\r
sw.print("(Node root)");\r
hasContext = true;\r
}\r
\r
// short circuit #foo\r
if (sel != null && sel.value().matches("^#\\w+$")) {\r
- sw.println("return "+wrap(method, "JSArray.create(((Document)" + (hasContext ? "root" : "(Node)Document.get()")\r
- + ").getElementById(\"" + sel.value().substring(1) + "\"))")+";");\r
- }\r
- // short circuit FOO\r
- else if (sel != null && sel.value().matches("^\\w+$")) {\r
- sw.println("return "+wrap(method, "JSArray.create(((Element)"+(hasContext ? "root" : "(Node)Document.get()")\r
- + ").getElementsByTagName(\"" + sel.value() + "\"))")+";");\r
- } // short circuit .foo for browsers with native getElementsByClassName \r
- else if (sel != null && sel.value().matches("^\\.\\w+$")\r
+ sw.println("return " + wrap(method, "JSArray.create(((Document)"\r
+ + (hasContext ? "root" : "(Node)Document.get()")\r
+ + ").getElementById(\"" + sel.value().substring(1) + "\"))") + ";");\r
+ } else if (sel != null && sel.value().matches("^\\w+$")) {\r
+ // short circuit FOO\r
+ sw.println("return " + wrap(method, "JSArray.create(((Element)"\r
+ + (hasContext ? "root" : "(Node)Document.get()")\r
+ + ").getElementsByTagName(\"" + sel.value() + "\"))") + ";");\r
+ } else if (sel != null && sel.value().matches("^\\.\\w+$")\r
&& hasGetElementsByClassName()) {\r
- sw.println("return "+wrap(method, "JSArray.create(getElementsByClassName(\""\r
- + sel.value().substring(1) + "\", " + (hasContext ? "root" : "(Node)Document.get()")\r
- + "))")+";");\r
+ // short circuit .foo for browsers with native getElementsByClassName \r
+ sw.println("return " + wrap(method,\r
+ "JSArray.create(getElementsByClassName(\"" + sel.value().substring(1)\r
+ + "\", " + (hasContext ? "root" : "(Node)Document.get()") + "))")\r
+ + ";");\r
} else {\r
generateMethodBody(sw, method, logger, hasContext);\r
}\r
sw.outdent();\r
}\r
\r
- protected boolean hasGetElementsByClassName() {\r
- return false;\r
- }\r
-\r
protected void debug(String s) {\r
// System.err.println(s);\r
treeLogger.log(TreeLogger.DEBUG, s, null);\r
}\r
\r
- protected boolean notNull(String s) {\r
- return s != null && !"".equals(s);\r
+ protected abstract void generateMethodBody(SourceWriter sw, JMethod method,\r
+ TreeLogger logger, boolean hasContext) throws UnableToCompleteException;\r
+\r
+ protected String getImplSuffix() {\r
+ return "Impl";\r
}\r
\r
protected SourceWriter getSourceWriter(TreeLogger logger,\r
return composerFactory.createSourceWriter(context, printWriter);\r
}\r
\r
+ protected boolean hasGetElementsByClassName() {\r
+ return false;\r
+ }\r
+\r
+ protected boolean notNull(String s) {\r
+ return s != null && !"".equals(s);\r
+ }\r
+\r
protected String wrap(JMethod method, String expr) {\r
- if("NodeList".equals(method.getReturnType().getSimpleSourceName())) {\r
+ if ("NodeList".equals(method.getReturnType().getSimpleSourceName())) {\r
return expr;\r
+ } else {\r
+ return "new GQuery(" + expr + ")";\r
}\r
- else {\r
- return "new GQuery("+expr+")";\r
- }\r
- \r
}\r
- \r
+\r
protected String wrapJS(JMethod method, String expr) {\r
- if("GQuery".equals(method.getReturnType().getSimpleSourceName())) {\r
+ if ("GQuery".equals(method.getReturnType().getSimpleSourceName())) {\r
return expr;\r
+ } else {\r
+ return "new GQuery(" + expr + ")";\r
}\r
- else {\r
- return "new GQuery("+expr+")";\r
+ }\r
+\r
+ // used by benchmark harness\r
+ private void genGetAllMethod(SourceWriter sw, JMethod[] methods,\r
+ TreeLogger treeLogger) {\r
+ sw.println("public DeferredGQuery[] getAllSelectors() {");\r
+ sw.indent();\r
+ sw.println(\r
+ "DeferredGQuery[] dg = new DeferredGQuery[" + (methods.length) + "];");\r
+ int i = 0;\r
+ for (JMethod m : methods) {\r
+ Selector selectorAnnotation = m.getAnnotation(Selector.class);\r
+ if (selectorAnnotation == null) {\r
+ continue;\r
+ }\r
+ String selector = selectorAnnotation.value();\r
+\r
+ sw.println("dg[" + i + "]=new DeferredGQuery() {");\r
+ sw.indent();\r
+ sw.println(\r
+ "public String getSelector() { return \"" + selector + "\"; }");\r
+ sw.println("public GQuery eval(Node ctx) { return " + wrapJS(m,\r
+ m.getName() + (m.getParameters().length == 0 ? "()" : "(ctx)") + "")\r
+ + " ;}");\r
+ sw.println("public NodeList<Element> array(Node ctx) { return "\r
+ + ("NodeList".equals(m.getReturnType().getSimpleSourceName()) ? (\r
+ m.getName() + (m.getParameters().length == 0 ? "(); " : "(ctx); "))\r
+ : "eval" + (m.getParameters().length == 0 ? "(null).get(); "\r
+ : "(ctx).get(); ")) + "}");\r
+\r
+ i++;\r
+ sw.outdent();\r
+ sw.println("};");\r
}\r
- \r
+ sw.println("return dg;");\r
+ sw.outdent();\r
+ sw.println("}");\r
}\r
- \r
- protected abstract void generateMethodBody(SourceWriter sw, JMethod method,\r
- TreeLogger logger, boolean hasContext) throws UnableToCompleteException;\r
}\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.rebind;\r
\r
import com.google.gwt.core.ext.TreeLogger;\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.rebind;\r
\r
import com.google.gwt.core.ext.TreeLogger;\r
import com.google.gwt.core.ext.UnableToCompleteException;\r
import com.google.gwt.core.ext.typeinfo.JMethod;\r
import com.google.gwt.user.rebind.SourceWriter;\r
+import com.google.gwt.query.client.Selector;\r
\r
import java.util.regex.Pattern;\r
\r
-import com.google.gwt.query.client.Selector;\r
\r
/**\r
*\r
*/\r
public class SelectorGeneratorJSOptimal extends SelectorGeneratorBase {\r
\r
- protected static Pattern nonSpace = Pattern.compile("\\S/");\r
+ static class RuleMatcher {\r
\r
- private static final String trimReStr = "^\\s+|\\s+$";\r
+ public Pattern re;\r
+\r
+ public String fnTemplate;\r
+\r
+ RuleMatcher(String pat, String fnT) {\r
+ this.re = Pattern.compile(pat);\r
+ this.fnTemplate = fnT;\r
+ }\r
+ }\r
+\r
+ protected static Pattern nonSpace = Pattern.compile("\\S/");\r
\r
protected static Pattern trimRe = Pattern.compile(trimReStr);\r
\r
\r
protected static Pattern nthRe2 = Pattern.compile("\\D");\r
\r
- protected static RuleMatcher[] matchers = new RuleMatcher[]{new RuleMatcher(\r
- "^\\.([a-zA-Z_0-9-]+)", "n = byClassName(n, null, \"{0}\");"),\r
+ protected static RuleMatcher[] matchers = new RuleMatcher[]{\r
+ new RuleMatcher("^\\.([a-zA-Z_0-9-]+)",\r
+ "n = byClassName(n, null, \"{0}\");"),\r
new RuleMatcher("^\\:([a-zA-Z_0-9-]+)(?:\\(((?:[^ >]*|.*?))\\))?",\r
"n = byPseudo(n, \"{0}\", \"{1}\");"), new RuleMatcher(\r
- "^(?:([\\[\\{])(?:@)?([a-zA-Z_0-9-]+)\\s?(?:(=|.=)\\s?['\"]?(.*?)[\"']?)?[\\]\\}])",\r
- "n = byAttribute(n, \"{1}\", \"{3}\", \"{2}\", \"{0}\");"),\r
+ "^(?:([\\[\\{])(?:@)?([a-zA-Z_0-9-]+)\\s?(?:(=|.=)\\s?['\"]?(.*?)[\"']?)?[\\]\\}])",\r
+ "n = byAttribute(n, \"{1}\", \"{3}\", \"{2}\", \"{0}\");"),\r
new RuleMatcher("^#([a-zA-Z_0-9-]+)", "n = byId(n, null, \"{0}\");")};\r
\r
- protected String getImplSuffix() {\r
- return "JS"+super.getImplSuffix();\r
- }\r
+ private static final String trimReStr = "^\\s+|\\s+$";\r
\r
protected void generateMethodBody(SourceWriter sw, JMethod method,\r
- TreeLogger treeLogger, boolean hasContext) throws UnableToCompleteException {\r
+ TreeLogger treeLogger, boolean hasContext)\r
+ throws UnableToCompleteException {\r
\r
String selector = method.getAnnotation(Selector.class).value();\r
- if(!hasContext) sw.println("Node root = Document.get();");\r
- \r
- sw.println("return "+wrap(method, "new SelectorEngine().select(\""+selector+"\", root)")+";");\r
+ if (!hasContext) {\r
+ sw.println("Node root = Document.get();");\r
+ }\r
+\r
+ sw.println("return " + wrap(method,\r
+ "new SelectorEngine().select(\"" + selector + "\", root)") + ";");\r
// sw.println("JSArray n = JSArray.create();");\r
// if(!hasContext) { \r
// sw.println("Node root = Document.get();");\r
// sw.println("return "+wrap(method, "nodup(n)")+";");\r
}\r
\r
- \r
- static class RuleMatcher {\r
-\r
- public Pattern re;\r
-\r
- public String fnTemplate;\r
-\r
- RuleMatcher(String pat, String fnT) {\r
- this.re = Pattern.compile(pat);\r
- this.fnTemplate = fnT;\r
- }\r
+ protected String getImplSuffix() {\r
+ return "JS" + super.getImplSuffix();\r
}\r
}
\ No newline at end of file
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.rebind;\r
\r
import com.google.gwt.core.ext.TreeLogger;\r
+/*\r
+ * Copyright 2009 Google Inc.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
+ * use this file except in compliance with the License. You may obtain a copy of\r
+ * the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
+ * License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
package com.google.gwt.query.rebind;\r
\r
import com.google.gwt.core.ext.TreeLogger;\r
*/\r
public class SelectorGeneratorXPath extends SelectorGeneratorBase {\r
\r
- private static Pattern cssSelectorRegExp = Pattern.compile(\r
- "^(\\w+)?(#[a-zA-Z_0-9\u00C0-\uFFFF\\-\\_]+|(\\*))?((\\.[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[a-zA-Z_0-9\u00C0-\uFFFF\\s\\-\\_\\.]+)?\\]+)*)?(((:\\w+[a-zA-Z_0-9\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+|((\\w*\\.[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[a-zA-Z_0-9\u00C0-\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[a-zA-Z_0-9\\-]*))\\))?)*)?(>|\\+|~)?");\r
+ static class Sequence {\r
\r
- private static Pattern selectorSplitRegExp = Pattern\r
- .compile("(?:\\[[^\\[]*\\]|\\(.*\\)|[^\\s\\+>~\\[\\(])+|[\\+>~]");\r
+ public int start;\r
\r
- private String prefix = "";\r
+ public int max;\r
+\r
+ public int add;\r
+\r
+ public int modVal;\r
+ }\r
\r
static class SplitRule {\r
\r
public String tagRelation;\r
}\r
\r
- protected String getImplSuffix() {\r
- return "XPath" + super.getImplSuffix();\r
- }\r
+ private static Pattern cssSelectorRegExp = Pattern.compile(\r
+ "^(\\w+)?(#[a-zA-Z_0-9\u00C0-\uFFFF\\-\\_]+|(\\*))?((\\.[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[a-zA-Z_0-9\u00C0-\uFFFF\\s\\-\\_\\.]+)?\\]+)*)?(((:\\w+[a-zA-Z_0-9\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+|((\\w*\\.[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[a-zA-Z_0-9\u00C0-\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[a-zA-Z_0-9\\-]*))\\))?)*)?(>|\\+|~)?");\r
+\r
+ private static Pattern selectorSplitRegExp = Pattern\r
+ .compile("(?:\\[[^\\[]*\\]|\\(.*\\)|[^\\s\\+>~\\[\\(])+|[\\+>~]");\r
+\r
+ private String prefix = "";\r
\r
protected void generateMethodBody(SourceWriter sw, JMethod method,\r
TreeLogger treeLogger, boolean hasContext)\r
+ ";");\r
}\r
\r
- static class Sequence {\r
-\r
- public int start;\r
-\r
- public int max;\r
-\r
- public int add;\r
-\r
- public int modVal;\r
- }\r
-\r
- private String pseudoToXPath(String tag, String pseudoClass,\r
- String pseudoValue) {\r
- tag = pseudoClass.matches(".*\\-child$") ? "*" : tag;\r
- String xpath = "";\r
- String pseudo[] = pseudoClass.split("-");\r
- if ("first".equals(pseudo[0])) {\r
- xpath = "not(preceding-sibling::" + tag + ")";\r
- } else if ("last".equals(pseudo[0])) {\r
- xpath = "not(following-sibling::" + tag + ")";\r
- } else if ("only".equals(pseudo[0])) {\r
- xpath = "not(preceding-sibling::" + tag + " or following-sibling::" + tag\r
- + ")";\r
- } else if ("nth".equals(pseudo[0])) {\r
- if (!pseudoValue.matches("^n$")) {\r
- String position =\r
- (("last".equals(pseudo[1])) ? "(count(following-sibling::"\r
- : "(count(preceding-sibling::") + tag + ") + 1)";\r
- Sequence sequence = getSequence(pseudoValue);\r
- if (sequence != null) {\r
- if (sequence.start == sequence.max) {\r
- xpath = position + " = " + sequence.start;\r
- } else {\r
- xpath = position + " mod " + sequence.add + " = " + sequence.modVal\r
- + ((sequence.start > 1) ? " and " + position + " >= "\r
- + sequence.start : "") + ((sequence.max > 0) ? " and "\r
- + position + " <= " + sequence.max : "");\r
- }\r
- }\r
- }\r
- } else if ("empty".equals(pseudo[0])) {\r
- xpath = "count(child::*) = 0 and string-length(text()) = 0";\r
- } else if ("contains".equals(pseudo[0])) {\r
- xpath = "contains(., '" + pseudoValue + "')";\r
- } else if ("enabled".equals(pseudo[0])) {\r
- xpath = "not(@disabled)";\r
- } else if ("disabled".equals(pseudo[0])) {\r
- xpath = "@disabled";\r
- } else if ("checked".equals(pseudo[0])) {\r
- xpath = "@checked='checked'"; // Doesn't work in Opera 9.24\r
- } else if ("not".equals(pseudo[0])) {\r
- if (pseudoValue.matches("^(:a-zA-Z_0-9+[a-zA-Z_0-9\\-]*)$")) {\r
- xpath = "not(" + pseudoToXPath(tag, pseudoValue.substring(1), "") + ")";\r
- } else {\r
- pseudoValue = pseudoValue\r
- .replaceAll("^\\[#([a-zA-Z_0-9\u00C0-\uFFFF\\-\\_]+)\\]$",\r
- "[id=$1]");\r
- String notSelector = pseudoValue\r
- .replaceFirst("^(a-zA-Z_0-9+)", "self::$1");\r
- notSelector = notSelector\r
- .replaceAll("^\\.([a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)",\r
- "contains(concat(' ', @class, ' '), ' $1 ')");\r
- notSelector = attrToXPath(notSelector,\r
- "\\[(a-zA-Z_0-9+)(\\^|\\$|\\*|\\||~)?=?([a-zA-Z_0-9\u00C0-\uFFFF\\s\\-_\\.]+)?\\]");\r
- xpath = "not(" + notSelector + ")";\r
- }\r
- } else {\r
- xpath = "@" + pseudoClass + "='" + pseudoValue + "'";\r
- }\r
- return xpath;\r
+ protected String getImplSuffix() {\r
+ return "XPath" + super.getImplSuffix();\r
}\r
\r
private String attrToXPath(String notSelector, String pattern) {\r
return notSelector;\r
}\r
\r
+ private int getInt(String s, int i) {\r
+ try {\r
+ if (s.startsWith("+")) {\r
+ s = s.substring(1);\r
+ }\r
+ return Integer.parseInt(s);\r
+ } catch (Exception e) {\r
+ debug("error parsing Integer " + s);\r
+ return i;\r
+ }\r
+ }\r
+\r
private Sequence getSequence(String expression) {\r
int start = 0, add = 2, max = -1, modVal = -1;\r
Pattern expressionRegExp = Pattern.compile(\r
return s;\r
}\r
\r
- private int getInt(String s, int i) {\r
- try {\r
- if (s.startsWith("+")) {\r
- s = s.substring(1);\r
+ private String pseudoToXPath(String tag, String pseudoClass,\r
+ String pseudoValue) {\r
+ tag = pseudoClass.matches(".*\\-child$") ? "*" : tag;\r
+ String xpath = "";\r
+ String pseudo[] = pseudoClass.split("-");\r
+ if ("first".equals(pseudo[0])) {\r
+ xpath = "not(preceding-sibling::" + tag + ")";\r
+ } else if ("last".equals(pseudo[0])) {\r
+ xpath = "not(following-sibling::" + tag + ")";\r
+ } else if ("only".equals(pseudo[0])) {\r
+ xpath = "not(preceding-sibling::" + tag + " or following-sibling::" + tag\r
+ + ")";\r
+ } else if ("nth".equals(pseudo[0])) {\r
+ if (!pseudoValue.matches("^n$")) {\r
+ String position =\r
+ (("last".equals(pseudo[1])) ? "(count(following-sibling::"\r
+ : "(count(preceding-sibling::") + tag + ") + 1)";\r
+ Sequence sequence = getSequence(pseudoValue);\r
+ if (sequence != null) {\r
+ if (sequence.start == sequence.max) {\r
+ xpath = position + " = " + sequence.start;\r
+ } else {\r
+ xpath = position + " mod " + sequence.add + " = " + sequence.modVal\r
+ + ((sequence.start > 1) ? " and " + position + " >= "\r
+ + sequence.start : "") + ((sequence.max > 0) ? " and "\r
+ + position + " <= " + sequence.max : "");\r
+ }\r
+ }\r
}\r
- return Integer.parseInt(s);\r
- } catch (Exception e) {\r
- debug("error parsing Integer " + s);\r
- return i;\r
+ } else if ("empty".equals(pseudo[0])) {\r
+ xpath = "count(child::*) = 0 and string-length(text()) = 0";\r
+ } else if ("contains".equals(pseudo[0])) {\r
+ xpath = "contains(., '" + pseudoValue + "')";\r
+ } else if ("enabled".equals(pseudo[0])) {\r
+ xpath = "not(@disabled)";\r
+ } else if ("disabled".equals(pseudo[0])) {\r
+ xpath = "@disabled";\r
+ } else if ("checked".equals(pseudo[0])) {\r
+ xpath = "@checked='checked'"; // Doesn't work in Opera 9.24\r
+ } else if ("not".equals(pseudo[0])) {\r
+ if (pseudoValue.matches("^(:a-zA-Z_0-9+[a-zA-Z_0-9\\-]*)$")) {\r
+ xpath = "not(" + pseudoToXPath(tag, pseudoValue.substring(1), "") + ")";\r
+ } else {\r
+ pseudoValue = pseudoValue\r
+ .replaceAll("^\\[#([a-zA-Z_0-9\u00C0-\uFFFF\\-\\_]+)\\]$",\r
+ "[id=$1]");\r
+ String notSelector = pseudoValue\r
+ .replaceFirst("^(a-zA-Z_0-9+)", "self::$1");\r
+ notSelector = notSelector\r
+ .replaceAll("^\\.([a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)",\r
+ "contains(concat(' ', @class, ' '), ' $1 ')");\r
+ notSelector = attrToXPath(notSelector,\r
+ "\\[(a-zA-Z_0-9+)(\\^|\\$|\\*|\\||~)?=?([a-zA-Z_0-9\u00C0-\uFFFF\\s\\-_\\.]+)?\\]");\r
+ xpath = "not(" + notSelector + ")";\r
+ }\r
+ } else {\r
+ xpath = "@" + pseudoClass + "='" + pseudoValue + "'";\r
}\r
+ return xpath;\r
}\r
}
\ No newline at end of file
+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.google.gwt.query.client;
-import static com.google.gwt.query.client.GQuery.$;
-import com.google.gwt.query.client.GQuery;
-import com.google.gwt.query.client.Properties;
-import com.google.gwt.query.client.Function;
-
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.junit.client.GWTTestCase;
+import static com.google.gwt.query.client.GQuery.$;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HTML;
*/
public class GwtQueryCoreTest extends GWTTestCase {
- public String getModuleName() {
- return "com.google.gwt.query.Query";
- }
-
- static HTML testPanel = null;
- static Element e = null;
-
- public void gwtSetUp() {
- if (e == null) {
- testPanel = new HTML();
- RootPanel.get().add(testPanel);
- e = testPanel.getElement();
- e.setId("tst");
- } else {
- e.setInnerHTML("");
- }
- }
-
- public void testBrowserStartUp() {
- // just a test for seeing in eclipse that GWTTestCase internal browser is starting
- assertTrue(true);
- }
-
- public void testInnerMethods() {
- String txt = "<p>I would like to say: </p>";
-
- // Check that setHTML and getHTML works as GQuery html()
- testPanel.setHTML(txt);
- assertEquals(txt, testPanel.getHTML());
- assertEquals(txt, $(e).html());
- assertEquals(txt, $("#tst").html());
- $(e).html("");
- assertEquals("", $(e).html());
- $(e).html(txt);
- assertEquals(txt, $(e).html());
-
- // toString()
- assertEquals(txt, $("p", e).toString());
-
- // remove()
- $("p", e).remove();
- assertEquals("", $(e).html());
-
- // text()
- String expected = "I would like to say: I would like to say: ";
- $(e).html(txt + txt);
- assertEquals(expected, $("p", e).text());
-
- // empty()
- expected = "<p></p><p></p>";
- $("p", e).empty();
- assertEquals(expected, $(e).html());
- }
-
- public void testAttributeMethods() {
-
- $(e).html("<p class=\"a1\">Content</p>");
- GQuery gq = $("p", e);
-
- // attr()
- assertEquals("a1", gq.attr("class"));
- gq.attr("class", "b1 b2");
-
- // hasClass()
- assertTrue(gq.hasClass("b1"));
- assertTrue(gq.hasClass("b2"));
-
- // addClass()
- gq.addClass("c1", "c2");
- assertTrue(gq.hasClass("b1"));
- assertTrue(gq.hasClass("b2"));
- assertTrue(gq.hasClass("c1"));
- assertTrue(gq.hasClass("c2"));
-
- // removeClass()
- gq.removeClass("c2", "c1");
- assertTrue(gq.hasClass("b1"));
- assertTrue(gq.hasClass("b2"));
- assertFalse(gq.hasClass("c1"));
- assertFalse(gq.hasClass("c2"));
-
- // css()
- String content = "<p style='color:red;'>Test Paragraph.</p>";
- $(e).html(content);
- assertEquals("red", $("p", e).css("color"));
- $("p", e).css("font-weight", "bold");
- assertEquals("bold", $("p", e).css("font-weight"));
-
- // css() properties
- $(e).html("<p>Test Paragraph.</p>");
- $("p", e).css(Properties.create("color: 'red', 'font-weight': 'bold', background: 'blue'"));
- assertEquals("red", $("p", e).css("color"));
- assertEquals("bold", $("p", e).css("font-weight"));
- assertEquals("blue", $("p", e).css("background-color"));
-
- // css() camelize and uppercase
- $(e).html("<p>Test Paragraph.</p>");
- $("p", e).css(Properties.create("COLOR: 'red', 'FONT-WEIGHT': 'bold'"));
- assertEquals("red", $("p", e).css("color"));
- assertEquals("", $("p", e).css("background"));
-
- }
-
- public void testSliceMethods() {
- String content = "<p>This is just a test.</p><p>So is this</p>";
- $(e).html(content);
-
- String expected = "<p>So is this</p>";
- assertEquals(1, $("p", e).eq(1).size());
- assertEquals(expected, $("p", e).eq(1).toString());
+ static HTML testPanel = null;
- expected = "<p>This is just a test.</p>";
- assertEquals(1, $("p", e).lt(1).size());
- assertEquals(expected, $("p", e).lt(1).toString());
+ static Element e = null;
- expected = "<p>So is this</p>";
- assertEquals(1, $("p", e).gt(0).size());
- assertEquals(expected, $("p", e).gt(0).toString());
+ public String getModuleName() {
+ return "com.google.gwt.query.Query";
+ }
- assertEquals(2, $("p", e).slice(0, 2).size());
- assertEquals(2, $("p", e).slice(0, -1).size());
- assertEquals(0, $("p", e).slice(3, 2).size());
+ public void gwtSetUp() {
+ if (e == null) {
+ testPanel = new HTML();
+ RootPanel.get().add(testPanel);
+ e = testPanel.getElement();
+ e.setId("tst");
+ } else {
+ e.setInnerHTML("");
}
-
- public void testRelativeMethods() {
- String content = "<p><span>Hello</span>, how are you?</p>";
- String expected = "<span>Hello</span>";
-
- // find()
- $(e).html(content);
- assertEquals(expected, $("p", e).find("span").toString());
-
- // filter()
- content = "<p>First</p><p class=\"selected\">Hello</p><p>How are you?</p>";
- $(e).html(content);
- expected = "<p class=\"selected\">Hello</p>";
- assertEquals(expected, $("p", e).filter(".selected").toString());
-
- // filter()
- // Commented because GQuery doesn't support this syntax yet
- // expected = "<p class=\"selected\">Hello</p>";
- // assertEquals(expected, $("p", e).filter(".selected, :first").toString());
-
- // not()
- expected = "<p>First</p><p>How are you?</p>";
- assertEquals(2, $("p", e).not(".selected").size());
- assertEquals(expected, $("p", e).not(".selected").toString());
- assertEquals(2, $("p", e).not($(".selected")).size());
- assertEquals(expected, $("p", e).not($(".selected")).toString());
- assertEquals(2, $("p", e).not($(".selected").get(0)).size());
- assertEquals(expected, $("p", e).not($(".selected").get(0)).toString());
-
- // add()
- String added = "<p>Last</p>";
- expected = content + added;
- assertEquals(4, $("p", e).add(added).size());
- assertEquals(expected, $("p", e).add(added).toString());
-
- // parent()
- expected = content = "<div><p>Hello</p><p>Hello</p></div>";
- $(e).html(content);
- assertEquals(expected, $("p", e).parent().toString());
-
- // parent()
- content = "<div><p>Hello</p></div><div class=\"selected\"><p>Hello Again</p></div>";
- expected = "<div class=\"selected\"><p>Hello Again</p></div>";
- $(e).html(content);
- assertEquals(expected, $("p", e).parent(".selected").toString());
-
- // parents()
- content = "<div><p><span>Hello</span></p><span>Hello Again</span></div>";
- $(e).html(content);
- assertEquals(2, $("span", e).size());
- assertTrue(3 < $("span", e).parents().size());
- assertEquals(1, $("span", e).parents().filter("body").size());
- $("span", e).parents().filter("body").toString().contains(content);
-
- // is()
- content = "<form><input type=\"checkbox\"></form>";
- $(e).html(content);
- assertEquals(true, $("input[type=\"checkbox\"]", e).parent().is("form"));
-
- // is()
- content = "<form><p><input type=\"checkbox\"></p></form>";
- $(e).html(content);
- assertEquals(false, $("input[type='checkbox']", e).parent().is("form"));
-
- // next()
- content = "<p>Hello</p><p>Hello Again</p><div><span>And Again</span></div>";
- String next1 = "<p>Hello Again</p>";
- String next2 = "<div><span>And Again</span></div>";
- $(e).html(content);
- assertEquals(2, $("p", e).next().size());
- assertEquals(next1, $("p", e).next().get(0).getString());
- assertEquals(next2, $("p", e).next().get(1).getString());
-
- // next()
- content = "<p>Hello</p><p class=\"selected\">Hello Again</p><div><span>And Again</span></div>";
- expected = "<p class=\"selected\">Hello Again</p>";
- $(e).html(content);
- assertEquals(1, $("p", e).next(".selected").size());
- assertEquals(expected, $("p", e).next(".selected").get(0).getString());
-
- // prev()
- content = "<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>";
- expected = "<div><span>Hello Again</span></div>";
- $(e).html(content);
- assertEquals(1, $("p", e).prev().size());
- assertEquals(expected, $("p", e).prev().get(0).getString());
-
- // prev()
- content = "<div><span>Hello</span></div><p class=\"selected\">Hello Again</p><p>And Again</p>";
- expected = "<p class=\"selected\">Hello Again</p>";
- $(e).html(content);
- assertEquals(2, $("p", e).prev().size());
- assertEquals(1, $("p", e).prev(".selected").size());
- assertEquals(expected, $("p", e).prev(".selected").get(0).getString());
-
- // siblings()
- content = "<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>";
- next1 = "<p>Hello</p>";
- next2 = "<p>And Again</p>";
- $(e).html(content);
- assertEquals(2, $("div", e).siblings().size());
- assertEquals(next1, $("div", e).siblings().get(0).getString());
- assertEquals(next2, $("div", e).siblings().get(1).getString());
-
- // siblings()
- content = "<div><span>Hello</span></div><p class=\"selected\">Hello Again</p><p>And Again</p>";
- expected = "<p class=\"selected\">Hello Again</p>";
- $(e).html(content);
- assertEquals(1, $("p", e).siblings(".selected").size());
- assertEquals(expected, $("p", e).siblings(".selected").get(0).getString());
-
- // children()
- content = "<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>";
- expected = "<span>Hello Again</span>";
- $(e).html(content);
- assertEquals(expected, $("div", e).children().toString());
-
- // children()
- content = "<div><span>Hello</span><p class=\"selected\">Hello Again</p><p>And Again</p></div>";
- expected = "<p class=\"selected\">Hello Again</p>";
- $(e).html(content);
- assertEquals(expected, $("div", e).children(".selected").toString());
-
- // contains()
- content = "<p>This is just a test.</p><p>So is this</p>";
- expected = "<p>This is just a test.</p>";
- $(e).html(content);
- assertEquals(expected, $("p", e).contains("test").toString());
- }
-
- public void testModifyMethods() {
- String p_txt = "<p>I would like to say: </p>";
- String b_txt = "<b>Hello</b>";
-
- // append()
- String expected = "<p>I would like to say: <b>Hello</b></p>";
- $(e).html(p_txt);
- $("p", e).append(b_txt);
- assertEquals(expected, $(e).html());
-
- // appendTo()
- expected = "<p>I would like to say: <b>Hello</b></p>";
- $(e).html(b_txt + p_txt);
- $("b", e).appendTo($("p", e));
- assertEquals(expected, $(e).html());
-
- // prepend()
- expected = "<p><b>Hello</b>I would like to say: </p>";
- $(e).html(p_txt);
- $("p", e).prepend(b_txt);
- assertEquals(expected, $(e).html());
-
- // prependTo()
- expected = "<p><b>Hello</b>I would like to say: </p>";
- $(e).html(b_txt + p_txt);
- $("b", e).prependTo($("p", e));
- assertEquals(expected, $(e).html());
-
- // prependTo()
- expected = "<b>Hello</b><p><b>Hello</b>I would like to say: </p>";
- $(e).html(b_txt + p_txt);
- $("b", e).clone().prependTo($("p", e));
- assertEquals(expected, $(e).html());
-
- // before()
- expected = "<b>Hello</b><p>I would like to say: </p>";
- $(e).html(p_txt);
- $("p", e).before(b_txt);
- assertEquals(expected, $(e).html());
-
- // before()
- expected = "<b>Hello</b><p>I would like to say: </p>";
- $(e).html(p_txt + b_txt);
- $("p", e).before($("b", e));
- assertEquals(expected, $(e).html());
-
- // before()
- expected = "<b>Hello</b><p>I would like to say: </p><b>Hello</b>";
- $(e).html(p_txt + b_txt);
- $("p", e).before($("b", e).clone());
- assertEquals(expected, $(e).html());
-
- // insertBefore()
- expected = "<b>Hello</b><p>I would like to say: </p>";
- $(e).html(p_txt + b_txt);
- $("b", e).insertBefore($("p", e));
- assertEquals(expected, $(e).html());
-
- // insertBefore()
- expected = "<b>Hello</b><p>I would like to say: </p><b>Hello</b>";
- $(e).html(p_txt + b_txt);
- $("b", e).clone().insertBefore($("p", e));
- assertEquals(expected, $(e).html());
-
- // after()
- expected = "<p>I would like to say: </p><b>Hello</b>";
- $(e).html(p_txt);
- $("p", e).after(b_txt);
- assertEquals(expected, testPanel.getHTML());
-
- // after()
- expected = "<p>I would like to say: </p><b>Hello</b>";
- $(e).html(b_txt + p_txt);
- $("p", e).after($("b", e));
- assertEquals(expected, $(e).html());
-
- // after()
- expected = "<b>Hello</b><p>I would like to say: </p><b>Hello</b>";
- $(e).html(b_txt + p_txt);
- $("p", e).after($("b", e).clone());
- assertEquals(expected, $(e).html());
- }
-
- public void testWrapMethod() {
- String content = "<p>Test Paragraph.</p><div id=\"content\">Content</div>";
-
- String expected = "<div id=\"content\">Content<p>Test Paragraph.</p></div>";
- $(e).html(content);
-
- $("p", e).wrap($("div", e).get(0));
- assertEquals(expected, $(e).html());
-
- expected = "<b><p>Test Paragraph.</p></b><b><div id=\"content\">Content</div></b>";
- $(e).html(content);
- $("*", e).wrap("<b></b>");
- assertEquals(expected, $(e).html());
- }
-
- public void testInputValueMethods() {
- // imput text
- $(e).html("<input type='text'/>");
- GQuery gq = $("input", e);
- assertEquals("", gq.val());
- gq.val("some value");
- assertEquals("some value", gq.val());
-
- // select
- $(e).html("<select name='n'><option value='v1'>1</option><option value='v2' selected='selected'>2</option></select>");
- gq = $("select", e);
- assertEquals("v2", gq.val());
- gq.val("v1");
- assertEquals("v1", gq.val());
-
- // select multiple
- $(e).html("<select name='n' multiple='multiple'><option value='v1'>1</option><option value='v2' selected='selected'>2</option><option value='v3'>3</option></select>");
- gq = $("select", e);
- gq.val("v1","v3","invalid");
- assertEquals(2, gq.vals().length);
- assertEquals("v1", gq.vals()[0]);
- assertEquals("v3", gq.vals()[1]);
- gq.val("v1");
- assertEquals(1, gq.vals().length);
- assertEquals("v1", gq.val());
-
- // input radio
- $(e).html("<input type='radio' name='n' value='v1'>1</input><input type='radio' name='n' value='v2' checked='checked'>2</input>");
- gq = $("input", e);
- assertEquals("v2", gq.val());
- gq.val("v1");
- assertEquals("v1", gq.val());
- gq.val("v2");
- assertEquals("v2", gq.val());
-
- // input checkbox
- $(e).html("<input type='checkbox' name='n1' value='v1'>1</input><input type='checkbox' name='n2' value='v2' checked='checked'>2</input>");
- gq = $("input", e);
- assertEquals("", gq.val());
- gq.val("v1");
- assertEquals("v1", gq.val());
- }
-
- public void testEventsPlugin() {
- $(e).html("<p>Content</p>");
-
- // click
- $("p", e).click(new Function() {
- public void f(Element elem) {
- $(elem).css("color", "red");
- }
- });
- $("p", e).trigger(Event.ONCLICK);
- assertEquals("red", $("p", e).css("color"));
-
- // unbind
- $("p", e).css("color", "");
- $("p", e).unbind(Event.ONCLICK);
- $("p", e).trigger(Event.ONCLICK);
- assertEquals("rgb(0, 0, 0)", $("p", e).css("color"));
-
- // one
- $("p", e).one(Event.ONCLICK, null, new Function() {
- public void f(Element elem) {
- $(elem).css("color", "red");
- }
- });
- $("p", e).trigger(Event.ONCLICK);
- assertEquals("red", $("p", e).css("color"));
- $("p", e).css("color", "");
- $("p", e).trigger(Event.ONCLICK);
- assertEquals("rgb(0, 0, 0)", $("p", e).css("color"));
-
- // hover (mouseover, mouseout)
- $("p", e).hover(new Function() {
- public void f(Element elem) {
- $(elem).css("background-color", "yellow");
- }
- }, new Function() {
- public void f(Element elem) {
- $(elem).css("background-color", "");
- }
- });
- $("p", e).trigger(Event.ONMOUSEOVER);
- assertEquals("yellow", $("p", e).css("background-color"));
- $("p", e).trigger(Event.ONMOUSEOUT);
- assertEquals("rgba(0, 0, 0, 0)", $("p", e).css("background-color"));
-
- // focus
- $("p", e).focus(new Function() {
- public void f(Element elem) {
- $(elem).css("border", "1px dotted black");
- }
- });
- $("p", e).trigger(Event.ONFOCUS);
- assertEquals("1px dotted black", $("p", e).css("border"));
-
- // blur
- $("p", e).blur(new Function() {
- public void f(Element elem) {
- $(elem).css("border", "");
- }
- });
- $("p", e).trigger(Event.ONBLUR);
- assertEquals("", $("p", e).css("border"));
-
- // keypressed
- $(e).html("<input type='text'/>");
- $("input", e).keypressed(new Function() {
- public boolean f(Event evnt) {
- Element elem = evnt.getCurrentTarget();
- InputElement input = InputElement.as(elem);
- input.setValue(input.getValue() + Character.toString((char) evnt.getKeyCode()));
- return false;
- }
- });
- $("input", e).trigger(Event.ONFOCUS);
- $("input", e).trigger(Event.ONKEYPRESS, 'a');
- assertEquals("a", InputElement.as($("input", e).get(0)).getValue());
-
- }
-
- public void testEffectsPlugin() {
- $(e).html("<p id='id1'>Content 1</p><p id='id2'>Content 2</p><p id='id3'>Content 3</p>");
-
- final GQuery sect_a = $("#id1");
- final GQuery sect_b = $("#id2");
- final GQuery sect_c = $("#id3");
-
- // hide()
- sect_a.hide();
- assertEquals("none", sect_a.css("display"));
-
- // show()
- sect_b.show();
- assertEquals("", sect_b.css("display"));
-
- // toggle()
- assertEquals("", sect_c.css("display"));
- sect_c.toggle();
- assertEquals("none", sect_c.css("display"));
- sect_c.toggle();
- assertEquals("", sect_c.css("display"));
-
- // fadeIn() & fadeOut() are tested with delayed assertions
- sect_a.fadeIn(2000);
- sect_b.fadeOut(2000);
-
- // Configure the max duration for this test
- // If the test exceeds the timeout without calling finishTest() it will fail
- delayTestFinish(2500);
-
- // Delayed assertions at different intervals
- Timer timer_shortTime = new Timer() {
- public void run() {
- double o = Double.valueOf(sect_a.css("opacity"));
- assertTrue(o > 0 && o < 0.5);
- o = Double.valueOf(sect_b.css("opacity"));
- assertTrue(o > 0.5 && o < 1);
- }
- };
- Timer timer_midTime = new Timer() {
- public void run() {
- assertEquals("", sect_a.css("display"));
- assertEquals("", sect_b.css("display"));
- double o = Double.valueOf(sect_a.css("opacity"));
- assertTrue(o > 0.5 && o < 1);
- o = Double.valueOf(sect_b.css("opacity"));
- assertTrue(o > 0 && o < 0.5);
- }
- };
- Timer timer_longTime = new Timer() {
- public void run() {
- assertEquals("", sect_a.css("display"));
- assertEquals("none", sect_b.css("display"));
- // Last delayed assertion has to stop the test to avoid a timeout failure
- finishTest();
- }
- };
- // schedule the delayed assertions
- timer_shortTime.schedule(200);
- timer_midTime.schedule(1200);
- timer_longTime.schedule(2200);
-
- }
-
+ }
+
+ public void testAttributeMethods() {
+
+ $(e).html("<p class=\"a1\">Content</p>");
+ GQuery gq = $("p", e);
+
+ // attr()
+ assertEquals("a1", gq.attr("class"));
+ gq.attr("class", "b1 b2");
+
+ // hasClass()
+ assertTrue(gq.hasClass("b1"));
+ assertTrue(gq.hasClass("b2"));
+
+ // addClass()
+ gq.addClass("c1", "c2");
+ assertTrue(gq.hasClass("b1"));
+ assertTrue(gq.hasClass("b2"));
+ assertTrue(gq.hasClass("c1"));
+ assertTrue(gq.hasClass("c2"));
+
+ // removeClass()
+ gq.removeClass("c2", "c1");
+ assertTrue(gq.hasClass("b1"));
+ assertTrue(gq.hasClass("b2"));
+ assertFalse(gq.hasClass("c1"));
+ assertFalse(gq.hasClass("c2"));
+
+ // css()
+ String content = "<p style='color:red;'>Test Paragraph.</p>";
+ $(e).html(content);
+ assertEquals("red", $("p", e).css("color"));
+ $("p", e).css("font-weight", "bold");
+ assertEquals("bold", $("p", e).css("font-weight"));
+
+ // css() properties
+ $(e).html("<p>Test Paragraph.</p>");
+ $("p", e).css(Properties.create(
+ "color: 'red', 'font-weight': 'bold', background: 'blue'"));
+ assertEquals("red", $("p", e).css("color"));
+ assertEquals("bold", $("p", e).css("font-weight"));
+ assertEquals("blue", $("p", e).css("background-color"));
+
+ // css() camelize and uppercase
+ $(e).html("<p>Test Paragraph.</p>");
+ $("p", e).css(Properties.create("COLOR: 'red', 'FONT-WEIGHT': 'bold'"));
+ assertEquals("red", $("p", e).css("color"));
+ assertEquals("", $("p", e).css("background"));
+ }
+
+ public void testBrowserStartUp() {
+ // just a test for seeing in eclipse that GWTTestCase internal browser is starting
+ assertTrue(true);
+ }
+
+ public void testEffectsPlugin() {
+ $(e).html(
+ "<p id='id1'>Content 1</p><p id='id2'>Content 2</p><p id='id3'>Content 3</p>");
+
+ final GQuery sectA = $("#id1");
+ final GQuery sectB = $("#id2");
+ final GQuery sectC = $("#id3");
+
+ // hide()
+ sectA.hide();
+ assertEquals("none", sectA.css("display"));
+
+ // show()
+ sectB.show();
+ assertEquals("", sectB.css("display"));
+
+ // toggle()
+ assertEquals("", sectC.css("display"));
+ sectC.toggle();
+ assertEquals("none", sectC.css("display"));
+ sectC.toggle();
+ assertEquals("", sectC.css("display"));
+
+ // fadeIn() & fadeOut() are tested with delayed assertions
+ sectA.fadeIn(2000);
+ sectB.fadeOut(2000);
+
+ // Configure the max duration for this test
+ // If the test exceeds the timeout without calling finishTest() it will fail
+ delayTestFinish(2500);
+
+ // Delayed assertions at different intervals
+ Timer timerShortTime = new Timer() {
+ public void run() {
+ double o = Double.valueOf(sectA.css("opacity"));
+ assertTrue(o > 0 && o < 0.5);
+ o = Double.valueOf(sectB.css("opacity"));
+ assertTrue(o > 0.5 && o < 1);
+ }
+ };
+ Timer timerMidTime = new Timer() {
+ public void run() {
+ assertEquals("", sectA.css("display"));
+ assertEquals("", sectB.css("display"));
+ double o = Double.valueOf(sectA.css("opacity"));
+ assertTrue(o > 0.5 && o < 1);
+ o = Double.valueOf(sectB.css("opacity"));
+ assertTrue(o > 0 && o < 0.5);
+ }
+ };
+ Timer timerLongTime = new Timer() {
+ public void run() {
+ assertEquals("", sectA.css("display"));
+ assertEquals("none", sectB.css("display"));
+ // Last delayed assertion has to stop the test to avoid a timeout failure
+ finishTest();
+ }
+ };
+ // schedule the delayed assertions
+ timerShortTime.schedule(200);
+ timerMidTime.schedule(1200);
+ timerLongTime.schedule(2200);
+ }
+
+ public void testEventsPlugin() {
+ $(e).html("<p>Content</p>");
+
+ // click
+ $("p", e).click(new Function() {
+ public void f(Element elem) {
+ $(elem).css("color", "red");
+ }
+ });
+ $("p", e).trigger(Event.ONCLICK);
+ assertEquals("red", $("p", e).css("color"));
+
+ // unbind
+ $("p", e).css("color", "");
+ $("p", e).unbind(Event.ONCLICK);
+ $("p", e).trigger(Event.ONCLICK);
+ assertEquals("rgb(0, 0, 0)", $("p", e).css("color"));
+
+ // one
+ $("p", e).one(Event.ONCLICK, null, new Function() {
+ public void f(Element elem) {
+ $(elem).css("color", "red");
+ }
+ });
+ $("p", e).trigger(Event.ONCLICK);
+ assertEquals("red", $("p", e).css("color"));
+ $("p", e).css("color", "");
+ $("p", e).trigger(Event.ONCLICK);
+ assertEquals("rgb(0, 0, 0)", $("p", e).css("color"));
+
+ // hover (mouseover, mouseout)
+ $("p", e).hover(new Function() {
+ public void f(Element elem) {
+ $(elem).css("background-color", "yellow");
+ }
+ }, new Function() {
+ public void f(Element elem) {
+ $(elem).css("background-color", "");
+ }
+ });
+ $("p", e).trigger(Event.ONMOUSEOVER);
+ assertEquals("yellow", $("p", e).css("background-color"));
+ $("p", e).trigger(Event.ONMOUSEOUT);
+ assertEquals("rgba(0, 0, 0, 0)", $("p", e).css("background-color"));
+
+ // focus
+ $("p", e).focus(new Function() {
+ public void f(Element elem) {
+ $(elem).css("border", "1px dotted black");
+ }
+ });
+ $("p", e).trigger(Event.ONFOCUS);
+ assertEquals("1px dotted black", $("p", e).css("border"));
+
+ // blur
+ $("p", e).blur(new Function() {
+ public void f(Element elem) {
+ $(elem).css("border", "");
+ }
+ });
+ $("p", e).trigger(Event.ONBLUR);
+ assertEquals("", $("p", e).css("border"));
+
+ // keypressed
+ $(e).html("<input type='text'/>");
+ $("input", e).keypressed(new Function() {
+ public boolean f(Event evnt) {
+ Element elem = evnt.getCurrentTarget();
+ InputElement input = InputElement.as(elem);
+ input.setValue(
+ input.getValue() + Character.toString((char) evnt.getKeyCode()));
+ return false;
+ }
+ });
+ $("input", e).trigger(Event.ONFOCUS);
+ $("input", e).trigger(Event.ONKEYPRESS, 'a');
+ assertEquals("a", InputElement.as($("input", e).get(0)).getValue());
+ }
+
+ public void testInnerMethods() {
+ String txt = "<p>I would like to say: </p>";
+
+ // Check that setHTML and getHTML works as GQuery html()
+ testPanel.setHTML(txt);
+ assertEquals(txt, testPanel.getHTML());
+ assertEquals(txt, $(e).html());
+ assertEquals(txt, $("#tst").html());
+ $(e).html("");
+ assertEquals("", $(e).html());
+ $(e).html(txt);
+ assertEquals(txt, $(e).html());
+
+ // toString()
+ assertEquals(txt, $("p", e).toString());
+
+ // remove()
+ $("p", e).remove();
+ assertEquals("", $(e).html());
+
+ // text()
+ String expected = "I would like to say: I would like to say: ";
+ $(e).html(txt + txt);
+ assertEquals(expected, $("p", e).text());
+
+ // empty()
+ expected = "<p></p><p></p>";
+ $("p", e).empty();
+ assertEquals(expected, $(e).html());
+ }
+
+ public void testInputValueMethods() {
+ // imput text
+ $(e).html("<input type='text'/>");
+ GQuery gq = $("input", e);
+ assertEquals("", gq.val());
+ gq.val("some value");
+ assertEquals("some value", gq.val());
+
+ // select
+ $(e).html(
+ "<select name='n'><option value='v1'>1</option><option value='v2' selected='selected'>2</option></select>");
+ gq = $("select", e);
+ assertEquals("v2", gq.val());
+ gq.val("v1");
+ assertEquals("v1", gq.val());
+
+ // select multiple
+ $(e).html(
+ "<select name='n' multiple='multiple'><option value='v1'>1</option><option value='v2' selected='selected'>2</option><option value='v3'>3</option></select>");
+ gq = $("select", e);
+ gq.val("v1", "v3", "invalid");
+ assertEquals(2, gq.vals().length);
+ assertEquals("v1", gq.vals()[0]);
+ assertEquals("v3", gq.vals()[1]);
+ gq.val("v1");
+ assertEquals(1, gq.vals().length);
+ assertEquals("v1", gq.val());
+
+ // input radio
+ $(e).html(
+ "<input type='radio' name='n' value='v1'>1</input><input type='radio' name='n' value='v2' checked='checked'>2</input>");
+ gq = $("input", e);
+ assertEquals("v2", gq.val());
+ gq.val("v1");
+ assertEquals("v1", gq.val());
+ gq.val("v2");
+ assertEquals("v2", gq.val());
+
+ // input checkbox
+ $(e).html(
+ "<input type='checkbox' name='n1' value='v1'>1</input><input type='checkbox' name='n2' value='v2' checked='checked'>2</input>");
+ gq = $("input", e);
+ assertEquals("", gq.val());
+ gq.val("v1");
+ assertEquals("v1", gq.val());
+ }
+
+ public void testModifyMethods() {
+ String pTxt = "<p>I would like to say: </p>";
+ String bTxt = "<b>Hello</b>";
+
+ // append()
+ String expected = "<p>I would like to say: <b>Hello</b></p>";
+ $(e).html(pTxt);
+ $("p", e).append(bTxt);
+ assertEquals(expected, $(e).html());
+
+ // appendTo()
+ expected = "<p>I would like to say: <b>Hello</b></p>";
+ $(e).html(bTxt + pTxt);
+ $("b", e).appendTo($("p", e));
+ assertEquals(expected, $(e).html());
+
+ // prepend()
+ expected = "<p><b>Hello</b>I would like to say: </p>";
+ $(e).html(pTxt);
+ $("p", e).prepend(bTxt);
+ assertEquals(expected, $(e).html());
+
+ // prependTo()
+ expected = "<p><b>Hello</b>I would like to say: </p>";
+ $(e).html(bTxt + pTxt);
+ $("b", e).prependTo($("p", e));
+ assertEquals(expected, $(e).html());
+
+ // prependTo()
+ expected = "<b>Hello</b><p><b>Hello</b>I would like to say: </p>";
+ $(e).html(bTxt + pTxt);
+ $("b", e).clone().prependTo($("p", e));
+ assertEquals(expected, $(e).html());
+
+ // before()
+ expected = "<b>Hello</b><p>I would like to say: </p>";
+ $(e).html(pTxt);
+ $("p", e).before(bTxt);
+ assertEquals(expected, $(e).html());
+
+ // before()
+ expected = "<b>Hello</b><p>I would like to say: </p>";
+ $(e).html(pTxt + bTxt);
+ $("p", e).before($("b", e));
+ assertEquals(expected, $(e).html());
+
+ // before()
+ expected = "<b>Hello</b><p>I would like to say: </p><b>Hello</b>";
+ $(e).html(pTxt + bTxt);
+ $("p", e).before($("b", e).clone());
+ assertEquals(expected, $(e).html());
+
+ // insertBefore()
+ expected = "<b>Hello</b><p>I would like to say: </p>";
+ $(e).html(pTxt + bTxt);
+ $("b", e).insertBefore($("p", e));
+ assertEquals(expected, $(e).html());
+
+ // insertBefore()
+ expected = "<b>Hello</b><p>I would like to say: </p><b>Hello</b>";
+ $(e).html(pTxt + bTxt);
+ $("b", e).clone().insertBefore($("p", e));
+ assertEquals(expected, $(e).html());
+
+ // after()
+ expected = "<p>I would like to say: </p><b>Hello</b>";
+ $(e).html(pTxt);
+ $("p", e).after(bTxt);
+ assertEquals(expected, testPanel.getHTML());
+
+ // after()
+ expected = "<p>I would like to say: </p><b>Hello</b>";
+ $(e).html(bTxt + pTxt);
+ $("p", e).after($("b", e));
+ assertEquals(expected, $(e).html());
+
+ // after()
+ expected = "<b>Hello</b><p>I would like to say: </p><b>Hello</b>";
+ $(e).html(bTxt + pTxt);
+ $("p", e).after($("b", e).clone());
+ assertEquals(expected, $(e).html());
+ }
+
+ public void testRelativeMethods() {
+ String content = "<p><span>Hello</span>, how are you?</p>";
+ String expected = "<span>Hello</span>";
+
+ // find()
+ $(e).html(content);
+ assertEquals(expected, $("p", e).find("span").toString());
+
+ // filter()
+ content = "<p>First</p><p class=\"selected\">Hello</p><p>How are you?</p>";
+ $(e).html(content);
+ expected = "<p class=\"selected\">Hello</p>";
+ assertEquals(expected, $("p", e).filter(".selected").toString());
+
+ // filter()
+ // Commented because GQuery doesn't support this syntax yet
+ // expected = "<p class=\"selected\">Hello</p>";
+ // assertEquals(expected, $("p", e).filter(".selected, :first").toString());
+
+ // not()
+ expected = "<p>First</p><p>How are you?</p>";
+ assertEquals(2, $("p", e).not(".selected").size());
+ assertEquals(expected, $("p", e).not(".selected").toString());
+ assertEquals(2, $("p", e).not($(".selected")).size());
+ assertEquals(expected, $("p", e).not($(".selected")).toString());
+ assertEquals(2, $("p", e).not($(".selected").get(0)).size());
+ assertEquals(expected, $("p", e).not($(".selected").get(0)).toString());
+
+ // add()
+ String added = "<p>Last</p>";
+ expected = content + added;
+ assertEquals(4, $("p", e).add(added).size());
+ assertEquals(expected, $("p", e).add(added).toString());
+
+ // parent()
+ expected = content = "<div><p>Hello</p><p>Hello</p></div>";
+ $(e).html(content);
+ assertEquals(expected, $("p", e).parent().toString());
+
+ // parent()
+ content
+ = "<div><p>Hello</p></div><div class=\"selected\"><p>Hello Again</p></div>";
+ expected = "<div class=\"selected\"><p>Hello Again</p></div>";
+ $(e).html(content);
+ assertEquals(expected, $("p", e).parent(".selected").toString());
+
+ // parents()
+ content = "<div><p><span>Hello</span></p><span>Hello Again</span></div>";
+ $(e).html(content);
+ assertEquals(2, $("span", e).size());
+ assertTrue(3 < $("span", e).parents().size());
+ assertEquals(1, $("span", e).parents().filter("body").size());
+ $("span", e).parents().filter("body").toString().contains(content);
+
+ // is()
+ content = "<form><input type=\"checkbox\"></form>";
+ $(e).html(content);
+ assertEquals(true, $("input[type=\"checkbox\"]", e).parent().is("form"));
+
+ // is()
+ content = "<form><p><input type=\"checkbox\"></p></form>";
+ $(e).html(content);
+ assertEquals(false, $("input[type='checkbox']", e).parent().is("form"));
+
+ // next()
+ content = "<p>Hello</p><p>Hello Again</p><div><span>And Again</span></div>";
+ String next1 = "<p>Hello Again</p>";
+ String next2 = "<div><span>And Again</span></div>";
+ $(e).html(content);
+ assertEquals(2, $("p", e).next().size());
+ assertEquals(next1, $("p", e).next().get(0).getString());
+ assertEquals(next2, $("p", e).next().get(1).getString());
+
+ // next()
+ content
+ = "<p>Hello</p><p class=\"selected\">Hello Again</p><div><span>And Again</span></div>";
+ expected = "<p class=\"selected\">Hello Again</p>";
+ $(e).html(content);
+ assertEquals(1, $("p", e).next(".selected").size());
+ assertEquals(expected, $("p", e).next(".selected").get(0).getString());
+
+ // prev()
+ content = "<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>";
+ expected = "<div><span>Hello Again</span></div>";
+ $(e).html(content);
+ assertEquals(1, $("p", e).prev().size());
+ assertEquals(expected, $("p", e).prev().get(0).getString());
+
+ // prev()
+ content
+ = "<div><span>Hello</span></div><p class=\"selected\">Hello Again</p><p>And Again</p>";
+ expected = "<p class=\"selected\">Hello Again</p>";
+ $(e).html(content);
+ assertEquals(2, $("p", e).prev().size());
+ assertEquals(1, $("p", e).prev(".selected").size());
+ assertEquals(expected, $("p", e).prev(".selected").get(0).getString());
+
+ // siblings()
+ content = "<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>";
+ next1 = "<p>Hello</p>";
+ next2 = "<p>And Again</p>";
+ $(e).html(content);
+ assertEquals(2, $("div", e).siblings().size());
+ assertEquals(next1, $("div", e).siblings().get(0).getString());
+ assertEquals(next2, $("div", e).siblings().get(1).getString());
+
+ // siblings()
+ content
+ = "<div><span>Hello</span></div><p class=\"selected\">Hello Again</p><p>And Again</p>";
+ expected = "<p class=\"selected\">Hello Again</p>";
+ $(e).html(content);
+ assertEquals(1, $("p", e).siblings(".selected").size());
+ assertEquals(expected, $("p", e).siblings(".selected").get(0).getString());
+
+ // children()
+ content = "<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>";
+ expected = "<span>Hello Again</span>";
+ $(e).html(content);
+ assertEquals(expected, $("div", e).children().toString());
+
+ // children()
+ content
+ = "<div><span>Hello</span><p class=\"selected\">Hello Again</p><p>And Again</p></div>";
+ expected = "<p class=\"selected\">Hello Again</p>";
+ $(e).html(content);
+ assertEquals(expected, $("div", e).children(".selected").toString());
+
+ // contains()
+ content = "<p>This is just a test.</p><p>So is this</p>";
+ expected = "<p>This is just a test.</p>";
+ $(e).html(content);
+ assertEquals(expected, $("p", e).contains("test").toString());
+ }
+
+ public void testSliceMethods() {
+ String content = "<p>This is just a test.</p><p>So is this</p>";
+ $(e).html(content);
+
+ String expected = "<p>So is this</p>";
+ assertEquals(1, $("p", e).eq(1).size());
+ assertEquals(expected, $("p", e).eq(1).toString());
+
+ expected = "<p>This is just a test.</p>";
+ assertEquals(1, $("p", e).lt(1).size());
+ assertEquals(expected, $("p", e).lt(1).toString());
+
+ expected = "<p>So is this</p>";
+ assertEquals(1, $("p", e).gt(0).size());
+ assertEquals(expected, $("p", e).gt(0).toString());
+
+ assertEquals(2, $("p", e).slice(0, 2).size());
+ assertEquals(2, $("p", e).slice(0, -1).size());
+ assertEquals(0, $("p", e).slice(3, 2).size());
+ }
+
+ public void testWrapMethod() {
+ String content = "<p>Test Paragraph.</p><div id=\"content\">Content</div>";
+
+ String expected = "<div id=\"content\">Content<p>Test Paragraph.</p></div>";
+ $(e).html(content);
+
+ $("p", e).wrap($("div", e).get(0));
+ assertEquals(expected, $(e).html());
+
+ expected
+ = "<b><p>Test Paragraph.</p></b><b><div id=\"content\">Content</div></b>";
+ $(e).html(content);
+ $("*", e).wrap("<b></b>");
+ assertEquals(expected, $(e).html());
+ }
}
import com.google.gwt.query.client.Selectors;
/**
-*/
+ * Sample selectors from SlickSpeed benchmark.
+ */
public interface MySelectors extends Selectors {
- @Selector("#title,h1#title")
- NodeList<Element> titleAndh1Title();
-
+// @Selector("h1[id]:contains(Selectors)")
+// NodeList<Element> h1IdContainsSelectors();
+
+ //
+ @Selector("a[href][lang][class]")
+ NodeList<Element> aHrefLangClass();
+
+ @Selector("*:checked")
+ NodeList<Element> allChecked();
+
@Selector("body")
NodeList<Element> body();
@Selector("body div")
NodeList<Element> bodyDiv();
- @Selector("div p")
- NodeList<Element> divP();
+ @Selector("div .example")
+ NodeList<Element> divExample();
@Selector("div > div")
NodeList<Element> divGtP();
- @Selector("div + p")
- NodeList<Element> divPlusP();
+// @Selector("*:first")
+// NodeList<Element> allFirst();
- @Selector("div ~ p")
- NodeList<Element> divTildeP();
+ //
+ @Selector("div:not(.example)")
+ NodeList<Element> divNotExample();
- @Selector("div[class^=exa][class$=mple]")
- NodeList<Element> divPrefixExaSuffixMple();
+ @Selector("div p")
+ NodeList<Element> divP();
@Selector("div p a")
NodeList<Element> divPA();
-// @Selector("div, p a")
-// NodeList<Element> divCommaPA();
-
- @Selector(".note")
- NodeList<Element> note();
-
- @Selector("div .example")
- NodeList<Element> divExample();
-
- @Selector("ul .tocline2")
- NodeList<Element> ulTocline2();
-
- @Selector("#title")
- NodeList<Element> title();
+ @Selector("div + p")
+ NodeList<Element> divPlusP();
- @Selector("h1#title")
- NodeList<Element> h1Title();
+ @Selector("div[class^=exa][class$=mple]")
+ NodeList<Element> divPrefixExaSuffixMple();
@Selector("div #title")
NodeList<Element> divSpaceTitle();
- @Selector("ui.toc li.tocline2")
- NodeList<Element> ulTocLiTocLine2();
-
- @Selector("h1#title + div > p")
- NodeList<Element> h1TitlePlusDivGtP();
+ @Selector("div ~ p")
+ NodeList<Element> divTildeP();
-// @Selector("h1[id]:contains(Selectors)")
-// NodeList<Element> h1IdContainsSelectors();
-//
- @Selector("a[href][lang][class]")
- NodeList<Element> aHrefLangClass();
-
@Selector("div[class]")
NodeList<Element> divWithClass();
-
- @Selector("div[class=example]")
- NodeList<Element> divWithClassExample();
-
- @Selector("div[class^=exa]")
- NodeList<Element> divWithClassPrefixExa();
-
- @Selector("div[class$=mple]")
- NodeList<Element> divWithClassSuffixMple();
-
+
@Selector("div[class~=dialog]")
NodeList<Element> divWithClassContainsDialog();
-
+
@Selector("div[class*=e]")
NodeList<Element> divWithClassContainsE();
-
+
+ @Selector("div[class=example]")
+ NodeList<Element> divWithClassExample();
+
// @Selector("div[class!=madeup]")
// NodeList<Element> divWithClassNotContainsMadeup();
//
-
+
@Selector("div[class~=dialog]")
NodeList<Element> divWithClassListContainsDialog();
-
- @Selector("*:checked")
- NodeList<Element> allChecked();
-
-// @Selector("*:first")
-// NodeList<Element> allFirst();
-//
- @Selector("div:not(.example)")
- NodeList<Element> divNotExample();
-
+
+ @Selector("div[class^=exa]")
+ NodeList<Element> divWithClassPrefixExa();
+
+ @Selector("div[class$=mple]")
+ NodeList<Element> divWithClassSuffixMple();
+
+ @Selector("p:first-child")
+ NodeList<Element> firstChild();
+
+ @Selector("h1#title")
+ NodeList<Element> h1Title();
+
+ @Selector("h1#title + div > p")
+ NodeList<Element> h1TitlePlusDivGtP();
+
+ @Selector("p:last-child")
+ NodeList<Element> lastChild();
+
+// @Selector("div, p a")
+// NodeList<Element> divCommaPA();
+
+ @Selector(".note")
+ NodeList<Element> note();
+
+ @Selector("p:nth-child(n)")
+ NodeList<Element> nthChild();
+
+ @Selector("p:nth-child(2n)")
+ NodeList<Element> nThChild2n();
+
+ @Selector("p:nth-child(2n+1)")
+ NodeList<Element> nThChild2nPlus1();
+
// @Selector("p:contains(selectors)")
// NodeList<Element> pContainsSelectors();
-
+
@Selector("p:nth-child(even)")
NodeList<Element> nThChildEven();
-
- @Selector("p:nth-child(2n)")
- NodeList<Element> nThChild2n();
-
+
@Selector("p:nth-child(odd)")
NodeList<Element> nThChildOdd();
-
- @Selector("p:nth-child(2n+1)")
- NodeList<Element> nThChild2nPlus1();
-
- @Selector("p:nth-child(n)")
- NodeList<Element> nthChild();
-
+
@Selector("p:only-child")
NodeList<Element> onlyChild();
-
- @Selector("p:last-child")
- NodeList<Element> lastChild();
-
- @Selector("p:first-child")
- NodeList<Element> firstChild();
+
+ @Selector("#title")
+ NodeList<Element> title();
+
+ @Selector("#title,h1#title")
+ NodeList<Element> titleAndh1Title();
+
+ @Selector("ul .tocline2")
+ NodeList<Element> ulTocline2();
+
+ @Selector("ui.toc li.tocline2")
+ NodeList<Element> ulTocLiTocLine2();
}