### Basic Combo Box Setup Source: https://github.com/vaadin/docs/blob/main/articles/components/combo-box/index.adoc Demonstrates the basic setup for a Vaadin Combo Box component. This example shows how to initialize the component with a list of options. ```typescript import { html, LitElement, TemplateResult } from "lit"; import { customElement, property, } from "lit/decorators"; import "@vaadin/combo-box"; import type { ComboBoxLitRenderer, ComboBoxItemModel, } from "@vaadin/combo-box"; interface Country { label: string; code: string; } @customElement("combo-box-basic-lit") export class ComboBoxBasicLit extends LitElement { @property({ type: Array }) items: Country[] = [ { label: "Austria", code: "AT" }, { label: "Belgium", code: "BE" }, { label: "Bulgaria", code: "BG" }, { label: "Croatia", code: "HR" }, { label: "Cyprus", code: "CY" }, { label: "Czech Republic", code: "CZ" }, { label: "Denmark", code: "DK" }, { label: "Estonia", code: "EE" }, { label: "Finland", code: "FI" }, { label: "France", code: "FR" }, { label: "Germany", code: "DE" }, { label: "Greece", code: "GR" }, { label: "Hungary", code: "HU" }, { label: "Ireland", code: "IE" }, { label: "Italy", code: "IT" }, { label: "Latvia", code: "LV" }, { label: "Lithuania", code: "LT" }, { label: "Luxembourg", code: "LU" }, { label: "Malta", code: "MT" }, { label: "Netherlands", code: "NL" }, { label: "Poland", code: "PL" }, { label: "Portugal", code: "PT" }, { label: "Romania", code: "RO" }, { label: "Slovakia", code: "SK" }, { label: "Slovenia", code: "SI" }, { label: "Spain", code: "ES" }, { label: "Sweden", code: "SE" }, ]; render(): TemplateResult { return html` `; } } ``` ```java package com.vaadin.demo.component.combobox; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.router.Route; import java.util.Arrays; import java.util.List; @Route("combo-box-basic") public class ComboBoxBasic extends Div { public ComboBoxBasic() { // tag::snippet[] ComboBox comboBox = new ComboBox<>("Country"); comboBox.setItems(getCountries()); comboBox.setItemLabelGenerator(Country::getLabel); add(comboBox); // end::snippet[] } private List getCountries() { return Arrays.asList( new Country("Austria", "AT"), new Country("Belgium", "BE"), new Country("Bulgaria", "BG"), new Country("Croatia", "HR"), new Country("Cyprus", "CY"), new Country("Czech Republic", "CZ"), new Country("Denmark", "DK"), new Country("Estonia", "EE"), new Country("Finland", "FI"), new Country("France", "FR"), new Country("Germany", "DE"), new Country("Greece", "GR"), new Country("Hungary", "HU"), new Country("Ireland", "IE"), new Country("Italy", "IT"), new Country("Latvia", "LV"), new Country("Lithuania", "LT"), new Country("Luxembourg", "LU"), new Country("Malta", "MT"), new Country("Netherlands", "NL"), new Country("Poland", "PL"), new Country("Portugal", "PT"), new Country("Romania", "RO"), new Country("Slovakia", "SK"), new Country("Slovenia", "SI"), new Country("Spain", "ES"), new Country("Sweden", "SE") ); } } ``` ```tsx import React, { useState, useEffect } from 'react'; import { ComboBox, ComboBoxItem, } from '@vaadin/react-components/ComboBox'; interface Country { label: string; code: string; } export const ComboBoxBasic = () => { const [countries, setCountries] = useState([]); useEffect(() => { // In a real application, you would fetch this data from an API const fetchedCountries: Country[] = [ { label: 'Austria', code: 'AT' }, { label: 'Belgium', code: 'BE' }, { label: 'Bulgaria', code: 'BG' }, { label: 'Croatia', code: 'HR' }, { label: 'Cyprus', code: 'CY' }, { label: 'Czech Republic', code: 'CZ' }, { label: 'Denmark', code: 'DK' }, { label: 'Estonia', code: 'EE' }, { label: 'Finland', code: 'FI' }, { label: 'France', code: 'FR' }, { label: 'Germany', code: 'DE' }, { label: 'Greece', code: 'GR' }, { label: 'Hungary', code: 'HU' }, { label: 'Ireland', code: 'IE' }, { label: 'Italy', code: 'IT' }, { label: 'Latvia', code: 'LV' }, { label: 'Lithuania', code: 'LT' }, { label: 'Luxembourg', code: 'LU' }, { label: 'Malta', code: 'MT' }, { label: 'Netherlands', code: 'NL' }, { label: 'Poland', code: 'PL' }, { label: 'Portugal', code: 'PT' }, { label: 'Romania', code: 'RO' }, { label: 'Slovakia', code: 'SK' }, { label: 'Slovenia', code: 'SI' }, { label: 'Spain', code: 'ES' }, { label: 'Sweden', code: 'SE' }, ]; setCountries(fetchedCountries); }, []); return (
); }; ``` -------------------------------- ### Waterfall Chart Setup Source: https://github.com/vaadin/docs/blob/main/articles/components/charts/charttypes.adoc Example of how to create and configure a Waterfall chart. ```APIDOC ## POST /api/charts/waterfall ### Description Creates and configures a Waterfall chart. ### Method POST ### Endpoint /api/charts/waterfall ### Request Body - **chartType** (string) - Required - The type of chart, should be 'WATERFALL'. - **dataSeries** (object) - Required - Configuration for the data series. - **configuration** (object) - Optional - General chart configuration. ### Request Example ```json { "chartType": "WATERFALL", "dataSeries": { "items": [ {"name": "Start", "y": 120000}, {"name": "Product Revenue", "y": 569000}, {"name": "Service Revenue", "y": 231000}, {"name": "Positive Balance", "intermediate": true}, {"name": "Fixed Costs", "y": -342000}, {"name": "Variable Costs", "y": -233000}, {"name": "Balance"} ] }, "configuration": { "xAxis": { "type": "CATEGORY" }, "plotOptions": { "waterfall": { "dataLabels": { "enabled": true, "verticalAlign": "TOP", "y": -30, "formatter": "function() { return this.y / 1000 + 'k'; }" } } } } } ``` ### Response #### Success Response (200) - **chartId** (string) - The ID of the created chart. #### Response Example ```json { "chartId": "chart123" } ``` ``` -------------------------------- ### Populate Tree Grid with Root Items and Child Provider Source: https://github.com/vaadin/docs/blob/main/articles/components/tree-grid/data-binding.adoc Use the `setItems` method for a quick setup from a collection of root items and a callback that returns their children. This example demonstrates creating a folder hierarchy. ```java Folder invoices = new Folder("Invoices", List.of()); Folder documents = new Folder("Documents", List.of(invoices)); Folder work = new Folder("Work", List.of(documents)); Folder family = new Folder("Family", List.of()); // First argument: root-level folders shown at the top level of the tree. // Second argument: a callback that returns the children of each folder. treeGrid.setItems(List.of(work, family), Folder::children); // Result: // // ├── Work // │ ├── Documents // │ ├── Invoices // └── Family ``` ```java public record Folder(String name, List children) {} ``` -------------------------------- ### Full Maven Configuration for Load Testing Source: https://github.com/vaadin/docs/blob/main/articles/flow/testing/load-testing/index.adoc A comprehensive Maven configuration example demonstrating the entire load testing workflow. This includes starting the server, recording scenarios, running load tests, and stopping the server. ```xml 8081 my-app.jar 8082 com.vaadin testbench-converter-plugin ${vaadin.version} start-server start-server ${project.build.directory}/${applicationJar} ${serverPort} ${managementPort} record-scenarios integration-test record HelloWorldIT CrudExampleIT ${serverPort} run-load-tests integration-test run 100 2m ${serverPort} true true helloWorld:70,crudExample:30 ``` -------------------------------- ### Install Observability Kit Client Package Source: https://github.com/vaadin/docs/blob/main/articles/tools/observability/getting-started.adoc Execute this command in your terminal to install the client-side component of the Observability Kit. ```bash npm install @hilla/observability-kit-client ``` -------------------------------- ### Binder Integration Example Source: https://github.com/vaadin/docs/blob/main/articles/flow/ui-state/usage-examples/binder-integration.adoc This is the main example demonstrating Binder integration with signals for dynamic validation. ```java ValueSignal accountTypeSignal = new ValueSignal<>(AccountType.PERSONAL); ValueSignal ageSignal = new ValueSignal<>(0); accountTypeSelect.bindValue(accountTypeSignal, accountTypeSignal::set); ageField.bindValue(ageSignal, ageSignal::set); Signal ageValidSignal = Signal.computed(() -> { Integer age = ageSignal.get(); AccountType accountType = accountTypeSignal.get(); if (age == null) { return false; } return accountType == AccountType.BUSINESS ? age >= 18 : age >= 14; }); binder.forField(ageField) .withValidator(value -> ageValidSignal.get(), value -> { AccountType accountType = accountTypeSignal.get(); return accountType == AccountType.BUSINESS ? "Business accounts require age 18 or older" : "Personal accounts require age 14 or older"; }) .bind("age"); Binder.Binding pwBinding = binder .forField(passwordField) .withValidator(value -> value != null && value.length() >= 8, "Password must be at least 8 characters") .bind("password"); binder.forField(confirmPasswordField) .withValidator(value -> value != null && value.equals(pwBinding.valueSignal().get()), "Passwords do not match") .bind("confirmPassword"); submitButton.bindEnabled( binder.validationStatusSignal().map(BinderValidationStatus::isOk)); ``` -------------------------------- ### Start Design System Publisher Development Server Source: https://github.com/vaadin/docs/blob/main/articles/flow/kb/index.adoc Command to start the development server for Design System Publisher. Ensure npm scripts are not ignored and necessary tools like Xcode command line tools (on macOS) are installed. ```bash npm run dspublisher:start ``` -------------------------------- ### Basic Master-Detail Layout Example Source: https://github.com/vaadin/docs/blob/main/articles/components/master-detail-layout/index.adoc This example demonstrates a typical Master-Detail Layout setup where clicking a table row reveals the detail area. The layout is responsive and can switch to an overlay when space is limited. It requires importing the component and defining the master and detail content. ```typescript import "@vaadin/master-detail-layout/theme/lumo/vaadin-master-detail-layout.js"; import "@vaadin/grid/theme/lumo/vaadin-grid.js"; import "@vaadin/button/theme/lumo/vaadin-button.js"; import { MasterDetailLayout, MasterDetailLayoutOpenedChangeEvent, } from "@vaadin/master-detail-layout"; import "@vaadin/master-detail-layout/src/vaadin-master-detail-layout-overlay.js"; const masterDetailLayout = document.createElement("vaadin-master-detail-layout"); const personList = document.createElement("person-list"); personList.items = [ { name: "Alice", surname: "Smith", email: "alice@example.com" }, { name: "Bob", surname: "Johnson", email: "bob@example.com" }, { name: "Charlie", surname: "Williams", email: "charlie@example.com" }, ]; personList.addEventListener("item-click", (e: CustomEvent) => { masterDetailLayout.detailVisible = true; masterDetailLayout.detail = document.createElement("person-detail"); (masterDetailLayout.detail as PersonDetail).person = e.detail; }); masterDetailLayout.appendChild(personList); masterDetailLayout.addEventListener( "opened-change", (e: CustomEvent) => { if (!e.detail.value) { masterDetailLayout.detail = null; } } ); document.body.appendChild(masterDetailLayout); customElements.define("person-list", class PersonList extends HTMLElement { set items(items: Person[]) { this.innerHTML = "
    " + items .map( (item) => `
  • ${item.name} ${item.surname}
  • ` ) .join("") + "
"; this.querySelectorAll("li").forEach((li) => { li.addEventListener("click", () => { const email = li.dataset.email; const item = items.find((item) => item.email === email); if (item) { this.dispatchEvent( new CustomEvent("item-click", { detail: item, }) ); } }); }); } }); customElements.define("person-detail", class PersonDetail extends HTMLElement { set person(person: Person) { this.innerHTML = `

