Close

Using Vaadin Elements with Vaadin Framework

Note: This post has been updated to use Vaadin 8.

Many Vaadin Framework users have been wondering why we have started the pure client side Elements project. As discussed last month, the ultimate plan is to start using these Web Components based client side components in the client side of an upcoming version of the framework. In that version, you’ll have a plain Java API for all Vaadin Elements and it will be super easy to wrap any Web Component as a Vaadin add-on.

Although the time may still not be right for a fully Web Component based client side engine, you can today already use Elements and other Web Components with Vaadin Framework. This can be done as with any other JS integration, as we have presented before, or using the Elements add-on, a helper library from our labs that makes it really easy to wrap Web Components as add-ons with a fully featured Java API.

As an example, let's see what is needed to wrap the ComboBox element as an add-on and how to share the plain Java API with others via Vaadin Directory (vaadin.com/directory).

Make sure you have Maven and Bower installed before following this guide.

Step 1: Create a new Vaadin add-on project

Start by creating a new add-on project using the archetype-vaadin-addon:

mvn archetype:generate -B \
   -DarchetypeGroupId=in.virit  \
   -DarchetypeArtifactId=archetype-vaadin-addon  \
   -DarchetypeRepository=https://oss.sonatype.org/content/repositories/snapshots/  \
   -DarchetypeVersion=2.0-SNAPSHOT \
   -DgroupId=org.vaadin.elements \
   -DartifactId=combobox-element \
   -Dversion=1.0-SNAPSHOT

Optionally, remove the example and test code (except the Server class which is used to run the test application).

Step 2: Add the required dependencies

Add the Elements add-on dependency in the pom.xml file:

<dependency>
  <groupId>org.vaadin</groupId>
  <artifactId>elements</artifactId>
  <version>0.2.0</version>
</dependency>

Download the vaadin-combo-box HTML element by running the following command from the src/main/resources/VAADIN directory (create it, if it doesn’t exist):

    cd src/main/resources/VAADIN
    bower install --save vaadin-combo-box

Alternatively, you can add a .bowerrc file to avoid changing to the VAADIN directory when you need to install multiple elements, for example.

Step 3: Extend the Element interface

Define a new ComboBoxElement interface that extends Element and sets its tag as the vaadin-combo-box HTML element:

package org.vaadin.elements;

@Tag("vaadin-combo-box")
public interface ComboBoxElement extends Element {

    static ComboBoxElement create() {
        return Elements.create(ComboBoxElement.class);
    }

    void setLabel(String label);

    void setItems(String items);

    void setValue(String value);

    String getValue();
}

You don’t have to implement this interface. The Elements add-on will provide an implementation at runtime and will match the setters and getters with the corresponding attributes of the HTML element.

Step 4: Wrap the element in a Vaadin component

Implement a new ComboBoxComponent class that imports the vaadin-combo-box element and encapsulates the related low-level logic:

package org.vaadin.elements;

import elemental.json.JsonArray;
import elemental.json.impl.JreJsonFactory;

@HtmlImport(
    "vaadin://bower_components/vaadin-combo-box/vaadin-combo-box.html")
public class ComboBoxComponent extends AbstractElementComponent {

    public static interface ValueChangeListener {
        void valueChange(String option);
    }

    private ComboBoxElement element;

    public ComboBoxComponent(String label, String... options) {
        element = ComboBoxElement.create();
        element.bindAttribute("value", "change");
        element.setLabel(label);

        if (options != null) {
            JsonArray array = new JreJsonFactory().createArray();

            for (int i = 0; i < options.length; i++) {
                array.set(i, options[i]);
            }
            element.setItems(array.toJson());
        }

        Root root = ElementIntegration.getRoot(this);
        root.appendChild(element);
    }

    public String getValue() {
        return element.getValue();
    }

    public void setValue(String value) {
        element.setValue(value);
    }

    public void addValueChangeListener(ValueChangeListener listener) {
        element.addEventListener("change",
                args -> listener.valueChange(getValue()));
    }
}

This class uses the Elements add-on to implement a Vaadin UI component that you can add into any component container, such as VerticalLayout or Panel. To make it simple for this guide, we are extending AbstractElementComponent, however, you can extend any Vaadin component that suits your specific use case (see for example the DatePicker add-on).

Step 5: Implement a test UI

Implement a test UI inside the test directory:

package org.vaadin.elements;

