diff --git a/CHANGELOG.md b/CHANGELOG.md
index f046e30..46eecef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Plugin API** (`window.floorplanStudio`): third-party integrations can register their own
+ device sources, toolbar actions and style defaults via `registerPlugin({id, apiVersion, provides})`.
+ The manifest is data plus functions the editor calls — no DOM refs are handed out, unknown
+ `provides` keys are ignored so plugins and the editor version independently. Capability slots:
+ `deviceSources` (shown in the **Devices** modal: `fetch(ws)` for live import, `parse(text)` for
+ offline input), `actions` (toolbar items that emit a documented `floorplan-studio:action`
+ CustomEvent with `{pluginId, actionId, projectId, floorId, selection}`), `iconMap`,
+ `markerDefaults`, `stateRulePresets` (role-bound rules appended to imported markers) and `css`
+ (injected once, into the card's shadow root in HACS mode). Also new: `importProject()` merging a
+ project fragment in one undo step, `projects.*` (list/get/save/remove/open) replacing direct
+ IndexedDB access, `callWS()` for the active HA link, and documented events
+ (`floorplan-studio:action`, `floorplan-studio:project-imported`,
+ `floorplan-studio:plugins-changed`). See USER_GUIDE → *Plugin API for integrations*; the bundled
+ RAMSES source registers through the same public API as the reference implementation.
- **Import a floorplan card already in Home Assistant** (toolbar → **Import card**): scans every
Lovelace dashboard over the WebSocket (or takes pasted card / view / dashboard YAML) for
`custom:floorplan-card` and `picture-elements` cards and imports one as a new project or a new
@@ -19,7 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
area / name; the remaining drawing becomes the background with converted elements stripped.
Studio's own exports round-trip icons, colours, labels and state rules.
- Room inspector keeps an imported HA area visible even when it isn't in the entity list.
-- **RAMSES RF / Ramses Extras import** (toolbar → **RAMSES**): adds evohome / RAMSES-II
+- **RAMSES RF / Ramses Extras import** (toolbar → **Devices** → *RAMSES RF / Ramses Extras*): adds evohome / RAMSES-II
devices as markers. Reads live from Ramses Extras'
`ramses_extras/floorplan_helper/get_topology` WebSocket command, falling back to the HA
device/entity registries filtered to `ramses_cc` when Extras isn't installed. Offline it accepts a
diff --git a/README.md b/README.md
index b355f8b..75074ce 100644
--- a/README.md
+++ b/README.md
@@ -79,10 +79,12 @@ no HACS? The standalone build below still works.
picture-elements cards and bring them back as an editable floor: bound SVG elements → markers at
their real positions, `area.*` / `room_*` shapes → rooms, the rest of the drawing → background.
Round-trips Studio's own exports and Ramses Extras' generated floorplans.
-- **RAMSES RF / Ramses Extras import** — pull evohome zones, TRVs, thermostats, ventilation units,
- CO₂ sensors and remotes straight from HA (Ramses Extras' floorplan helper, or plain `ramses_cc`),
- or paste a topology / `floorplan_seed_studio` result / `known_list`. Devices auto-place into the
- room mapped to their HA area, with class icons and ready-made state rules.
+- **Integration device import** — pull devices straight from HA via plugin-provided
+ sources, or paste whatever a source recognises offline. Devices auto-place into the
+ room mapped to their HA area, with class icons and ready-made state rules. Integrations
+ ship their own source (e.g. Ramses Extras registers RAMSES devices via
+ `ramses_extras/floorplan_helper`); a bundled **HA registry** source serves as the reference
+ example.
- **Persistence** — named projects in IndexedDB with autosave; JSON export/import for
portable backups; undo/redo history.
- **Export** — ha-floorplan (SVG + `custom:floorplan-card` YAML + stylesheet), Picture
diff --git a/USER_GUIDE.md b/USER_GUIDE.md
index 4d1d1e0..14c5922 100644
--- a/USER_GUIDE.md
+++ b/USER_GUIDE.md
@@ -110,32 +110,45 @@ What you get:
- **picture-elements**: the image becomes the background (canvas = image size) and each positioned
entity element a marker (`state-label` → live label, conditional elements → marker visibility).
-### Import RAMSES RF / Ramses Extras devices
+### Import devices (registered integrations)
-For evohome / RAMSES-II systems run through [Ramses RF](https://github.com/ramses-rf/ramses_cc)
-(`ramses_cc`) and, optionally, [Ramses Extras](https://github.com/wimpie70/ramses_extras):
+The **Devices** toolbar button opens the generic device importer. The sources it lists come from
+integrations registered through the [plugin API](#plugin-api-for-integrations) — Floorplan Studio
+ships a bundled RAMSES RF source described below; other integrations (yours?) can register their own.
1. Draw a room for every space and set its **HA area** in the Inspector (or give the room the same
name as the HA area). This is how devices find their room.
-2. Click **RAMSES** in the toolbar.
-3. **Read RAMSES devices** (needs the Home Assistant link — token or dashboard-card mode):
- - with **Ramses Extras** installed it calls `ramses_extras/floorplan_helper/get_topology`, which
- already resolves zones, parent links, display names and each device's primary entity;
- - without Extras it rebuilds the same list from the HA device/entity/area/floor registries,
- filtered to `ramses_cc`.
-4. Or **paste / load** offline data:
- - a saved `get_topology` result (raw or wrapped in the WebSocket `result`),
- - the response of the Extras service `ramses_extras.floorplan_seed_studio` (or any studio project
- JSON) — its markers and missing rooms are **merged** into the current project, scaled to this
- canvas,
- - a ramses_cc `known_list`, a ramses_rf schema or even a packet log — every device id
- (`04:123456`, zones `01:123456_02`) is matched to your HA entities.
-5. Review the table: tick devices (gateway is off by default), choose labels, extra entities
+2. Click **Devices** in the toolbar and pick a source (needs the Home Assistant link — token or
+ dashboard-card mode).
+3. Or **paste / load** whatever a source recognises offline — the modal tries each registered
+ source's parser, and a raw studio project JSON merges without one.
+
+**Bundled source: MQTT** (`src/examples/ha-devices.ts`) — lists every device in the HA registry, grouped by integration
+via the HA entity registry. It exists as the **reference implementation** for the plugin
+API, not as an integration play: real integrations ship their own provider as a Lovelace
+resource (see below).
+
+**RAMSES RF / Ramses Extras** — for evohome / RAMSES-II systems run through
+[Ramses RF](https://github.com/ramses-rf/ramses_cc) (`ramses_cc`),
+[Ramses Extras](https://github.com/wimpie70/ramses_extras) ships its own provider
+(`ramses-studio-provider.js`, auto-registered by the integration):
+
+- **RAMSES RF / Ramses Extras** (live) — with **Ramses Extras** installed it calls
+ `ramses_extras/floorplan_helper/get_topology`, which already resolves zones, parent links,
+ display names and each device's primary entity; without Extras it rebuilds the same list from
+ the HA device/entity/area/floor registries, filtered to `ramses_cc` (reading both `via_device_id`
+ and the HA 2026.9+ `parent_device_id` for parent links).
+- Offline **paste / load**: a saved `get_topology` result (raw or wrapped in the WebSocket
+ `result`), the response of the Extras service `ramses_extras.floorplan_seed_studio` (or any
+ studio project JSON) — its markers and missing rooms are **merged** into the current project,
+ scaled to this canvas — or a ramses_cc `known_list`, ramses_rf schema or packet log: every device
+ id (`04:123456`, zones `01:123456_02`) is matched to your HA entities.
+4. Review the table: tick devices (gateways are off by default), choose labels, extra entities
(temperature, heat demand, CO₂…), ready-made **state rules** (offline grey, battery-low blink,
window-open icon, heat-demand gradient) and marker size. Each row shows where the device goes:
*room*, *staging row* (bottom edge of the floor matching the area's HA floor, else the active
floor) or *already on plan*.
-6. **Add markers**. The whole import is one undo step, and running it again only adds devices that
+5. **Add markers**. The whole import is one undo step, and running it again only adds devices that
aren't on the plan yet.
Icons follow the device class: zone `home-thermometer`, TRV `radiator`, controller `thermostat`,
@@ -197,3 +210,63 @@ After adding the card, toggle one of your lights from the map and confirm the ma
colour follows the entity state, and that any sensor markers show their live value. If a
marker sits slightly off, nudge it in the editor (arrow keys) and re-export — because the
export is embedded, that's just Copy YAML → replace the card contents.
+
+---
+
+## Plugin API for integrations
+
+Floorplan Studio exposes `window.floorplanStudio` so third-party integrations can register their own
+**device sources, actions and style defaults** — no integration-specific code needs to live
+in this repository. The bundled HA-registry source (`src/examples/ha-devices.ts`) registers through exactly
+this public API and doubles as the reference implementation.
+
+```ts
+window.floorplanStudio.registerPlugin({
+ id: 'ramses', // unique; re-registering replaces (external may supersede bundled)
+ apiVersion: 1,
+ provides: {
+ deviceSources: [{
+ id: 'ramses',
+ title: 'RAMSES RF / Ramses Extras', // label in the Devices modal
+ description: 'evohome / RAMSES-II devices',
+ fetch: async (ws, ctx) => ({ // live: called with the active HA WebSocket
+ topology: { source: 'ramses_extras', devices: [...], areas: {}, floors: {} },
+ note: 'optional extra line under the count',
+ }),
+ parse: (text, ctx) => ({ kind: 'topology' | 'project' | 'error' | 'nomatch', ... }),
+ }],
+ actions: [{
+ id: 'ramses.seed-devices', label: 'Add devices', icon: 'devices', location: 'toolbar',
+ }],
+ iconMap: { FAN: 'fan', TRV: 'radiator' }, // class token → mdi icon fallback
+ markerDefaults: { size: 40 }, // merged: plugin < user opts < device hints
+ stateRulePresets: [ // appended to imported markers, role-bound
+ { entityRole: 'battery', mode: 'stringMatch', match: 'on', color: '#ef4444', animation: 'blink' },
+ ],
+ css: '/local/my_integration/floorplan.css', // injected once (card mode: shadow root)
+ },
+});
+```
+
+- **The manifest is data + functions the editor calls** — no DOM refs, no component internals,
+ the editor keeps lifecycle control. Unknown `provides` keys are ignored: plugins and the editor
+ version independently (`apiVersion`).
+- **DeviceTopology** is the neutral model sources return: `devices[]` with `device_id`,
+ `device_class`/`group` (free-form display/grouping tokens), `area_id`, `primary_entity`,
+ `entities[]` (`{entity_id, domain, role}`), plus optional `icon`/`color`/`kind`/`suggested`
+ presentation hints, `actions`/`style`/`visibility` passthrough (per-gesture overrides, e.g. a
+ FAN's double-tap opening a custom card — users can still edit per-marker afterwards), and
+ `parent` for topology-aware integrations.
+- **Events** need no registry — just `addEventListener` on `window`:
+ - `floorplan-studio:action` — a plugin action was clicked.
+ `detail: {pluginId, actionId, projectId, floorId, selection: string[]}`
+ - `floorplan-studio:project-imported` — `detail: {pluginId?, mode, markers, rooms}`
+ - `floorplan-studio:plugins-changed` — `detail: {plugins: string[]}`
+- **`floorplanStudio.importProject(json, {mode})`** — merge a studio project/fragment into the open
+ project in one undo step (`'merge'`, default; floors pair by name, scaled to the canvas) or
+ `'replace'` it. This replaces writing to the editor's IndexedDB directly.
+- **`floorplanStudio.projects`** — `active()`, `list()`, `get(id)`, `save(p)`, `remove(id)`,
+ `open(id)` — the supported way to read/write stored projects.
+- **`floorplanStudio.callWS(msg)`** — call the active Home Assistant WebSocket (throws when not
+ connected); also `floorplanStudio.registry.*` for introspection and `subscribe(cb)` to be notified
+ when the plugin set changes.
diff --git a/src/App.tsx b/src/App.tsx
index 0d15543..f1e97ef 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -4,6 +4,7 @@ import { loadImageFile } from './ui/imageLoad';
import { useKeyboard } from './ui/useKeyboard';
import { Toolbar } from './panels/Toolbar';
import { EntityBrowser } from './panels/EntityBrowser';
+import { DevicePanel } from './panels/DevicePanel';
import { Inspector } from './panels/Inspector';
import { LayerPanel } from './panels/LayerPanel';
import { CanvasSvg } from './canvas/CanvasSvg';
@@ -11,16 +12,27 @@ import { HelpModal } from './ui/HelpModal';
import { ConnectModal } from './ha/ConnectModal';
import { ProjectsModal } from './persist/ProjectsModal';
import { ExportModal } from './export/ExportModal';
-import { RamsesImportModal } from './ramses/RamsesImportModal';
+import { DeviceImportModal } from './import/DeviceImportModal';
import { HaImportModal } from './haimport/HaImportModal';
import { useAutosave } from './persist/useAutosave';
import { subscribeHass, hassToSource, getHass, HassLike } from './ha/hassBridge';
-type ModalId = null | 'help' | 'connect' | 'projects' | 'export' | 'ramses' | 'haimport';
+type ModalId = null | 'help' | 'connect' | 'projects' | 'export' | 'import' | 'haimport';
+
+function LeftTab({ id, label }: { id: 'entities' | 'devices' | 'layers'; label: string }) {
+ const active = useStore((s) => s.leftTab === id);
+ const setLeftTab = useStore((s) => s.setLeftTab);
+ return (
+
+ );
+}
export default function App() {
const [modal, setModal] = useState(null);
const mode = useStore((s) => s.mode);
+ const leftTab = useStore((s) => s.leftTab);
useKeyboard();
useAutosave();
@@ -99,15 +111,20 @@ export default function App() {
onOpenExport={() => setModal('export')}
onOpenProjects={() => setModal('projects')}
onOpenConnect={() => setModal('connect')}
- onOpenRamses={() => setModal('ramses')}
- onOpenHaImport={() => setModal('haimport')}
+ onOpenImport={() => useStore.getState().setLeftTab('devices')}
onOpenHelp={() => setModal('help')}
/>
No floorplan or picture-elements cards found on your dashboards.
+ ) : (
+
+
+
+
+
+ )}
+ {updateMsg &&
{updateMsg.text}
}
+
+ )}
diff --git a/src/ha/wsCaller.ts b/src/ha/wsCaller.ts
new file mode 100644
index 0000000..01541ea
--- /dev/null
+++ b/src/ha/wsCaller.ts
@@ -0,0 +1,23 @@
+// A WebSocket caller bound to whichever Home Assistant link is active:
+// the URL+token HaClient (standalone) or the `hass` object Lovelace injects
+// (HACS card mode). Shared by the editor's own importers and exposed to
+// plugins as `floorplanStudio.callWS`.
+import { haClient } from './client';
+import { getHass } from './hassBridge';
+import { useStore } from '../state/store';
+import type { WsCall } from '../plugins/types';
+
+export type { WsCall };
+
+/** A WebSocket caller for the live HA link, or null when running on demo data. */
+export function liveWsCaller(): WsCall | null {
+ const { conn, usingDemo } = useStore.getState();
+ if (usingDemo || conn.status !== 'connected') return null;
+ if (conn.url === 'this dashboard') {
+ const h = getHass();
+ if (h?.callWS) return (msg) => h.callWS!(msg);
+ if (h?.connection?.sendMessagePromise) return (msg) => h.connection!.sendMessagePromise(msg);
+ return null;
+ }
+ return haClient.connected ? (msg) => haClient.sendWS(msg) : null;
+}
diff --git a/src/hacs-card.tsx b/src/hacs-card.tsx
index 05026ac..a2120f9 100644
--- a/src/hacs-card.tsx
+++ b/src/hacs-card.tsx
@@ -4,10 +4,13 @@
//
// Built by vite.hacs.config.ts into a single dist-hacs/floorplan-studio.js that
// HACS serves as a Lovelace resource.
+import './plugins/install'; // window.floorplanStudio before providers register
+import './examples/ha-devices'; // bundled example device source (self-registers)
import { StrictMode } from 'react';
import { createRoot, Root } from 'react-dom/client';
import App from './App';
import { setHass, HassLike } from './ha/hassBridge';
+import { setPluginStyleRoot } from './plugins/registry';
// `?inline` gives the CSS as a string instead of injecting it into document
// — we put it in the shadow root instead.
import cssText from './styles.css?inline';
@@ -38,6 +41,8 @@ class FloorplanStudioCard extends HTMLElement {
if (this.mounted) return;
this.mounted = true;
const shadow = this.attachShadow({ mode: 'open' });
+ // plugin css links land inside this shadow root, not document.head
+ setPluginStyleRoot(shadow as unknown as HTMLElement);
const style = document.createElement('style');
style.textContent = HOST_CSS + cssText;
shadow.appendChild(style);
diff --git a/src/haimport/HaImportModal.tsx b/src/haimport/HaImportModal.tsx
index 782d71c..913e70c 100644
--- a/src/haimport/HaImportModal.tsx
+++ b/src/haimport/HaImportModal.tsx
@@ -4,7 +4,7 @@ import { useStore } from '../state/store';
import { Modal } from '../ui/Modal';
import { createProject } from '../model/defaults';
import { saveProject } from '../persist/db';
-import { liveWsCaller } from '../ramses/fetch';
+import { liveWsCaller } from '../ha/wsCaller';
import { cardsFromText, cardSummary, FoundCard, parseFloorplanCard, parsePictureElements, shortRef } from './cards';
import { basename, isSvgRef, liveAssetContext, loadText } from './assets';
import { scanDashboards } from './scan';
diff --git a/src/haimport/cards.test.ts b/src/haimport/cards.test.ts
index 6cb5fed..06b081c 100644
--- a/src/haimport/cards.test.ts
+++ b/src/haimport/cards.test.ts
@@ -11,6 +11,7 @@ import {
parseFloorplanCard,
parsePictureElements,
pictureImageRef,
+ replaceCardAtIndex,
} from './cards';
const dashboard = {
@@ -62,6 +63,24 @@ describe('card discovery', () => {
]);
});
+ it('replaces a discovered card in-place by its discovery index', () => {
+ const clone = structuredClone(dashboard);
+ const ok0 = replaceCardAtIndex(clone, 0, { type: 'custom:floorplan-card', config: { image: '/local/new.svg', rules: [] } });
+ expect(ok0).toBe(true);
+ expect(findCards(clone, 'Home')[0].card).toEqual({
+ type: 'custom:floorplan-card',
+ config: { image: '/local/new.svg', rules: [] },
+ });
+
+ const ok1 = replaceCardAtIndex(clone, 1, { type: 'picture-elements', image: '/local/new.png', elements: [] });
+ expect(ok1).toBe(true);
+ expect(findCards(clone, 'Home')[1].card).toEqual({
+ type: 'picture-elements',
+ image: '/local/new.png',
+ elements: [],
+ });
+ });
+
it('accepts pasted single cards, lists and bare ha-floorplan config bodies', () => {
expect(cardsFromText('type: picture-elements\nimage: /local/a.png\nelements: []')).toHaveLength(1);
expect(cardsFromText(yaml.dump([{ type: 'picture-elements', image: 'x' }, { type: 'custom:floorplan-card', config: {} }]))).toHaveLength(2);
diff --git a/src/haimport/cards.ts b/src/haimport/cards.ts
index 0921732..8bee84d 100644
--- a/src/haimport/cards.ts
+++ b/src/haimport/cards.ts
@@ -19,6 +19,12 @@ export interface FoundCard {
where: string;
/** the card object itself (type + config / image + elements) */
card: Loose;
+ /** dashboard url_path (null = default Overview dashboard) when scanned live */
+ urlPath?: string | null;
+ /** 0-based index among floorplan/picture-elements cards in that dashboard */
+ cardIndex?: number;
+ /** dashboard mode ('storage' is writable via lovelace/config/save; 'yaml' is read-only) */
+ dashboardMode?: string;
}
// ---------------------------------------------------------------------------
@@ -69,6 +75,53 @@ export function findCards(root: unknown, dashboardTitle: string): FoundCard[] {
return out;
}
+/**
+ * Replace the `targetIndex`-th floorplan / picture-elements card inside a cloned
+ * Lovelace dashboard config (walking in the exact same order as `findCards`).
+ * Returns true if the card was found and replaced.
+ */
+export function replaceCardAtIndex(root: unknown, targetIndex: number, replacement: Loose): boolean {
+ let seenCount = 0;
+ const visited = new Set();
+
+ function walk(node: unknown): boolean {
+ if (!node || typeof node !== 'object' || visited.has(node)) return false;
+ visited.add(node);
+ if (Array.isArray(node)) {
+ for (let i = 0; i < node.length; i++) {
+ const item = node[i];
+ if (isObj(item) && cardKind(item)) {
+ if (seenCount === targetIndex) {
+ node[i] = replacement;
+ return true;
+ }
+ seenCount++;
+ continue;
+ }
+ if (walk(item)) return true;
+ }
+ return false;
+ }
+ const o = node as Loose;
+ for (const k of ['views', 'sections', 'cards', 'card', 'elements']) {
+ if (!(k in o)) continue;
+ const child = o[k];
+ if (!Array.isArray(child) && isObj(child) && cardKind(child)) {
+ if (seenCount === targetIndex) {
+ o[k] = replacement;
+ return true;
+ }
+ seenCount++;
+ continue;
+ }
+ if (walk(child)) return true;
+ }
+ return false;
+ }
+
+ return walk(root);
+}
+
/** Cards from pasted YAML/JSON: a single card, a list, a view or a full dashboard. */
export function cardsFromText(text: string): FoundCard[] {
let data: unknown;
diff --git a/src/haimport/scan.ts b/src/haimport/scan.ts
index 126870a..5f12b96 100644
--- a/src/haimport/scan.ts
+++ b/src/haimport/scan.ts
@@ -1,6 +1,7 @@
// Read every Lovelace dashboard over the WebSocket and collect floorplan cards.
-import type { WsCall } from '../ramses/fetch';
-import { FoundCard, findCards } from './cards';
+import yaml from 'js-yaml';
+import type { WsCall } from '../ha/wsCaller';
+import { FoundCard, findCards, replaceCardAtIndex } from './cards';
interface DashboardInfo {
url_path: string | null;
@@ -10,14 +11,22 @@ interface DashboardInfo {
export async function scanDashboards(call: WsCall): Promise<{ cards: FoundCard[]; errors: string[] }> {
const list = await call({ type: 'lovelace/dashboards/list' }).catch(() => [] as DashboardInfo[]);
- const targets: DashboardInfo[] = [{ url_path: null, title: 'Overview' }, ...list];
+ const targets: DashboardInfo[] = [{ url_path: null, title: 'Overview', mode: 'storage' }, ...list];
const cards: FoundCard[] = [];
const errors: string[] = [];
await Promise.all(
targets.map(async (d) => {
try {
const cfg = await call({ type: 'lovelace/config', url_path: d.url_path, force: false });
- cards.push(...findCards(cfg, d.title || d.url_path || 'Dashboard').map((c) => ({ ...c, key: `${d.url_path ?? ''}#${c.key}` })));
+ cards.push(
+ ...findCards(cfg, d.title || d.url_path || 'Dashboard').map((c, idx) => ({
+ ...c,
+ key: `${d.url_path ?? ''}#${c.key}`,
+ urlPath: d.url_path,
+ cardIndex: idx,
+ dashboardMode: d.mode ?? 'storage',
+ })),
+ );
} catch (e) {
const msg = (e as { code?: string; message?: string })?.code ?? '';
// The auto-generated default dashboard has no stored config — not an error.
@@ -28,3 +37,38 @@ export async function scanDashboards(call: WsCall): Promise<{ cards: FoundCard[]
cards.sort((a, b) => a.where.localeCompare(b.where));
return { cards, errors };
}
+
+/**
+ * Write exported card YAML back into an existing Lovelace card on a storage-mode
+ * dashboard via `lovelace/config/save`.
+ */
+export async function updateDashboardCard(
+ call: WsCall,
+ target: FoundCard,
+ yamlText: string,
+): Promise {
+ if (target.dashboardMode && target.dashboardMode !== 'storage') {
+ throw new Error(`Dashboard "${target.where}" is in ${target.dashboardMode} mode (read-only via WebSocket).`);
+ }
+ if (typeof target.cardIndex !== 'number') {
+ throw new Error('Target card is missing its dashboard index.');
+ }
+ const parsed = yaml.load(yamlText);
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error('Exported YAML did not parse as a card mapping.');
+ }
+ const cfg = await call>({
+ type: 'lovelace/config',
+ url_path: target.urlPath ?? null,
+ force: true,
+ });
+ const nextCfg = structuredClone(cfg);
+ if (!replaceCardAtIndex(nextCfg, target.cardIndex, parsed as Record)) {
+ throw new Error(`Card #${target.cardIndex} in "${target.where}" was not found (dashboard changed?).`);
+ }
+ await call({
+ type: 'lovelace/config/save',
+ url_path: target.urlPath ?? null,
+ config: nextCfg,
+ });
+}
diff --git a/src/ramses/RamsesImportModal.tsx b/src/import/DeviceImportModal.tsx
similarity index 69%
rename from src/ramses/RamsesImportModal.tsx
rename to src/import/DeviceImportModal.tsx
index 9f29770..3e6e696 100644
--- a/src/ramses/RamsesImportModal.tsx
+++ b/src/import/DeviceImportModal.tsx
@@ -1,23 +1,26 @@
+// Generic "Import devices" modal — the editor side of the deviceSources
+// capability. Registered providers (src/plugins/types.ts) supply fetch/parse;
+// this modal only knows the neutral DeviceTopology contract: tick devices,
+// preview placement (room match / staging row), apply in one undo step.
import { useMemo, useRef, useState } from 'react';
import { useStore } from '../state/store';
import { Modal } from '../ui/Modal';
import { iconPath } from '../ui/icons';
import type { Project } from '../model/schema';
-import { EXTRAS_TOPOLOGY_WS, fetchRamsesTopology, liveWsCaller } from './fetch';
+import { liveWsCaller } from '../ha/wsCaller';
import {
- CLASS_LABEL,
- GROUP_COLOR,
- iconForClass,
- parseRamsesInput,
- RamsesTopology,
- topologyFromIds,
-} from './topology';
+ getDeviceSources,
+ getIconMap,
+ getMarkerDefaults,
+ getStateRulePresets,
+} from '../plugins/registry';
+import type { DeviceTopology, ParsedSourceInput } from '../plugins/types';
import {
applyMerge,
applyPlan,
defaultSelection,
planProjectMerge,
- planRamsesImport,
+ planDeviceImport,
RowStatus,
} from './plan';
@@ -31,23 +34,26 @@ const STATUS_TEXT: Record = {
off: 'skipped',
};
-const SOURCE_TEXT: Record = {
- ramses_extras: 'Ramses Extras floorplan helper',
- ramses_cc: 'ramses_cc device registry',
- device_ids: 'device ids matched to HA entities',
-};
+const FALLBACK_COLOR = '#ffc107';
+
+function isProject(v: unknown): v is Project {
+ return !!v && typeof v === 'object' && Array.isArray((v as { floors?: unknown }).floors);
+}
-export function RamsesImportModal({ onClose }: { onClose: () => void }) {
+export function DeviceImportModal({ onClose }: { onClose: () => void }) {
const project = useStore((s) => s.project);
const entities = useStore((s) => s.entities);
const usingDemo = useStore((s) => s.usingDemo);
useStore((s) => s.conn); // re-render when the HA link changes
const call = liveWsCaller();
+ const sources = getDeviceSources();
+ const ctx = useMemo(() => ({ entities, usingDemo }), [entities, usingDemo]);
+
const [text, setText] = useState('');
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState(null);
- const [topo, setTopo] = useState(null);
+ const [topo, setTopo] = useState(null);
const [incoming, setIncoming] = useState(null);
const [selected, setSelected] = useState>(new Set());
const [markerSize, setMarkerSize] = useState(32);
@@ -58,22 +64,23 @@ export function RamsesImportModal({ onClose }: { onClose: () => void }) {
const [includeRooms, setIncludeRooms] = useState(true);
const fileRef = useRef(null);
- function loadTopology(t: RamsesTopology, note?: string) {
+ function loadTopology(t: DeviceTopology, note?: string) {
setTopo(t);
setIncoming(null);
setSelected(defaultSelection(useStore.getState().project, t));
setMsg({
kind: 'info',
- text: `${t.devices.length} RAMSES devices from the ${SOURCE_TEXT[t.source]}.${note ? ' ' + note : ''}`,
+ text: `${t.devices.length} devices from ${t.sourceLabel ?? t.source}.${note ? ' ' + note : ''}`,
});
}
- async function fetchLive() {
- if (!call) return;
+ async function fetchSource(id: string) {
+ const src = sources.find((s) => s.source.id === id)?.source;
+ if (!src?.fetch || !call) return;
setBusy(true);
setMsg(null);
try {
- const { topology, note } = await fetchRamsesTopology(call);
+ const { topology, note } = await src.fetch(call, ctx);
loadTopology(topology, note);
} catch (e) {
setMsg({ kind: 'err', text: (e as Error).message || String(e) });
@@ -83,30 +90,53 @@ export function RamsesImportModal({ onClose }: { onClose: () => void }) {
}
function parse(src: string) {
- const r = parseRamsesInput(src);
- switch (r.kind) {
- case 'topology':
- return loadTopology(r.topology);
- case 'project':
- setTopo(null);
- setIncoming(r.project);
- return setMsg({
- kind: 'info',
- text: `Studio project "${r.project.name ?? 'seeded'}" with ${r.project.floors.length} floor(s) — its markers can be merged into this project.`,
- });
- case 'ids': {
- const t = topologyFromIds(r.ids, entities);
- const matched = t.devices.filter((d) => d.entities.length).length;
- return loadTopology(
- t,
- usingDemo
- ? 'Connect to Home Assistant first — device ids are matched against your real entity list.'
- : `${matched} matched to HA entities by id.`,
- );
+ // A raw studio project merges without needing a provider's parser.
+ try {
+ const data = JSON.parse(src);
+ const unwrapped = (data as { project_json?: unknown })?.project_json ?? data;
+ if (typeof unwrapped === 'string') {
+ const inner = JSON.parse(unwrapped);
+ if (isProject(inner)) return loadProject(inner);
}
- default:
- setMsg({ kind: 'err', text: r.error });
+ if (isProject(unwrapped)) return loadProject(unwrapped);
+ } catch {
+ /* not JSON — fall through to provider parsers */
}
+ for (const { source } of sources) {
+ if (!source.parse) continue;
+ let r: ParsedSourceInput;
+ try {
+ r = source.parse(src, ctx);
+ } catch (e) {
+ setMsg({ kind: 'err', text: `${source.title}: ${(e as Error).message || e}` });
+ return;
+ }
+ switch (r.kind) {
+ case 'topology':
+ return loadTopology(r.topology, r.note);
+ case 'project':
+ return loadProject(r.project);
+ case 'error':
+ return setMsg({ kind: 'err', text: r.error });
+ default:
+ continue; // nomatch — try the next source
+ }
+ }
+ setMsg({
+ kind: 'err',
+ text: sources.some((s) => s.source.parse)
+ ? 'No registered source recognised this input.'
+ : 'No source can parse pasted input — connect to Home Assistant and fetch devices instead.',
+ });
+ }
+
+ function loadProject(p: Project) {
+ setTopo(null);
+ setIncoming(p);
+ setMsg({
+ kind: 'info',
+ text: `Studio project "${p.name ?? 'seeded'}" with ${p.floors.length} floor(s) — its markers can be merged into this project.`,
+ });
}
async function loadFile(file?: File | null) {
@@ -119,13 +149,16 @@ export function RamsesImportModal({ onClose }: { onClose: () => void }) {
const plan = useMemo(
() =>
topo
- ? planRamsesImport(project, topo, project.activeFloorId, {
+ ? planDeviceImport(project, topo, project.activeFloorId, {
selected,
markerSize,
labels,
extraEntities,
stateRules,
allFloors,
+ iconMap: getIconMap(),
+ markerDefaults: getMarkerDefaults(),
+ presets: getStateRulePresets().map((p) => p.preset),
})
: null,
[project, topo, selected, markerSize, labels, extraEntities, stateRules, allFloors],
@@ -149,6 +182,12 @@ export function RamsesImportModal({ onClose }: { onClose: () => void }) {
return c;
}, [plan]);
+ /** distinct group tokens present in the topology → one select-button each */
+ const groups = useMemo(
+ () => (topo ? [...new Set(topo.devices.map((d) => d.group).filter(Boolean))] : []),
+ [topo],
+ );
+
function toggle(id: string) {
setSelected((s) => {
const n = new Set(s);
@@ -197,26 +236,34 @@ export function RamsesImportModal({ onClose }: { onClose: () => void }) {
const mergeMarkers = merge?.reduce((n, m) => n + m.markers.length, 0) ?? 0;
const mergeRooms = merge?.reduce((n, m) => n + m.rooms.length, 0) ?? 0;
+ const iconMap = getIconMap();
return (
-
+
- Drop your evohome / RAMSES-II devices onto the plan as markers — zones, radiator valves, thermostats,
- ventilation units, CO₂ sensors and remotes. Devices whose HA area matches a room (the room's{' '}
+ Drop devices onto the plan as markers. Devices whose HA area matches a room (the room's{' '}
HA area or its name) land inside that room; the rest wait in a staging row at the bottom of
- the floor.
+ the floor. Sources below are contributed by registered integrations.
- {call
- ? 'Uses Ramses Extras when installed, otherwise the ramses_cc integration directly.'
- : 'Connect to Home Assistant first (top-right HA button).'}
+ {call ? '' : 'Connect to Home Assistant first (top-right HA button).'}
@@ -225,7 +272,9 @@ export function RamsesImportModal({ onClose }: { onClose: () => void }) {
className="fp-rx-paste"
value={text}
onChange={(e) => setText(e.target.value)}
- placeholder={`Ramses Extras ${EXTRAS_TOPOLOGY_WS} result,\nfloorplan_seed_studio response / studio project JSON,\nor ramses_cc known_list / schema (any text with ids like 04:123456)`}
+ placeholder={
+ 'A studio project JSON, an integration topology response,\nor any text a registered source recognises'
+ }
spellCheck={false}
/>