${person.name} ${person.surname}

${person.email}

`; } }); interface Person { name: string; surname: string; email: string; } ``` -------------------------------- ### Combined Code Examples for UI Components Source: https://github.com/vaadin/docs/blob/main/articles/contributing/docs/dspublisher/editing.adoc Demonstrates how to group related Java and data model code examples within a single block using the AsciiDoc 'example' style. ```java List people = DataService.`getPeople(); // See Person.java` VirtualList list = new VirtualList<>(); list.setItems(people); ``` ```java public class Person { // The source of the Person object } ``` ```java public class Address { // The source of the Address object } ``` -------------------------------- ### Run Vaadin Design System Documentation Server Source: https://github.com/vaadin/docs/blob/main/articles/contributing/docs/dspublisher/production.adoc Starts the executable, server-side counterpart for the documentation website. This JAR file responds to client requests and is necessary for live examples with Java code. ```bash java -jar docs.jar ``` -------------------------------- ### Minimal Custom AI Controller Implementation Source: https://github.com/vaadin/docs/blob/main/articles/flow/ai-support/controllers.adoc This example demonstrates a basic implementation of the AIController interface, defining a single tool for retrieving weather information. It includes the necessary methods for getting tools, handling responses, and defining tool specifications like name, description, parameters schema, and execution logic. ```java public class WeatherController implements AIController { @Override public List getTools() { return List.of(new LLMProvider.ToolSpec() { @Override public String getName() { return "get_weather"; } @Override public String getDescription() { return "Returns the current weather for a city."; } @Override public String getParametersSchema() { return """ { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] }""" } @Override public String execute(JsonNode arguments) { String city = arguments.get("city").asString(); return weatherService.lookup(city); } }); } @Override public void onResponse(Throwable error) { if (error != null) { return; } // Apply any deferred state changes here. } } ``` -------------------------------- ### Install Hilla SSO Kit Client for Lit Source: https://github.com/vaadin/docs/blob/main/articles/tools/sso/getting-started/hilla.adoc Install the SSO Kit client dependency for Lit applications. This provides the `SingleSignOnContext` class. ```bash npm install --save @hilla/sso-kit-client-lit ``` -------------------------------- ### Full Master-Detail View Example Source: https://github.com/vaadin/docs/blob/main/articles/building-apps/views/add-master-detail.adoc This is a complete example of a master-detail view that can be copied into a Vaadin project. ```java package com.vaadin.demo.buildingapps.masterdetail; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.ListItem; import com.vaadin.flow.component.html.Paragraph; import com.vaadin.flow.component.html.Ul; import com.vaadin.flow.component.orderedlayout.FlexLayout; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteAlias; import com.vaadin.ui.MasterDetailLayout; import com.vaadin.ui.Signal; @Route("building-apps/master-detail") @RouteAlias("building-apps/master-detail-view") public class MasterDetailView extends MasterDetailLayout { private static final String[] ITEMS = {"Alice", "Bob", "Charlie", "David", "Eve"}; MasterDetailView() { setSizeFull(); // Master component Ul list = new Ul(); list.setHeightFull(); list.getStyle().set("overflow-y", "auto"); // Signal to hold the selection Signal selection = Signal.create(); // Add items to the master list for (String item : ITEMS) { ListItem listItem = new ListItem(new Button(item, e -> selection.set(item))); list.add(listItem); } // Add a button to clear the selection list.add(new ListItem(new Button("Master only", e -> selection.clear()))); setMasterComponent(list); // Detail component Div detailContainer = new Div(); detailContainer.setSizeFull(); detailContainer.getStyle().set("padding", "var(--lumo-space-m)"); // Placeholder for when nothing is selected Paragraph placeholder = new Paragraph("Select an item from the list."); placeholder.getStyle().set("color", "var(--lumo-secondary-text-color)"); placeholder.getStyle().set("margin", "0"); detailContainer.add(placeholder); // Signal effect to update the detail component selection.createEffect(selectedItem -> { detailContainer.removeAll(); if (selectedItem == null) { detailContainer.add(placeholder); } else { H2 title = new H2("Details for " + selectedItem); detailContainer.add(title); detailContainer.add(new Paragraph("This is the detail view for " + selectedItem + ".")); // In a real app, you would load more data here } return null; }); setDetailComponent(detailContainer); } } ``` -------------------------------- ### Start Jetty Server for Testing Source: https://github.com/vaadin/docs/blob/main/articles/contributing/tests.adoc Command to start the Jetty server for a specific Vaadin test module to allow browser-based testing. ```shell mvn jetty:run -pl flow-test-core ``` -------------------------------- ### Install Linux Dependencies for Vaadin Source: https://github.com/vaadin/docs/blob/main/articles/flow/kb/index.adoc Install necessary build dependencies on Linux systems when the application fails to start. Ensure all listed packages are installed. ```bash sudo apt install build-essential autoconf automake libtool pkg-config libpng-dev nasm zlib1g-dev ``` -------------------------------- ### Basic GridAIController Setup Source: https://github.com/vaadin/docs/blob/main/articles/flow/ai-support/ai-powered-grid.adoc Initialize a Grid with AIDataRow, create a DatabaseProvider, and set up the GridAIController. Attach the controller to an AIOrchestrator to enable natural language data population. ```java Grid grid = new Grid<>(); MessageInput messageInput = new MessageInput(); DatabaseProvider databaseProvider = new JdbcDatabaseProvider(dataSource); GridAIController controller = new GridAIController(grid, databaseProvider); AIOrchestrator.builder(provider, systemPrompt) .withInput(messageInput) .withController(controller) .build(); add(messageInput, grid); ``` -------------------------------- ### Start Local Server with Maven Source: https://github.com/vaadin/docs/blob/main/articles/building-apps/components/package-component.adoc Run this command to start a local Jetty server for testing your add-on. It configures the server to use the `test` classpath, making classes in `src/test/java` available as routes. ```terminal mvn ``` -------------------------------- ### Context Menu Best Practices (Flow) Source: https://github.com/vaadin/docs/blob/main/articles/components/context-menu/index.adoc Example demonstrating best practices for Context Menu usage, including opening on right-click and using icons and labels appropriately. ```java contextMenu.setOpenWithMouseEvents(true); contextMenu.setOpenWithTouchEvents(true); ``` -------------------------------- ### Set and Get Rich Text Editor Value (Flow) Source: https://github.com/vaadin/docs/blob/main/articles/components/rich-text-editor/index.adoc Example of setting and getting the HTML value of the Rich Text Editor component in a Vaadin Flow application. ```java RichTextEditor richTextEditor = new RichTextEditor(); richTextEditor.setHtmlValue("

