> Markdown version of [Dashboard](https://vaadin.com/docs/v24/components/dashboard). Section index: [llms.txt](https://vaadin.com/docs/v24/components/llms.txt)

# Dashboard

A component for building static dashboard layouts and dynamic, user-configurable dashboards.

> **Note: Commercial Feature**
>
> A commercial Vaadin subscription is required to use Dashboard in your project.
>
> - [Start Free Trial](https://vaadin.com/trial)
>
> - [See Pricing](https://vaadin.com/pricing)

**Flow** — `DashboardBasic.java`

```java
Dashboard dashboard = new Dashboard();
dashboard.setMinimumColumnWidth("150px");
dashboard.setMaximumColumnCount(3);

DashboardWidget visitors = new DashboardWidget("Visitors");
visitors.setContent(createWidgetContent());
dashboard.add(visitors);

DashboardWidget downloads = new DashboardWidget("Downloads");
downloads.setContent(createWidgetContent());
dashboard.add(downloads);

DashboardWidget conversions = new DashboardWidget("Conversions");
conversions.setContent(createWidgetContent());
dashboard.add(conversions);

DashboardWidget visitorsByCountry = new DashboardWidget(
        "Visitors by country");
visitorsByCountry.setContent(createWidgetContent());
visitorsByCountry.setRowspan(2);
dashboard.add(visitorsByCountry);

DashboardWidget browserDistribution = new DashboardWidget("Browsers");
browserDistribution.setContent(createWidgetContent());
dashboard.add(browserDistribution);

DashboardWidget catImage = new DashboardWidget("A kittykat!");
catImage.setContent(createWidgetContent());
dashboard.add(catImage);

DashboardWidget visitorsByBrowser = new DashboardWidget(
        "Visitors by browser");
visitorsByBrowser.setContent(createWidgetContent());
visitorsByBrowser.setColspan(2);
dashboard.add(visitorsByBrowser);

add(dashboard);
```

**React** — `dashboard-basic.tsx`

```tsx
<DashboardLayout
  style={{
    '--vaadin-dashboard-col-min-width': '150px',
    '--vaadin-dashboard-col-max-count': '3',
  }}
>
  <DashboardWidget widgetTitle="Visitors">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget widgetTitle="Downloads">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget widgetTitle="Conversions">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget
    widgetTitle="Visitors by country"
    style={{ '--vaadin-dashboard-widget-rowspan': '2' }}
  >
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget widgetTitle="Browsers">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget widgetTitle="A kittykat!">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget
    widgetTitle="Visitors by browser"
    style={{ '--vaadin-dashboard-widget-colspan': '2' }}
  >
    <div className="dashboard-widget-content" />
  </DashboardWidget>
</DashboardLayout>
```

**Lit** — `dashboard-basic.ts`

```html
<vaadin-dashboard-layout
  style="--vaadin-dashboard-col-min-width: 150px; --vaadin-dashboard-col-max-count: 3"
>
  <vaadin-dashboard-widget widget-title="Visitors">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget widget-title="Downloads">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget widget-title="Conversions">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget
    widget-title="Visitors by country"
    style="--vaadin-dashboard-widget-rowspan: 2;"
  >
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget widget-title="Browsers">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget widget-title="A kittykat!">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget
    widget-title="Visitors by browser"
    style="--vaadin-dashboard-widget-colspan: 2;"
  >
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
</vaadin-dashboard-layout>
```

## <a id="key-features"></a>Key Features

- **Static & Dynamic Dashboards**

  **[Static](#static-dashboards)**: You define a dashboard and its widgets declaratively or imperatively. The React and Web Components for this are `<DashboardLayout>` & `<DashboardWidget>` and `<vaadin-dashboard-layout>` & `<vaadin-dashboard-widget>` respectively.

  **[Dynamic](#dynamic-dashboards)**: You define the data and Dashboard generates widgets using a renderer. Dynamic dashboards support edit mode that allows the end user to move, resize, and remove widgets. The React and Web Components for this are `<Dashboard>` and `<vaadin-dashboard>`, respectively.

  In Flow, the `Dashboard` and `DashboardWidget` classes are used for both approaches.

- **Widgets, Columns & Rows**

  Widgets are placed in columns and rows automatically, in the order supplied, based on the dashboard’s width and the [column configuration](#columns-and-rows). As the dashboard’s width changes, the number of columns is automatically adjusted based on their configured minimum and maximum width, and the widget positions are adjusted so.

  You can’t place a widget in a specific column or row.

- **Scrolling**

  Dashboard scrolls vertically if the contents overflow its defined height. Individual widgets don’t scroll (see [Widget Content Sizing](#widget-content-sizing)).

## <a id="configuration"></a>Configuration

The following configuration options are available for the Dashboard component.

### <a id="columns-and-rows"></a>Columns & Rows

Column width can vary between a minimum and maximum size. The default maximum width is `1fr`, which allows the columns to expand to fill any available space. If a fixed length value is provided, empty space is reserved at the end of rows once the columns reach their maximum width.

By default there is no limit on the number of columns, but one can be provided if needed.

The height of each dashboard row is determined by the tallest widget in that row, whose height in turn is determined by its contents. A minimum row height determines the height of empty rows, such as when a widget’s row span is stretched into an unoccupied row. The minimum height can be configured.

**Flow**

```java
dashboard.setMinimumColumnWidth("150px");
dashboard.setMaximumColumnWidth("300px");
dashboard.setMaximumColumnCount(4);
dashboard.setMinimumRowHeight("100px");
```

**React**

```tsx
<DashboardLayout style={{
    '--vaadin-dashboard-col-min-width': '150px',
    '--vaadin-dashboard-col-max-width': '300px',
    '--vaadin-dashboard-col-max-count': '4',
    '--vaadin-dashboard-row-min-height': '100px'
}}>
...
</DashboardLayout>
```

**Lit**

```html
<vaadin-dashboard-layout style="--vaadin-dashboard-col-min-width: 150px; --vaadin-dashboard-col-max-width: 300px; --vaadin-dashboard-col-max-count: 4; --vaadin-dashboard-row-min-height: 100px">
...
</vaadin-dashboard-layout>
```

### <a id="whitespace"></a>Whitespace

The horizontal and vertical spacing between widgets, and the padding along the dashboard’s edges, can be configured.

**Flow**

```java
dashboard.setGap("10px");
dashboard.setPadding("20px");
```

**React**

```tsx
<DashboardLayout style={{
    '--vaadin-dashboard-gap': '10px',
    '--vaadin-dashboard-padding': '20px',
}}>
...
</DashboardLayout>
```

**Lit**

```html
<vaadin-dashboard-layout style="--vaadin-dashboard-gap: 10px; --vaadin-dashboard-padding: 20px">
...
</vaadin-dashboard-layout>
```

### <a id="dense-layout"></a>Dense Layout

This mode uses the dense packing algorithm in the CSS grid layout model. It attempts to fill in empty slots in the layout by placing smaller widgets in them. This can affect the order of the widgets. It should be used with caution in user-configurable dashboards, as the automatic reordering of widgets may be confusing during editing.

**Flow**

```java
dashboard.setDenseLayout(true);
```

**React**

```tsx
<DashboardLayout denseLayout>
...
</DashboardLayout>
```

**Lit**

```html
<vaadin-dashboard-layout dense-layout>
...
</vaadin-dashboard-layout>
```

`dashboard-dense-layout.ts`

```typescript
import '@vaadin/checkbox';
import '@vaadin/dashboard/vaadin-dashboard-layout.js';
import '@vaadin/dashboard/vaadin-dashboard-widget.js';
import { html, LitElement } from 'lit';
import { customElement, state } from 'lit/decorators.js';
import { applyTheme } from 'Frontend/generated/theme';

@customElement('dashboard-dense-layout')
export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  @state()
  private denseLayout = false;

  protected override render() {
    return html`
      <vaadin-checkbox
        label="Use dense layout"
        @change="${() => {
          this.denseLayout = !this.denseLayout;
        }}"
      ></vaadin-checkbox>
      <vaadin-dashboard-layout
        .denseLayout="${this.denseLayout}"
        style="--vaadin-dashboard-col-min-width: 0; --vaadin-dashboard-col-max-count: 3; --vaadin-dashboard-row-min-height: 50px;"
      >
        <vaadin-dashboard-widget
          widget-title="Wide widget 1"
          style="--vaadin-dashboard-widget-colspan: 2"
        >
          <div class="dashboard-widget-content small"></div>
        </vaadin-dashboard-widget>
        <vaadin-dashboard-widget
          widget-title="Wide widget 2"
          style="--vaadin-dashboard-widget-colspan: 2"
        >
          <div class="dashboard-widget-content small"></div>
        </vaadin-dashboard-widget>
        <vaadin-dashboard-widget widget-title="Small widget 1">
          <div class="dashboard-widget-content small"></div>
        </vaadin-dashboard-widget>
        <vaadin-dashboard-widget widget-title="Small widget 2">
          <div class="dashboard-widget-content small"></div>
        </vaadin-dashboard-widget>
      </vaadin-dashboard-layout>
    `;
  }
}
```

## <a id="widgets"></a>Widgets

Widgets consist of a content area and a header containing the widget’s title and a slot for more elements.

**Flow** — `DashboardWidgetContents.java`

```java
DashboardWidget widget = new DashboardWidget("Widget title");
widget.setContent(new Span("Widget content"));
widget.setHeaderContent(new Span("Additional header content"));
```

**React** — `dashboard-widget-contents.tsx`

```tsx
<DashboardWidget widgetTitle="Widget title">
  <span>Widget content</span>
  <span slot="header-content">Additional header content</span>
</DashboardWidget>
```

**Lit** — `dashboard-widget-contents.ts`

```html
<vaadin-dashboard-widget widget-title="Widget title">
  <span>Widget content</span>
  <span slot="header-content">Additional header content</span>
</vaadin-dashboard-widget>
```

You can set the column span and row span to make a widget take up more than one column or row in the dashboard’s layout. The actual number of columns a widget spans is limited by the current number of columns in the dashboard, however.

### <a id="widget-content-sizing"></a>Widget Content Sizing

The height of a widget’s contents define its default height. The height can grow because of row span or other taller widgets on the same dashboard row. If the height of the widget is constrained (e.g., by an explicitly set height), the contents of the card can overflow. You may need to incorporate a scrollable area (e.g., with [Scroller](https://vaadin.com/docs/v24/components/scroller.md)) to accommodate a height smaller than the contents you place in a widget.

The width of a widget is determined by the current column width and the widget’s column span.

Contents that should cover the entire widget area should therefore be configured with 100% width and height, as well as a minimum height corresponding to its desired default height.

## <a id="static-dashboards"></a>Static Dashboards

Static dashboards are populated declaratively (in React and Lit) / imperatively (in Flow), like normal layouts. They are a good choice for hard-coded dashboards.

|                       |                             |
| --------------------- | --------------------------- |
| **Flow**              | `Dashboard`                 |
| **React**             | `<DashboardLayout>`         |
| **Lit Web Component** | `<vaadin-dashboard-layout>` |

**Flow** — `DashboardBasic.java`

```java
Dashboard dashboard = new Dashboard();
dashboard.setMinimumColumnWidth("150px");
dashboard.setMaximumColumnCount(3);

DashboardWidget visitors = new DashboardWidget("Visitors");
visitors.setContent(createWidgetContent());
dashboard.add(visitors);

DashboardWidget downloads = new DashboardWidget("Downloads");
downloads.setContent(createWidgetContent());
dashboard.add(downloads);

DashboardWidget conversions = new DashboardWidget("Conversions");
conversions.setContent(createWidgetContent());
dashboard.add(conversions);

DashboardWidget visitorsByCountry = new DashboardWidget(
        "Visitors by country");
visitorsByCountry.setContent(createWidgetContent());
visitorsByCountry.setRowspan(2);
dashboard.add(visitorsByCountry);

DashboardWidget browserDistribution = new DashboardWidget("Browsers");
browserDistribution.setContent(createWidgetContent());
dashboard.add(browserDistribution);

DashboardWidget catImage = new DashboardWidget("A kittykat!");
catImage.setContent(createWidgetContent());
dashboard.add(catImage);

DashboardWidget visitorsByBrowser = new DashboardWidget(
        "Visitors by browser");
visitorsByBrowser.setContent(createWidgetContent());
visitorsByBrowser.setColspan(2);
dashboard.add(visitorsByBrowser);

add(dashboard);
```

**React** — `dashboard-basic.tsx`

```tsx
<DashboardLayout
  style={{
    '--vaadin-dashboard-col-min-width': '150px',
    '--vaadin-dashboard-col-max-count': '3',
  }}
>
  <DashboardWidget widgetTitle="Visitors">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget widgetTitle="Downloads">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget widgetTitle="Conversions">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget
    widgetTitle="Visitors by country"
    style={{ '--vaadin-dashboard-widget-rowspan': '2' }}
  >
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget widgetTitle="Browsers">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget widgetTitle="A kittykat!">
    <div className="dashboard-widget-content" />
  </DashboardWidget>
  <DashboardWidget
    widgetTitle="Visitors by browser"
    style={{ '--vaadin-dashboard-widget-colspan': '2' }}
  >
    <div className="dashboard-widget-content" />
  </DashboardWidget>
</DashboardLayout>
```

**Lit** — `dashboard-basic.ts`

```html
<vaadin-dashboard-layout
  style="--vaadin-dashboard-col-min-width: 150px; --vaadin-dashboard-col-max-count: 3"
>
  <vaadin-dashboard-widget widget-title="Visitors">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget widget-title="Downloads">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget widget-title="Conversions">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget
    widget-title="Visitors by country"
    style="--vaadin-dashboard-widget-rowspan: 2;"
  >
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget widget-title="Browsers">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget widget-title="A kittykat!">
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
  <vaadin-dashboard-widget
    widget-title="Visitors by browser"
    style="--vaadin-dashboard-widget-colspan: 2;"
  >
    <div class="dashboard-widget-content"></div>
  </vaadin-dashboard-widget>
</vaadin-dashboard-layout>
```

## <a id="dynamic-dashboards"></a>Dynamic, Editable Dashboards

Dynamic dashboards offer end users the possibility to edit the layout. Dynamic dashboards are populated through a data-binding API coupled with a widget renderer function. This makes the layout configuration easy to persist and load from storage, such as a database.

|                       |                      |
| --------------------- | -------------------- |
| **Flow**              | `Dashboard`          |
| **React**             | `<Dashboard>`        |
| **Lit Web Component** | `<vaadin-dashboard>` |

**Flow** — `DashboardEditable.java`

```java
// NOTE: This example uses the additional classes WidgetConfig and
// DashboardStorage, which you can find by switching to the respective file
// tab.

// Since the default DashboardWidget class doesn't allow setting custom
// data, we create a custom class that extends DashboardWidget, and add a
// field for storing the widget type.
public static class CustomWidget extends DashboardWidget {
    private final WidgetConfig.WidgetType type;

    public CustomWidget(WidgetConfig.WidgetType type, String title) {
        super(title);
        this.type = type;
    }

    public WidgetConfig.WidgetType getType() {
        return type;
    }
}

// This is the default configuration for the dashboard. Note that the order
// of the widgets in the list determines the order in which they are
// displayed in the dashboard.
private final List<WidgetConfig> defaultConfig = List.of(
        new WidgetConfig(WidgetConfig.WidgetType.VISITORS, 1, 1),
        new WidgetConfig(WidgetConfig.WidgetType.DOWNLOADS, 1, 1),
        new WidgetConfig(WidgetConfig.WidgetType.CONVERSIONS, 1, 1),
        new WidgetConfig(WidgetConfig.WidgetType.VISITORS_BY_COUNTRY, 1, 2),
        new WidgetConfig(WidgetConfig.WidgetType.BROWSER_DISTRIBUTION, 1,
                1),
        new WidgetConfig(WidgetConfig.WidgetType.CAT_IMAGE, 1, 1),
        new WidgetConfig(WidgetConfig.WidgetType.VISITORS_BY_BROWSER, 2,
                1));

public DashboardEditable(DashboardStorage dashboardStorage) {
    this.dashboardStorage = dashboardStorage;

    createToolbar();
    createDashboard();
}

private void createDashboard() {
    // Create dashboard and load initial configuration
    dashboard = new Dashboard();
    loadConfiguration();

    dashboard.setMinimumColumnWidth("150px");
    dashboard.setMaximumColumnCount(3);
    add(dashboard);
}

private void createToolbar() {
    MenuBar toolbar = new MenuBar();
    toolbar.addThemeVariants(MenuBarVariant.LUMO_DROPDOWN_INDICATORS);

    MenuItem edit = toolbar.addItem("Edit");
    edit.addThemeNames("primary");
    edit.addClickListener(event -> {
        if (dashboard.isEditable()) {
            dashboard.setEditable(false);
            edit.setText("Edit");
        } else {
            dashboard.setEditable(true);
            edit.setText("Apply");
        }
    });

    MenuItem save = toolbar.addItem("Save");
    save.addClickListener(event -> saveConfiguration());

    MenuItem load = toolbar.addItem("Load");
    load.addClickListener(event -> loadConfiguration());

    MenuItem addWidget = toolbar.addItem("Add widget");
    for (WidgetConfig.WidgetType widgetType : WidgetConfig.WidgetType
            .values()) {
        addWidget.getSubMenu().addItem(widgetType.getLabel(),
                event -> addWidget(widgetType));
    }

    MenuItem restore = toolbar.addItem("Restore default");
    restore.addThemeNames("error");
    restore.addClickListener(event -> restoreDefault());

    add(toolbar);
}

private void saveConfiguration() {
    // To save the dashboard configuration, we iterate over the current
    // widgets in the dashboard and map them into configuration objects.
    List<WidgetConfig> dashboardConfig = dashboard.getWidgets().stream()
            .map(widget -> {
                // Cast to our custom widget class and extract type,
                // colspan, and rowspan
                CustomWidget customWidget = (CustomWidget) widget;
                return new WidgetConfig(customWidget.getType(),
                        widget.getColspan(), widget.getRowspan());
            }).toList();

    // Then save the configuration to the database or other storage
    // In this example, we just store it in a session-scoped bean
    dashboardStorage.save(dashboardConfig);
}

private void loadConfiguration() {
    // Load the dashboard configuration from database or other storage
    // In this example, we just load it from a session-scoped bean
    // If no configuration is found, use the default configuration
    List<WidgetConfig> dashboardConfig = dashboardStorage.load();
    if (dashboardConfig == null) {
        dashboardConfig = defaultConfig;
    }

    applyConfiguration(dashboardConfig);
}

private void applyConfiguration(List<WidgetConfig> dashboardConfig) {
    // To apply a dashboard configuration, we first clear the dashboard and
    // then create widgets based on the configuration
    dashboard.removeAll();
    for (WidgetConfig config : dashboardConfig) {
        CustomWidget widget = createWidget(config);
        dashboard.add(widget);
    }
}

private CustomWidget createWidget(WidgetConfig config) {
    // In this example all widget types have the same content, and the title
    // is stored in the enum, so we can use generic logic to create a widget
    CustomWidget widget = new CustomWidget(config.getType(),
            config.getType().getLabel());
    widget.setContent(createWidgetContent());
    widget.setColspan(config.getColspan());
    widget.setRowspan(config.getRowspan());

    // In practice, different widget types will have different content. In
    // that case you can use a switch statement to create the widget content
    // based on the type.
    //
    // switch (config.type()) {
    //     case VISITORS:
    //         widget.setTitle("Visitors");
    //         widget.setContent(new VisitorsWidgetContent());
    //         break;
    //     ...
    // }
    return widget;
}

private void addWidget(WidgetConfig.WidgetType widgetType) {
    // For adding a new widget, we retrieve the default configuration for
    // the widget type and create a widget based on that configuration
    WidgetConfig defaultWidgetConfig = defaultConfig.stream()
            .filter(widgetConfig -> widgetConfig.getType() == widgetType)
            .findFirst().orElseThrow();
    CustomWidget widget = createWidget(defaultWidgetConfig);

    dashboard.add(widget);
}

private void restoreDefault() {
    // To restore defaults, we just apply the default configuration
    applyConfiguration(defaultConfig);
}
```

**Flow** — `WidgetConfig.java`

```java
// In order to save and load the dashboard configuration we need a class for storing
// the configuration of individual widgets. In this example we'll use a class that
// holds the widget type, colspan, and rowspan.
public class WidgetConfig {
    public enum WidgetType {
        VISITORS("Visitors"),
        DOWNLOADS("Downloads"),
        CONVERSIONS("Conversions"),
        VISITORS_BY_COUNTRY("Visitors by country"),
        BROWSER_DISTRIBUTION("Browser distribution"),
        CAT_IMAGE("Cat image"),
        VISITORS_BY_BROWSER("Visitors by browser");

        private final String label;

        WidgetType(String label) {
            this.label = label;
        }

        public String getLabel() {
            return label;
        }
    }

    private WidgetType type;
    private int colspan;
    private int rowspan;

    public WidgetConfig() {
    }

    public WidgetConfig(WidgetType type, int colspan, int rowspan) {
        this.type = type;
        this.colspan = colspan;
        this.rowspan = rowspan;
    }

    @NonNull
    public WidgetType getType() {
        return type;
    }

    public void setType(WidgetType type) {
        this.type = type;
    }

    @NonNull
    public int getColspan() {
        return colspan;
    }

    public void setColspan(int colspan) {
        this.colspan = colspan;
    }

    @NonNull
    public int getRowspan() {
        return rowspan;
    }

    public void setRowspan(int rowspan) {
        this.rowspan = rowspan;
    }
}
```

**Flow** — `DashboardStorage.java`

```java
@SessionScope
@Component
public class DashboardStorage {
    private List<WidgetConfig> config;

    public List<WidgetConfig> load() {
        return config;
    }

    public void save(List<WidgetConfig> config) {
        this.config = config;
    }
}
```

**React** — `dashboard-editable.tsx`

```tsx
// NOTE: This example uses the additional classes WidgetConfig and DashboardService,
// which you can find by switching to the respective file tab.

// This is the default configuration for the dashboard. Note that the order
// of the widgets in the array determines the order in which they are
// displayed in the dashboard.
const defaultConfig: WidgetConfig[] = [
  { type: WidgetType.VISITORS, colspan: 1, rowspan: 1 },
  { type: WidgetType.DOWNLOADS, colspan: 1, rowspan: 1 },
  { type: WidgetType.CONVERSIONS, colspan: 1, rowspan: 1 },
  { type: WidgetType.VISITORS_BY_COUNTRY, colspan: 1, rowspan: 2 },
  { type: WidgetType.BROWSER_DISTRIBUTION, colspan: 1, rowspan: 1 },
  { type: WidgetType.CAT_IMAGE, colspan: 1, rowspan: 1 },
  { type: WidgetType.VISITORS_BY_BROWSER, colspan: 2, rowspan: 1 },
];

// Define a mapping from widget types to human-readable titles
const widgetTitles: Record<WidgetType, string> = {
  [WidgetType.VISITORS]: 'Visitors',
  [WidgetType.DOWNLOADS]: 'Downloads',
  [WidgetType.CONVERSIONS]: 'Conversions',
  [WidgetType.VISITORS_BY_COUNTRY]: 'Visitors by country',
  [WidgetType.BROWSER_DISTRIBUTION]: 'Browsers',
  [WidgetType.CAT_IMAGE]: 'A kittykat!',
  [WidgetType.VISITORS_BY_BROWSER]: 'Visitors by browser',
};

// Helper type to allow defining a custom action for a menu item
type CustomMenuItem = MenuBarItem & {
  action?(): unknown;
};

function Example() {
  const widgets = useSignal<WidgetConfig[]>([]);
  const editable = useSignal<boolean>(false);

  function toggleEditing() {
    editable.value = !editable.value;
  }

  function save() {
    // To save the dashboard configuration, we can just take the current
    // widget items array and pass it to a server-side service for
    // persisting it.
    DashboardService.saveDashboard(widgets.value);
  }

  async function load() {
    // To load the dashboard configuration, we just load it from a server-side
    // service. If there is no configuration saved, we use a copy of the default
    // configuration.
    let config = await DashboardService.loadDashboard();
    if (!config) {
      config = [...defaultConfig];
    }
    widgets.value = config;
  }

  function addWidget(type: WidgetType) {
    // For adding a new widget, we retrieve the default configuration for the
    // widget type and add a copy of that to the widgets array.
    const defaultWidgetConfig = defaultConfig.find((widget) => widget.type === type);
    if (!defaultWidgetConfig) {
      return;
    }
    widgets.value = [...widgets.value, { ...defaultWidgetConfig }];
  }

  function restore() {
    // To restore defaults, we just set a copy of the default configuration
    widgets.value = [...defaultConfig];
  }

  // Render function should be memoized to avoid unnecessary re-renders
  const renderWidget = useCallback(({ item }: DashboardReactRendererProps<WidgetConfig>) => {
    // This function is used to render the actual widgets into the dashboard.
    // It is called by Dashboard once for each config in the widgets array
    // and should return a React element. Note that the colspan and rowspan
    // from the widget config are automatically applied by Dashboard.
    // In this example all widget types have the same content, so we can use
    // generic logic to render a widget.
    const widget = (
      <DashboardWidget widgetTitle={widgetTitles[item.type]}>
        <div className="dashboard-widget-content" />
      </DashboardWidget>
    );

    // In practice, different widget types will have different content.
    // In that case you can use a switch statement to render the widget
    // content based on the type.
    //
    // switch (item.type) {
    //   case WidgetType.Visitors:
    //     return (
    //       <DashboardWidget widgetTitle={widgetTitles[item.type]}>
    //         <VisitorsWidgetContent />
    //       </DashboardWidget>
    //     );
    //   ...
    // }
    return widget;
  }, []);

  // Load the initial configuration of the dashboard
  useEffect(() => {
    load();
  }, []);

  const menuItems: CustomMenuItem[] = [
    {
      text: editable.value ? 'Apply' : 'Edit',
      action: toggleEditing,
      theme: 'primary',
    },
    {
      text: 'Save',
      action: save,
    },
    {
      text: 'Load',
      action: load,
    },
    {
      text: 'Add widget',
      children: Object.values(WidgetType).map((type) => ({
        text: widgetTitles[type as WidgetType],
        action: () => addWidget(type as WidgetType),
      })),
    },
    {
      text: 'Restore default',
      action: restore,
      theme: 'error',
    },
  ];

  return (
    <>
      <MenuBar
        theme="dropdown-indicators"
        items={menuItems}
        onItemSelected={(e) => (e.detail.value as CustomMenuItem).action?.()}
      />
      <Dashboard
        style={{
          '--vaadin-dashboard-col-min-width': '150px',
          '--vaadin-dashboard-col-max-count': '3',
        }}
        editable={editable.value}
        items={widgets.value}
        onDashboardItemMoved={(e) => {
          // Store updated widgets after user has modified them
          widgets.value = e.detail.items as WidgetConfig[];
        }}
        onDashboardItemResized={(e) => {
          widgets.value = e.detail.items as WidgetConfig[];
        }}
        onDashboardItemRemoved={(e) => {
          widgets.value = e.detail.items as WidgetConfig[];
        }}
      >
        {renderWidget}
      </Dashboard>
    </>
  );
}
```

**React** — `WidgetConfig.java`

```java
// In order to save and load the dashboard configuration we need a class for storing
// the configuration of individual widgets. In this example we'll use a class that
// holds the widget type, colspan, and rowspan.
public class WidgetConfig {
    public enum WidgetType {
        VISITORS("Visitors"),
        DOWNLOADS("Downloads"),
        CONVERSIONS("Conversions"),
        VISITORS_BY_COUNTRY("Visitors by country"),
        BROWSER_DISTRIBUTION("Browser distribution"),
        CAT_IMAGE("Cat image"),
        VISITORS_BY_BROWSER("Visitors by browser");

        private final String label;

        WidgetType(String label) {
            this.label = label;
        }

        public String getLabel() {
            return label;
        }
    }

    private WidgetType type;
    private int colspan;
    private int rowspan;

    public WidgetConfig() {
    }

    public WidgetConfig(WidgetType type, int colspan, int rowspan) {
        this.type = type;
        this.colspan = colspan;
        this.rowspan = rowspan;
    }

    @NonNull
    public WidgetType getType() {
        return type;
    }

    public void setType(WidgetType type) {
        this.type = type;
    }

    @NonNull
    public int getColspan() {
        return colspan;
    }

    public void setColspan(int colspan) {
        this.colspan = colspan;
    }

    @NonNull
    public int getRowspan() {
        return rowspan;
    }

    public void setRowspan(int rowspan) {
        this.rowspan = rowspan;
    }
}
```

**React** — `DashboardService.java`

```java
// This is a simple browser-callable server that allows saving and loading a
// dashboard configuration. For this example, we just store the configuration
// in a session-scoped bean. In practice, you'd want to store the configuration
// in a database or some other persistent storage along with the user ID.
@BrowserCallable
public class DashboardService {
    private final DashboardStorage dashboardStorage;

    public DashboardService(DashboardStorage dashboardStorage) {
        this.dashboardStorage = dashboardStorage;
    }

    public void saveDashboard(@NonNull List<@NonNull WidgetConfig> config) {
        dashboardStorage.save(config);
    }

    public List<@NonNull WidgetConfig> loadDashboard() {
        return dashboardStorage.load();
    }
}
```

**Lit** — `dashboard-editable.ts`

```typescript
// NOTE: This example uses the additional classes WidgetConfig and DashboardService,
// which you can find by switching to the respective file tab.

// This is the default configuration for the dashboard. Note that the order
// of the widgets in the array determines the order in which they are
// displayed in the dashboard.
const defaultConfig: WidgetConfig[] = [
  { type: WidgetType.VISITORS, colspan: 1, rowspan: 1 },
  { type: WidgetType.DOWNLOADS, colspan: 1, rowspan: 1 },
  { type: WidgetType.CONVERSIONS, colspan: 1, rowspan: 1 },
  { type: WidgetType.VISITORS_BY_COUNTRY, colspan: 1, rowspan: 2 },
  { type: WidgetType.BROWSER_DISTRIBUTION, colspan: 1, rowspan: 1 },
  { type: WidgetType.CAT_IMAGE, colspan: 1, rowspan: 1 },
  { type: WidgetType.VISITORS_BY_BROWSER, colspan: 2, rowspan: 1 },
];

// Define a mapping from widget types to human-readable titles
const widgetTitles: Record<WidgetType, string> = {
  [WidgetType.VISITORS]: 'Visitors',
  [WidgetType.DOWNLOADS]: 'Downloads',
  [WidgetType.CONVERSIONS]: 'Conversions',
  [WidgetType.VISITORS_BY_COUNTRY]: 'Visitors by country',
  [WidgetType.BROWSER_DISTRIBUTION]: 'Browsers',
  [WidgetType.CAT_IMAGE]: 'A kittykat!',
  [WidgetType.VISITORS_BY_BROWSER]: 'Visitors by browser',
};

// Helper type to allow defining a custom action for a menu item
type CustomMenuItem = MenuBarItem & {
  action?(): unknown;
};

@customElement('dashboard-editable')
export class Example extends LitElement {
  @state()
  widgets: WidgetConfig[] = [];

  @state()
  editable = false;

  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  firstUpdated() {
    // Load the initial configuration of the dashboard
    this.load();
  }

  toggleEditing() {
    this.editable = !this.editable;
  }

  async load() {
    // To load the dashboard configuration, we just load it from a server-side
    // service. If there is no configuration saved, we use a copy of the default
    // configuration.
    const config = await DashboardService.loadDashboard();
    this.widgets = config ?? [...defaultConfig];
  }

  save() {
    // To save the dashboard configuration, we can just take the current
    // widget items array and pass it to a server-side service for
    // persisting it.
    DashboardService.saveDashboard(this.widgets);
  }

  addWidget(type: WidgetType) {
    // For adding a new widget, we retrieve the default configuration for the
    // widget type and add a copy of that to the widgets array.
    const defaultWidgetConfig = defaultConfig.find((widget) => widget.type === type);
    if (defaultWidgetConfig) {
      this.widgets = [...this.widgets, { ...defaultWidgetConfig }];
    }
  }

  restore() {
    // To restore defaults, we just set a copy of the default configuration
    this.widgets = [...defaultConfig];
  }

  render() {
    return html` ${this.renderMenu()} ${this.renderDashboard()} `;
  }

  renderMenu() {
    const menuItems = [
      {
        text: this.editable ? 'Apply' : 'Edit',
        action: this.toggleEditing.bind(this),
        theme: 'primary',
      },
      {
        text: 'Save',
        action: this.save.bind(this),
      },
      {
        text: 'Load',
        action: this.load.bind(this),
      },
      {
        text: 'Add widget',
        children: Object.values(WidgetType).map((type) => ({
          text: widgetTitles[type],
          action: () => this.addWidget(type),
        })),
      },
      {
        text: 'Restore default',
        action: this.restore.bind(this),
        theme: 'error',
      },
    ];

    return html`
      <vaadin-menu-bar
        .items="${menuItems}"
        @item-selected="${(e: MenuBarItemSelectedEvent) => {
          const item = e.detail.value as CustomMenuItem;
          item.action?.();
        }}"
        theme="dropdown-indicators"
      ></vaadin-menu-bar>
    `;
  }

  renderDashboard() {
    return html`
      <vaadin-dashboard
        style="--vaadin-dashboard-col-min-width: 150px; --vaadin-dashboard-col-max-count: 3;"
        .editable="${this.editable}"
        .items="${this.widgets}"
        .renderer="${this.renderWidget}"
        @dashboard-item-moved="${(e: DashboardItemMovedEvent<WidgetConfig>) => {
          // Store updated widgets after user has modified them
          this.widgets = e.detail.items as WidgetConfig[];
        }}"
        @dashboard-item-resized="${(e: DashboardItemResizedEvent<WidgetConfig>) => {
          this.widgets = e.detail.items as WidgetConfig[];
        }}"
        @dashboard-item-removed="${(e: DashboardItemRemovedEvent<WidgetConfig>) => {
          this.widgets = e.detail.items as WidgetConfig[];
        }}"
      ></vaadin-dashboard>
    `;
  }

  renderWidget(root: HTMLElement, _dashboard: Dashboard, { item }: { item: WidgetConfig }) {
    // This method is used to render the actual widgets into the dashboard.
    // It is called by vaadin-dashboard once for each config in the widgets
    // array and should render content into the provided root element. Note
    // that the colspan and rowspan from the widget config are
    // automatically applied by vaadin-dashboard.
    // In this example all widget types have the same content, so we can
    // use generic logic to render a widget.
    render(
      html`
        <vaadin-dashboard-widget .widgetTitle="${widgetTitles[item.type]}">
          <div class="dashboard-widget-content"></div>
        </vaadin-dashboard-widget>
      `,
      root
    );

    // In practice, different widget types will have different content.
    // In that case you can use a switch statement to render the widget
    // content based on the type.
    //
    // let widget: TemplateResult;
    //
    // switch (item.type) {
    //   case WidgetType.Visitors:
    //     widget = html`
    //       <vaadin-dashboard-widget .widgetTitle="Visitors">
    //         <visitors-widget-content></visitors-widget-content>
    //       </vaadin-dashboard-widget>
    //     `;
    //     break;
    //   ...
    // }
    //
    // render(widget, root);
  }
}
```

**Lit** — `WidgetConfig.java`

```java
// In order to save and load the dashboard configuration we need a class for storing
// the configuration of individual widgets. In this example we'll use a class that
// holds the widget type, colspan, and rowspan.
public class WidgetConfig {
    public enum WidgetType {
        VISITORS("Visitors"),
        DOWNLOADS("Downloads"),
        CONVERSIONS("Conversions"),
        VISITORS_BY_COUNTRY("Visitors by country"),
        BROWSER_DISTRIBUTION("Browser distribution"),
        CAT_IMAGE("Cat image"),
        VISITORS_BY_BROWSER("Visitors by browser");

