Java Code Examples for com.vaadin.flow.dom.Element#setAttribute()

The following examples show how to use com.vaadin.flow.dom.Element#setAttribute() . 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: SelectView.java    From flow with Apache License 2.0 6 votes vote down vote up
public SelectView() {
    Div log = new Div();
    log.setId("log");

    Element select = new Element("select");
    for (int i = 1; i < 10; i++) {
        select.appendChild(
                new Element("option").setAttribute("id", "id" + i)
                        .setAttribute("value", "value" + i)
                        .setText("Visible text " + i));
    }
    select.setAttribute("id", "input");
    select.addEventListener("change", e -> {
        log.setText("Value is '"
                + e.getEventData().getString("element.value") + "'");
    }).synchronizeProperty("element.value");
    add(log);
    getElement().appendChild(select);
}
 
Example 2
Source File: FlowClassesSerializableTest.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a serialization bug (probably located in JVM ) when serialized
 * {@link Command} is deserialized as some internal lambda and produces
 * {@link ClassCastException}
 *
 * see the workaround in ElementAttributeMap#deferRegistration
 */
@Test
public void streamResource() throws Throwable {
    UI ui = new UI();
    UI.setCurrent(ui);
    try {
        Element element = new Element("dummy-element");
        StreamReceiver streamReceiver = new StreamReceiver(
                element.getNode(), "upload", new MyStreamVariable());
        Assert.assertEquals(ui, UI.getCurrent());
        element.setAttribute("target", streamReceiver);
        serializeAndDeserialize(element);
        assertTrue("Basic smoke test with ",
                element.getAttribute("target").length() > 10);

    } finally {
        UI.setCurrent(null);
    }
}
 
Example 3
Source File: SendMultibyteCharactersUI.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    Push push = getClass().getAnnotation(Push.class);

    getPushConfiguration().setPushMode(push.value());
    getPushConfiguration().setTransport(push.transport());

    Div div = new Div();
    div.setText("Just a label");
    div.setId("label");
    add(div);
    Element area = ElementFactory.createTextarea();
    area.addPropertyChangeListener("value", "change", event -> {
    });
    area.setAttribute("id", "text");
    getElement().appendChild(area);
}
 
Example 4
Source File: ReturnChannelView.java    From flow with Apache License 2.0 6 votes vote down vote up
public ReturnChannelView() {
    Element button = new Element("button");
    button.setAttribute("id", "button");
    button.setText("Send message to channel");

    ReturnChannelRegistration channel = button.getNode()
            .getFeature(ReturnChannelMap.class)
            .registerChannel(arguments -> button.setText(
                    "Click registered: " + arguments.getString(0)));

    button.executeJs(
            "this.addEventListener('click', function() { $0('hello') })",
            channel);

    getElement().appendChild(button);
}
 
Example 5
Source File: NavigationTriggerView.java    From flow with Apache License 2.0 6 votes vote down vote up
public NavigationTriggerView() {
    // Cannot use the RouterLink component since these views are not
    // registered as regular views.
    Element routerLink = ElementFactory
            .createRouterLink(CLASS_NAME + "/routerlink/", "Router link");
    routerLink.setAttribute("id", "routerlink");

    Element navigateButton = ElementFactory.createButton("UI.navigate");
    navigateButton.addEventListener("click",
            e -> getUI().get().navigate(CLASS_NAME + "/navigate"));
    navigateButton.setAttribute("id", "navigate");

    Element forwardButton = ElementFactory.createButton("forward");
    forwardButton.addEventListener("click", e -> getUI().get()
            .navigate(NavigationTriggerView.class, "forward"));
    forwardButton.setAttribute("id", "forwardButton");

    Element rerouteButton = ElementFactory.createButton("reroute");
    rerouteButton.addEventListener("click", e -> getUI().get()
            .navigate(NavigationTriggerView.class, "reroute"));
    rerouteButton.setAttribute("id", "rerouteButton");

    getElement().appendChild(routerLink, navigateButton, forwardButton,
            rerouteButton);
}
 
