Skip to content

armgit / core

Public Imported from GitHub
0

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

fix: commit location coordinates input on blur so Save enables (#3017)

Matt Van Hornf9ac14b7d334
diff --git a/AGENTS.md b/AGENTS.md
index 551a838ba..be83d9c25 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -86,6 +86,7 @@ Stories call `getORStorybookHelpers(tagName)` (from `ui/component/storybook-util
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`). CI runs `./gradlew -p ui/component npmTest`, which only executes packages that register an `npmTest` task, so when adding the first test to a package also register `npmTest` (and `npmTestUI`) in its `build.gradle` file; copy the tasks from a sibling package. 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.
+- **Use only one `mount()` call per test.** Multiple mounts do not resolve to separate locator paths and can hang until the test times out on a strict mode violation.
- **Imports referenced outside a `mount()` call are evaluated in Node, where browser-only modules crash.** Any such usage (a props-building helper, a spread like `...StandardRenderers`) makes Node evaluate the imported module chain, which crashes on the `require("*.css")` calls in `or-mwc-components` (`SyntaxError: Unexpected token '.'`). Pass non-serializable values such as renderer arrays as bare identifiers inline in the `mount()` props. The inverse also holds: imported plain *data* referenced inside `mount()` is mistaken for a component and replaced by an import-ref object, so extract the needed values to a local variable outside the call first (`const id = importedAsset.id`).
- **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([])`.
diff --git a/ui/component/or-map/build.gradle b/ui/component/or-map/build.gradle
index 1f2c121dc..0cc980e7a 100644
--- a/ui/component/or-map/build.gradle
+++ b/ui/component/or-map/build.gradle
@@ -26,3 +26,13 @@ tasks.register('npmBuild', Exec) {
dependsOn getYarnInstallTask()
commandLine npmCommand("yarn"), "run", "build"
}
+
+tasks.register('npmTest', Exec) {
+ dependsOn getYarnInstallTask()
+ commandLine npmCommand("yarn"), "run", "test"
+}
+
+tasks.register('npmTestUI', Exec) {
+ dependsOn getYarnInstallTask()
+ commandLine npmCommand("yarn"), "run", "test", "--ui"
+}
diff --git a/ui/component/or-map/package.json b/ui/component/or-map/package.json
index 330075f49..e76d52a9c 100644
--- a/ui/component/or-map/package.json
+++ b/ui/component/or-map/package.json
@@ -16,7 +16,7 @@
"scripts": {
"analyze": "npx cem analyze --config ../custom-elements-manifest.config.mjs",
"build": "npx tsc -b",
- "test": "echo \"No tests\" && exit 0",
+ "test": "npx tsc -b && npx playwright test",
"prepack": "npx rspack"
},
"author": "OpenRemote",
diff --git a/ui/component/or-map/playwright.config.ts b/ui/component/or-map/playwright.config.ts
new file mode 100644
index 000000000..94d454129
--- /dev/null
+++ b/ui/component/or-map/playwright.config.ts
@@ -0,0 +1,3 @@
+import { defineCtConfig } from "@openremote/test/component.config";
+
+export default defineCtConfig(__dirname);
diff --git a/ui/component/or-map/src/controls/coordinates.ts b/ui/component/or-map/src/controls/coordinates.ts
index 8109d57a2..78b7de9f8 100644
--- a/ui/component/or-map/src/controls/coordinates.ts
+++ b/ui/component/or-map/src/controls/coordinates.ts
@@ -22,24 +22,38 @@ import { OrMapBaseControl } from "./base";
import "@openremote/or-vaadin-components/or-vaadin-text-field";
import "@openremote/or-icon";
-export const CoordinatesRegexPattern = "^[ ]*(?:Lat: )?(-?\\d+\\.?\\d*)[, ]+(?:Lng: )?(-?\\d+\\.?\\d*)[ ]*$";
+const CoordinateNumberPattern = "-?\\d+\\.?\\d*";
+export const CoordinatesRegexPattern = `^[ ]*(?:Lat:[ ]*(${CoordinateNumberPattern})[, ]+Lng:[ ]*(${CoordinateNumberPattern})|(${CoordinateNumberPattern})[, ]+(${CoordinateNumberPattern}))[ ]*$`;
-export function getCoordinatesInputKeyHandler(valueChangedHandler: (value: LngLat | undefined) => void) {
+export function commitCoordinatesInputValue(e: Event, valueChangedHandler: (value: LngLat | null) => void) {
+ const input = e.target as HTMLInputElement;
+ if (input.readOnly || input.disabled || input.hasAttribute("readonly") || input.hasAttribute("disabled")) {
+ return;
+ }
+
+ if (!input.value.trim()) {
+ valueChangedHandler(null);
+ return;
+ }
+
+ const match = new RegExp(CoordinatesRegexPattern).exec(input.value);
+ if (!match) {
+ return;
+ }
+
+ const lng = Number(match[2] ?? match[3]);
+ const lat = Number(match[1] ?? match[4]);
+ if (!Number.isFinite(lng) || !Number.isFinite(lat) || lng < -180 || lng > 180 || lat < -90 || lat > 90) {
+ return;
+ }
+
+ valueChangedHandler(new LngLat(lng, lat));
+}
+
+export function getCoordinatesInputKeyHandler(valueChangedHandler: (value: LngLat | null) => void) {
return (e: KeyboardEvent) => {
if (e.code === "Enter" || e.code === "NumpadEnter") {
- const valStr = (e.target as any).value as string;
- let value: LngLat | undefined = !valStr ? undefined : {} as LngLat;
-
- if (valStr) {
- const lngLatArr = valStr.split(/[ ,]/).filter(v => !!v);
- if (lngLatArr.length === 2) {
- value = new LngLat(
- Number.parseFloat(lngLatArr[0]),
- Number.parseFloat(lngLatArr[1])
- );
- }
- }
- valueChangedHandler(value);
+ commitCoordinatesInputValue(e, valueChangedHandler);
}
};
}
@@ -48,9 +62,9 @@ export class CoordinatesControl extends OrMapBaseControl {
protected input?: HTMLElement;
protected _readonly = false;
protected _value: any;
- protected _valueChangedHandler: (value: LngLat | undefined) => void;
+ protected _valueChangedHandler: (value: LngLat | null) => void;
- constructor(disabled = false, valueChangedHandler: (value: LngLat | undefined) => void) {
+ constructor(disabled = false, valueChangedHandler: (value: LngLat | null) => void) {
super();
this._readonly = disabled;
this._valueChangedHandler = valueChangedHandler;
@@ -64,6 +78,7 @@ export class CoordinatesControl extends OrMapBaseControl {
if (this._value != null) (input as any).value = this._value;
input.setAttribute("pattern", CoordinatesRegexPattern);
input.addEventListener("keyup", getCoordinatesInputKeyHandler(this._valueChangedHandler) as EventListener);
+ input.addEventListener("change", (e) => commitCoordinatesInputValue(e, this._valueChangedHandler));
const icon = document.createElement("or-icon") as HTMLElement;
icon.setAttribute("icon", "mdi:crosshairs");
diff --git a/ui/component/or-map/src/index.ts b/ui/component/or-map/src/index.ts
index dd2571cc3..ee9b8b627 100644
--- a/ui/component/or-map/src/index.ts
+++ b/ui/component/or-map/src/index.ts
@@ -36,7 +36,7 @@ import {getMarkerIconAndColorFromAssetType} from "./util";
import {i18next} from "@openremote/or-translate";
import debounce from "lodash.debounce";
import { AttributeEvent, GeoJsonConfig } from "@openremote/model";
-import { CoordinatesControl, CoordinatesRegexPattern, getCoordinatesInputKeyHandler } from "./controls/coordinates";
+import { commitCoordinatesInputValue, CoordinatesControl, CoordinatesRegexPattern, getCoordinatesInputKeyHandler } from "./controls/coordinates";
import { AssetMap } from "./asset-map";
import { OrMapCenterControl } from "./controls/center";
import { OrMapGeolocateControl } from "./controls/geolocate";
@@ -128,7 +128,7 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
const compact = !!(options && options.compact);
const centerControl = new OrMapCenterControl();
- const valueChangeHandler = (value: LngLatLike | undefined) => {
+ const valueChangeHandler = (value: LngLatLike | null | undefined) => {
if (!valueChangeNotifier) {
return;
}
@@ -259,7 +259,8 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
}
</style>
<div id="geo-json-point-input-compact-wrapper">
- <or-vaadin-text-field style="width: auto;" value=${ifDefined(centerStr)} pattern=${CoordinatesRegexPattern}
+ <or-vaadin-text-field style="width: auto;" value=${ifDefined(centerStr)} pattern=${CoordinatesRegexPattern} ?readonly=${readonly} ?disabled=${disabled || sending || loading}
+ @change="${(e: Event) => commitCoordinatesInputValue(e, valueChangeHandler)}"
@keyup="${(e: KeyboardEvent) => getCoordinatesInputKeyHandler(valueChangeHandler)(e)}">
</or-vaadin-text-field>
<or-vaadin-button theme="icon" @click=${onClick}>
diff --git a/ui/component/or-map/test/coordinates.test.ts b/ui/component/or-map/test/coordinates.test.ts
new file mode 100644
index 000000000..44b92c230
--- /dev/null
+++ b/ui/component/or-map/test/coordinates.test.ts
@@ -0,0 +1,69 @@
+/*
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+import { ct, expect, type SharedComponentTestFixtures } from "@openremote/test";
+import { CoordinatesControlFixture } from "./fixtures/coordinates-control.js";
+
+type Mount = SharedComponentTestFixtures["mount"];
+async function mountCoordinatesControl(mount: Mount, value: string, event: "change" | "Enter", readonly = false) {
+ const fixture = await mount(CoordinatesControlFixture);
+ return fixture.evaluate((element, args) => (element as HTMLElement & {
+ commit(value: string, event: "change" | "Enter", readonly: boolean): {lng: number, lat: number} | null | undefined;
+ }).commit(args.value, args.event, args.readonly), {value, event, readonly});
+}
+
+ct("should commit valid coordinates on change", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, "4.89, 52.37", "change")).toEqual({lng: 4.89, lat: 52.37});
+});
+
+ct("should commit valid coordinates on Enter", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, "4.89, 52.37", "Enter")).toEqual({lng: 4.89, lat: 52.37});
+});
+
+ct("should commit labeled coordinates", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, "Lat: 52.37, Lng: 4.89", "change")).toEqual({lng: 4.89, lat: 52.37});
+});
+
+ct("should accept the lower longitude boundary", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, "-180, 52.37", "change")).toEqual({lng: -180, lat: 52.37});
+});
+
+ct("should accept the upper longitude boundary", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, "180, 52.37", "change")).toEqual({lng: 180, lat: 52.37});
+});
+
+ct("should clear coordinates on change", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, " ", "change")).toBeNull();
+});
+
+ct("should not commit invalid coordinates", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, "not coordinates", "change")).toBeUndefined();
+});
+
+ct("should not commit longitude below -180", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, "-180.1, 52.37", "change")).toBeUndefined();
+});
+
+ct("should not commit longitude above 180", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, "180.1, 52.37", "change")).toBeUndefined();
+});
+
+ct("should not commit readonly coordinates", async ({mount}) => {
+ expect(await mountCoordinatesControl(mount, "4.89, 52.37", "change", true)).toBeUndefined();
+});
diff --git a/ui/component/or-map/test/fixtures/coordinates-control.js b/ui/component/or-map/test/fixtures/coordinates-control.js
new file mode 100644
index 000000000..4132eb3b1
--- /dev/null
+++ b/ui/component/or-map/test/fixtures/coordinates-control.js
@@ -0,0 +1,20 @@
+import { CoordinatesControl } from "@openremote/or-map/controls/coordinates";
+
+export class CoordinatesControlFixture extends HTMLElement {
+ commit(value, event, readonly) {
+ let result;
+ const control = new CoordinatesControl(readonly, (lngLat) => {
+ result = lngLat ? {lng: lngLat.lng, lat: lngLat.lat} : null;
+ });
+ const input = control.onAdd()
+ .querySelector("or-vaadin-text-field");
+ input.value = value;
+ input.dispatchEvent(event === "change"
+ ? new Event("change", {bubbles: true})
+ : new KeyboardEvent("keyup", {code: "Enter", bubbles: true}));
+ control.onRemove();
+ return result;
+ }
+}
+
+customElements.define("coordinates-control-fixture", CoordinatesControlFixture);