        private final String label;

        WidgetType(String label) {
            this.label = label;
        }

        public String getLabel() {
            return label;
        }
    }

    private WidgetType type;
    private int colspan;
    private int rowspan;

    public WidgetConfig() {
    }

    public WidgetConfig(WidgetType type, int colspan, int rowspan) {
        this.type = type;
        this.colspan = colspan;
        this.rowspan = rowspan;
    }

    @NonNull
    public WidgetType getType() {
        return type;
    }

    public void setType(WidgetType type) {
        this.type = type;
    }

    @NonNull
    public int getColspan() {
        return colspan;
    }

    public void setColspan(int colspan) {
        this.colspan = colspan;
    }

    @NonNull
    public int getRowspan() {
        return rowspan;
    }

    public void setRowspan(int rowspan) {
        this.rowspan = rowspan;
    }
}
```

**Lit** — `DashboardService.java`

```java
// This is a simple browser-callable server that allows saving and loading a
// dashboard configuration. For this example, we just store the configuration
// in a session-scoped bean. In practice, you'd want to store the configuration
// in a database or some other persistent storage along with the user ID.
@BrowserCallable
public class DashboardService {
    private final DashboardStorage dashboardStorage;

    public DashboardService(DashboardStorage dashboardStorage) {
        this.dashboardStorage = dashboardStorage;
    }

