Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Implement or-vaadin-toggle (#2981)

Koene3f64140f13c
diff --git a/AGENTS.md b/AGENTS.md
index 7d5d761c9..0b70dde72 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -14,3 +14,50 @@ In sandboxed environments, add `--offline` (requires dependencies to already be
When running integration tests, part of the stack (PostgreSQL and Keycloak) must be running. Start it with `mkdir -pm 777 tmp && docker compose -f profile/dev-testing.yml -p openremote up -d --no-build`.
Running `./gradlew clean` deletes the root `tmp/` directory that is mounted into PostgreSQL (see `profile/dev-testing.yml`), so recreate it and restart the stack before running tests again.
+
+## UI
+
+### Adding a new Vaadin component
+
+Vaadin-based components live in `ui/component/or-vaadin-components/src/` as thin wrappers that extend a Vaadin class and re-register it under an `or-vaadin-<name>` tag, e.g. `export class OrVaadinX extends (X as new () => X & LitElement)` with `@customElement("or-vaadin-x")`. Keep all `@vaadin/*` dependency versions aligned.
+
+#### Styling the component's shadow-DOM internals
+
+Pick the approach by how much of the base component you need to keep. The base + Lumo styles are keyed off the element's `static get is()`, so a wrapper that does *not* override `is` still reports the base tag (e.g. `vaadin-checkbox-group`) and inherits the full base + Lumo theme.
+
+**Small tweaks to an existing component (preferred default).** For small visual tweaks to an existing component, do NOT override `is`, since that detaches the element from the base + Lumo styles keyed off `is` and strips the inherited theme/layout entirely. Instead, apply the styles in the following ways:
+- Add the rules to a theme module in `ui/component/theme/src/components/or-vaadin-<name>.css` and `@import` it from that dir's `index.css`.
+- Reach shadow parts from *outside* with an external `::part()` rule keyed on the real tag name, e.g. `or-vaadin-<tag>::part(<part>) { … }`. Such a rule is invisible to the `is`-based lookup, so it scopes cleanly to that tag only (see `or-vaadin-toggle-group.ts` and its theme `or-vaadin-toggle-group.css`).
+
+**A component that fully owns its visuals via `registerStyles()`.** Only when the component re-implements the look from scratch (so it has no inherited theme to preserve) override `is` and register styles from its own module; do NOT use `static get styles()`. Vaadin's `ThemableMixin.finalizeStyles()` injects `static` styles *before* the Lumo theme injector, so the theme overrides them and nothing appears to apply; styles registered via `registerStyles()` are injected *after* the injector, so they always win. Recipe (see `or-vaadin-toggle.ts`):
+- Call `registerStyles("or-vaadin-<tag>", css\`...\`)` from `@vaadin/vaadin-themable-mixin/register-styles.js` at module top (before the element is finalized).
+- Override `static get is() { return "or-vaadin-<tag>"; }`. The base class reports its own tag (e.g. `vaadin-checkbox`), and `registerStyles`/`getStylesForThis()` key off `is`; without this the styles either don't match or leak onto every instance of the base component. (This same override is what detaches the element from the base theme, which is acceptable here because the component re-styles everything itself.)
+- Out-specify base rules with `:host(...)` prefixes (e.g. the checkbox base hides its marker with `:host(:not([checked])) [part='checkbox']::after { opacity: 0 }`).
+- Give every themed CSS var a hard-coded fallback (e.g. `var(--lumo-primary-color, #47a942)`) so the component also looks correct standalone, with no theme loaded.
+
+#### Registering an input type in the input pipeline
+
+To make an input type usable through the input pipeline, register it in `or-vaadin-input.ts` (`TEMPLATES` map + a `getXTemplate`, and `nativeValue` if it is a boolean that exposes `checked` instead of `value`) and update `value-input-provider.ts` (boolean/checked types use the `checked` attribute, not `value`).
+
+### Storybook
+
+Component docs are MDX under `ui/app/storybook/docs/components/or-vaadin-<name>.mdx`; the stories are under `ui/component/or-vaadin-components/stories/or-vaadin-<name>.stories.ts`. To add one, copy an existing pair (e.g. `or-vaadin-checkbox`), keeping the relative story import in the MDX and the `ComponentDocs` block.
+
+Stories call `getORStorybookHelpers(tagName)` and `setCustomElementsManifest(customElements)` using the `../custom-elements.json` manifest. That manifest is generated by `npm run analyze`, so a newly added component will render but show no args/argTypes/description until the manifest is regenerated.
+
+Storybook covers any component under `ui/component/` (e.g. `or-chart`, `or-map`, `or-mwc-components`, `or-tree-menu`, `or-vaadin-components`). For each component package the stories live in that package's own `stories/` dir (`ui/component/<pkg>/stories/<name>.stories.ts`), and the human-readable docs are MDX under `ui/app/storybook/docs/components/<name>.mdx`. To add a component, copy an existing pair from the same package, keeping the relative story import in the MDX and the `ComponentDocs` block.
+
+Stories call `getORStorybookHelpers(tagName)` (from `ui/component/storybook-utils.js`) and `setCustomElementsManifest(customElements)` off the package's own `../custom-elements.json`. That manifest is generated per-package by `npm run analyze` (cem), so a newly added component will render but show no args/argTypes/description until you regenerate its package's manifest. `custom-elements.json` (and `custom-elements-jsx.d.ts`) are generated and untracked.
+
+
+### Component testing
+
+Component tests use Playwright component testing (`@sand4rt/experimental-ct-web`). They live in each package's `test/*.test.ts`, import `{ ct, expect }` from `@openremote/test`, and `mount(ComponentClass, { props, slots, on })`. Run them with `npm test` in the package (which does `tsc -b && playwright test`). Prefer web-first, role-based assertions (`getByRole("checkbox", { name }).toBeChecked()`, `toHaveCount(...)`) over poking at JS properties (`toHaveJSProperty`) or internal locators. Some important quirks to know about:
+
+- **Custom elements used as slotted/appended children must be eagerly registered.** Playwright CT turns each imported component into a *lazy* dynamic import that only runs when that component is `mount()`ed, so a child element that is never mounted itself (e.g. `or-vaadin-toggle` slotted inside `or-vaadin-toggle-group`) never gets `customElements.define`d and stays an inert, unupgraded tag that appends to the DOM but does not render. Declare such components in the test itself via `mount(..., { hooksConfig: { components: [OrVaadinToggle] } })`; the `beforeMount` hook in `ui/test/playwright/index.js` resolves their import refs, which runs their modules and registers them before the mount.
+- **The `on` handler receives `event.detail`, not the event** (`listener(event.detail)`). This is inherent to `@sand4rt/experimental-ct-web`, which expects components to emit `CustomEvent`s and forwards only their `detail`, while components may also emit native events (like `change`) that carry no detail. So assert event values via events whose detail carries them; for Vaadin fields that is the `<prop>-changed` notify event (detail `{ value }`), while the native `change` event can only be counted. To await a single event's value, use the `shared.promiseEventDispatch()` fixture helper.
+- **Vaadin fires an initial `<prop>-changed` at mount** (notify-on-first-commit), so a freshly mounted toggle emits `checked-changed(false)` before any interaction. Assert on the user-driven transitions (e.g. the last two values), not exact-array equality, and prove "emits nothing" with `not.toContain(true)` rather than `toEqual([])`.
+- **Vaadin `<prop>-changed` events do not bubble or compose**, so a listener on a parent/group will not catch a child field's event; attach it to the field itself.
+- **The default slot must be an array of single-element strings.** The CT runner builds each slot via `createContextualFragment(str).firstChild`, so a single string containing multiple elements silently keeps only the first; pass `slots: { default: ["<a>…</a>", "<b>…</b>"] }`.
+- **Vaadin's `theme` is attribute-only.** `ThemePropertyMixin` derives a read-only `_theme` from the `theme` *attribute*; there is no writable reflecting `theme` property. So `mount(..., { props: { theme: "vertical" } })` sets an ignored JS property and the `:host([theme~='vertical'])` styles never apply (e.g. a "vertical" checkbox-group stays horizontal). Set it as an attribute instead: `await component.evaluate((el) => el.setAttribute("theme", "vertical"))`. (In Storybook/Lit templates `theme="vertical"` is already a real attribute, so it works there.)
+- The `on` handler type is `Record<string, Function>`, so typed handler params are fine.
diff --git a/ui/app/storybook/docs/components/or-vaadin-toggle.mdx b/ui/app/storybook/docs/components/or-vaadin-toggle.mdx
new file mode 100644
index 000000000..f42775521
--- /dev/null
+++ b/ui/app/storybook/docs/components/or-vaadin-toggle.mdx
@@ -0,0 +1,27 @@
+{/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/}
+
+import { Meta } from '@storybook/addon-docs/blocks';
+import * as ComponentStory from "../../../../component/or-vaadin-components/stories/or-vaadin-toggle.stories"; // stories need relative imports
+import {ComponentDocs} from "../../util/componentdocs.mdx";
+
+<Meta title="Components/Toggle" />
+
+<ComponentDocs story={ComponentStory} options={{displayName: "Toggle"}} elementsjson={ComponentStory.customElements} />
diff --git a/ui/component/or-vaadin-components/package.json b/ui/component/or-vaadin-components/package.json
index f0d6d2791..5854e8086 100644
--- a/ui/component/or-vaadin-components/package.json
+++ b/ui/component/or-vaadin-components/package.json
@@ -51,6 +51,7 @@
"@vaadin/text-area": "~25.1.4",
"@vaadin/text-field": "~25.1.4",
"@vaadin/time-picker": "~25.1.4",
+ "@vaadin/vaadin-themable-mixin": "~25.1.4",
"lit": "^3.3.1"
},
"publishConfig": {
diff --git a/ui/component/or-vaadin-components/src/or-vaadin-checkbox-group.ts b/ui/component/or-vaadin-components/src/or-vaadin-checkbox-group.ts
index 02340bde2..028d74a6d 100644
--- a/ui/component/or-vaadin-components/src/or-vaadin-checkbox-group.ts
+++ b/ui/component/or-vaadin-components/src/or-vaadin-checkbox-group.ts
@@ -19,10 +19,23 @@
*/
import { customElement } from "lit/decorators.js";
import { CheckboxGroup } from "@vaadin/checkbox-group";
+import { Checkbox } from "@vaadin/checkbox";
import { OrVaadinComponent } from "./util";
import "@vaadin/checkbox";
export type * from "@vaadin/checkbox-group";
@customElement("or-vaadin-checkbox-group")
-export class OrVaadinCheckboxGroup extends CheckboxGroup implements OrVaadinComponent {}
+export class OrVaadinCheckboxGroup extends CheckboxGroup implements OrVaadinComponent {
+
+ /*
+ * Vaadin's `CheckboxGroupMixin` recognises group items via a strict `localName === "vaadin-checkbox"`
+ * check, so wrapped children (`or-vaadin-checkbox`, `or-vaadin-toggle`) would never register: the
+ * group's `value`, its validation and its disabled/readonly propagation would all ignore them.
+ * Accept any `Checkbox` subclass instead. This overrides a private Vaadin API, so re-check it when
+ * upgrading Vaadin (verified against 25.1.4).
+ */
+ private __filterCheckboxes(nodes: Node[]): Checkbox[] {
+ return nodes.filter((node): node is Checkbox => node instanceof Checkbox);
+ }
+}
diff --git a/ui/component/or-vaadin-components/src/or-vaadin-input.ts b/ui/component/or-vaadin-components/src/or-vaadin-input.ts
index b72bd51e6..bb6d6acf6 100644
--- a/ui/component/or-vaadin-components/src/or-vaadin-input.ts
+++ b/ui/component/or-vaadin-components/src/or-vaadin-input.ts
@@ -28,6 +28,7 @@ import "./or-vaadin-select";
import "./or-vaadin-slider";
import "./or-vaadin-text-field";
import "./or-vaadin-text-area";
+import "./or-vaadin-toggle";
/**
* Function to register properties (get/setter) of a CustomElement to the child Vaadin element.
@@ -78,6 +79,7 @@ export class OrVaadinInput extends LitElement {
[InputType.PASSWORD, OrVaadinInput.getPasswordFieldTemplate],
[InputType.RANGE, OrVaadinInput.getSliderTemplate],
[InputType.SELECT, OrVaadinInput.getSelectTemplate],
+ [InputType.SWITCH, OrVaadinInput.getSwitchTemplate],
[InputType.TEXT, OrVaadinInput.getTextFieldTemplate],
[InputType.TEXTAREA, OrVaadinInput.getTextAreaTemplate]
]);
@@ -162,7 +164,8 @@ export class OrVaadinInput extends LitElement {
*/
public get nativeValue(): any {
switch (this.type) {
- case InputType.CHECKBOX: {
+ case InputType.CHECKBOX:
+ case InputType.SWITCH: {
return (this._elem as HTMLInputElement | undefined)?.checked;
}
default: {
@@ -270,6 +273,10 @@ export class OrVaadinInput extends LitElement {
return html`<or-vaadin-slider id="elem" @change=${onChange}></or-vaadin-slider>`
}
+ public static getSwitchTemplate(onChange?: (e: Event) => void) {
+ return html`<or-vaadin-toggle id="elem" @change=${onChange}></or-vaadin-toggle>`;
+ }
+
public static getTextAreaTemplate(onChange?: (e: Event) => void) {
return html`<or-vaadin-text-area id="elem" @change=${onChange}></or-vaadin-text-area>`;
}
diff --git a/ui/component/or-vaadin-components/src/or-vaadin-toggle-group.ts b/ui/component/or-vaadin-components/src/or-vaadin-toggle-group.ts
new file mode 100644
index 000000000..77c12ea5d
--- /dev/null
+++ b/ui/component/or-vaadin-components/src/or-vaadin-toggle-group.ts
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import { customElement } from "lit/decorators.js";
+import { OrVaadinCheckboxGroup } from "./or-vaadin-checkbox-group";
+import "./or-vaadin-toggle";
+
+/*
+ * A checkbox-group specialised for `<or-vaadin-toggle>` children. It exists only to give the toggle
+ * group its own tag so the spacing between toggles can be set (in the theme) without committing the
+ * shared `<or-vaadin-checkbox-group>` to a gap value (still undecided for checkboxes).
+ */
+@customElement("or-vaadin-toggle-group")
+export class OrVaadinToggleGroup extends OrVaadinCheckboxGroup {}
diff --git a/ui/component/or-vaadin-components/src/or-vaadin-toggle.ts b/ui/component/or-vaadin-components/src/or-vaadin-toggle.ts
new file mode 100644
index 000000000..5aea8e37e
--- /dev/null
+++ b/ui/component/or-vaadin-components/src/or-vaadin-toggle.ts
@@ -0,0 +1,163 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {customElement} from "lit/decorators.js";
+import {Checkbox} from "@vaadin/checkbox";
+import {registerStyles, css} from "@vaadin/vaadin-themable-mixin/register-styles.js";
+import {OrVaadinComponent} from "./util";
+import {type LitElement} from "lit";
+
+/*
+ * The toggle reuses the Vaadin `<vaadin-checkbox>` as its base, so it inherits the checkbox's
+ * behaviour, form participation, accessibility and `checked` / `readonly` / `disabled` states.
+ * Only the visuals and the exposed role differ: the `checkbox` part is restyled into a pill-shaped
+ * track with a sliding knob, and the input is exposed as a `switch` to assistive technology.
+ *
+ * The styles are applied through Vaadin's `registerStyles()` rather than a `static get styles()`
+ * override, because `finalizeStyles()` injects `static` styles BEFORE the (Lumo) theme injector,
+ * meaning a themed environment would override them. Styles registered via `registerStyles()` are
+ * injected AFTER the theme, so they always take effect - both when the OpenRemote theme is applied
+ * and when the component is used standalone (hence every value below has a hard-coded fallback
+ * alongside its theme variable).
+ *
+ * `registerStyles()` targets a component by its `is` tag name and must run before the element is
+ * finalized. It is therefore called at module load, and `is` is overridden to `or-vaadin-toggle`
+ * (the base class would otherwise report `vaadin-checkbox`, causing these styles to leak onto every
+ * checkbox, or not match at all).
+ */
+registerStyles("or-vaadin-toggle", css`
+ :host {
+ /* Public variables, overridable by consumers; the values are defaults with standalone fallbacks */
+ --or-toggle-track-width: 30px;
+ --or-toggle-track-height: 20px;
+ --or-toggle-knob-size: 14px;
+ --or-toggle-knob-inset: 3px;
+ --or-toggle-radius: var(--lumo-border-radius-l, 12px);
+ --or-toggle-track-off-color: var(--lumo-contrast-30pct, #c4c8c4);
+ --or-toggle-track-on-color: var(--lumo-primary-color, #47a942);
+ --or-toggle-knob-color: var(--lumo-base-color, #ffffff);
+ --or-toggle-gap: 6px;
+ --or-toggle-transition-duration: 0.15s;
+
+ align-items: center;
+ --vaadin-checkbox-gap: var(--or-toggle-gap);
+ }
+
+ /*
+ * The Vaadin base styles give the label a 500 font weight. Lumo resets that for the checkbox,
+ * but that reset is keyed off 'is' (overridden here), so restore the default weight ourselves.
+ */
+ :host [part='label'],
+ :host([has-label]) ::slotted([slot='label']) {
+ font-weight: 400;
+ }
+
+ /*
+ * Turn the square checkbox part into a pill-shaped track. Selectors are deliberately prefixed
+ * with :host(...) to out-specify the Vaadin/Lumo base rules (e.g. the base hides the ::after
+ * marker with a high-specificity ':host(:not([checked])) [part=checkbox]::after { opacity: 0 }'
+ * rule, which would otherwise hide the knob in the off state).
+ */
+ :host [part='checkbox'] {
+ box-sizing: border-box;
+ width: var(--or-toggle-track-width);
+ min-width: var(--or-toggle-track-width);
+ height: var(--or-toggle-track-height);
+ border: none;
+ border-radius: var(--or-toggle-radius);
+ background: var(--or-toggle-track-off-color);
+ transition: background-color var(--or-toggle-transition-duration, 0.15s) ease-in-out;
+ }
+
+ :host([checked]) [part='checkbox'] {
+ background: var(--or-toggle-track-on-color);
+ }
+
+ :host([disabled]) {
+ opacity: 0.5;
+ }
+
+ /* Replace the checkmark with a sliding knob */
+ :host [part='checkbox']::after {
+ content: "";
+ position: absolute;
+ inset: auto;
+ top: 50%;
+ width: var(--or-toggle-knob-size);
+ height: var(--or-toggle-knob-size);
+ min-width: 0;
+ border-radius: 50%;
+ background: var(--or-toggle-knob-color);
+ mask: none;
+ -webkit-mask: none;
+ filter: none;
+ transform: translateY(-50%);
+ transition: left var(--or-toggle-transition-duration, 0.15s) ease-in-out;
+ }
+
+ :host(:not([checked])) [part='checkbox']::after {
+ opacity: 1;
+ left: var(--or-toggle-knob-inset);
+ }
+
+ :host([checked]) [part='checkbox']::after {
+ opacity: 1;
+ left: calc(var(--or-toggle-track-width) - var(--or-toggle-knob-size) - var(--or-toggle-knob-inset));
+ }
+
+ :host([focus-ring]) [part='checkbox'] {
+ outline: 2px solid var(--or-toggle-track-on-color);
+ outline-offset: 2px;
+ }
+`);
+
+/**
+ * A toggle (switch) component representing a binary on/off choice.
+ *
+ * @customElement "or-vaadin-toggle"
+ * @fires {Event} change - Fired when the toggle is switched on or off by the user.
+ * @fires {CustomEvent} checked-changed - Fired when the `checked` property changes.
+ * @cssprop --or-toggle-track-width - Width of the track.
+ * @cssprop --or-toggle-track-height - Height of the track.
+ * @cssprop --or-toggle-knob-size - Diameter of the sliding knob.
+ * @cssprop --or-toggle-knob-inset - Distance between the knob and the track edge.
+ * @cssprop --or-toggle-radius - Border radius of the track.
+ * @cssprop --or-toggle-track-off-color - Track color in the off state.
+ * @cssprop --or-toggle-track-on-color - Track color in the on state.
+ * @cssprop --or-toggle-knob-color - Color of the knob.
+ * @cssprop --or-toggle-gap - Gap between the track and the label.
+ * @cssprop --or-toggle-transition-duration - Duration of the track color and knob slide transitions.
+ */
+@customElement("or-vaadin-toggle")
+export class OrVaadinToggle extends (Checkbox as new () => Checkbox & LitElement) implements OrVaadinComponent {
+
+ static get is() {
+ return "or-vaadin-toggle";
+ }
+
+ /**
+ * Exposes the control to assistive technology as a switch instead of a checkbox, matching its
+ * on/off semantics (and the `role="switch"` of the or-mwc-input switch it replaces). The native
+ * checkbox input keeps mapping its checked state to `aria-checked`.
+ */
+ protected override _inputElementChanged(input: HTMLElement, oldInput: HTMLElement) {
+ super._inputElementChanged(input, oldInput);
+ input?.setAttribute("role", "switch");
+ }
+}
diff --git a/ui/component/or-vaadin-components/src/value-input-provider.ts b/ui/component/or-vaadin-components/src/value-input-provider.ts
index c3cc4e2aa..332d2f306 100644
--- a/ui/component/or-vaadin-components/src/value-input-provider.ts
+++ b/ui/component/or-vaadin-components/src/value-input-provider.ts
@@ -105,7 +105,7 @@ export const getValueHolderInputTemplateProvider: ValueInputProviderGenerator =
const constraints: ValueConstraint[] = (valueHolder && ((valueHolder as MetaHolder).meta) || (valueDescriptor && (valueDescriptor as MetaHolder).meta) ? Util.getAttributeValueConstraints(valueHolder as Attribute<any>, valueHolderDescriptor as AttributeDescriptor, assetType) : Util.getMetaValueConstraints(valueHolder as NameValueHolder<any>, valueHolderDescriptor as AttributeDescriptor, assetType)) || [];
const format: ValueFormat | undefined = (valueHolder && ((valueHolder as MetaHolder).meta) || (valueDescriptor && (valueDescriptor as MetaHolder).meta) ? Util.getAttributeValueFormat(valueHolder as Attribute<any>, valueHolderDescriptor as AttributeDescriptor, assetType) : Util.getMetaValueFormat(valueHolder as Attribute<any>, valueHolderDescriptor as AttributeDescriptor, assetType));
- const supportsVaadinInput = (type: InputType) => (OrVaadinInput.TEMPLATES.has(type) && !format?.asOnOff);
+ const supportsVaadinInput = (type: InputType) => OrVaadinInput.TEMPLATES.has(type);
// Enforces which value types are supported making SUPPORTED_WELLKNOWN_VALUE_TYPES the single source of truth through type checking
let _exhaustiveTypeCheck: never
@@ -333,9 +333,9 @@ export const getValueHolderInputTemplateProvider: ValueInputProviderGenerator =
if (supportsVaadinInput(inputType)) {
- // or-vaadin-checkbox has multiple states (like indeterminate), so it uses the 'checked' HTML attribute instead of 'value'.
+ // or-vaadin-checkbox and or-vaadin-toggle represent a boolean state, so they use the 'checked' HTML attribute instead of 'value'.
let checked = false;
- if (inputType === InputType.CHECKBOX) {
+ if (inputType === InputType.CHECKBOX || inputType === InputType.SWITCH) {
checked = Boolean(value);
value = undefined;
}
diff --git a/ui/component/or-vaadin-components/stories/or-vaadin-toggle.stories.ts b/ui/component/or-vaadin-components/stories/or-vaadin-toggle.stories.ts
new file mode 100644
index 000000000..402b87ded
--- /dev/null
+++ b/ui/component/or-vaadin-components/stories/or-vaadin-toggle.stories.ts
@@ -0,0 +1,135 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {setCustomElementsManifest, type Meta, type StoryObj} from "@storybook/web-components";
+import {getORStorybookHelpers} from "../../storybook-utils";
+import customElements from "../custom-elements.json" with {type: "json"};
+import packageJson from "../package.json" with {type: "json"};
+import {html} from "lit";
+import "../src/or-vaadin-toggle";
+import "../src/or-vaadin-toggle-group";
+
+const tagName = "or-vaadin-toggle";
+type Story = StoryObj;
+setCustomElementsManifest(customElements);
+
+const { events, args, argTypes, template } = getORStorybookHelpers(tagName);
+
+const meta: Meta = {
+ title: "Playground/or-vaadin-components/toggle",
+ component: tagName,
+ args: args,
+ argTypes: argTypes,
+ render: storyArgs => template(storyArgs),
+ excludeStories: /^[a-z].*/,
+ parameters: {
+ actions: {
+ handles: events
+ },
+ docs: {
+ subtitle: `<${tagName}>`,
+ description: "Toggle is an input field representing a binary on/off choice. It reuses the Vaadin checkbox as its base, so it supports the same states (checked, disabled, readonly, required) and events (`change`, `checked-changed`), while being exposed to assistive technology as a switch."
+ }
+ }
+};
+
+export const Primary: Story = {
+ args: {
+ label: "Toggle",
+ checked: true
+ }
+};
+
+/** Disabled and readonly toggles, in both the off and on state. */
+export const DisabledReadonly: Story = {
+ name: "Disabled & Readonly",
+ parameters: {
+ title: "Disabled & Readonly",
+ summary: "Use `disabled` to block interaction entirely and `readonly` to show a value that cannot be edited. Both combine with `checked`.",
+ docs: {
+ story: {
+ height: "130px"
+ }
+ }
+ },
+ render: () => html`
+ <div style="display: grid; grid-template-columns: repeat(2, max-content); gap: 24px 64px; padding: 8px;">
+ <or-vaadin-toggle label="Disabled, off" disabled></or-vaadin-toggle>
+ <or-vaadin-toggle label="Disabled, on" checked disabled></or-vaadin-toggle>
+ <or-vaadin-toggle label="Readonly, off" readonly></or-vaadin-toggle>
+ <or-vaadin-toggle label="Readonly, on" checked readonly></or-vaadin-toggle>
+ </div>
+ `
+};
+
+/** Several toggles combined inside a toggle group, in both orientations. */
+export const Groups: Story = {
+ name: "Groups",
+ parameters: {
+ title: "Groups",
+ summary: "Multiple toggles can be combined inside an `<or-vaadin-toggle-group>` to share a group label, helper text and validation. Under the theme the group is horizontal by default; use `theme=\"vertical\"` to stack them.",
+ docs: {
+ story: {
+ height: "280px"
+ }
+ }
+ },
+ render: () => html`
+ <div style="display: flex; flex-direction: column; gap: 32px; padding: 8px;">
+ <or-vaadin-toggle-group label="Notifications (vertical)" theme="vertical" helper-text="Choose how you want to be notified">
+ <or-vaadin-toggle label="Email" value="email" checked></or-vaadin-toggle>
+ <or-vaadin-toggle label="SMS" value="sms"></or-vaadin-toggle>
+ <or-vaadin-toggle label="Push" value="push" checked></or-vaadin-toggle>
+ </or-vaadin-toggle-group>
+
+ <or-vaadin-toggle-group label="Notifications (horizontal)" helper-text="Choose how you want to be notified">
+ <or-vaadin-toggle label="Email" value="email" checked></or-vaadin-toggle>
+ <or-vaadin-toggle label="SMS" value="sms"></or-vaadin-toggle>
+ <or-vaadin-toggle label="Push" value="push" checked></or-vaadin-toggle>
+ </or-vaadin-toggle-group>
+ </div>
+ `
+};
+
+/** Helper text gives extra context below the toggle. */
+export const HelperText: Story = {
+ name: "Helper text",
+ parameters: {
+ title: "Helper text",
+ summary: "Use `helper-text` to show additional context below the toggle, for example to explain why a choice is `required`.",
+ docs: {
+ story: {
+ height: "110px"
+ }
+ }
+ },
+ render: () => html`
+ <div style="display: grid; grid-template-columns: repeat(2, max-content); gap: 24px 64px; padding: 8px;">
+ <or-vaadin-toggle label="With helper text" checked helper-text="Additional context shown below the toggle"></or-vaadin-toggle>
+ <or-vaadin-toggle label="Required" required helper-text="This choice is required"></or-vaadin-toggle>
+ </div>
+ `
+};
+
+export const examples = [DisabledReadonly, Groups, HelperText];
+
+export {customElements, packageJson};
+
+
+export default meta;
diff --git a/ui/component/or-vaadin-components/test/or-vaadin-toggle.test.ts b/ui/component/or-vaadin-components/test/or-vaadin-toggle.test.ts
new file mode 100644
index 000000000..dc5075d8d
--- /dev/null
+++ b/ui/component/or-vaadin-components/test/or-vaadin-toggle.test.ts
@@ -0,0 +1,362 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import { ct, expect, type Locator } from "@openremote/test";
+
+import { OrVaadinToggle } from "@openremote/or-vaadin-components/or-vaadin-toggle";
+import { OrVaadinToggleGroup } from "@openremote/or-vaadin-components/or-vaadin-toggle-group";
+
+/*
+ * These tests mirror the scenarios in `stories/or-vaadin-toggle.stories.ts`:
+ * the Primary, "Disabled & Readonly", "Helper text" and "Groups"
+ * (vertical + horizontal) stories.
+ *
+ * Note: the component-test runner (@sand4rt/experimental-ct-web) forwards only
+ * `event.detail` to `on` handlers, so the boolean state that comes through is
+ * asserted via the `checked-changed` event (detail = `{ value: boolean }`); the
+ * native `change` event carries no useful detail so it is only counted.
+ */
+
+ct.describe("Primary", () => {
+ ct("renders label and checked state", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, {
+ props: { label: "Toggle", checked: true },
+ });
+
+ // The toggle is exposed to assistive technology with the `switch` role, not `checkbox`.
+ await expect(component.getByRole("switch", { name: "Toggle" })).toBeChecked();
+ await expect(component).toContainText("Toggle");
+ });
+});
+
+ct.describe("Events", () => {
+ ct("change + checked-changed emit the new value on user toggle", async ({ mount }) => {
+ const checkedChanges: boolean[] = [];
+ let changeCount = 0;
+
+ const component = await mount(OrVaadinToggle, {
+ props: { label: "Toggle" },
+ on: {
+ change: () => {
+ changeCount += 1;
+ },
+ "checked-changed": (detail: { value: boolean }) => {
+ checkedChanges.push(detail.value);
+ },
+ },
+ });
+
+ const input = component.getByRole("switch", { name: "Toggle" });
+ await expect(input).not.toBeChecked();
+
+ // Turn on
+ await input.click();
+ await expect(input).toBeChecked();
+
+ // Turn off
+ await input.click();
+ await expect(input).not.toBeChecked();
+
+ // Vaadin emits an initial checked-changed(false) at mount, so assert on the user-driven
+ // transitions (the last two values) and that `change` only fires on interaction.
+ await expect.poll(() => changeCount).toBe(2);
+ await expect.poll(() => checkedChanges.slice(-2)).toEqual([true, false]);
+ });
+});
+
+ct.describe("State", () => {
+ ct("off (default) is unchecked", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, { props: { label: "Off (default)" } });
+ await expect(component.getByRole("switch", { name: "Off (default)" })).not.toBeChecked();
+ });
+
+ ct("on is checked", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, { props: { label: "On", checked: true } });
+ await expect(component.getByRole("switch", { name: "On" })).toBeChecked();
+ });
+
+ ct("disabled cannot be toggled and emits no change event", async ({ mount }) => {
+ const checkedChanges: boolean[] = [];
+ let changeCount = 0;
+ const component = await mount(OrVaadinToggle, {
+ props: { label: "Disabled", disabled: true },
+ on: {
+ change: () => {
+ changeCount += 1;
+ },
+ "checked-changed": (detail: { value: boolean }) => checkedChanges.push(detail.value),
+ },
+ });
+
+ const input = component.getByRole("switch", { name: "Disabled" });
+ await expect(input).toBeDisabled();
+ await input.click({ force: true });
+ await expect(input).not.toBeChecked();
+ // The click must fire no `change` event (which has no mount-time noise); and `checked-changed`
+ // must never carry `true` (a single checked-changed(false) may be emitted once at mount).
+ expect(changeCount).toBe(0);
+ expect(checkedChanges).not.toContain(true);
+ });
+
+ ct("disabled + on stays checked", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, { props: { label: "Disabled on", checked: true, disabled: true } });
+ const input = component.getByRole("switch", { name: "Disabled on" });
+ await expect(input).toBeDisabled();
+ await expect(input).toBeChecked();
+ });
+
+ ct("readonly does not change on click and emits no change event", async ({ mount }) => {
+ const checkedChanges: boolean[] = [];
+ let changeCount = 0;
+ const component = await mount(OrVaadinToggle, {
+ props: { label: "Readonly", readonly: true },
+ on: {
+ change: () => {
+ changeCount += 1;
+ },
+ "checked-changed": (detail: { value: boolean }) => checkedChanges.push(detail.value),
+ },
+ });
+
+ const input = component.getByRole("switch", { name: "Readonly" });
+ await input.click({ force: true });
+ await expect(input).not.toBeChecked();
+ // The click must fire no `change` event (which has no mount-time noise); and `checked-changed`
+ // must never carry `true` (a single checked-changed(false) may be emitted once at mount).
+ expect(changeCount).toBe(0);
+ expect(checkedChanges).not.toContain(true);
+ });
+
+ ct("readonly + on stays checked", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, { props: { label: "Readonly on", checked: true, readonly: true } });
+ await expect(component.getByRole("switch", { name: "Readonly on" })).toBeChecked();
+ });
+
+ ct("helper text renders below the toggle", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, {
+ props: { label: "Toggle", helperText: "Helper text shown below the toggle" },
+ });
+
+ await expect(component).toContainText("Helper text shown below the toggle");
+ await expect(component).toHaveAttribute("has-helper");
+ });
+
+ ct("required reflects the required attribute", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, { props: { label: "Required", required: true } });
+ await expect(component).toHaveAttribute("required");
+ });
+
+ ct("renders without a label", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, { props: { checked: true } });
+ await expect(component.getByRole("switch")).toBeChecked();
+ await expect(component).not.toHaveAttribute("has-label");
+ });
+});
+
+ct.describe("Group", () => {
+ ct("vertical: stacks grouped toggles in a column layout", async ({ mount }) => {
+ const component = await mount(OrVaadinToggleGroup, {
+ props: { label: "Notifications" },
+ hooksConfig: { components: [OrVaadinToggle] },
+ slots: {
+ default: [
+ '<or-vaadin-toggle label="Email" value="email"></or-vaadin-toggle>',
+ '<or-vaadin-toggle label="SMS" value="sms"></or-vaadin-toggle>',
+ '<or-vaadin-toggle label="Push" value="push"></or-vaadin-toggle>',
+ ],
+ },
+ });
+
+ // `theme` is attribute-driven (there is no writable reflecting property), and mount `props` set JS
+ // properties which Vaadin's theme handling ignores - so set the vertical theme as an attribute.
+ await component.evaluate((el) => el.setAttribute("theme", "vertical"));
+
+ await expect(component).toContainText("Notifications");
+ await expect(component.getByRole("switch")).toHaveCount(3);
+
+ // The vertical theme stacks the toggles: shared left edge, increasing top.
+ const email = await component.getByRole("switch", { name: "Email" }).boundingBox();
+ const sms = await component.getByRole("switch", { name: "SMS" }).boundingBox();
+ expect(email).not.toBeNull();
+ expect(sms).not.toBeNull();
+ expect(Math.abs(email!.x - sms!.x)).toBeLessThan(4);
+ expect(sms!.y).toBeGreaterThan(email!.y);
+ });
+
+ ct("horizontal: renders grouped toggles in a row layout", async ({ mount }) => {
+ const component = await mount(OrVaadinToggleGroup, {
+ props: { label: "Notifications" },
+ hooksConfig: { components: [OrVaadinToggle] },
+ slots: {
+ default: [
+ '<or-vaadin-toggle label="Email" value="email"></or-vaadin-toggle>',
+ '<or-vaadin-toggle label="SMS" value="sms"></or-vaadin-toggle>',
+ '<or-vaadin-toggle label="Push" value="push"></or-vaadin-toggle>',
+ ],
+ },
+ });
+
+ await expect(component.getByRole("switch")).toHaveCount(3);
+
+ // Under the theme the group is horizontal by default: the toggles share a row (same top edge).
+ const first = await component.getByRole("switch", { name: "Email" }).boundingBox();
+ const second = await component.getByRole("switch", { name: "SMS" }).boundingBox();
+ expect(first).not.toBeNull();
+ expect(second).not.toBeNull();
+ expect(Math.abs(first!.y - second!.y)).toBeLessThan(4);
+ expect(second!.x).toBeGreaterThan(first!.x);
+ });
+
+ ct("registers toggles as group items and tracks the group value", async ({ mount }) => {
+ // Guards the `__filterCheckboxes` override in `or-vaadin-checkbox-group`: without it, Vaadin only
+ // registers literal `vaadin-checkbox` tags and the group `value` would stay empty.
+ const component = await mount(OrVaadinToggleGroup, {
+ props: { label: "Notifications" },
+ hooksConfig: { components: [OrVaadinToggle] },
+ slots: {
+ default: [
+ '<or-vaadin-toggle label="Email" value="email"></or-vaadin-toggle>',
+ '<or-vaadin-toggle label="SMS" value="sms"></or-vaadin-toggle>',
+ '<or-vaadin-toggle label="Push" value="push"></or-vaadin-toggle>',
+ ],
+ },
+ });
+
+ await expect.poll(() => component.evaluate((el: any) => el.value)).toEqual([]);
+
+ await component.getByRole("switch", { name: "Email" }).click();
+ await expect.poll(() => component.evaluate((el: any) => el.value)).toEqual(["email"]);
+
+ await component.getByRole("switch", { name: "Push" }).click();
+ await expect.poll(() => component.evaluate((el: any) => el.value)).toEqual(["email", "push"]);
+
+ await component.getByRole("switch", { name: "SMS" }).click();
+ await expect.poll(() => component.evaluate((el: any) => el.value)).toEqual(["email", "push", "sms"]);
+
+ await component.getByRole("switch", { name: "Email" }).click();
+ await expect.poll(() => component.evaluate((el: any) => el.value)).toEqual(["push", "sms"]);
+ });
+
+ ct("disabled and readonly propagate to the slotted toggles", async ({ mount }) => {
+ const component = await mount(OrVaadinToggleGroup, {
+ props: { label: "Notifications" },
+ hooksConfig: { components: [OrVaadinToggle] },
+ slots: {
+ default: [
+ '<or-vaadin-toggle label="Email" value="email"></or-vaadin-toggle>',
+ '<or-vaadin-toggle label="SMS" value="sms"></or-vaadin-toggle>',
+ ],
+ },
+ });
+
+ await component.evaluate((el: any) => {
+ el.disabled = true;
+ });
+ await expect(component.getByRole("switch", { name: "Email" })).toBeDisabled();
+ await expect(component.getByRole("switch", { name: "SMS" })).toBeDisabled();
+
+ await component.evaluate((el: any) => {
+ el.disabled = false;
+ el.readonly = true;
+ });
+ const email = component.getByRole("switch", { name: "Email" });
+ await email.click({ force: true });
+ await expect(email).not.toBeChecked();
+ });
+
+ ct("a child toggle switches independently when clicked", async ({ mount }) => {
+ // Note: Vaadin's `checked-changed` is dispatched without `bubbles`/`composed`, so it does not
+ // reach a group-level listener - the per-toggle event flow is covered by the "Events" tests above.
+ const component = await mount(OrVaadinToggleGroup, {
+ props: { label: "Notifications" },
+ hooksConfig: { components: [OrVaadinToggle] },
+ slots: {
+ default: [
+ '<or-vaadin-toggle label="Email" value="email"></or-vaadin-toggle>',
+ '<or-vaadin-toggle label="SMS" value="sms"></or-vaadin-toggle>',
+ ],
+ },
+ });
+
+ const email = component.getByRole("switch", { name: "Email" });
+ const sms = component.getByRole("switch", { name: "SMS" });
+ await email.click();
+ await expect(email).toBeChecked();
+ await expect(sms).not.toBeChecked();
+ });
+});
+
+/*
+ * Image snapshots are not used in this repo, so the toggle's key visual invariants are asserted
+ * through computed styles instead. This guards the restyled shadow internals against Vaadin
+ * upgrades: a change in the base checkbox styles could otherwise e.g. hide the knob in the off
+ * state or restore the 500 label weight without any of the behavioural tests failing.
+ * The expected values are the defaults of the public `--or-toggle-*` variables.
+ */
+ct.describe("Styling", () => {
+ /** Reads the computed styles of the sliding knob (the `::after` pseudo-element of the track). */
+ function getKnobStyles(track: Locator) {
+ return track.evaluate((el) => {
+ const style = getComputedStyle(el, "::after");
+ return { width: style.width, height: style.height, opacity: style.opacity, left: style.left };
+ });
+ }
+
+ ct("track is a 30x20 pill that changes color when toggled on", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, { props: { label: "Toggle" } });
+ const track = component.locator("[part='checkbox']");
+
+ await expect(track).toHaveCSS("width", "30px");
+ await expect(track).toHaveCSS("height", "20px");
+
+ const offColor = await track.evaluate((el) => getComputedStyle(el).backgroundColor);
+ await component.getByRole("switch").click();
+ await expect(track).not.toHaveCSS("background-color", offColor);
+ });
+
+ ct("knob is visible in both states and slides when toggled", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, { props: { label: "Toggle" } });
+ const track = component.locator("[part='checkbox']");
+
+ // Off state: the knob must be visible at the left inset. The Vaadin base styles hide the
+ // checkmark marker when unchecked, which must not apply to the knob.
+ await expect
+ .poll(() => getKnobStyles(track))
+ .toEqual({ width: "14px", height: "14px", opacity: "1", left: "3px" });
+
+ await component.getByRole("switch").click();
+
+ // On state: still visible, slid to the right (track width - knob size - inset).
+ await expect
+ .poll(() => getKnobStyles(track))
+ .toEqual({ width: "14px", height: "14px", opacity: "1", left: "13px" });
+ });
+
+ ct("label uses the default 400 font weight", async ({ mount }) => {
+ // The Vaadin base styles set a 500 label weight that Lumo normally resets; the toggle
+ // restores the default weight itself because the Lumo reset is keyed off the overridden `is`.
+ const component = await mount(OrVaadinToggle, { props: { label: "Toggle" } });
+ await expect(component.locator("[part='label']")).toHaveCSS("font-weight", "400");
+ });
+
+ ct("disabled dims the whole toggle", async ({ mount }) => {
+ const component = await mount(OrVaadinToggle, { props: { label: "Disabled", disabled: true } });
+ await expect(component).toHaveCSS("opacity", "0.5");
+ });
+});
diff --git a/ui/component/theme/src/components/index.css b/ui/component/theme/src/components/index.css
index af002a593..16e0dc385 100644
--- a/ui/component/theme/src/components/index.css
+++ b/ui/component/theme/src/components/index.css
@@ -42,3 +42,4 @@
@import "./or-vaadin-text-area.css";
@import "./or-vaadin-text-field.css";
@import "./or-vaadin-time-picker.css"; /* Must be after the date-time-picker */
+@import "./or-vaadin-toggle-group.css"; /* Must be after the checkbox-group */
diff --git a/ui/component/theme/src/components/or-vaadin-toggle-group.css b/ui/component/theme/src/components/or-vaadin-toggle-group.css
new file mode 100644
index 000000000..8c7f1ef5d
--- /dev/null
+++ b/ui/component/theme/src/components/or-vaadin-toggle-group.css
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/*
+ * Spacing between grouped toggles. Scoped to the `or-vaadin-toggle-group` tag (not the shared
+ * `or-vaadin-checkbox-group`, whose gap is still undecided) via an external `::part()` rule.
+ * row-gap = --lumo-space-xs, column-gap = --lumo-space-m.
+ */
+or-vaadin-toggle-group::part(group-field) {
+ gap: var(--lumo-space-xs) var(--lumo-space-m);
+}
diff --git a/ui/test/fixtures/component.ts b/ui/test/fixtures/component.ts
index 3a153f804..2bd5e3c01 100644
--- a/ui/test/fixtures/component.ts
+++ b/ui/test/fixtures/component.ts
@@ -19,11 +19,21 @@ type ComponentSlots = Record<string, ComponentSlot> & { default?: ComponentSlot
type ComponentEvents = Record<string, (detail: any) => void>;
+export interface ComponentHooksConfig {
+ /**
+ * Components used by the mounted markup as slotted/appended children rather than as the test
+ * root. Playwright CT only imports the `mount()`ed component, so components listed here are
+ * imported (and thereby registered with `customElements.define`) by the `beforeMount` hook in
+ * `playwright/index.js` before the test mounts.
+ */
+ components?: (new (...args: any[]) => HTMLElement)[];
+}
+
export interface MountOptions<HooksConfig, Component extends HTMLElement> {
props?: ComponentProps<Component>;
slots?: ComponentSlots;
on?: ComponentEvents;
- hooksConfig?: HooksConfig;
+ hooksConfig?: HooksConfig & ComponentHooksConfig;
}
export interface MountResult<Component extends HTMLElement> extends Locator {
diff --git a/ui/test/playwright/index.js b/ui/test/playwright/index.js
index 910a49a2a..1e44cbe00 100644
--- a/ui/test/playwright/index.js
+++ b/ui/test/playwright/index.js
@@ -8,6 +8,21 @@ import HttpBackend from "i18next-http-backend";
import { IconSets, OrIconSet, createMdiIconSet, createSvgIconSet } from "@openremote/or-icon";
import { AssetEventCause, AssetModelUtil, ClientRole } from "@openremote/model";
+import { beforeMount } from "@sand4rt/experimental-ct-web/hooks";
+
+// Playwright CT imports a component's module only when it is `mount()`ed, so a custom element that
+// only appears as a slotted/appended child inside the mounted component would never be defined. A
+// test declares such components via `hooksConfig.components` (see `ComponentHooksConfig`); their
+// import refs are resolved here, which runs their modules and registers them before the mount.
+beforeMount(async ({ hooksConfig }) => {
+ const components = Array.isArray(hooksConfig?.components) ? hooksConfig.components : [];
+ for (const component of components) {
+ if (component?.__pw_type === "importRef") {
+ await window.__pwRegistry?.resolveImportRef(component);
+ }
+ }
+});
+
const style = document.createElement("style");
style.textContent = themeCss;
document.head.appendChild(style);
diff --git a/yarn.lock b/yarn.lock
index 30c2cbb5b..b7af8cf68 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2433,6 +2433,7 @@ __metadata:
"@vaadin/text-area": "npm:~25.1.4"
"@vaadin/text-field": "npm:~25.1.4"
"@vaadin/time-picker": "npm:~25.1.4"
+ "@vaadin/vaadin-themable-mixin": "npm:~25.1.4"
lit: "npm:^3.3.1"
languageName: unknown
linkType: soft