Java Code Examples for com.vaadin.flow.dom.Element

The following examples show how to use com.vaadin.flow.dom.Element. These examples are extracted from open source projects. 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 Project: flow   Source File: DependencyUI.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    getElement().appendChild(ElementFactory.createDiv(
            "This test initially loads a stylesheet which makes all text red and a JavaScript which listens to body clicks"));
    getElement().appendChild(ElementFactory.createHr());
    add(new JsResourceComponent());

    Element jsOrder = ElementFactory.createButton("Load js")
            .setAttribute("id", "loadJs");
    StreamRegistration jsStreamRegistration = getSession()
            .getResourceRegistry().registerResource(getJsResource());
    jsOrder.addEventListener("click", e -> {
        getPage().addJavaScript("base://"
                + jsStreamRegistration.getResourceUri().toString());
    });
    Element allBlue = ElementFactory
            .createButton("Load 'everything blue' stylesheet")
            .setAttribute("id", "loadBlue");
    allBlue.addEventListener("click", e -> {
        add(new AllBlueImportantComponent());

    });
    getElement().appendChild(jsOrder, allBlue, ElementFactory.createHr());
}
 
Example 2
Source Project: flow   Source File: EventUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void inspectChildrenHierarchy_selective() throws Exception {
    Element node = new Element("root");
    node.appendChild(new Element("main"), new Element("menu"));
    Element nested = new Element("nested");
    nested.appendChild(new Element("nested-child"),
            new Element("nested-child-2"));

    node.appendChild(nested);

    List<Element> elements = new ArrayList<>();

    EventUtil.inspectHierarchy(node, elements,
            element -> !nested.equals(element));

    Assert.assertEquals("Missing elements from list.", 3, elements.size());
}
 
Example 3
Source Project: flow   Source File: IdMapper.java    License: Apache License 2.0 6 votes vote down vote up
private void injectClientSideElement(String tagName, String id, Field field,
        Consumer<Element> beforeComponentInject) {
    Class<?> fieldType = field.getType();

    Tag tag = fieldType.getAnnotation(Tag.class);
    if (tag != null && tagName != null && !tagName.equalsIgnoreCase(tag.value())) {
        String msg = String.format(
                "Class '%s' has field '%s' whose type '%s' is annotated with "
                        + "tag '%s' but the element defined in the HTML "
                        + "template with id '%s' has tag name '%s'",
                getContainerClass().getName(), field.getName(),
                fieldType.getName(), tag.value(), id, tagName);
        throw new IllegalStateException(msg);
    }
    if (tag != null) {
        // tag can be null if injecting Element
        // tagName is the tag parsed from the template and it is null for Lit templates,
        // which are not parsed
        tagName = tag.value();
    }
    attachExistingElementById(tagName, id, field, beforeComponentInject);
}
 
Example 4
Source Project: flow   Source File: ElementFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
private String getOuterHtml(Element e) {
    StringBuilder sb = new StringBuilder();
    sb.append("<");
    sb.append(e.getTag());
    String attrs = e.getAttributeNames().sorted()
            .map(name -> name + "='" + e.getAttribute(name) + "'")
            .collect(Collectors.joining(" "));
    if (!attrs.isEmpty()) {
        sb.append(" ").append(attrs);
    }
    sb.append(">");
    sb.append(e.getTextRecursively());
    sb.append("</");
    sb.append(e.getTag());
    sb.append(">");

    return sb.toString();
}
 
Example 5
Source Project: flow   Source File: RendererUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void registerEventHandlers_setupEvenHandlersOnAttach() {
    UI ui = new TestUI();
    TestUIInternals internals = (TestUIInternals) ui.getInternals();

    Renderer<String> renderer = new Renderer<>();

    renderer.setEventHandler("foo", value -> {
    });

    Element contentTemplate = new Element(Tag.DIV);
    Element templateDataHost = new Element(Tag.SPAN);

    RendererUtil.registerEventHandlers(renderer, contentTemplate,
            templateDataHost, ValueProvider.identity());

    attachElements(ui, contentTemplate, templateDataHost);
    assertJSExecutions(ui, internals, contentTemplate, templateDataHost);

    ui.getElement().removeAllChildren();
    internals.invocations.clear();

    attachElements(ui, contentTemplate, templateDataHost);
    assertJSExecutions(ui, internals, contentTemplate, templateDataHost);
}
 