    public void saveDashboard(@NonNull List<@NonNull WidgetConfig> config) {
        dashboardStorage.save(config);
    }

    public List<@NonNull WidgetConfig> loadDashboard() {
        return dashboardStorage.load();
    }
}
```

### <a id="editing"></a>Editing

You can make dynamic dashboards editable by turning on editing mode, as seen in the sample above.

> **Note: Editing mode should be temporary.**
>
> The end user turns on editing mode when they want to edit the dashboard’s contents and turns it off when they finish editing. When turned off, you typically want to persist the dashboard configuration to a storage. While in editing mode, the widget contents are visible but not interactable.

The following operations are available in editing mode.

#### <a id="widget-selection-by-keyboard"></a>Widget Selection by Keyboard

In editing mode, widgets can be selected by keyboard by moving focus to the desired widget using the `Tab` key and pressing `Space` or `Enter`. Once selected, arrow keys can be used to move and resize widgets, and to engage the accessible move and resize modes.

Widget selection is not required for editing by pointer device.

#### <a id="moving-widgets"></a>Moving Widgets

In editing mode, widgets can be moved around by:

- drag & drop;

- arrow keys, once the widget has been selected;

- an accessible move-mode engaged by clicking the drag-handle in the widget’s top left corner. Move-mode is disengaged by clicking the apply-button in the widget’s center, or by pressing `Esc`.

Widgets can only be moved backwards and forwards. Moving a widget past the start or end of a row moves it to the preceding or following row.

#### <a id="resizing-widgets"></a>Resizing Widgets

In editing mode, widgets can be resized by increasing and decreasing their column span and row span by:

- dragging from the drag-handle in the widget’s bottom right corner;

- `Shift` + arrow keys, once the widget has been selected;

- an accessible resize-mode engaged by clicking the resize-handle. Resize-mode is disengaged by clicking the apply-button in the widget’s center, or by pressing `Esc`.

#### <a id="removing-widgets"></a>Removing Widgets

In editing mode, widgets can be removed by clicking the **Remove** button in the widget’s top right corner.

#### <a id="adding-widgets"></a>Adding Widgets

Dashboard has no built-in mechanism for adding new widgets. You can implement this using an external widget selector, such as a [Select](https://vaadin.com/docs/v24/components/select.md) drop-down, that adds the corresponding item to the dashboard.

#### <a id="screen-reader-announcements"></a>Screen Reader Announcements

Although widget selection is announced via a widget’s title, and the various buttons all have accessible names, the component doesn’t announce changes to a widget’s position and size out of the box. These can be provided by listening to related events emitted by the component and updating custom live regions with appropriate announcements.

**Flow** — `DashboardAnnouncements.java`

```java
// Live region for screen reader announcements. Changing its text
// content will result in a new announcement. This element is only
// visible for demonstration purposes. In your application you should
// visually hide it using CSS, for example by using the sr-only Lumo
// utility class:
// liveRegion.addClassName(LumoUtility.Accessibility.SCREEN_READER_ONLY)
Div liveRegion = new Div();
liveRegion.getElement().setAttribute("aria-live", "polite");
add(liveRegion);