Example 6
Source File: SynchronizedPropertyView.java    From flow with Apache License 2.0 6 votes vote down vote up
private void addSyncWithInitialValue() {
    add(new Text("Synchronized on 'change' event with initial value"));
    final Div syncOnChangeInitialValueLabel = new Div();
    syncOnChangeInitialValueLabel.setId("syncOnChangeInitialValueLabel");
    Element syncOnChangeInitialValue = ElementFactory.createInput();
    syncOnChangeInitialValueLabel.setText("Server value on create: "
            + syncOnChangeInitialValue.getProperty("value"));
    syncOnChangeInitialValue.setAttribute("id", "syncOnChangeInitialValue");
    syncOnChangeInitialValue.addPropertyChangeListener("value", "change",
            event -> {
            });
    syncOnChangeInitialValue.addEventListener("change", e -> {
        syncOnChangeInitialValueLabel
                .setText("Server value in change listener: "
                        + syncOnChangeInitialValue.getProperty("value"));
    });
    syncOnChangeInitialValue.setProperty("value", "initial");

    getElement().appendChild(syncOnChangeInitialValue);
    add(syncOnChangeInitialValueLabel);
}
 
Example 7
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 8
Source File: ComponentTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void wrappedComponentUsesElement() {
    Element div = new Element("div");
    div.setAttribute("id", "foo");
    Assert.assertEquals(Optional.of("foo"), div.as(TestDiv.class).getId());

}
 
Example 9
Source File: SourceContent.java    From flow with Apache License 2.0 5 votes vote down vote up
private void addSourceCodeBlock(String text, String className) {
    Element pre = new Element("pre");
    Element code = new Element("code");
    pre.appendChild(code);
    code.setAttribute("spellcheck", "false");
    code.getClassList().add(className);
    code.setText(text);
    getElement().appendChild(pre);
    code.executeJs("Prism.highlightElement(this);");
}
 
Example 10
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;
}
 
Example 11
Source File: EventHandlerView.java    From flow with Apache License 2.0 5 votes vote down vote up
@ClientCallable
private String handleClientCall(String msg, boolean enabled) {
    if (!enabled) {
        throw new RuntimeException("Method is not enabled");
    }
    Element div = ElementFactory.createDiv(
            "Call from client, message: " + msg + ", " + enabled);
    div.setAttribute("id", "client-call");
    getParent().get().getElement().appendChild(div);

    return msg.toUpperCase();
}
 
Example 12
Source File: EventHandlerView.java    From flow with Apache License 2.0 5 votes vote down vote up
@EventHandler
private void overriddenClick(@EventData("event.result") String result) {
    Element label = ElementFactory.createLabel(
            "Overridden server event was invoked with result: " + result);
    label.setAttribute("id", "overridden-event-handler-result");
    getParent().get().getElement().appendChild(label);
}
 
Example 13
Source File: EventHandlerView.java    From flow with Apache License 2.0 5 votes vote down vote up
@EventHandler
private void sendData(@EventData("event.button") int button,
        @EventData("event.type") String type,
        @EventData("event.srcElement.tagName") String tag) {
    Element container = ElementFactory.createDiv();
    container.appendChild(ElementFactory
            .createDiv("Received event from the client with the data:"));
    container.appendChild(ElementFactory.createDiv("button: " + button));
    container.appendChild(ElementFactory.createDiv("type: " + type));
    container.appendChild(ElementFactory
            .createDiv("tag: " + tag.toLowerCase(Locale.ENGLISH)));
    container.setAttribute("id", "event-data");
    getParent().get().getElement().appendChild(container);
}
 
