elemental.dom.Node Java Examples

The following examples show how to use elemental.dom.Node. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AnotherTest.java    From vertxui with GNU General Public License v3.0 6 votes vote down vote up
private void printStructure(Element element) {
	console.log("<" + element.getNodeName());
	NamedNodeMap attributes = element.getAttributes();
	if (attributes != null) {
		for (int x = 0; x < attributes.length(); x++) {
			Node attr = attributes.item(x);
			console.log(" " + attr.getNodeName() + "=" + attr.getNodeValue());
		}
	}
	console.log(">");
	if (element.getTextContent() != null) {
		console.log(element.getTextContent());
	}
	NodeList children = element.getChildNodes();
	for (int x = 0; x < children.getLength(); x++) {
		printStructure((Element) children.at(x));
	}
	console.log("</" + element.getNodeName() + ">");
}
 
Example #2
Source File: Debouncer.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an existing debouncer or creates a new one associated with the given
 * DOM node, identifier and debounce timeout.
 *
 * @param element
 *            the DOM node to which this debouncer is bound
 * @param identifier
 *            a unique identifier string in the scope of the provided
 *            element
 * @param debounce
 *            the debounce timeout
 * @return a debouncer instance
 */
public static Debouncer getOrCreate(Node element, String identifier,
        double debounce) {
    JsMap<String, JsMap<Double, Debouncer>> elementMap = debouncers
            .get(element);
    if (elementMap == null) {
        elementMap = JsCollections.map();
        debouncers.set(element, elementMap);
    }

    JsMap<Double, Debouncer> identifierMap = elementMap.get(identifier);
    if (identifierMap == null) {
        identifierMap = JsCollections.map();
        elementMap.set(identifier, identifierMap);
    }

    Debouncer debouncer = identifierMap.get(Double.valueOf(debounce));
    if (debouncer == null) {
        debouncer = new Debouncer(element, identifier, debounce);
        identifierMap.set(Double.valueOf(debounce), debouncer);
    }

    return debouncer;
}
 