// This event is fired when the user starts or stops editing a widget
dashboard.addItemSelectedChangedListener(event -> {
    String title = ((DashboardWidget) event.getItem()).getTitle();
    String selected = event.isSelected() ? "selected" : "deselected";

    liveRegion.setText("Widget " + title + " " + selected);
});

// This event is fired when the user enters or exits move mode
dashboard.addItemMoveModeChangedListener(event -> {
    if (event.isMoveMode()) {
        liveRegion.setText("Entered move mode");
    } else {
        liveRegion.setText("Exited move mode");
    }
});

// This event is fired when the user enters or exits resize mode
dashboard.addItemResizeModeChangedListener(event -> {
    if (event.isResizeMode()) {
        liveRegion.setText("Entered resize mode");
    } else {
        liveRegion.setText("Exited resize mode");
    }
});

// This event is fired when the user moves a widget
dashboard.addItemMovedListener(event -> {
    int position = event.getItems().indexOf(event.getItem()) + 1;
    int total = event.getItems().size();
    String title = ((DashboardWidget) event.getItem()).getTitle();

    liveRegion.setText("Moved widget " + title + " to position "
            + position + " of " + total);
});

// This event is fired when the user resizes a widget
dashboard.addItemResizedListener(event -> {
    int colspan = event.getItem().getColspan();
    int rowspan = event.getItem().getRowspan();
    String title = event.getItem().getTitle();

    liveRegion.setText("Resized widget " + title + " to " + colspan
            + " columns, " + rowspan + " rows");
});