This is bold text

"); // ... String value = richTextEditor.getHtmlValue(); ``` -------------------------------- ### Page Hierarchy Example Source: https://github.com/vaadin/docs/blob/main/articles/contributing/docs/dspublisher/editing.adoc Demonstrates how file paths map to website URLs and navigation hierarchy using AsciiDoc. ```text | Path | URL | Navigation hierarchy | `articles/components/button/style.adoc` | `\https://localhost:8000/components/button/style` | menu:Components[Button → Style] |=== ``` -------------------------------- ### Start Background Job with Callbacks Source: https://github.com/vaadin/docs/blob/main/articles/building-apps/server-push/callbacks.adoc This example demonstrates starting a background job and using UI.accessLater() to schedule UI updates for completion, progress, and failure. The UI updates are safely handled by the Vaadin framework. ```java button.addClickListener(clickEvent -> { var ui = UI.getCurrentOrThrow(); service.startBackgroundJob( ui.accessLater(this::onJobCompleted, null), // <1> ui.accessLater(progressBar::setValue, null), ui.accessLater(this::onJobFailed, null) ); }); ``` -------------------------------- ### Pyramid Chart Example (TypeScript/Java) Source: https://github.com/vaadin/docs/blob/main/articles/components/charts/charttypes.adoc Illustrates how to implement a pyramid chart. This example provides code for both web component (TypeScript) and Vaadin Flow (Java) integrations, covering basic chart setup and data series. ```typescript include::{root}/frontend/demo/component/charts/charttypes/chart-type-libraries.ts[preimport,hidden] ``` ```java include::{root}/src/main/java/com/vaadin/demo/component/charts/charttypes/ChartTypePyramid.java[render,tags=snippet,indent=0,group=Flow] ``` -------------------------------- ### Complete Responsive AlignItems Example Source: https://github.com/vaadin/docs/blob/main/articles/styling/themes/lumo/lumo-breakpoint.adoc Demonstrates a full example of creating a responsive flex container with varying `align-items` properties across different breakpoints. This is useful for building adaptive UI layouts. ```java import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H3; import com.vaadin.flow.theme.lumo.LumoUtility; public class ResponsiveAlignItemsExample extends Div { public ResponsiveAlignItemsExample() { H3 title = new H3("Responsive Align Items Example"); Div responsiveContainer = new Div(); responsiveContainer.addClassNames( LumoUtility.Display.FLEX, LumoUtility.FlexDirection.COLUMN, LumoUtility.Padding.MEDIUM, LumoUtility.AlignItems.END, LumoUtility.AlignItems.Breakpoint.Medium.CENTER, LumoUtility.AlignItems.Breakpoint.Large.START ); responsiveContainer.add( new Button("Button 1"), new Button("Button 2"), new Button("Button 3") ); add(title, responsiveContainer); } } ``` -------------------------------- ### Basic Map Setup Source: https://github.com/vaadin/docs/blob/main/articles/components/map/index.adoc Demonstrates the basic setup for the Map component. Ensure you have a commercial map data service arranged for production use, as OpenStreetMap is only for development. ```java include::{root}/src/main/java/com/vaadin/demo/component/map/MapBasic.java[render,tags=snippet,indent=0,group=Flow] ``` -------------------------------- ### Fill Form (JUnit 5) Source: https://github.com/vaadin/docs/blob/main/articles/flow/testing/end-to-end/creating-tests.adoc This example shows a test method using JUnit 5's `@BrowserTest` annotation. It demonstrates filling text fields, similar to the JUnit 4 example, highlighting the setup for newer JUnit versions. ```java @BrowserTest public void fillForm() { $(TextFieldElement.class).id("firstName").setValue("John"); ``` -------------------------------- ### Configure DSPublisher to Load All Frontend Resources Source: https://github.com/vaadin/docs/blob/main/articles/contributing/docs/dspublisher/editing.adoc Configures DSPublisher to load all frontend resources upfront using the `DOCS_IMPORT_EXAMPLE_RESOURCES` option. This allows including Java examples without a separate hidden TypeScript example. ```terminal DOCS_IMPORT_EXAMPLE_RESOURCES="true" npm run dspublisher:start ``` -------------------------------- ### Basic Message Input configuration Source: https://github.com/vaadin/docs/blob/main/articles/components/message-input/index.adoc A standard configuration example for the Message Input component. This shows the basic setup required to integrate the component into a view. ```typescript const messageInput = document.createElement('vaadin-message-input'); document.body.appendChild(messageInput); ``` ```java MessageInput messageInput = new MessageInput(); add(messageInput); ``` ```tsx ``` -------------------------------- ### Context Menu Best Practices (Lit) Source: https://github.com/vaadin/docs/blob/main/articles/components/context-menu/index.adoc Example demonstrating best practices for Context Menu usage, including opening on right-click and using icons and labels appropriately. ```typescript contextMenu.open(event.target); ``` ```typescript Item with icon Action... ``` -------------------------------- ### Custom ComboBox Filtering Logic Source: https://github.com/vaadin/docs/blob/main/articles/components/combo-box/index.adoc Implement custom filtering logic for a ComboBox. This example filters items to show only those that start with the user's input. ```typescript import { html, render } from "lit"; import "@vaadin/combo-box"; const comboBox = document.createElement("vaadin-combo-box"); comboBox.label = "Fruit"; comboBox.items = [ { label: "Apple", value: "apple" }, { label: "Apricot", value: "apricot" }, { label: "Banana", value: "banana" }, { label: "Orange", value: "orange" }, ]; // Custom filtering logic: only items starting with the input comboBox.filter = (item, value) => { return item.label.toLowerCase().startsWith(value.toLowerCase()); }; document.body.appendChild(comboBox); ``` ```java package com.vaadin.demo.component.combobox; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.router.Route; import java.util.Arrays; @Route("combo-box-filtering-custom") public class ComboBoxFiltering2 extends Div { public ComboBoxFiltering2() { ComboBox comboBox = new ComboBox<>("Fruit"); comboBox.setItems(Arrays.asList("Apple", "Apricot", "Banana", "Orange")); // Custom filtering logic: only items starting with the input comboBox.setItems(query -> Arrays.stream(new String[] { "Apple", "Apricot", "Banana", "Orange" }).filter(s -> s.toLowerCase().startsWith(query.getFilter().toLowerCase())).limit(20)); add(comboBox); } } ``` ```tsx import { ComboBox } from "@vaadin/react-components"; import { useState } from "react"; const fruits = [ { label: "Apple", value: "apple" }, { label: "Apricot", value: "apricot" }, { label: "Banana", value: "banana" }, { label: "Orange", value: "orange" }, ]; export const ComboBoxFilteringCustom = () => { const [fruit, setFruit] = useState(""); const filterFruits = (value: string) => { return fruits.filter((item) => item.label.toLowerCase().startsWith(value.toLowerCase()) ); }; return ( setFruit(value)} /> ); }; ``` -------------------------------- ### Custom Field Styles (React) Source: https://github.com/vaadin/docs/blob/main/articles/components/custom-field/styling.adoc Example of how to style the Custom Field component in a React application. This snippet is intended for use within a React project setup. ```tsx include::{root}/frontend/demo/component/custom-field/react/custom-field-styles.tsx[render,tags=snippet,indent=0,group=React] ``` -------------------------------- ### Collaboration Avatar Group - Getting Started Source: https://github.com/vaadin/docs/blob/main/articles/tools/collaboration/components/collaboration-avatar-group.adoc This snippet shows how to initialize and add the CollaborationAvatarGroup to your Vaadin view. It requires providing user information and a topic identifier. ```APIDOC ## Collaboration Avatar Group - Getting Started ### Description Initializes and adds the `CollaborationAvatarGroup` component to a Vaadin view, automatically updating avatars based on user presence within a specified topic. ### Method Not applicable (Java code example) ### Endpoint Not applicable (Java code example) ### Parameters (Java method parameters) ### Request Example (No direct request body, Java initialization) ### Response (No direct response, UI component) #### Success Response (200) (UI updates) #### Response Example (Visual representation of avatars in the UI) ```java // Java code snippet demonstrating initialization // Assuming UserInfo, UserService, and CollaborationAvatarGroup are available // UserInfo represents the current active user UserInfo currentUser = ...; // "insuranceClaims" is a unique identifier for the collaboration topic String topicId = "insuranceClaims"; CollaborationAvatarGroup avatarGroup = new CollaborationAvatarGroup(currentUser, topicId); // Add the component to your view layout add(avatarGroup); ``` ``` -------------------------------- ### Basic AI Orchestrator Setup Source: https://github.com/vaadin/docs/blob/main/articles/flow/ai-support/index.adoc Demonstrates the basic setup of an AI Orchestrator using a mock LLM provider. Replace with a real provider like SpringAILLMProvider or LangChain4JLLMProvider in production. The orchestrator handles message display, LLM interaction, streaming, and history. ```java var orchestrator = AIOrchestrator.builder() .withLLMProvider(new MockLLMProvider()) .withMessageList(messageList) .withMessageInput(messageInput) .build(); ``` -------------------------------- ### Run Vaadin Application Source: https://github.com/vaadin/docs/blob/main/articles/hilla/guides/data-grids/index.adoc Run the Vaadin application using the default Maven goal. This command installs dependencies and starts the application, which may take some time. ```terminal mvn ``` -------------------------------- ### Basic Grid Setup Source: https://github.com/vaadin/docs/blob/main/articles/components/grid/index.adoc Demonstrates the basic setup for a Vaadin Grid component. For Flow, auto-generated columns are possible by passing the bean class to the constructor. ```typescript include::{root}/frontend/demo/component/grid/grid-basic.ts[render,tags=snippet,indent=0,group=Lit] ``` ```java include::{root}/src/main/java/com/vaadin/demo/component/grid/GridBasic.java[render,tags=snippet,indent=0,group=Flow] ``` ```java include::{root}/src/main/java/com/vaadin/demo/domain/Person.java[group=Flow,tags=snippet] ``` ```typescript include::{root}/frontend/demo/component/grid/react/grid-basic.tsx[render,tags=snippet,indent=0,group=React] ``` -------------------------------- ### Register Routes on Application Startup Source: https://github.com/vaadin/docs/blob/main/articles/flow/routing/dynamic.adoc Use `ServiceInitListener` to register routes dynamically when the application starts. This example shows how to add a route only when the application is not in production mode. ```java public class ApplicationServiceInitListener implements VaadinServiceInitListener { @Override public void serviceInit(ServiceInitEvent event) { // add view only during development time if (!event.getSource() .getDeploymentConfiguration() .isProductionMode()) { RouteConfiguration configuration = RouteConfiguration.forApplicationScope(); configuration.setRoute( "crud", //path DBCrudView.class //navigation target ); } } } ``` -------------------------------- ### Spring Security Configuration for Hilla Source: https://github.com/vaadin/docs/blob/main/articles/hilla/guides/security/spring-login.adoc Configure Spring Security to handle authentication for your Hilla application. This example shows basic setup for user details and password encoding. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfiguration { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorize -> authorize .requestMatchers("/login", "/vaadinService/**").permitAll() .requestMatchers("/images/**").permitAll() .requestMatchers("/frontend/**").permitAll() .requestMatchers("/webjars/**").permitAll() .requestMatchers("/actuator/**").hasRole("ADMIN") .anyRequest().authenticated() ) .formLogin(formLogin -> formLogin .loginPage("/login") .permitAll() ) .logout(logout -> logout .logoutSuccessUrl("/login?logout") ); return http.build(); } @Bean public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) { UserDetails user = User.withUsername("user") .password(passwordEncoder.encode("password")) .roles("USER") .build(); UserDetails admin = User.withUsername("admin") .password(passwordEncoder.encode("admin")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user, admin); } @Bean public PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } } ``` -------------------------------- ### Clone and Start Documentation Server Source: https://github.com/vaadin/docs/blob/main/articles/contributing/docs/index.adoc Commands to clone the Vaadin documentation repository and start the local development server using Design System Publisher. ```terminal git clone https://github.com/vaadin/docs cd docs npm run dspublisher:start ``` -------------------------------- ### Project Structure Example Source: https://github.com/vaadin/docs/blob/main/articles/contributing/docs/dspublisher/editing.adoc Illustrates the typical file and directory structure for a documentation project, including content, theme, and source code folders. ```text my-docs <1> ├── articles/ <2> ├── dspublisher/ │ └──docs-theme │ └──global.css <3> ├── frontend/ <4> ├── src/main/java/ <5> └── pom.xml <6> ``` -------------------------------- ### Access and Modify Array Values Source: https://github.com/vaadin/docs/blob/main/articles/hilla/guides/forms/binding-arrays.adoc Access and modify the array bound to the 'tags' field. This example demonstrates how to get the current array, add a new element, and then update the form. ```java var form = new ItemForm(); form.bind("tags", Arrays.asList("tag1", "tag2")); // Get the array List tags = form.get("tags"); // Add a new tag tags.add("tag3"); // Update the form form.set("tags", tags); ``` -------------------------------- ### Context Menu Best Practices (React) Source: https://github.com/vaadin/docs/blob/main/articles/components/context-menu/index.adoc Example demonstrating best practices for Context Menu usage, including opening on right-click and using icons and labels appropriately. ```tsx const contextMenu = useRef(null); useEffect(() => { // Ensure context menu opens on right-click and long-press contextMenu.current?.addEventListener('vaadin-context-menu-open', (e) => { // Handle menu open event }); }, []); return ( Item with icon Action... ); ``` -------------------------------- ### Parameterized Test in JUnit 4 Source: https://github.com/vaadin/docs/blob/main/articles/flow/testing/end-to-end/advanced-concepts.adoc Example of a parameterized test using JUnit 4's @RunWith(Parameterized.class) and @Parameterized.Parameters annotations. Requires TestBenchTestCase and specific setup for driver management. ```java @RunWith(Parameterized.class) public class MyTestClass extends TestBenchTestCase { @Parameterized.Parameters public static Iterable data() { return List.of("first", "second"); } private final String parameter; public MyTestClass(String parameter) { this.parameter = parameter; } @Test public void myTestMethod() { getDriver().get("http://localhost:8080/" + parameter); } @Before public void setup() { setDriver(new ChromeDriver()); } @After public void tearDown() { getDriver().quit(); } } ``` -------------------------------- ### Basic Select Component Usage Source: https://github.com/vaadin/docs/blob/main/articles/components/select/index.adoc Demonstrates the fundamental usage of the Vaadin Select component to allow users to choose a single value from a list of options. This example covers the core functionality and setup. ```typescript import { html, LitElement, TemplateResult } from 'lit'; import { customElement } from 'lit/decorators.js'; @customElement('select-basic-lit') export class SelectBasicLit extends LitElement { protected render(): TemplateResult { return html` `; } } ``` ```java import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.select.Select; import com.vaadin.flow.component.select.SelectVariant; import com.vaadin.flow.router.Route; @Route("select-basic-java") public class SelectBasicJava extends Div { public SelectBasicJava() { // Basic select Select select = new Select("Option 1", "Option 2", "Option 3"); select.setLabel("Basic select"); select.setPlaceholder("Choose an option"); select.addThemeVariants(SelectVariant.LUMO_SMALL); add(select); } } ``` ```tsx import React from 'react'; import { Select, SelectItem } from '@vaadin/react-components/Select'; export const SelectBasicReact = () => { return ( ); }; ``` -------------------------------- ### Funnel Chart Example (TypeScript/Java) Source: https://github.com/vaadin/docs/blob/main/articles/components/charts/charttypes.adoc Demonstrates the creation and configuration of a funnel chart. It includes setup for both web components (TypeScript) and Flow (Java) environments, showcasing how to define chart data and options. ```typescript include::{root}/frontend/demo/component/charts/charttypes/chart-type-libraries.ts[preimport,hidden] ``` ```java include::{root}/src/main/java/com/vaadin/demo/component/charts/charttypes/ChartTypeFunnel.java[render,tags=snippet,indent=0,group=Flow] ``` -------------------------------- ### Clean Documentation Build Source: https://github.com/vaadin/docs/blob/main/CLAUDE.md Commands to clean, start, and build the documentation server using npm. ```bash # Clean npm run dspublisher:clean # Start the documentation server npm run dspublisher:start # Build the documentation for production npm run dspublisher:build ``` -------------------------------- ### Configure CycloneDX Maven Plugin for SBOM Generation Source: https://github.com/vaadin/docs/blob/main/articles/tools/appsec/getting-started.adoc Add this plugin configuration to your pom.xml to generate an aggregate SBOM file from Maven dependencies. Ensure 'maven install' is run before starting the application. ```xml org.cyclonedx cyclonedx-maven-plugin 2.7.7 generate-resources makeAggregateBom library 1.4 true true true true true false false true json bom ${project.build.outputDirectory}/resources false ``` -------------------------------- ### Add Observability Kit Starter Dependency Source: https://github.com/vaadin/docs/blob/main/articles/tools/observability/getting-started.adoc Add the Observability Kit Starter dependency to your project's pom.xml file. ```xml com.vaadin observability-kit-starter ``` -------------------------------- ### Basic Upload Manager Setup (Java) Source: https://github.com/vaadin/docs/blob/main/articles/components/upload/modular-upload.adoc Instantiate an UploadManager and pass it to UI components like UploadButton and UploadFileList. Components automatically synchronize with the manager's state. ```java UploadManager manager = new UploadManager((file, progress) -> { // Handle file upload logic here System.out.println("Uploading file: " + file.getFileName()); // Simulate upload progress for (int uploaded = 0; uploaded < 100; uploaded += 10) { try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } progress.accept(uploaded); } System.out.println("Upload complete for: " + file.getFileName()); }); UploadButton uploadButton = new UploadButton(); uploadButton.setManager(manager); UploadFileList fileList = new UploadFileList(); fileList.setManager(manager); add(uploadButton, fileList); ``` -------------------------------- ### Handle pasted files in batches with PasteFileHandler Source: https://github.com/vaadin/docs/blob/main/articles/flow/browser-apis/clipboard-api.adoc Manage paste events in batches, handling the start, individual files, and completion of a paste gesture. This example shows progress updates during the paste process. ```java Clipboard.onFilePaste(this, PasteFileHandler.batch() .onStart(start -> progress.setVisible(true)) .onFile(file -> addAttachment(file.fileName(), file.bytes())) .onComplete(complete -> progress.setVisible(false)) .build()); ``` -------------------------------- ### Build for Production Source: https://github.com/vaadin/docs/blob/main/articles/hilla/lit/guides/upgrading/index.adoc Demonstrates the command to build the project in production mode using the updated vaadin.productionMode property. ```bash ./gradlew -Pvaadin.productionMode build ``` -------------------------------- ### Basic Features of Radio Button Group Source: https://github.com/vaadin/docs/blob/main/articles/components/radio-button/index.adoc Illustrates the fundamental features and usage of the Radio Button Group component. This includes basic setup and interaction patterns. Examples are provided for Lit, Flow, and React. ```typescript include::{root}/frontend/demo/component/radiobutton/radio-button-group-basic-features.ts[render,tags=snippet,indent=0,group=Lit] ``` ```java include::{root}/src/main/java/com/vaadin/demo/component/radiobutton/RadioButtonGroupBasicFeatures.java[render,tags=snippet,indent=0,group=Flow] ``` ```tsx include::{root}/frontend/demo/component/radiobutton/react/radio-button-group-basic-features.tsx[render,tags=snippet,indent=0,group=React] ``` -------------------------------- ### Add SSO Kit Starter Dependency Source: https://github.com/vaadin/docs/blob/main/articles/tools/sso/getting-started/hilla.adoc Include the SSO Kit starter module in your project's pom.xml to enable backend SSO functionality. Check the SSO Kit releases page for the latest version. ```xml com.vaadin.hilla sso-kit-starter 2.1.0 ``` -------------------------------- ### Initialize Hilla Starter Application Source: https://github.com/vaadin/docs/blob/main/articles/hilla/lit/guides/production/cloud-providers/azure/index.adoc Commands to initialize a new Hilla project using the CLI. Use the Lit version for Lit-based projects or the standard command for React-based projects. ```terminal npx @hilla/cli init --lit my-app ``` ```terminal npx @hilla/cli init my-app ```