Example 6
Source Project: flow   Source File: EventUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getImplementingComponents() throws Exception {
    Element node = new Element("root");
    node.appendChild(new Element("main"), new Element("menu"));
    Element nested = new Element("nested");
    nested.appendChild(new Element("nested-child"),
            new Element("nested-child-2"));

    node.appendChild(nested);
    Component.from(nested, EnterObserver.class);

    List<Element> elements = new ArrayList<>();

    EventUtil.inspectHierarchy(node, elements, element -> true);

    List<BeforeEnterObserver> listenerComponents = EventUtil
            .getImplementingComponents(elements.stream(),
                    BeforeEnterObserver.class)
            .collect(Collectors.toList());

    Assert.assertEquals("Wrong amount of listener instances found", 1,
            listenerComponents.size());
}
 
Example 7
Source Project: flow   Source File: WhenDefinedManager.java    License: Apache License 2.0 6 votes vote down vote up
private static Set<String> collectVaadinTagNames(
        Component[] rootComponents) {
    Set<String> vaadinTagNames = new HashSet<>();

    for (Component rootComponent : rootComponents) {
        rootComponent.getElement().accept(new NodeVisitor() {
            @Override
            public boolean visit(ElementType type, Element element) {
                if (!element.isTextNode()) {
                    String tag = element.getTag();
                    if (tag.startsWith("vaadin-")) {
                        vaadinTagNames.add(tag);
                    }
                }
                return true;
            }

            @Override
            public boolean visit(ShadowRoot root) {
                return true;
            }
        });
    }

    return vaadinTagNames;
}
 
Example 8
Source Project: flow   Source File: AttachExistingElementFeatureTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void forEachChild_register_registeredStatNodeIsAChild() {
    StateNode node = new StateNode();
    AttachExistingElementFeature feature = new AttachExistingElementFeature(
            node);

    Element element = Mockito.mock(Element.class);
    StateNode child = Mockito.mock(StateNode.class);
    ChildElementConsumer callback = Mockito
            .mock(ChildElementConsumer.class);
    Node<?> parent = Mockito.mock(Node.class);
    feature.register(parent, element, child, callback);

    List<StateNode> children = new ArrayList<>(1);
    feature.forEachChild(children::add);
    Assert.assertEquals(1, children.size());
    Assert.assertEquals(child, children.get(0));
}
 
Example 9
Source Project: flow   Source File: ElementStyleView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onShow() {
    Element mainElement = getElement();
    mainElement.getStyle().set("--foo", RED_BORDER);

    Div div = new Div();
    div.setId("red-border");
    div.getElement().getStyle().set("border", "var(--foo)");
    div.setText("Div");

    Div div2 = new Div();
    div2.setId("green-border");
    div2.setText("Div 2");
    div2.getStyle().set("--foo", GREEN_BORDER);
    div2.getElement().getStyle().set("border", "var(--foo)");
    add(div, div2);

}
 
Example 10
Source Project: flow   Source File: EventUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void collectLocaleChangeObserverFromComponentList_elementHasVirtualChildren()
        throws Exception {
    Foo foo = new Foo();
    foo.getElement().appendChild(new Locale().getElement());
    Bar bar = new Bar();

    Element nested = new Element("nested-locale");
    nested.appendChild(new Element("nested-child"),
            new Locale().getElement());

    bar.getElement().appendChild(new Foo().getElement(), nested);

    List<LocaleChangeObserver> beforeNavigationObservers = EventUtil
            .collectLocaleChangeObservers(Arrays.asList(foo, bar));

    Assert.assertEquals("Wrong amount of listener instances found", 2,
            beforeNavigationObservers.size());
}
 