// This event is fired when the user removes a widget
dashboard.addItemRemovedListener(event -> {
    String title = ((DashboardWidget) event.getItem()).getTitle();

    liveRegion.setText("Removed widget " + title);
});
```

**React** — `dashboard-announcements.tsx`

```tsx
const announcement = useSignal('');

function handleSelectedChange(e: DashboardItemSelectedChangedEvent<WidgetConfig>) {
  // This event is fired when the user starts or stops editing a widget
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
  const title = widgetTitles[(e.detail.item as WidgetConfig).type];
  const selected = e.detail.value ? 'selected' : 'deselected';

  announcement.value = `Widget ${title} ${selected}`;
}

function handleMoveModeChange(e: DashboardItemMoveModeChangedEvent<WidgetConfig>) {
  // This event is fired when the user enters or exits move mode
  if (e.detail.value) {
    announcement.value = 'Entered move mode';
  } else {
    announcement.value = 'Exited move mode';
  }
}

function handleResizeModeChange(e: DashboardItemResizeModeChangedEvent<WidgetConfig>) {
  // This event is fired when the user enters or exits resize mode
  if (e.detail.value) {
    announcement.value = 'Entered resize mode';
  } else {
    announcement.value = 'Exited resize mode';
  }
}

function handleMove(e: DashboardItemMovedEvent<WidgetConfig>) {
  // This event is fired when the user moves a widget
  const position = e.detail.items.findIndex((widget) => widget === e.detail.item) + 1;
  const total = e.detail.items.length;
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
  const title = widgetTitles[(e.detail.item as WidgetConfig).type];

  announcement.value = `Moved widget ${title} to position ${position} of ${total}`;

  // Store updated widgets after user has modified them
  widgets.value = e.detail.items as WidgetConfig[];
}