Example 14
Source File: SynchronizedPropertyView.java    From flow with Apache License 2.0 5 votes vote down vote up
private void addSyncMultipleProperties() {
    add(new Text(
            "Synchronize 'value' on 'input' event and 'valueAsNumber' on 'blur'"));
    Div valueLabel = new Div();
    valueLabel.setId("multiSyncValueLabel");
    Div valueAsNumberLabel = new Div();
    valueAsNumberLabel.setId("multiSyncValueAsNumberLabel");

    Element multiSync = ElementFactory.createInput("number");
    multiSync.setAttribute("id", "multiSyncValue");
    multiSync.addPropertyChangeListener("valueAsNumber", "blur", event -> {
    });
    multiSync.addPropertyChangeListener("value", "input", event -> {
    });

    multiSync.addEventListener("input", e -> {
        valueLabel
                .setText("Server value: " + multiSync.getProperty("value"));
    });
    multiSync.addEventListener("blur", e -> {
        valueAsNumberLabel.setText("Server valueAsNumber: "
                + multiSync.getProperty("valueAsNumber"));
    });

    getElement().appendChild(multiSync);
    add(valueLabel, valueAsNumberLabel);
}
 
Example 15
Source File: PushRouteNotFoundView.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
protected void onAttach(AttachEvent attachEvent) {
    if (isPushPath) {
        Element div = ElementFactory.createDiv("Push mode: "
                + attachEvent.getUI().getPushConfiguration().getPushMode());
        div.setAttribute("id", "push-mode");
        getElement().appendChild(div);
    }
}
 
Example 16
Source File: ElementInitOrderView.java    From flow with Apache License 2.0 5 votes vote down vote up
private static Element createElement(String tag) {
    Element element = new Element(tag);
    element.appendChild(new Element("span"));
    element.getStyle().set("animationName", "style");
    element.getClassList().add("class");
    element.setAttribute("attribute", "attribute");
    element.setProperty("property", "property");
    return element;
}
 
Example 17
Source File: EventHandlerView.java    From flow with Apache License 2.0 4 votes vote down vote up
@EventHandler
private void handleClick() {
    Element label = ElementFactory.createLabel("Event handler is invoked");
    label.setAttribute("id", "event-handler-result");
    getParent().get().getElement().appendChild(label);
}
 
Example 18
Source File: BasicElementView.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
protected void onShow() {
    Element mainElement = getElement();
    mainElement.getStyle().set("margin", "1em");

    Element button = ElementFactory.createButton("Click me");

    Element input = ElementFactory.createInput().setAttribute("placeholder",
            "Synchronized on change event");
    input.addPropertyChangeListener("value", "change", event -> {
    });

    button.addEventListener("click", e -> {
        JsonObject eventData = e.getEventData();
        String buttonText = eventData.getString("element.textContent");
        int clientX = (int) eventData.getNumber("event.clientX");
        int clientY = (int) eventData.getNumber("event.clientY");
        Element greeting = ElementFactory.createDiv(
                "Thank you for clicking \"" + buttonText + "\" at ("
                        + clientX + "," + clientY + ")! The field value is "
                        + input.getProperty("value"));
        greeting.setAttribute("class", "thankYou");
        greeting.addEventListener("click",
                e2 -> greeting.removeFromParent());

        mainElement.appendChild(greeting);
    }).addEventData("element.textContent").addEventData("event.clientX")
            .addEventData("event.clientY");

    Element helloWorldElement = ElementFactory.createDiv("Hello world");

    Set<String> spanClasses = helloWorldElement.getClassList();

    helloWorldElement.setProperty("id", "hello-world");
    spanClasses.add("hello");
    helloWorldEventRemover = helloWorldElement.addEventListener("click",
            e -> {
                if (helloWorldElement.getText().equals("Hello world")) {
                    helloWorldElement.setText("Stop touching me!");
                } else {
                    // We never get to this code as long as the event
                    // removal actually works
                    helloWorldElement.setText(helloWorldElement.getText()
                            + " This might be your last warning!");
                }
                spanClasses.clear();
                helloWorldEventRemover.remove();
            });
    Style s = helloWorldElement.getStyle();
    s.set("color", "red");
    s.set("fontWeight", "bold");

    Element elementContainer = ElementFactory.createDiv();

    Element toRemove = ElementFactory.createDiv("To Remove")
            .setAttribute("id", "to-remove");
    elementContainer.appendChild(toRemove);

    elementContainer.setAttribute("id", "addremovecontainer");
    Element addRemoveButton = ElementFactory
            .createButton("Add and remove element");
    addRemoveButton.setAttribute("id", "addremovebutton");

    addRemoveButton.addEventListener("click", e -> {
        // very basic usecase: append and then immediately remove
        Element div = ElementFactory.createDiv("foobar");
        elementContainer.appendChild(div);
        elementContainer.removeChild(div);

        elementContainer.removeChild(toRemove);
        elementContainer.appendChild(toRemove);

        // Now let's have two "add" operation and then two "remove"
        // operation so that removal has an addition right before which
        // targets different element
        Element div2 = ElementFactory.createDiv("foobar");
        elementContainer.appendChild(div);
        elementContainer.appendChild(div2);

        Element ok = ElementFactory.createDiv("OK");
        ok.setAttribute("id", "ok");
        elementContainer.appendChild(ok);

        elementContainer.removeChild(div);
        elementContainer.removeChild(div2);
    });

    mainElement.appendChild(helloWorldElement, button, input,
            addRemoveButton, elementContainer);

}
 