Example 11
Source Project: flow   Source File: BasicRenderer.java    License: Apache License 2.0 6 votes vote down vote up
private void setupTemplateWhenAttached(Element owner,
        SimpleValueRendering rendering, DataKeyMapper<SOURCE> keyMapper) {

    Element templateElement = rendering.getTemplateElement();
    owner.appendChild(templateElement);

    if (keyMapper != null) {
        String propertyName = getTemplatePropertyName(rendering);

        templateElement.setProperty("innerHTML", getTemplateForProperty(
                "[[item." + propertyName + "]]", rendering));
        rendering.setPropertyName(propertyName);

        RendererUtil.registerEventHandlers(this, templateElement, owner,
                keyMapper::get);
    } else {
        String value = getFormattedValue(null);
        templateElement.setProperty("innerHTML",
                getTemplateForProperty(value, rendering));
        rendering.setContainer(owner);
    }
}
 
Example 12
Source Project: flow   Source File: EventUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void collectBeforeNavigationObserversFromUI_elementHasVirtualChildren()
        throws Exception {
    UI ui = UI.getCurrent();
    Element node = ui.getElement();
    node.appendChild(new Element("main"), new Element("menu"));
    Element nested = new Element("nested");
    nested.appendVirtualChild(new Element("nested-child"),
            new Element("nested-child-2"));

    node.appendChild(nested);

    node.getStateProvider().appendVirtualChild(node.getNode(),
            new Element("attached-by-id"), NodeProperties.INJECT_BY_ID,
            "id");

    Component.from(nested, LeaveObserver.class);

    List<BeforeLeaveObserver> beforeNavigationObservers = EventUtil
            .collectBeforeLeaveObservers(ui);

    Assert.assertEquals("Wrong amount of listener instances found", 1,
            beforeNavigationObservers.size());
}
 
Example 13
Source Project: flow   Source File: AttachExistingElementFeature.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Registers the data for the {@code child} node requested as being attached
 * to an existing element.
 *
 * @param parent
 *            parent node of the {@code child}
 * @param previousSibling
 *            previous sibling for the requested existing element
 * @param child
 *            the state node that is going to be associated with the
 *            existing element
 * @param callback
 *            the callback to report the result
 */
public void register(Node<?> parent, Element previousSibling,
        StateNode child, ChildElementConsumer callback) {
    if (callbacks == null) {
        callbacks = new HashMap<>();
    }
    if (parentNodes == null) {
        parentNodes = new HashMap<>();
    }
    if (siblings == null) {
        siblings = new HashMap<>();
    }
    callbacks.put(child, callback);
    parentNodes.put(child, parent);
    siblings.put(child, previousSibling);
    child.setParent(getNode());
}
 
Example 14
Source Project: flow   Source File: StateNodeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void collectChanges_initiallyInactiveElement_sendOnlyDisalowAndReportedFeatures_sendAllChangesWhenActive() {
    Element element = ElementFactory.createAnchor();

    StateNode stateNode = element.getNode();

    ElementData visibility = stateNode.getFeature(ElementData.class);
    ElementPropertyMap properties = stateNode
            .getFeature(ElementPropertyMap.class);

    TestStateTree tree = new TestStateTree();

    // attach the node to be able to get changes
    tree.getRootNode().getFeature(ElementChildrenList.class).add(0,
            stateNode);

    assertCollectChanges_initiallyInactive(stateNode, properties,
            isVisible -> {
                visibility.setVisible(isVisible);
                stateNode.updateActiveState();
            });
}
 
Example 15
Source Project: flow   Source File: ShadowRootView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onShow() {
    Div div = new Div();
    div.getElement().setAttribute("id", "test-element");
    add(div);

    ShadowRoot shadowRoot = div.getElement().attachShadow();
    Element shadowDiv = ElementFactory.createDiv();
    shadowDiv.setText("Div inside shadow DOM");
    shadowDiv.setAttribute("id", "shadow-div");
    shadowRoot.appendChild(shadowDiv);
    Element shadowLabel = ElementFactory
            .createLabel("Label inside shadow DOM");
    shadowLabel.setAttribute("id", "shadow-label");
    shadowRoot.appendChild(shadowLabel);

    NativeButton removeChild = createButton(
            "Remove the last child from the shadow root", "remove",
            event -> shadowRoot.removeChild(shadowLabel));
    add(removeChild);
}
 