function handleResize(e: DashboardItemResizedEvent<WidgetConfig>) {
  // This event is fired when the user resizes a widget
  const colspan = e.detail.item.colspan;
  const rowspan = e.detail.item.rowspan;
  const title = widgetTitles[e.detail.item.type];

  announcement.value = `Resized widget ${title} to ${colspan} columns, ${rowspan} rows`;

  // Store updated widgets after user has modified them
  widgets.value = e.detail.items as WidgetConfig[];
}

function handleRemove(e: DashboardItemRemovedEvent<WidgetConfig>) {
  // This event is fired when the user removes a widget
  const title = widgetTitles[(e.detail.item as WidgetConfig).type];

  announcement.value = `Removed widget ${title}`;

  // Store updated widgets after user has modified them
  widgets.value = e.detail.items as WidgetConfig[];
}

return (
  <>
    <p>Live announcement:</p>
    {/* Live region for screen reader announcements. Changing its text content will result */}
    {/* in a new announcement. This element is only visible for demonstration purposes. In */}
    {/* your application you should visually hide it using CSS, for example by using the   */}
    {/* sr-only Lumo utility class: */}
    {/* <div className="sr-only" aria-live="polite">{announcement}</div> */}
    <div aria-live="polite">{announcement}</div>
    <Dashboard
      style={{
        '--vaadin-dashboard-col-min-width': '150px',
        '--vaadin-dashboard-col-max-count': '3',
      }}
      editable
      items={widgets.value}
      onDashboardItemSelectedChanged={handleSelectedChange}
      onDashboardItemMoveModeChanged={handleMoveModeChange}
      onDashboardItemResizeModeChanged={handleResizeModeChange}
      onDashboardItemMoved={handleMove}
      onDashboardItemResized={handleResize}
      onDashboardItemRemoved={handleRemove}
    >
      {renderWidget}
    </Dashboard>
  </>
);
```

**React** — `WidgetConfig.java`

```java
// In order to save and load the dashboard configuration we need a class for storing
// the configuration of individual widgets. In this example we'll use a class that
// holds the widget type, colspan, and rowspan.
public class WidgetConfig {
    public enum WidgetType {
        VISITORS("Visitors"),
        DOWNLOADS("Downloads"),
        CONVERSIONS("Conversions"),
        VISITORS_BY_COUNTRY("Visitors by country"),
        BROWSER_DISTRIBUTION("Browser distribution"),
        CAT_IMAGE("Cat image"),
        VISITORS_BY_BROWSER("Visitors by browser");