Example 19
Source File: DomEventFilterView.java    From flow with Apache License 2.0 4 votes vote down vote up
public DomEventFilterView() {
    Element space = new Element("input");
    space.setAttribute("id", "space");

    space.addEventListener("keypress",
            e -> addMessage("Space listener triggered"))
            .setFilter("event.key == ' ' || event.key == 'Spacebar'");
    // The key is called 'Spacebar' on IE11

    Element debounce = new Element("input");
    debounce.setAttribute("id", "debounce");

    debounce.addEventListener("input",
            e -> addMessage("Trailing: "
                    + e.getEventData().getString("element.value")))
            .debounce(1000).addEventData("element.value");
    debounce.addEventListener("input",
            e -> addMessage("Leading: "
                    + e.getEventData().getString("element.value")))
            .debounce(1000, DebouncePhase.LEADING);
    debounce.addEventListener("input",
            e -> addMessage("Throttle: "
                    + e.getEventData().getString("element.value")))
            .throttle(1000);

    DebounceComponent component = new DebounceComponent();
    component.setId("debounce-component");
    component.addInputListener(
            e -> addMessage("Component: " + e.getValue()), 1000);

    messages.setAttribute("id", "messages");
    getElement().appendChild(space, debounce, component.getElement(),
            messages);

    // tests for#5090
    final AtomicReference<DomListenerRegistration> atomicReference = new AtomicReference<>();
    final Paragraph resultParagraph = new Paragraph();
    resultParagraph.setId("result-paragraph");

    NativeButton removalButton = new NativeButton("Remove DOM listener", event -> {
        resultParagraph.setText("REMOVED");
        atomicReference.get().remove();
    });
    removalButton.setId("listener-removal-button");

    Input listenerInput = new Input(ValueChangeMode.ON_CHANGE);
    listenerInput.setId("listener-input");

    /*
    The event.preventDefault() is here to make sure that the listener
     has been cleaned on the client-side as well. The server-side
     cleaning is not really in question.
     */
    ComponentUtil.addListener(listenerInput, KeyDownEvent.class,
            event -> resultParagraph.setText("A"), registration -> {
                atomicReference.set(registration);
                registration.setFilter("event.key === 'a' && " +
                        "(event.preventDefault() || true)");
            });
    ComponentUtil.addListener(listenerInput, KeyDownEvent.class,
            event -> resultParagraph.setText("B"),
            registration -> registration.setFilter("event.key === 'b' && " +
                    "(event.preventDefault() || true)"));

    add(listenerInput, removalButton, resultParagraph);
}
 
Example 20
Source File: ScriptInjectView.java    From flow with Apache License 2.0 4 votes vote down vote up
private void createInput(String endTag) {
    String string = getValue(endTag);
    Element input = ElementFactory.createInput();
    input.setAttribute("value", string);
    getElement().appendChild(input);
}