Example 16
Source Project: flow   Source File: ElementPropertyMapTest.java    License: Apache License 2.0 6 votes vote down vote up
private void listenerIsNotified(boolean clientEvent) {
    ElementPropertyMap map = createSimplePropertyMap();
    StateNode node = map.getNode();

    AtomicReference<PropertyChangeEvent> event = new AtomicReference<>();
    PropertyChangeListener listener = ev -> {
        Assert.assertNull(event.get());
        event.set(ev);
    };
    map.addPropertyChangeListener("foo", listener);
    map.setProperty("foo", "bar", !clientEvent);

    Assert.assertNull(event.get().getOldValue());
    Assert.assertEquals("bar", event.get().getValue());
    Assert.assertEquals("foo", event.get().getPropertyName());
    Assert.assertEquals(Element.get(node), event.get().getSource());
    Assert.assertEquals(clientEvent, event.get().isUserOriginated());

    // listener is not called. Otherwise its assertion fails.
    map.setProperty("bar", "foo");
}
 
Example 17
Source Project: flow   Source File: WebComponentExporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void configuration_createWebComponentBinding_overridesDefaultValues() {
    exporter.addProperty("value", 1).onChange(MyComponent::update);

    config = (WebComponentConfiguration<MyComponent>) new WebComponentExporter.WebComponentConfigurationFactory()
            .create(exporter);

    // attribute: value=2
    WebComponentBinding<MyComponent> binding = config
            .createWebComponentBinding(new MockInstantiator(),
                    mock(Element.class), Json.parse("{\"value\":2}"));

    Assert.assertEquals("attribute should have set default value to two",
            2, binding.getComponent().value);
}
 