        private final String label;

        WidgetType(String label) {
            this.label = label;
        }

        public String getLabel() {
            return label;
        }
    }

    private WidgetType type;
    private int colspan;
    private int rowspan;

    public WidgetConfig() {
    }

    public WidgetConfig(WidgetType type, int colspan, int rowspan) {
        this.type = type;
        this.colspan = colspan;
        this.rowspan = rowspan;
    }

    @NonNull
    public WidgetType getType() {
        return type;
    }

    public void setType(WidgetType type) {
        this.type = type;
    }

    @NonNull
    public int getColspan() {
        return colspan;
    }

    public void setColspan(int colspan) {
        this.colspan = colspan;
    }

    @NonNull
    public int getRowspan() {
        return rowspan;
    }

    public void setRowspan(int rowspan) {
        this.rowspan = rowspan;
    }
}
```

**Lit** — `dashboard-announcements.ts`

```typescript
@state()
announcement: string = '';

handleSelectedChange(e: DashboardItemSelectedChangedEvent<WidgetConfig>) {
  // This event is fired when the user starts or stops editing a widget
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
  const title = widgetTitles[(e.detail.item as WidgetConfig).type];
  const selected = e.detail.value ? 'selected' : 'deselected';

  this.announcement = `Widget ${title} ${selected}`;
}

handleMoveModeChange(e: DashboardItemMoveModeChangedEvent<WidgetConfig>) {
  // This event is fired when the user enters or exits move mode
  if (e.detail.value) {
    this.announcement = 'Entered move mode';
  } else {
    this.announcement = 'Exited move mode';
  }
}

handleResizeModeChange(e: DashboardItemResizeModeChangedEvent<WidgetConfig>) {
  // This event is fired when the user enters or exits resize mode
  if (e.detail.value) {
    this.announcement = 'Entered resize mode';
  } else {
    this.announcement = 'Exited resize mode';
  }
}

handleMove(e: DashboardItemMovedEvent<WidgetConfig>) {
  // This event is fired when the user moves a widget
  const position = e.detail.items.findIndex((widget) => widget === e.detail.item) + 1;
  const total = e.detail.items.length;
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
  const title = widgetTitles[(e.detail.item as WidgetConfig).type];
  this.announcement = `Moved widget ${title} to position ${position} of ${total}`;

  // Store updated widgets after user has modified them
  this.widgets = e.detail.items as WidgetConfig[];
}

handleResize(e: DashboardItemResizedEvent<WidgetConfig>) {
  // This event is fired when the user resizes a widget
  const colspan = e.detail.item.colspan;
  const rowspan = e.detail.item.rowspan;
  const title = widgetTitles[e.detail.item.type];

  this.announcement = `Resized widget ${title} to ${colspan} columns, ${rowspan} rows`;

  // Store updated widgets after user has modified them
  this.widgets = e.detail.items as WidgetConfig[];
}

handleRemove(e: DashboardItemRemovedEvent<WidgetConfig>) {
  // This event is fired when the user removes a widget
  const title = widgetTitles[(e.detail.item as WidgetConfig).type];

  this.announcement = `Removed widget ${title}`;

  // Store updated widgets after user has modified them
  this.widgets = e.detail.items as WidgetConfig[];
}

render() {
  return html`
    <p>Live announcement:</p>
    <!--
    Live region for screen reader announcements. Changing its text content will result
    in a new announcement. This element is only visible for demonstration purposes. In
    your application you should visually hide it using CSS, for example by using the
    sr-only Lumo utility class:
    <div className="sr-only" aria-live="polite">{announcement}</div>
    -->
    <div aria-live="polite">${this.announcement}</div>
    <vaadin-dashboard
      style="--vaadin-dashboard-col-min-width: 150px; --vaadin-dashboard-col-max-count: 3;"
      editable
      .items="${this.widgets}"
      .renderer="${this.renderWidget}"
      @dashboard-item-selected-changed="${this.handleSelectedChange}"
      @dashboard-item-move-mode-changed="${this.handleMoveModeChange}"
      @dashboard-item-resize-mode-changed="${this.handleResizeModeChange}"
      @dashboard-item-moved="${this.handleMove}"
      @dashboard-item-resized="${this.handleResize}"
      @dashboard-item-removed="${this.handleRemove}"
    ></vaadin-dashboard>
  `;
}
```

**Lit** — `WidgetConfig.java`

```java
// In order to save and load the dashboard configuration we need a class for storing
// the configuration of individual widgets. In this example we'll use a class that
// holds the widget type, colspan, and rowspan.
public class WidgetConfig {
    public enum WidgetType {
        VISITORS("Visitors"),
        DOWNLOADS("Downloads"),
        CONVERSIONS("Conversions"),
        VISITORS_BY_COUNTRY("Visitors by country"),
        BROWSER_DISTRIBUTION("Browser distribution"),
        CAT_IMAGE("Cat image"),
        VISITORS_BY_BROWSER("Visitors by browser");

        private final String label;

        WidgetType(String label) {
            this.label = label;
        }

        public String getLabel() {
            return label;
        }
    }

    private WidgetType type;
    private int colspan;
    private int rowspan;

    public WidgetConfig() {
    }

    public WidgetConfig(WidgetType type, int colspan, int rowspan) {
        this.type = type;
        this.colspan = colspan;
        this.rowspan = rowspan;
    }

    @NonNull
    public WidgetType getType() {
        return type;
    }

    public void setType(WidgetType type) {
        this.type = type;
    }

    @NonNull
    public int getColspan() {
        return colspan;
    }

    public void setColspan(int colspan) {
        this.colspan = colspan;
    }

    @NonNull
    public int getRowspan() {
        return rowspan;
    }