import com.vaadin.annotations.JavaScript;
import com.vaadin.ui.Component;
import com.vaadin.ui.Notification;
import org.vaadin.addonhelpers.AbstractTest;

@JavaScript(
    "vaadin://bower_components/webcomponentsjs/webcomponents.js")
public class BasicComboBoxComponentUsageUI extends AbstractTest {

    @Override
    public Component getTestComponent() {
        ComboBoxComponent comboBox =
            new ComboBoxComponent("Select an option",
                "Option 1", "Option 2", "Option 3");

        comboBox.setValue("Option 2");
        comboBox.addValueChangeListener(
            value -> Notification.show(value));

        return comboBox;
    }
}

The Maven archetype we used includes a set of utilities to make the development of add-ons easier. One of these utilities is a Server that creates a UI that discovers instances of type AbstractTest (which in turn, extends UI) and shows them on a list allowing you to select the AbstractTest you want to try.

Please note that at the time of writing this not all browsers natively support the technologies that enable Web Components. However, it’s possible to include a set of pollyfills by including the webcomponents.js file via the @JavaScript annotation.

Step 6: Run the test application

Run the Server.main() method from your IDE or using Maven:

    mvn package exec:java -Dexec.mainClass="org.vaadin.elements.uiserver.Server" -Dexec.classpathScope=test

Point your browser to http://localhost:9998 and click the BasicComboBoxComponentUsageUI link.

The following is a screenshot of the application:

Screen Shot 2016-10-19 at 15.26.31.png

Step 7: Publishing the component as an add-on

To publish the add-on at https://vaadin.com/directory, follow the instructions in the generated README.md file.

The example add-on I implemented in this exercise is already available via Directory. It probably makes no sense to use this add-on instead of the ComboBox component from the core, but I hope it inspires you to wrap other Web Components with a plain Java API!
 

Check out the full example on GitHub

New Vaadin Training: Learn about Progressive Web Apps with Polymer

We are proud to present a new training course “Building Progressive Web Apps with Polymer”. The course is intended for anybody wanting to learn more about Web Components, Google’s Polymer library and Progressive Web Applications (PWAs). You’ll also get to know Vaadin Elements, which are built with the Polymer library. No prior knowledge is required. This course is intended for users of any web framework.

The training is an interactive two-day, hands-on course held in a classroom near you. The first training will be held in Helsinki on December 13th-14th by Vaadin Expert Sami Suo-Heikki. 

Check out the full agenda

We believe that Progressive Web Apps are the future of mobile and web development. Therefore we follow their development around the world, such as at the Polymer Roadshow and the Polymer Summit in London. PWAs are built on new standards based technologies, which have the  commitment of industry leaders like Chrome, Firefox, Opera, Samsung and Microsoft. As shown by Gartner, companies will adapt these more “applike” PWAs in order to save costs and increase the user experience for their customers. Resulting, we believe that this will lead to a whole new standard of web development. 

 

What will you gain from this course?

With the knowledge obtained in this course you’ll be able to develop responsive, high quality web apps without having to fear performance issues due to bad connectivity or issues with the network. 

By enrolling to the course you will acquire new skills and become a pioneer that helps to shape the future of web development.

Want to take this training near you? Suggest a time or place in the comments below.

 

Spring Boot - a perfect platform for a Vaadin UI

Vaadin Framework is a web app UI framework that requires just a Java virtual machine and a servlet container. In theory that is all you need to build your application, but for most real business apps, you are much better off when you base your app on some application framework.

Spring Framework and Spring Boot are among the best things you can use as a basis for your Vaadin application. These together provide a dependency injection container, an easy way to develop and deploy your application without separate application servers and, using Spring Boot’s convetion over configuration approach, a really easy way to consume the large number of other handy Spring projects.

One of the Spring Boot developers, Stéphane Nicoll, visited the Vaadin offices a couple of weeks ago and I had the pleasure to host a webinar with Stéphane, naturally about Spring Boot and Vaadin. The webinar gives you an overview of what you can accomplish with this great combo and also several handy productivity tips for the more experienced Spring users, related to devtools, Spring Data, database schema versioning & updates using Flyway and consuming RESTful web services.

See also the forum thread, with direct links to the example projects.

PS. Vaadin Spring 1.1, which we promised in the webinar, is almost here. Release candidate 1.1.0.rc2 should appear to the pre-release repository tomorrow. More about that soon!