com.vaadin.flow.dom.Element Java Examples

The following examples show how to use com.vaadin.flow.dom.Element. 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: ShadowRootView.java    From flow with 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 #2
Source File: EventUtilTest.java    From flow with 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 #3
Source File: ElementFactoryTest.java    From flow with 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 #4
Source File: DependencyUI.java    From flow with 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 #5
Source File: RendererUtil.java    From flow with 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 #6
Source File: WebComponentExporterTest.java    From flow with 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 #7
Source File: ElementPropertyMapTest.java    From flow with 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 #8
Source File: RendererUtilTest.java    From flow with 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 #9
Source File: IdMapper.java    From flow with 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 #10
Source File: RouterLinkView.java    From flow with 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 #11
Source File: EventUtilTest.java    From flow with 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 #12
Source File: Component.java    From flow with 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 #13
Source File: WhenDefinedManager.java    From flow with 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 #14
Source File: AttachExistingElementFeatureTest.java    From flow with 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 #15
Source File: ElementStyleView.java    From flow with 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 #16
Source File: AbstractNavigationStateRenderer.java    From flow with 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 #17
Source File: ComponentRenderer.java    From flow with 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 #18
Source File: EventUtilTest.java    From flow with 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 #19
Source File: StateNodeTest.java    From flow with 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 #20
Source File: BasicRenderer.java    From flow with 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 #21
Source File: PropertyDescriptors.java    From flow with 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 #22
Source File: EventUtilTest.java    From flow with 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 #23
Source File: ShortcutRegistrationTest.java    From flow with 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 #24
Source File: MapSyncRpcHandlerTest.java    From flow with 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 #25
Source File: AttachExistingElementFeature.java    From flow with 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 #26
Source File: DataCommunicator.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Fire a size change event if the last event was fired for a different size
 * from the last sent one.
 *
 * @param dataSize
 *            data size to send
 */
private void fireSizeEvent(int dataSize) {
    if (lastSent != dataSize) {
        final Optional<Component> component = Element.get(stateNode)
                .getComponent();
        if (component.isPresent()) {
            ComponentUtil.fireEvent(component.get(),
                    new SizeChangeEvent<>(component.get(), dataSize));
        }
        lastSent = dataSize;
    }
}
 
Example #27
Source File: AttachExistingElementRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void handleNode_requestedIdEqualsAssignedId() {
    AttachExistingElementRpcHandler handler = new AttachExistingElementRpcHandler();

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

    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);

    Mockito.when(requested.hasFeature(Mockito.any())).thenReturn(true);

    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);

    assertNodeIsUnregistered(node, requested, feature);
    Mockito.verify(parentNode).insertChild(index, Element.get(requested));
    Mockito.verify(consumer).accept(Element.get(requested));
}
 
Example #28
Source File: HTMLTest.java    From flow with 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());
}
 
Example #29
Source File: DomListenerOnAttachView.java    From flow with Apache License 2.0 5 votes vote down vote up
public DomListenerOnAttachView() {
    Div status = new Div();
    status.setText("Waiting for event");
    status.setId("status");

    Element element = new Element("event-on-attach");
    element.addEventListener("attach", event -> {
        status.setText("Event received");
    });

    getElement().appendChild(element, status.getElement());
}
 
Example #30
Source File: PushStateScrollView.java    From flow with Apache License 2.0 5 votes vote down vote up
private static Element createButton(String name,
        BiConsumer<JsonValue, String> action) {
    String location = PushStateScrollView.class.getName() + "/" + name;

    Element button = ElementFactory.createButton(name);

    button.setAttribute("id", name);
    button.addEventListener("click", e -> action.accept(null, location));

    return button;
}