    public void setRowspan(int rowspan) {
        this.rowspan = rowspan;
    }
}
```

### <a id="persisting-and-loading-widgets"></a>Persisting and Loading Widgets

Dynamic dashboards, with their user-editable capabilities, often require the ability to persist and load customized widget configurations to and from storage, such as a database.

The most straightforward way to persist widget configurations is by defining a custom widget/item type. This type can include custom metadata relevant to the widget content, in addition to the built-in widget/item properties.

Once you’ve defined your custom type, you can establish a mapping between your data model and the widget configuration. This involves:

- Loading: When loading the persisted configuration, map the data from your storage to individual widget/item instances of your custom type. Each record corresponds to a single widget on the dashboard.

- Saving: When saving the user’s customized dashboard layout, map the current configuration (e.g., column span, row span, type, custom metadata) of your dashboard’s widgets back to your data model format.

This approach allows for flexible persistence of dashboard configurations, enabling users to save and load their customized layouts across sessions.

For a simple example of how to implement this persistence approach, see the [Dynamic, Editable Dashboards](#dynamic-dashboards) section above. While the example doesn’t explicitly show how to persist the data, it illustrates the concept of defining a custom type for the dashboard widgets. The specific implementation details depend on your chosen storage mechanism and data model.

## <a id="dashboard-sections"></a>Dashboard Sections

Complex dashboards can benefit from being divided into titled sections. Dashboard sections always span the full width of the dashboard, and follow the same column and row configuration as the dashboard itself. They support the same moving and removal operations in editing mode as widgets.

**Flow** — `DashboardSections.java`

```java
DashboardSection statsSection = dashboard
        .addSection("Monthly Funnel Stats");

DashboardWidget visitors = new DashboardWidget("Visitors");
visitors.setContent(createWidgetContent());
statsSection.add(visitors);

DashboardWidget downloads = new DashboardWidget("Downloads");
downloads.setContent(createWidgetContent());
statsSection.add(downloads);

DashboardWidget conversions = new DashboardWidget("Conversions");
conversions.setContent(createWidgetContent());
statsSection.add(conversions);
```

**React** — `dashboard-sections.tsx`

```tsx
<DashboardLayout
  style={{
    '--vaadin-dashboard-col-min-width': '150px',
    '--vaadin-dashboard-col-max-count': '3',
  }}
>
  <DashboardSection sectionTitle="Monthly Funnel Stats">
    <DashboardWidget widgetTitle="Visitors">
      <div className="dashboard-widget-content"></div>
    </DashboardWidget>
    <DashboardWidget widgetTitle="Downloads">
      <div className="dashboard-widget-content"></div>
    </DashboardWidget>
    <DashboardWidget widgetTitle="Conversions">
      <div className="dashboard-widget-content"></div>
    </DashboardWidget>
  </DashboardSection>
</DashboardLayout>
```

**Lit** — `dashboard-sections.ts`

```html
<vaadin-dashboard-layout
  style="--vaadin-dashboard-col-min-width: 150px; --vaadin-dashboard-col-max-count: 3"
>
  <vaadin-dashboard-section section-title="Monthly Funnel Stats">
    <vaadin-dashboard-widget widget-title="Visitors">
      <div class="dashboard-widget-content"></div>
    </vaadin-dashboard-widget>
    <vaadin-dashboard-widget widget-title="Downloads">
      <div class="dashboard-widget-content"></div>
    </vaadin-dashboard-widget>
    <vaadin-dashboard-widget widget-title="Conversions">
      <div class="dashboard-widget-content"></div>
    </vaadin-dashboard-widget>
  </vaadin-dashboard-section>
</vaadin-dashboard-layout>
```

## <a id="accessibility"></a>Accessibility

Dashboard widgets have an ARIA role of `article`.

Widget and section titles are rendered as headings. Root-level widgets and sections default to heading level 2 (corresponding to an `<h2>` element), while widgets within sections use one level below that of the section. The root heading level can be customized to match the dashboard’s correct placement in the heading hierarchy:

Flow

```java
dashboard.setRootHeadingLevel(3);
```

React

```tsx
<Dashboard rootHeadingLevel={3}>
```

Lit

```html
<vaadin-dashboard root-heading-level="3">
```

## <a id="internationalization"></a>Internationalization

The following texts in the dashboard can be localized through the internationalization object:

| Property             | Description                          |
| -------------------- | ------------------------------------ |
| `selectWidget`       | Widget selection trigger.            |
| `deselectWidget`     | Widget deselection trigger.          |
| `selectSection`      | Section selection trigger.           |
| `deselectSection`    | Section deselection trigger.         |
| `move`               | Button that engages move-mode.       |
| `moveForward`        | Move forward button in move-mode.    |
| `moveBackward`       | Move backward button in move-mode.   |
| `moveApply`          | Button that disengages move-mode.    |
| `resize`             | Button that engages resize-mode.     |
| `resizeGrowWidth`    | Grow width button in resize-mode.    |
| `resizeShrinkWidth`  | Shrink width button in resize-mode.  |
| `resizeGrowHeight`   | Grow height button in resize-mode.   |
| `resizeShrinkHeight` | Shrink height button in resize-mode. |
| `resizeApply`        | Button that disengages resize-mode.  |
| `remove`             | Remove button.                       |

**Flow** — `DashboardInternationalisation.java`

```java
Dashboard.DashboardI18n germanI18n = new Dashboard.DashboardI18n();
germanI18n.setSelectSection("Abschnitt auswählen");
germanI18n.setSelectWidget("Widget auswählen");
germanI18n.setRemove("Entfernen");
germanI18n.setResize("Größe ändern");
germanI18n.setResizeApply("Größenänderung anwenden");
germanI18n.setResizeShrinkWidth("Breite verkleinern");
germanI18n.setResizeGrowWidth("Breite vergrößern");
germanI18n.setResizeShrinkHeight("Höhe verkleinern");
germanI18n.setResizeGrowHeight("Höhe vergrößern");
germanI18n.setMove("Verschieben");
germanI18n.setMoveApply("Verschieben anwenden");
germanI18n.setMoveBackward("Nach hinten verschieben");
germanI18n.setMoveForward("Nach vorne verschieben");

dashboard.setI18n(germanI18n);
```

**React** — `dashboard-internationalisation.tsx`

```tsx
const germanI18n: DashboardI18n = {
  selectSection: 'Abschnitt auswählen',
  selectWidget: 'Widget auswählen',
  remove: 'Entfernen',
  resize: 'Größe ändern',
  resizeApply: 'Größenänderung anwenden',
  resizeShrinkWidth: 'Breite verkleinern',
  resizeGrowWidth: 'Breite vergrößern',
  resizeShrinkHeight: 'Höhe verkleinern',
  resizeGrowHeight: 'Höhe vergrößern',
  move: 'Verschieben',
  moveApply: 'Verschieben anwenden',
  moveBackward: 'Nach hinten verschieben',
  moveForward: 'Nach vorne verschieben',
};

function Example() {
  return <Dashboard i18n={germanI18n}></Dashboard>;
}
```

**Lit** — `dashboard-internationalisation.ts`

```typescript
const germanI18n: DashboardI18n = {
  selectSection: 'Abschnitt auswählen',
  selectWidget: 'Widget auswählen',
  remove: 'Entfernen',
  resize: 'Größe ändern',
  resizeApply: 'Größenänderung anwenden',
  resizeShrinkWidth: 'Breite verkleinern',
  resizeGrowWidth: 'Breite vergrößern',
  resizeShrinkHeight: 'Höhe verkleinern',
  resizeGrowHeight: 'Höhe vergrößern',
  move: 'Verschieben',
  moveApply: 'Verschieben anwenden',
  moveBackward: 'Nach hinten verschieben',
  moveForward: 'Nach vorne verschieben',
};

export class Example extends LitElement {
  render() {
    return html` <vaadin-dashboard-layout .i18n="${germanI18n}"></vaadin-dashboard-layout> `;
  }
}
```

## <a id="related-components"></a>Related Components

|                                                        |                                                       |
| ------------------------------------------------------ | ----------------------------------------------------- |
| Component                                              | Usage Recommendations                                 |
| [Card](https://vaadin.com/docs/v24/components/card.md) | Generic card component that can be used in any layout |

`d59db2ee-c3dd-446d-bd0d-40224b1f141e`