Example #3
Source File: ClientJsonCodec.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Decodes a value encoded on the server using
 * {@link JsonCodec#encodeWithTypeInfo(Object)}.
 *
 * @param tree
 *            the state tree to use for resolving nodes and elements
 * @param json
 *            the JSON value to decode
 * @return the decoded value
 */
public static Object decodeWithTypeInfo(StateTree tree, JsonValue json) {
    if (json.getType() == JsonType.ARRAY) {
        JsonArray array = (JsonArray) json;
        int typeId = (int) array.getNumber(0);
        switch (typeId) {
        case JsonCodec.NODE_TYPE: {
            int nodeId = (int) array.getNumber(1);
            Node domNode = tree.getNode(nodeId).getDomNode();
            return domNode;
        }
        case JsonCodec.ARRAY_TYPE:
            return jsonArrayAsJsArray(array.getArray(1));
        case JsonCodec.RETURN_CHANNEL_TYPE:
            return createReturnChannelCallback((int) array.getNumber(1),
                    (int) array.getNumber(2),
                    tree.getRegistry().getServerConnector());
        default:
            throw new IllegalArgumentException(
                    "Unsupported complex type in " + array.toJson());
        }
    } else {
        return decodeWithoutTypeInfo(json);
    }
}
 
Example #4
Source File: StateTree.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Unregisters all nodes except root from this tree, and clears the root's
 * features. Use to reset the tree in preparation for rebuilding it in in a
 * resynchronization response.
 */
public void prepareForResync() {
    rootNode.getList(NodeFeatures.VIRTUAL_CHILDREN)
            .forEach(sn -> clearLists((StateNode) sn));
    clearLists(rootNode);

    idToNode.forEach((node, b) -> {
        if (node != rootNode) {
            final Node dom = node.getDomNode();
            if (dom != null
                    && ServerEventObject.getIfPresent(dom) != null) {
                // reject any promise waiting on this node
                ServerEventObject.getIfPresent(dom).rejectPromises();
            }
            unregisterNode(node);
            node.setParent(null);
        }
    });
}
 
Example #5
Source File: SimpleElementBindingStrategy.java    From flow with Apache License 2.0 6 votes vote down vote up
private void attachShadow(BindingContext context) {
    NodeMap map = context.node.getMap(NodeFeatures.SHADOW_ROOT_DATA);
    StateNode shadowRootNode = (StateNode) map
            .getProperty(NodeProperties.SHADOW_ROOT).getValue();
    if (shadowRootNode != null) {
        NativeFunction function = NativeFunction.create("element",
                "if ( element.shadowRoot ) { return element.shadowRoot; } "
                        + "else { return element.attachShadow({'mode' : 'open'});}");
        Node shadowRoot = (Node) function.call(null, context.htmlNode);

        if (shadowRootNode.getDomNode() == null) {
            shadowRootNode.setDomNode(shadowRoot);
        }

        BindingContext newContext = new BindingContext(shadowRootNode,
                shadowRoot, context.binderContext);
        bindChildren(newContext);
    }
}
 
Example #6
Source File: ElementUtil.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Searches the shadow root of the given context element for the given id or
 * searches the light DOM if the element has no shadow root.
 *
 * @param context
 *            the container element to search through
 * @param id
 *            the identifier of the element to search for
 * @return the element with the given {@code id} if found, otherwise
 *         <code>null</code>
 */
public static native Element getElementById(Node context, String id)
/*-{
   if (document.body.$ && document.body.$[id]) {
     // Exported WCs add their id to body.$ and cannot be found using a real id attribute
     return document.body.$[id];
   } else if (context.shadowRoot) {
     return context.shadowRoot.getElementById(id);
   } else if (context.getElementById) {
     return context.getElementById(id);
   } else if (id && id.match("^[a-zA-Z0-9-_]*$")) {
     // No funky characters in id so querySelector can be used directly
     return context.querySelector("#" + id);
   } else {
     // Find all elements with an id attribute and filter out the correct one
     return Array.from(context.querySelectorAll('[id]')).find(function(e) {return e.id == id});
   }
}-*/;
 
Example #7
Source File: PolymerUtils.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the custom element using {@code path} of indices starting from the
 * {@code root}.
 *
 * @param root
 *            the root element to start from
 * @param path
 *            the indices path identifying the custom element.
 * @return the element inside the {@code root} by the path of indices
 */
public static Element getCustomElement(Node root, JsonArray path) {
    Node current = root;
    for (int i = 0; i < path.length(); i++) {
        JsonValue value = path.get(i);
        current = getChildIgnoringStyles(current, (int) value.asNumber());
    }
    if (current instanceof Element) {
        return (Element) current;
    } else if (current == null) {
        Console.warn(
                "There is no element addressed by the path '" + path + "'");
    } else {
        Console.warn("The node addressed by path " + path
                + " is not an Element");
    }
    return null;
}
 
Example #8
Source File: GwtEventHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Add get functionality to element if not defined. Add the key value pair
 * to property object or create object if not available.
 *
 * @param node
 *            Target node
 * @param property
 *            Property name of object
 * @param key
 *            Key to add to property object
 * @param value
 *            value to add
 */
private native void setNodeProperty(Node node, String property, String key,
        String value)
/*-{
    if(typeof(node.get) !== 'function') {
        node.get = function(propertyName) {
            return this[propertyName];
        }
    }
    var propertyValue = node.get(property);
    if(typeof(property) !== 'object') {
        node[property] = {};
        // If a number add as a number not as a string.
        if(parseInt(value) !== NaN){
            node[property][key] = parseInt(value);
        } else {
            node[property][key] = value;
        }
    } else {
        propertyValue.key = value;
    }
}-*/;
 
Example #9
Source File: DomApiAbstractionUsageTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private static void verifyMethod(String callingMethod,
        String targetClassName, String targetMethod) {
    // Won't care about overhead of loading all
    // classes since this is just a test
    Class<?> targetClass = getClass(targetClassName);

    if (!Node.class.isAssignableFrom(targetClass)) {
        return;
    }

    if (ignoredElementalClasses.contains(targetClass)) {
        return;
    }

    if ((Element.class == targetClass || Node.class == targetClass)
            && ignoredElementMethods.contains(targetMethod)) {
        return;
    }

    Assert.fail(callingMethod + " calls " + targetClass.getName() + "."
            + targetMethod);
}
 
Example #10
Source File: PolymerUtils.java    From flow with Apache License 2.0 6 votes vote down vote up
private static Node getChildIgnoringStyles(Node parent, int index) {
    HTMLCollection children = DomApi.wrap(parent).getChildren();
    int filteredIndex = -1;
    for (int i = 0; i < children.getLength(); i++) {
        Node next = children.item(i);
        assert next instanceof Element : "Unexpected element type in the collection of children. "
                + "DomElement::getChildren is supposed to return Element chidren only, but got "
                + next.getClass();
        Element element = (Element) next;
        if (!"style".equalsIgnoreCase(element.getTagName())) {
            filteredIndex++;
        }
        if (filteredIndex == index) {
            return next;
        }
    }
    return null;
}
 
Example #11
Source File: SimpleElementBindingStrategy.java    From flow with Apache License 2.0 5 votes vote down vote up
private void doBind(StateNode node, BinderContext nodeFactory) {
    Node domNode = node.getDomNode();
    // this will fire an event which gives a chance to run logic which
    // needs to know when the element is completely initialized
    node.setDomNode(null);
    node.setDomNode(domNode);
    nodeFactory.createAndBind(node);
}
 
Example #12
Source File: ServerEventObject.java    From flow with Apache License 2.0 5 votes vote down vote up
private native JsonObject getPolymerPropertyObject(Node node,
        String propertyName)
/*-{
    if (typeof(node.get) === 'function') {
        var polymerProperty = node.get(propertyName);
        if (typeof(polymerProperty) === 'object'
            && typeof(polymerProperty["nodeId"]) !== 'undefined') {
            return { nodeId: polymerProperty["nodeId"] };
        }
    }
    return null;
}-*/;
 
Example #13
Source File: Renderer.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
private static <T, V> void compareApplyRemove(Node element, T name, V value, What what) {
	// Fluent.console.log("removing " + name + " with " + value);
	switch (what) {
	case Attributes:
		switch ((Att) name) {
		case checked:
			((InputElement) element).setChecked(false);
			break;
		case value:
			((InputElement) element).setValue(null);
			break;
		case selectedIndex:
			// nothing to do
			// ((SelectElement) element).);
			break;
		default:
			((Element) element).removeAttribute(((Att) name).nameValid());
			break;
		}
		break;
	case Styles:
		((Element) element).getStyle().removeProperty(((Css) name).nameValid());
		break;
	case Listeners:
		element.removeEventListener((String) name, (EventListener) value);
		break;
	default:
		throw new IllegalArgumentException("Not possible");
	}
}
 
Example #14
Source File: SimpleElementBindingStrategy.java    From flow with Apache License 2.0 5 votes vote down vote up
private static boolean resolveDebounces(Node element, String debouncerId,
        JsonArray debounceList, Consumer<String> command) {
    boolean atLeastOneEager = false;

    for (int i = 0; i < debounceList.length(); i++) {
        // [timeout, phase1, phase2, ...]
        JsonArray debounceSettings = debounceList.getArray(i);

        double timeout = debounceSettings.getNumber(0);

        if (timeout == 0) {
            atLeastOneEager = true;
            continue;
        }

        JsSet<String> phases = JsCollections.set();
        for (int j = 1; j < debounceSettings.length(); j++) {
            phases.add(debounceSettings.getString(j));
        }

        boolean eager = Debouncer.getOrCreate(element, debouncerId, timeout)
                .trigger(phases, command);

        atLeastOneEager |= eager;
    }

    return atLeastOneEager;
}
 
Example #15
Source File: SimpleElementBindingStrategy.java    From flow with Apache License 2.0 5 votes vote down vote up
private static boolean resolveFilters(Node element, String eventType,
        JsonObject expressionSettings, JsonObject eventData,
        Consumer<String> sendCommand) {

    boolean noFilters = true;
    boolean atLeastOneFilterMatched = false;

    for (String expression : expressionSettings.keys()) {
        JsonValue settings = expressionSettings.get(expression);

        boolean hasDebounce = settings.getType() == JsonType.ARRAY;

        if (!hasDebounce && !settings.asBoolean()) {
            continue;
        }
        noFilters = false;

        boolean filterMatched = eventData != null
                && eventData.getBoolean(expression);
        if (hasDebounce && filterMatched) {
            String debouncerId = "on-" + eventType + ":" + expression;

            // Count as a match only if at least one debounce is eager
            filterMatched = resolveDebounces(element, debouncerId,
                    (JsonArray) settings, sendCommand);
        }

        atLeastOneFilterMatched |= filterMatched;
    }

    return noFilters || atLeastOneFilterMatched;
}
 
Example #16
Source File: SimpleElementBindingStrategy.java    From flow with Apache License 2.0 5 votes vote down vote up
private static Node getFirstNodeMappedAsStateNode(
        NodeList mappedNodeChildren, Node htmlNode) {

    JsArray<Node> clientList = DomApi.wrap(htmlNode).getChildNodes();
    for (int i = 0; i < clientList.length(); i++) {
        Node clientNode = clientList.get(i);
        for (int j = 0; j < mappedNodeChildren.length(); j++) {
            StateNode stateNode = (StateNode) mappedNodeChildren.get(j);
            if (clientNode.equals(stateNode.getDomNode())) {
                return clientNode;
            }
        }
    }
    return null;
}
 
Example #17
Source File: StateNode.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the DOM node associated with this state node.
 *
 * @param node
 *            the associated DOM node
 */
public void setDomNode(Node node) {
    assert domNode == null
            || node == null : "StateNode already has a DOM node";

    domNode = node;
    JsSet<Function<StateNode, Boolean>> copy = JsCollections
            .set(domNodeSetListeners);
    copy.forEach(listener -> {
        if (listener.apply(this) == Boolean.TRUE) {
            domNodeSetListeners.delete(listener);
        }
    });
}
 
Example #18
Source File: Renderer.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
private static <T, V> void compareApplySet(Node element, T name, V value, What what) {
	// Fluent.console.log("setting " + name + " with " + value);
	switch (what) {
	case Attributes:
		switch ((Att) name) {
		case checked:
			((InputElement) element).setChecked(true);
			break;
		case value:
			((InputElement) element).setValue((String) value);
			break;
		case selectedIndex:
			((SelectElement) element).setSelectedIndex(Integer.parseInt((String) value));
		default:
			((Element) element).setAttribute(((Att) name).nameValid(), (String) value);
			break;
		}
		break;
	case Styles:
		((Element) element).getStyle().setProperty(((Css) name).nameValid(), (String) value);
		break;
	case Listeners:
		element.addEventListener((String) name, (EventListener) value);
		break;
	default:
		throw new IllegalArgumentException("Not possible");
	}
}
 
Example #19
Source File: SimpleElementBindingStrategy.java    From flow with Apache License 2.0 5 votes vote down vote up
private EventRemover bindChildren(BindingContext context) {
    NodeList children = context.node.getList(NodeFeatures.ELEMENT_CHILDREN);
    if (children.hasBeenCleared()) {
        removeAllChildren(context.htmlNode);
    }

    for (int i = 0; i < children.length(); i++) {
        StateNode childNode = (StateNode) children.get(i);

        ExistingElementMap existingElementMap = childNode.getTree()
                .getRegistry().getExistingElementMap();
        Node child = existingElementMap.getElement(childNode.getId());
        if (child != null) {
            existingElementMap.remove(childNode.getId());
            childNode.setDomNode(child);
            context.binderContext.createAndBind(childNode);
        } else {
            child = context.binderContext.createAndBind(childNode);
            DomApi.wrap(context.htmlNode).appendChild(child);
        }
    }

    return children.addSpliceListener(e -> {
        /*
         * Handle lazily so we can create the children we need to insert.
         * The change that gives a child node an element tag name might not
         * yet have been applied at this point.
         */
        Reactive.addFlushListener(() -> handleChildrenSplice(e, context));
    });
}
 
Example #20
Source File: Binder.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Bind the {@code domNode} to the {@code stateNode}.
 *
 * @param stateNode
 *            the state node
 * @param domNode
 *            the DOM node to bind, not {@code null}
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void bind(StateNode stateNode, Node domNode) {
    assert !stateNode.getTree()
            .isUpdateInProgress() : "Binding state node while processing state tree changes";

    BindingStrategy applicable = getApplicableStrategy(stateNode);
    applicable.bind(stateNode, domNode, CONTEXT);
}
 
Example #21
Source File: PolymerUtils.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Store the StateNode.id into the polymer property under 'nodeId'
 *
 * @param domNode
 *            polymer dom node
 * @param id
 *            id of a state node
 * @param path
 *            polymer model path to property
 */
public static native void storeNodeId(Node domNode, int id, String path)
/*-{
    if (typeof(domNode.get) !== 'undefined') {
        var polymerProperty = domNode.get(path);
        if (typeof(polymerProperty) === 'object'
            && polymerProperty["nodeId"] === undefined) {
            polymerProperty["nodeId"] = id;
        }
    }
}-*/;
 
Example #22
Source File: Binder.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public Node createAndBind(StateNode stateNode) {
    BindingStrategy<?> strategy = getApplicableStrategy(stateNode);
    Node node = stateNode.getDomNode();
    if (stateNode.getDomNode() == null) {
        node = strategy.create(stateNode);
        assert node != null;
        stateNode.setDomNode(node);
    }
    bind(stateNode, node);

    return node;
}
 
Example #23
Source File: MessageHandler.java    From flow with Apache License 2.0 4 votes vote down vote up
private native void callAfterServerUpdates(Node node)
/*-{
    if ( node && node.afterServerUpdate ) {
        node.afterServerUpdate();
    }
}-*/;
 
Example #24
Source File: PolymerDomApiImpl.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public DomElement wrap(Node node) {
    return getPolymer().dom(node);
}
 
Example #25
Source File: Debouncer.java    From flow with Apache License 2.0 4 votes vote down vote up
private Debouncer(Node element, String identifier, double timeout) {
    this.element = element;
    this.identifier = identifier;
    this.timeout = timeout;
}
 
Example #26
Source File: SimpleElementBindingStrategy.java    From flow with Apache License 2.0 4 votes vote down vote up
private void addChildren(int index, BindingContext context,
        JsArray<?> add) {
    NodeList nodeChildren = context.node
            .getList(NodeFeatures.ELEMENT_CHILDREN);

    Node beforeRef;
    if (index == 0) {
        // Insert at the first position after the client-side-only nodes
        beforeRef = getFirstNodeMappedAsStateNode(nodeChildren,
                context.htmlNode);
    } else if (index <= nodeChildren.length() && index > 0) {
        StateNode previousSibling = getPreviousSibling(index, context);
        // Insert before the next sibling of the current node
        beforeRef = previousSibling == null ? null
                : DomApi.wrap(previousSibling.getDomNode())
                        .getNextSibling();
    } else {
        // Insert at the end
        beforeRef = null;
    }

    for (int i = 0; i < add.length(); i++) {
        Object newChildObject = add.get(i);
        StateNode newChild = (StateNode) newChildObject;

        ExistingElementMap existingElementMap = newChild.getTree()
                .getRegistry().getExistingElementMap();
        Node childNode = existingElementMap.getElement(newChild.getId());
        if (childNode != null) {
            existingElementMap.remove(newChild.getId());
            newChild.setDomNode(childNode);
            context.binderContext.createAndBind(newChild);
        } else {
            childNode = context.binderContext.createAndBind(newChild);

            DomApi.wrap(context.htmlNode).insertBefore(childNode,
                    beforeRef);
        }

        beforeRef = DomApi.wrap(childNode).getNextSibling();
    }
}
 
Example #27
Source File: Renderer.java    From vertxui with GNU General Public License v3.0 4 votes vote down vote up
private static <K extends Comparable<K>, V> void compareApply(Node element, TreeMap<K, V> treeNew,
		TreeMap<K, V> treeOld, K[] empty, What what) {

	K[] keysNew = (treeNew == null) ? empty : treeNew.keySet().toArray(empty);
	K[] keysOld = (treeOld == null) ? empty : treeOld.keySet().toArray(empty);

	// console.log("---START compareAttributes() kNew=" + kNew.length + "
	// kOld=" + kOld.length);
	int countNew = 0, countOld = 0;
	// avoiding creating new sets (guava, removeAll etc) and minimizing
	// lookups (.get)
	while (countNew < keysNew.length || countOld < keysOld.length) {
		K keyNew = null;
		if (treeNew != null && countNew < keysNew.length) {
			keyNew = keysNew[countNew];
			countNew++;
		}
		K keyOld = null;
		if (treeOld != null && countOld < keysOld.length) {
			keyOld = keysOld[countOld];
			countOld++;
		}
		if (keyNew != null && keyOld == null) {
			// console.log("setting attribute: " + attNew.nameValid() + ","
			// + treeNew.get(attNew));
			if (element != null) {
				compareApplySet(element, keyNew, treeNew.get(keyNew), what);
			}
		} else if (keyNew == null && keyOld != null) {
			// console.log("removing attribute: " + attOld.nameValid());
			if (element != null) {
				compareApplyRemove(element, keyOld, treeOld.get(keyOld), what);
			}
			// } else if (nAtt == null && oAtt == null) {
			// throw new IllegalArgumentException("both can not be null n="
			// + n + " o=" + o);
		} else { // both attributes must have a value here
			int compare = keyNew.compareTo(keyOld);
			// console.log("comparing "+attNew+" "+attOld);
			if (compare == 0) { // same keys
				V oldValue = treeOld.get(keyOld);
				V newValue = treeNew.get(keyNew);
				if (!compareApplyValueEquals(oldValue, newValue)) { // key
																	// same,
																	// other
																	// value
					// console.log(
					// "changing value for " + attNew.nameValid() + " old="
					// + oldValue + " new=" + newValue);
					if (element != null) {
						compareApplyRemove(element, keyNew, oldValue, what);
						compareApplySet(element, keyNew, newValue, what);
					}
					// } else {
					// console.log("no change " + attNew.nameValid() + "
					// value=" + oldValue);
				}
			} else if (compare < 0) {
				if (element != null) {
					compareApplySet(element, keyNew, treeNew.get(keyNew), what);
				}
				// console.log(" setting " + attNew.nameValid());
				countOld--;
			} else { // compare>0
				// console.log(" removing " + attOld.nameValid());
				if (element != null) {
					compareApplyRemove(element, keyOld, treeOld.get(keyOld), what);
				}
				countNew--;
			}
		}
	}
}
 
Example #28
Source File: ExecuteJavaScriptElementUtils.java    From flow with Apache License 2.0 4 votes vote down vote up
private static boolean hasTag(Node node, String tag) {
    return node instanceof Element
            && tag.equalsIgnoreCase(((Element) node).getTagName());
}
 
Example #29
Source File: ExecuteJavaScriptElementUtils.java    From flow with Apache License 2.0 4 votes vote down vote up
private static native boolean isPropertyDefined(Node node, String property)
/*-{
    return !!(node["constructor"] && node["constructor"]["properties"] &&
        node["constructor"]["properties"][property]) &&
             (typeof(node["constructor"]["properties"][property]["value"]) != "undefined");
}-*/;
 
Example #30
Source File: ApplicationConnection.java    From flow with Apache License 2.0 4 votes vote down vote up
private Node getDomElementByNodeId(int id) {
    StateNode node = registry.getStateTree().getNode(id);
    return node == null ? null : node.getDomNode();
}