Example 18
Source Project: flow   Source File: Component.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a component instance with an element created based on the
 * {@link Tag} annotation of the sub class.
 * <p>
 * If this is invoked through {@link #from(Element, Class)} or
 * {@link Element#as(Class)}, uses the element defined in those methods
 * instead of creating a new element.
 */
protected Component() {
    Optional<String> tagNameAnnotation = AnnotationReader
            .getAnnotationFor(getClass(), Tag.class).map(Tag::value);
    if (!tagNameAnnotation.isPresent()) {
        throw new IllegalStateException(getClass().getSimpleName()
                + " (or a super class) must be annotated with @"
                + Tag.class.getName()
                + " if the default constructor is used.");
    }

    String tagName = tagNameAnnotation.get();
    if (tagName.isEmpty()) {
        throw new IllegalStateException("@" + Tag.class.getSimpleName()
                + " value cannot be empty.");
    }

    if (elementToMapTo.get() != null) {
        mapToElement(tagName);
        templateMapped = element != null && element.isVirtualChild();
    } else {
        Element e = new Element(tagName);
        setElement(this, e);
        templateMapped = false;
    }
}
 
Example 19
Source Project: flow   Source File: PropertyDescriptors.java    License: Apache License 2.0 6 votes vote down vote up
private PropertyDescriptorImpl(String name, S defaultValue,
        BiConsumer<Element, S> setter, Consumer<Element> remover,
        Function<Element, S> getter,
        BiFunction<S, S, G> returnWrapper) {
    assert name != null;
    assert defaultValue != null;
    assert setter != null;
    assert remover != null;
    assert getter != null;

    this.name = name;
    this.defaultValue = defaultValue;
    this.setter = setter;
    this.remover = remover;
    this.getter = getter;
    this.returnWrapper = returnWrapper;
}
 
Example 20
Source Project: flow   Source File: ShortcutRegistrationTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Works only with the {@code registration} member variable, but allows
 * configuring the {@code listenOn} component
 *
 * Simulates a "beforeClientResponse" callback for the given
 * {@link ShortcutRegistration}
 */
private void clientResponse(Component[] listenOnMock) {
    for (Component component : listenOnMock) {
        when(component.getElement()).thenReturn(new Element("tag"));
        when(component.getEventBus())
                .thenReturn(new ComponentEventBus(component));
    }

    ArgumentCaptor<SerializableConsumer> captor = ArgumentCaptor
            .forClass(SerializableConsumer.class);

    verify(ui, atLeastOnce()).beforeClientResponse(eq(lifecycleOwner),
            captor.capture());

    SerializableConsumer consumer = captor.getValue();

    // Fake beforeClientExecution call.
    consumer.accept(mock(ExecutionContext.class));
}
 
Example 21
Source Project: flow   Source File: MapSyncRpcHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void implicitlyDisabledElement_updateIsAllowedByEventListener_updateIsDone()
        throws Exception {
    Element element = ElementFactory.createDiv();
    UI ui = new UI();
    ui.getElement().appendChild(element);

    ui.setEnabled(false);
    element.addEventListener(DUMMY_EVENT, event -> {
    }).synchronizeProperty(TEST_PROPERTY)
            .setDisabledUpdateMode(DisabledUpdateMode.ALWAYS);

    sendSynchronizePropertyEvent(element, ui, TEST_PROPERTY, NEW_VALUE);

    Assert.assertEquals(NEW_VALUE, element.getPropertyRaw(TEST_PROPERTY));
}
 
Example 22
Source Project: flow   Source File: ComponentRenderer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Rendering<SOURCE> render(Element container,
        DataKeyMapper<SOURCE> keyMapper, Element contentTemplate) {

    ComponentRendering rendering = new ComponentRendering(
            keyMapper == null ? null : keyMapper::key);
    rendering.setTemplateElement(contentTemplate);
    /*
     * setupTemplateWhenAttached does some setup that will be needed by
     * generateData. To ensure the setup has completed before it is needed,
     * we forego the general convention of using beforeClientResponse to
     * guard the action against duplicate invocation. This is not a big
     * problem in this case since setupTemplateWhenAttached only sets
     * properties but doesn't execute any JS.
     */
    container.getNode()
            .runWhenAttached(ui -> setupTemplateWhenAttached(
                    ui, container, rendering,
                    keyMapper));

    return rendering;
}
 
Example 23
Source Project: flow   Source File: AbstractNavigationStateRenderer.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean isComponentElementEqualsOrChild(
        BeforeEnterHandler eventHandler, Component component) {
    if (eventHandler instanceof HasElement) {
        HasElement hasElement = (HasElement) eventHandler;

        final Element componentElement = component.getElement();

        Element element = hasElement.getElement();
        while (element != null) {
            if (element.equals(componentElement)) {
                return true;
            }

            element = element.getParent();
        }
    }

    return false;
}
 
Example 24
Source Project: flow   Source File: RouterLinkView.java    License: Apache License 2.0 6 votes vote down vote up
protected void addLinks() {
    getElement().appendChild(
            // inside servlet mapping
            ElementFactory.createDiv("inside this servlet"),
            ElementFactory.createRouterLink("", "empty"), new Element("p"),
            createRouterLink("foo"), new Element("p"),
            createRouterLink("foo/bar"), new Element("p"),
            createRouterLink("./foobar"), new Element("p"),
            createRouterLink("./foobar?what=not"), new Element("p"),
            createRouterLink("./foobar?what=not#fragment"),
            new Element("p"), createRouterLink("/view/baz"),
            new Element("p"),
            // outside
            ElementFactory.createDiv("outside this servlet"),
            createRouterLink("/run"), new Element("p"),
            createRouterLink("/foo/bar"), new Element("p"),
            // external
            ElementFactory.createDiv("external"),
            createRouterLink("http://example.net/"));
}
 
Example 25
Source Project: flow   Source File: RendererUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static <T> void setupTemplateRendererEventHandler(UI ui,
        Element eventOrigin, String handlerName, Consumer<T> consumer,
        Function<String, T> keyMapper) {
    ui.getInternals().getStateTree()
            .beforeClientResponse(eventOrigin.getNode(), context ->
            // sendEventMessage is an exported function at the client side
            ui.getPage().executeJs(String.format(
                    "$0.%s = function(e) {Vaadin.Flow.clients[$1].sendEventMessage(%d, '%s', {key: e.model ? e.model.__data.item.key : e.target.__dataHost.__data.item.key})}",
                    handlerName, eventOrigin.getNode().getId(),
                    handlerName), eventOrigin,
                    ui.getInternals().getAppId()));

    DomListenerRegistration registration = eventOrigin.addEventListener(
            handlerName, event -> processEventFromTemplateRenderer(event,
                    handlerName, consumer, keyMapper));

    runOnceOnDetach(eventOrigin, registration::remove);
}
 
Example 26
Source Project: radman   Source File: MenuTemplate.java    License: MIT License 5 votes vote down vote up
private void addNavigation(Class<? extends Component> navigationTarget, String name) {
    Element li = ElementFactory.createListItem();
    RouterLink routerLink = new RouterLink(name, navigationTarget);
    routerLink.getClassNames().add("button");
    linksContainer.appendChild(li.appendChild(routerLink.getElement()));
    routerLink.setHighlightCondition((r, event) -> Objects.equals(r.getHref(), event.getLocation().getPath()));
    routerLink.setHighlightAction((r, highlight) -> {
        if (highlight) {
            routerLink.getElement().getClassList().add(SELECTED_CLASS_NAME);
        } else {
            routerLink.getElement().getClassList().remove(SELECTED_CLASS_NAME);
        }
    });
}
 
Example 27
Source Project: flow   Source File: ComponentTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void mapToComponentWhichCreatesComponentInConstructor() {
    Element e = new Element("div");
    TestComponentWhichCreatesComponentInConstructor c = Component.from(e,
            TestComponentWhichCreatesComponentInConstructor.class);
    Element buttonElement = c.getElement().getChild(0);

    Assert.assertEquals(e, c.getElement());
    Assert.assertNotEquals(e, buttonElement);
    Assert.assertEquals("button", buttonElement.getTag());
}
 
Example 28
Source Project: flow   Source File: AbstractNodeStateProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void insertChild(StateNode node, int index, Element child) {
    assert index >= 0;
    assert index <= getChildCount(node); // == if adding as last

    getChildrenFeature(node).add(index, child.getNode());
}
 
Example 29
Source Project: flow   Source File: AttachExistingElementRpcHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void handleNode_error() {
    AttachExistingElementRpcHandler handler = new AttachExistingElementRpcHandler();

    int requestedId = 1;
    JsonObject object = Json.createObject();
    object.put(JsonConstants.RPC_ATTACH_REQUESTED_ID, requestedId);
    object.put(JsonConstants.RPC_ATTACH_ASSIGNED_ID, -1);
    object.put(JsonConstants.RPC_ATTACH_TAG_NAME, "div");
    object.put(JsonConstants.RPC_ATTACH_INDEX, -1);

    StateNode node = Mockito.mock(StateNode.class);
    StateNode requested = Mockito.mock(StateNode.class);
    StateTree tree = Mockito.mock(StateTree.class);
    Mockito.when(node.getOwner()).thenReturn(tree);
    Mockito.when(tree.getNodeById(requestedId)).thenReturn(requested);

    AttachExistingElementFeature feature = new AttachExistingElementFeature(
            node);
    Node<?> parentNode = Mockito.mock(Node.class);
    ChildElementConsumer consumer = Mockito
            .mock(ChildElementConsumer.class);
    Element sibling = Mockito.mock(Element.class);
    feature.register(parentNode, sibling, requested, consumer);
    Mockito.when(node.getFeature(AttachExistingElementFeature.class))
            .thenReturn(feature);

    handler.handleNode(node, object);

    Mockito.verify(consumer).onError(parentNode, "div", sibling);
    assertNodeIsUnregistered(node, requested, feature);
}
 
Example 30
Source Project: flow   Source File: HTMLTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void rootSpecialAttributes() {
    Html html = new Html(
            "<span class='foo' style='color: red'>hello</span>");
    Element element = html.getElement();
    Assert.assertEquals(Tag.SPAN, element.getTag());

    Assert.assertEquals(2, element.getAttributeNames().count());
    Assert.assertEquals("foo", element.getAttribute("class"));
    Assert.assertEquals("color:red", element.getAttribute("style"));
    Assert.assertEquals("hello", html.getInnerHtml());
}