minor refactor
This commit is contained in:
1 parent
eee37346ab
commit
a9b2bdb775
76 files changed
+77
-77
No files matched your search
@@ -0,0 +1,59 @@
|
||||
import { AutomationData, BareAutomationData } from "types/automations";
|
||||
import { API } from "./base";
|
||||
import { ListData, ListParams } from "./types";
|
||||
import {
|
||||
AUTOMTAION_LIST,
|
||||
AUTOMTAION_ITEM,
|
||||
AUTOMTAION_ITEM_TAGS,
|
||||
} from "./paths";
|
||||
|
||||
export const makeAutomationAPI = (api: API) => ({
|
||||
async list({ offset, limit }: ListParams) {
|
||||
const data = await api.makeCall<ListData<AutomationData>, ListParams>({
|
||||
path: AUTOMTAION_LIST,
|
||||
data: {
|
||||
offset,
|
||||
limit,
|
||||
},
|
||||
});
|
||||
return data;
|
||||
},
|
||||
async update(auto: AutomationData) {
|
||||
return await api.makeCall({
|
||||
method: "PUT",
|
||||
path: AUTOMTAION_ITEM,
|
||||
data: auto,
|
||||
});
|
||||
},
|
||||
async create(auto: BareAutomationData) {
|
||||
return await api.makeCall({
|
||||
method: "POST",
|
||||
path: AUTOMTAION_ITEM,
|
||||
data: auto,
|
||||
});
|
||||
},
|
||||
async updateTags({
|
||||
automation_id,
|
||||
tags,
|
||||
}: {
|
||||
automation_id: string;
|
||||
tags: Record<string, string>;
|
||||
}) {
|
||||
return await api.makeCall({
|
||||
path: AUTOMTAION_ITEM_TAGS,
|
||||
data: {
|
||||
automation_id,
|
||||
tags,
|
||||
},
|
||||
});
|
||||
},
|
||||
async remove(auto: AutomationData) {
|
||||
return await api.makeCall({
|
||||
method: "DELETE",
|
||||
path: AUTOMTAION_ITEM,
|
||||
data: auto,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export type AutomationAPI = ReturnType<typeof makeAutomationAPI>;
|
||||
@@ -0,0 +1,43 @@
|
||||
import { APIRequest, APIResponse } from "./types";
|
||||
|
||||
export interface API {
|
||||
makeCall: <Res = any, Req = any>(
|
||||
req: APIRequest<Req>
|
||||
) => Promise<APIResponse<Res>>;
|
||||
}
|
||||
export const makeRemoteAPI = (baseURL: string): API => ({
|
||||
async makeCall({ path, method = "POST", data = {} }) {
|
||||
try {
|
||||
const payload: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
};
|
||||
if (method !== "GET") {
|
||||
payload["body"] = JSON.stringify(data);
|
||||
}
|
||||
const reply = await fetch(baseURL + path, payload);
|
||||
let response: APIResponse<any>;
|
||||
if (reply.status === 200) {
|
||||
response = {
|
||||
ok: true,
|
||||
data: await reply.json(),
|
||||
};
|
||||
} else {
|
||||
response = {
|
||||
ok: false,
|
||||
error: await reply.text(),
|
||||
};
|
||||
console.error(response);
|
||||
}
|
||||
return response;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return {
|
||||
ok: false,
|
||||
error: `Server error: ${method} ${path}`,
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
useDefaultApiState,
|
||||
makeReloadAutomations,
|
||||
makeProfileManager,
|
||||
} from "./util";
|
||||
import { AutomationAPI } from "./automations";
|
||||
import { UserProfileAPI } from "./profile";
|
||||
|
||||
export type ApiService = ReturnType<typeof useAPIService>;
|
||||
export const useAPIService = (
|
||||
automationAPI: AutomationAPI,
|
||||
userProfileAPI: UserProfileAPI
|
||||
) => {
|
||||
// state
|
||||
const [state, setState] = useDefaultApiState();
|
||||
const autoManager = makeReloadAutomations(automationAPI, state, setState);
|
||||
const userProfileManager = makeProfileManager(
|
||||
userProfileAPI,
|
||||
state,
|
||||
setState
|
||||
);
|
||||
|
||||
// initial load of autos
|
||||
useEffect(() => {
|
||||
if (state.automations.ready === undefined) {
|
||||
autoManager.reload();
|
||||
}
|
||||
}, [state.automations.ready, autoManager]);
|
||||
// initial load of profile
|
||||
useEffect(() => {
|
||||
if (state.userProfile.ready === undefined) {
|
||||
userProfileManager.reload();
|
||||
}
|
||||
}, [state.userProfile.ready, userProfileManager]);
|
||||
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
get theme(): "dark" | "light" {
|
||||
if (state.userProfile.ready && state.userProfile.ok) {
|
||||
if (["dark", "light"].includes(state.userProfile.data.theme)) {
|
||||
return state.userProfile.data.theme as any;
|
||||
}
|
||||
}
|
||||
return "dark";
|
||||
},
|
||||
},
|
||||
removeAutomation: autoManager.wrapCall(automationAPI.remove),
|
||||
updateAutomation: autoManager.wrapCall(automationAPI.update),
|
||||
createAutomation: autoManager.wrapCall(automationAPI.create),
|
||||
updateTags: autoManager.wrapCall(automationAPI.updateTags),
|
||||
setProfile: userProfileManager.update,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import { AutomationData } from "types/automations";
|
||||
import { makeAutomationAPI } from "./automations";
|
||||
import { makeRemoteAPI } from "./base";
|
||||
import { useAPIService } from "./core";
|
||||
import { useAutoMockAPI, useProfileMockAPI } from "./mock";
|
||||
import { createContext, useContext, useRef } from "react";
|
||||
import { makeProfileAPI } from "./profile";
|
||||
import { ApiState } from "./types";
|
||||
|
||||
const locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i);
|
||||
const baseURL = new URL(
|
||||
process.env.NODE_ENV === "development"
|
||||
? `http://${window.location.hostname}:8000`
|
||||
: window.location.origin + (!locationPrefixWeb ? "" : locationPrefixWeb[1])
|
||||
);
|
||||
export const wsURL = baseURL + "socket";
|
||||
export const remoteAutoAPI = makeRemoteAPI(baseURL + "automations");
|
||||
export const detailsAPI = makeRemoteAPI(baseURL + "details");
|
||||
export const useConnectedApiService = () =>
|
||||
useAPIService(makeAutomationAPI(remoteAutoAPI), makeProfileAPI(detailsAPI));
|
||||
export const useMockApiService = (
|
||||
initialAutos: AutomationData[],
|
||||
returnErrors: boolean = false
|
||||
) =>
|
||||
useAPIService(
|
||||
makeAutomationAPI(useAutoMockAPI(initialAutos, useRef, returnErrors)),
|
||||
makeProfileAPI(useProfileMockAPI())
|
||||
);
|
||||
|
||||
const ApiStateContext = createContext<ApiState>({
|
||||
automations: { ready: false },
|
||||
userProfile: { ready: false },
|
||||
});
|
||||
export const ApiStateProvider = ApiStateContext.Provider;
|
||||
export const useApiState = () => useContext(ApiStateContext);
|
||||
@@ -0,0 +1,95 @@
|
||||
import { useAutoMockAPI } from "./mock";
|
||||
import { makeAutomationAPI } from "./automations";
|
||||
import { createMockAuto } from "utils/mocks";
|
||||
import { AutomationData } from "types/automations";
|
||||
|
||||
const fakeUseRef = (a: any) => ({ current: a });
|
||||
|
||||
test("mock api uses initial autos for initial population -- empty", async () => {
|
||||
const mockApi = makeAutomationAPI(useAutoMockAPI([], fakeUseRef as any));
|
||||
const data = await mockApi.list({ limit: 10, offset: 0 });
|
||||
expect(data.ok).toBe(true);
|
||||
expect((data as any).data.data).toHaveLength(0);
|
||||
expect((data as any).data.totalItems).toBe(0);
|
||||
});
|
||||
|
||||
test("mock api uses initial autos for initial population -- some data", async () => {
|
||||
const initials = [createMockAuto(), createMockAuto()];
|
||||
const mockApi = makeAutomationAPI(
|
||||
useAutoMockAPI(initials, fakeUseRef as any)
|
||||
);
|
||||
const data = await mockApi.list({ limit: 10, offset: 0 });
|
||||
expect(data.ok).toBe(true);
|
||||
expect((data as any).data.data).toHaveLength(2);
|
||||
expect((data as any).data.totalItems).toBe(2);
|
||||
});
|
||||
|
||||
test("populate mock api with some data", async () => {
|
||||
const mockApi = makeAutomationAPI(useAutoMockAPI([], fakeUseRef as any));
|
||||
await mockApi.create(createMockAuto());
|
||||
let data = await mockApi.list({ limit: 10, offset: 0 });
|
||||
expect(data.ok).toBe(true);
|
||||
expect((data as any).data.data).toHaveLength(1);
|
||||
expect((data as any).data.totalItems).toBe(1);
|
||||
await mockApi.create(createMockAuto());
|
||||
data = await mockApi.list({ limit: 10, offset: 0 });
|
||||
expect((data as any).data.data).toHaveLength(2);
|
||||
expect((data as any).data.totalItems).toBe(2);
|
||||
});
|
||||
|
||||
test("delete/update data from mock api", async () => {
|
||||
const mockApi = makeAutomationAPI(
|
||||
useAutoMockAPI(
|
||||
[
|
||||
createMockAuto(),
|
||||
createMockAuto(),
|
||||
createMockAuto(),
|
||||
createMockAuto(),
|
||||
createMockAuto(),
|
||||
],
|
||||
fakeUseRef as any
|
||||
)
|
||||
);
|
||||
let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data;
|
||||
const toBeEdited = data[0];
|
||||
toBeEdited.alias = "Bob is my uncle";
|
||||
await mockApi.update(toBeEdited);
|
||||
data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data;
|
||||
expect(data[0].alias).toEqual("Bob is my uncle");
|
||||
await mockApi.remove(data[0]);
|
||||
data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data;
|
||||
expect(data[0].alias === "Bob is my uncle").toEqual(false);
|
||||
});
|
||||
|
||||
test("update tags from mock api", async () => {
|
||||
const mockApi = makeAutomationAPI(
|
||||
useAutoMockAPI(
|
||||
[
|
||||
createMockAuto(),
|
||||
createMockAuto(),
|
||||
createMockAuto(),
|
||||
createMockAuto(),
|
||||
createMockAuto(),
|
||||
],
|
||||
fakeUseRef as any
|
||||
)
|
||||
);
|
||||
let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data
|
||||
.data as AutomationData[];
|
||||
const autoId = data[0].id as string;
|
||||
expect(data[0].tags).toStrictEqual({});
|
||||
mockApi.updateTags({
|
||||
automation_id: autoId,
|
||||
tags: {
|
||||
room: "bathroom",
|
||||
type: "popup",
|
||||
},
|
||||
});
|
||||
data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data
|
||||
.data as AutomationData[];
|
||||
expect(data[0].id).toEqual(autoId);
|
||||
expect(data[0].tags).toStrictEqual({
|
||||
room: "bathroom",
|
||||
type: "popup",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { useRef } from "react";
|
||||
import { AutomationData, BareAutomationData } from "types/automations";
|
||||
import { API } from "./base";
|
||||
import { UserProfile } from "./types";
|
||||
import {
|
||||
AUTOMTAION_LIST,
|
||||
AUTOMTAION_ITEM,
|
||||
AUTOMTAION_ITEM_TAGS,
|
||||
USER_PROFILE_ROOT,
|
||||
} from "./paths";
|
||||
|
||||
export const useAutoMockAPI = (
|
||||
initialAutos: AutomationData[] = [],
|
||||
makeRef = useRef,
|
||||
returnErrors: boolean = false
|
||||
): API => {
|
||||
const automationsRef = makeRef(initialAutos);
|
||||
return {
|
||||
async makeCall({ path, method = "POST", data = {} }) {
|
||||
if (returnErrors) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "Test Error",
|
||||
};
|
||||
}
|
||||
// console.debug("[[mockCall]]", method, path, data);
|
||||
if (path === AUTOMTAION_LIST) {
|
||||
return {
|
||||
ok: true,
|
||||
data: JSON.parse(
|
||||
JSON.stringify({
|
||||
totalItems: automationsRef.current.length,
|
||||
params: { offset: 0, limit: 100 },
|
||||
data: automationsRef.current,
|
||||
})
|
||||
),
|
||||
} as any;
|
||||
}
|
||||
if (path === AUTOMTAION_ITEM) {
|
||||
if (method === "PUT") {
|
||||
const auto = data as AutomationData;
|
||||
const index = automationsRef.current.findIndex(
|
||||
({ id }) => auto.id === id
|
||||
);
|
||||
if (index < 0) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "Not Found",
|
||||
};
|
||||
} else {
|
||||
automationsRef.current = [
|
||||
...automationsRef.current.slice(0, index),
|
||||
auto,
|
||||
...automationsRef.current.slice(index + 1),
|
||||
];
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
data: {},
|
||||
};
|
||||
} else if (method === "DELETE") {
|
||||
const auto = data as AutomationData;
|
||||
automationsRef.current = automationsRef.current.filter(
|
||||
({ id }) => id !== auto.id
|
||||
);
|
||||
return {
|
||||
ok: true,
|
||||
data: {},
|
||||
};
|
||||
} else if (method === "POST") {
|
||||
const auto = data as BareAutomationData;
|
||||
automationsRef.current = [
|
||||
...automationsRef.current,
|
||||
{
|
||||
...auto,
|
||||
source_file: "automation.yaml",
|
||||
source_file_type: "list",
|
||||
configuration_key: ["automation"],
|
||||
},
|
||||
];
|
||||
return {
|
||||
ok: true,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
if (path === AUTOMTAION_ITEM_TAGS) {
|
||||
if (method === "POST") {
|
||||
const { automation_id, tags } = data as any;
|
||||
for (let i = 0; i < automationsRef.current.length; i++) {
|
||||
const auto = automationsRef.current[i];
|
||||
if (auto.id === automation_id) {
|
||||
automationsRef.current[i].tags = JSON.parse(JSON.stringify(tags));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
error: "PATH NOT FOUND " + method + ": " + path,
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const useProfileMockAPI = (
|
||||
initialProfile: UserProfile = {
|
||||
lang: "eng",
|
||||
theme: "dark",
|
||||
},
|
||||
makeRef = useRef,
|
||||
returnErrors: boolean = false
|
||||
): API => {
|
||||
const profileRef = makeRef(initialProfile);
|
||||
return {
|
||||
async makeCall({ path, method = "POST", data = {} }) {
|
||||
if (returnErrors) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "Test Error",
|
||||
};
|
||||
}
|
||||
if (path === USER_PROFILE_ROOT) {
|
||||
if (method === "GET") {
|
||||
return {
|
||||
ok: true,
|
||||
data: JSON.parse(JSON.stringify(profileRef.current)),
|
||||
} as any;
|
||||
} else if (method === "PUT") {
|
||||
profileRef.current = data as any;
|
||||
return { saved: "" };
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
error: "PATH NOT FOUND " + method + ": " + path,
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
export const AUTOMTAION_ROOT = "/" as const;
|
||||
export const AUTOMTAION_LIST = `${AUTOMTAION_ROOT}list` as const;
|
||||
export const AUTOMTAION_ITEM = `${AUTOMTAION_ROOT}item` as const;
|
||||
export const AUTOMTAION_ITEM_TAGS = `${AUTOMTAION_ITEM}/tags` as const;
|
||||
|
||||
export const USER_PROFILE_ROOT = "/profile" as const;
|
||||
@@ -0,0 +1,22 @@
|
||||
import { API } from "./base";
|
||||
import { UserProfile } from "./types";
|
||||
import { USER_PROFILE_ROOT } from "./paths";
|
||||
|
||||
export const makeProfileAPI = (api: API) => ({
|
||||
async get() {
|
||||
const data = await api.makeCall<UserProfile>({
|
||||
method: "GET",
|
||||
path: USER_PROFILE_ROOT,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
async update(data: UserProfile) {
|
||||
return await api.makeCall({
|
||||
method: "PUT",
|
||||
path: USER_PROFILE_ROOT,
|
||||
data,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export type UserProfileAPI = ReturnType<typeof makeProfileAPI>;
|
||||
@@ -0,0 +1,42 @@
|
||||
import { AutomationData } from "types/automations";
|
||||
|
||||
export interface ListParams {
|
||||
offset: number;
|
||||
limit: number;
|
||||
}
|
||||
export type APIRequest<D> = {
|
||||
path: string;
|
||||
method?: "POST" | "DELETE" | "GET" | "PUT";
|
||||
data?: D;
|
||||
};
|
||||
|
||||
export type APIResponse<D> =
|
||||
| {
|
||||
ok: true;
|
||||
data: D;
|
||||
}
|
||||
| {
|
||||
ok: false;
|
||||
error: string;
|
||||
};
|
||||
export type Waitable<D> =
|
||||
| { ready: undefined }
|
||||
| ({ ready: true } & APIResponse<D>)
|
||||
| {
|
||||
ready: false;
|
||||
};
|
||||
export interface ListData<D> {
|
||||
params: ListParams;
|
||||
totalItems: number;
|
||||
data: D[];
|
||||
}
|
||||
|
||||
export interface ApiState {
|
||||
automations: Waitable<ListData<AutomationData>>;
|
||||
userProfile: Waitable<UserProfile>;
|
||||
}
|
||||
|
||||
export type UserProfile = {
|
||||
theme: string;
|
||||
lang: string;
|
||||
};
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useState } from "react";
|
||||
import { ApiState } from "./types";
|
||||
import { AutomationAPI } from "./automations";
|
||||
import { UserProfileAPI } from "./profile";
|
||||
import { UserProfile } from "services/apiService/types";
|
||||
|
||||
export const useDefaultApiState = () =>
|
||||
useState<ApiState>({
|
||||
automations: { ready: undefined },
|
||||
userProfile: { ready: undefined },
|
||||
});
|
||||
|
||||
export const makeReloadAutomations = (
|
||||
automationAPI: AutomationAPI,
|
||||
state: ApiState,
|
||||
setState: (s: ApiState) => void
|
||||
) => {
|
||||
const reload = async () => {
|
||||
let params = { offset: 0, limit: 10000 };
|
||||
if (state.automations.ready && state.automations.ok) {
|
||||
params = state.automations.data.params;
|
||||
}
|
||||
const resp = await automationAPI.list(params);
|
||||
setState({
|
||||
...state,
|
||||
automations: {
|
||||
ready: true,
|
||||
...resp,
|
||||
},
|
||||
});
|
||||
};
|
||||
const wrapCall = <Call extends (a: any) => Promise<any>>(fcn: Call) => {
|
||||
return async (args: Parameters<Call>[0]) => {
|
||||
const resp = await fcn(args);
|
||||
await reload();
|
||||
return resp as ReturnType<Call>;
|
||||
};
|
||||
};
|
||||
return {
|
||||
reload,
|
||||
wrapCall,
|
||||
};
|
||||
};
|
||||
|
||||
export const makeProfileManager = (
|
||||
userProfileAPI: UserProfileAPI,
|
||||
state: ApiState,
|
||||
setState: (s: ApiState) => void
|
||||
) => {
|
||||
const reload = () =>
|
||||
userProfileAPI
|
||||
.get()
|
||||
.then((data) => {
|
||||
setState({
|
||||
...state,
|
||||
userProfile: {
|
||||
ready: true,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
})
|
||||
.catch((error) =>
|
||||
setState({
|
||||
...state,
|
||||
userProfile: {
|
||||
ready: true,
|
||||
ok: false,
|
||||
error: JSON.stringify(error),
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
reload,
|
||||
update: (data: UserProfile) =>
|
||||
userProfileAPI
|
||||
.update(data)
|
||||
.then(() => reload())
|
||||
.catch((err) =>
|
||||
setState({
|
||||
...state,
|
||||
userProfile: {
|
||||
ok: false,
|
||||
error: String(err),
|
||||
ready: true,
|
||||
},
|
||||
})
|
||||
),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,148 @@
|
||||
import { Connection, getCollection } from "home-assistant-js-websocket";
|
||||
import { useHassCollection } from "./useHassCollection";
|
||||
import {
|
||||
Option,
|
||||
BaseOption,
|
||||
} from "components/Inputs/AutoComplete/InputAutoComplete";
|
||||
import { EntityRegisteryItem, HassEntitiesRegistry } from "./types";
|
||||
import { prettyName } from "utils/formatting";
|
||||
|
||||
export interface AreaRegistryItem {
|
||||
area_id: string;
|
||||
name: string;
|
||||
picture: null | string;
|
||||
}
|
||||
export type AreaDB = Record<
|
||||
string,
|
||||
AreaRegistryItem & {
|
||||
domains: Set<string>;
|
||||
integrations: Set<string>;
|
||||
}
|
||||
>;
|
||||
|
||||
export const fetchAreaRegistry = (conn: Connection) =>
|
||||
Promise.all([
|
||||
conn.sendMessagePromise<AreaRegistryItem[]>({
|
||||
type: "config/area_registry/list",
|
||||
}),
|
||||
conn.sendMessagePromise<HassEntitiesRegistry>({
|
||||
type: "config/entity_registry/list",
|
||||
}),
|
||||
]).then(([areas, er]) => {
|
||||
const areaDB: AreaDB = areas.reduce<AreaDB>((all, item) => {
|
||||
return {
|
||||
...all,
|
||||
[item.area_id]: {
|
||||
...item,
|
||||
domains: new Set(),
|
||||
integrations: new Set(),
|
||||
},
|
||||
};
|
||||
}, {});
|
||||
er.forEach((eri) => {
|
||||
if (eri.area_id) {
|
||||
if (eri.entity_id) {
|
||||
areaDB[eri.area_id].domains.add(
|
||||
eri.entity_id.split(".")[0].toLowerCase()
|
||||
);
|
||||
}
|
||||
if (eri.platform) {
|
||||
areaDB[eri.area_id].domains.add(eri.platform);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return areaDB;
|
||||
});
|
||||
export const areaRegistryColl = (conn: Connection) =>
|
||||
getCollection<AreaDB>(conn, "_$earg", fetchAreaRegistry);
|
||||
|
||||
export type AreaOptionData = {
|
||||
data: Partial<EntityRegisteryItem>;
|
||||
};
|
||||
export type AreaBaseOption = BaseOption<AreaOptionData>;
|
||||
export type AreaOption = Option<AreaOptionData>;
|
||||
export const useHAAreas = () => {
|
||||
const areas = useHassCollection(areaRegistryColl);
|
||||
|
||||
const methods = {
|
||||
areaHasEntityDomain(areaId: string, domains: string[]): boolean {
|
||||
if (!areas.ready) {
|
||||
return true;
|
||||
}
|
||||
for (const d of domains) {
|
||||
if (!areas.collection[areaId].domains.has(d)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
areaHasEntityIntegration(areaId: string, integrations: string[]): boolean {
|
||||
if (!areas.ready) {
|
||||
return true;
|
||||
}
|
||||
for (const d of integrations) {
|
||||
if (!areas.collection[areaId].integrations.has(d)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
getBaseOption(opt: AreaOption): AreaBaseOption {
|
||||
if (!areas.ready) {
|
||||
throw new Error("Not Ready!");
|
||||
}
|
||||
if (typeof opt === "string") {
|
||||
return {
|
||||
id: opt,
|
||||
label: areas.collection[opt].name ?? prettyName(opt),
|
||||
data: areas.collection[opt],
|
||||
};
|
||||
}
|
||||
return opt;
|
||||
},
|
||||
getOptions(
|
||||
restrictToDomain?: string[],
|
||||
restrictedIntegrations?: string[]
|
||||
): AreaOption[] {
|
||||
if (!areas.ready) {
|
||||
return [];
|
||||
}
|
||||
let keys = Object.keys(areas.collection);
|
||||
if (restrictToDomain) {
|
||||
const domains = restrictToDomain.map((x) => x.toLowerCase());
|
||||
keys = keys.filter((key) => methods.areaHasEntityDomain(key, domains));
|
||||
}
|
||||
if (restrictedIntegrations) {
|
||||
const integrations = restrictedIntegrations.map((x) => x.toLowerCase());
|
||||
keys = keys.filter((key) =>
|
||||
methods.areaHasEntityIntegration(key, integrations)
|
||||
);
|
||||
}
|
||||
return keys.map((key) => ({
|
||||
id: key,
|
||||
label: areas.collection[key].name ?? prettyName(key),
|
||||
data: areas.collection[key],
|
||||
}));
|
||||
},
|
||||
getLabel: (opt: AreaOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
if (areas.ready) {
|
||||
return areas.collection[opt]
|
||||
? areas.collection[opt].name ?? prettyName(opt)
|
||||
: prettyName(opt);
|
||||
}
|
||||
return opt;
|
||||
}
|
||||
return opt.label ?? opt.id;
|
||||
},
|
||||
getID: (opt: AreaOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
return opt;
|
||||
}
|
||||
return opt.id;
|
||||
},
|
||||
};
|
||||
|
||||
return methods;
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { createHAEntitiesState } from "./HAEntities";
|
||||
import { EntitySource } from "./types";
|
||||
import { HassEntities } from "home-assistant-js-websocket";
|
||||
|
||||
export type MockHAEntitiesProps =
|
||||
| {
|
||||
loading: true;
|
||||
}
|
||||
| {
|
||||
loading: false;
|
||||
error?: false;
|
||||
entities: HassEntities;
|
||||
entitySource: Record<string, EntitySource>;
|
||||
}
|
||||
| {
|
||||
loading: false;
|
||||
error: {
|
||||
entities: any;
|
||||
entitySource: any;
|
||||
};
|
||||
};
|
||||
export const useMockHAEntities = (args: MockHAEntitiesProps) => {
|
||||
if (args.loading) {
|
||||
return createHAEntitiesState(
|
||||
{
|
||||
additional: {},
|
||||
ready: false,
|
||||
},
|
||||
{
|
||||
additional: {},
|
||||
ready: false,
|
||||
}
|
||||
);
|
||||
} else if (!args.error) {
|
||||
return createHAEntitiesState(
|
||||
{
|
||||
additional: {},
|
||||
ready: true,
|
||||
collection: args.entities,
|
||||
},
|
||||
{
|
||||
additional: {},
|
||||
ready: true,
|
||||
collection: args.entitySource,
|
||||
}
|
||||
);
|
||||
} else {
|
||||
return createHAEntitiesState(
|
||||
{
|
||||
additional: {},
|
||||
ready: false,
|
||||
error: args.error.entities,
|
||||
},
|
||||
{
|
||||
additional: {},
|
||||
ready: false,
|
||||
error: args.error.entitySource,
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,219 @@
|
||||
import { Option } from "components/Inputs/AutoComplete/InputAutoComplete";
|
||||
import { HACollectionState, useHassCollection } from "./useHassCollection";
|
||||
import { entitiesColl, HassEntities } from "home-assistant-js-websocket";
|
||||
import { entitySourceColl } from "./additionalCollections";
|
||||
import { EntitySource } from "./types";
|
||||
|
||||
export type EntityOption = Option<{ domain: string; integration: string }>;
|
||||
export type HAEntitiesState = ReturnType<typeof createHAEntitiesState>;
|
||||
export const useHAEntities = (): HAEntitiesState => {
|
||||
const entities = useHassCollection(entitiesColl, (state) => ({
|
||||
domains: Array.from(
|
||||
new Set(Object.keys(state).map((x) => x.split(".")[0])).keys()
|
||||
).sort(),
|
||||
}));
|
||||
const entitySource = useHassCollection(entitySourceColl);
|
||||
return createHAEntitiesState(entities, entitySource);
|
||||
};
|
||||
|
||||
export const createHAEntitiesState = (
|
||||
entities: HACollectionState<
|
||||
HassEntities,
|
||||
{
|
||||
domains: string[];
|
||||
}
|
||||
>,
|
||||
entitySource: HACollectionState<Record<string, EntitySource>, {}>
|
||||
) => {
|
||||
const methods = {
|
||||
getStates(inp: string[] | string, attribute?: string): string[] {
|
||||
if (!entities.ready) {
|
||||
return [];
|
||||
}
|
||||
let entityIds: string[] = [];
|
||||
if (typeof inp === "string") {
|
||||
entityIds = [inp];
|
||||
} else if (Array.isArray(inp)) {
|
||||
entityIds = inp;
|
||||
}
|
||||
let state: Set<string> = new Set();
|
||||
entityIds.forEach((entityId) => {
|
||||
if (entities.collection[entityId]) {
|
||||
if (!attribute) {
|
||||
state.add(entities.collection[entityId].state);
|
||||
} else {
|
||||
const val = (entities.collection[entityId]?.attributes ?? {})[
|
||||
attribute
|
||||
];
|
||||
if (val) {
|
||||
state.add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return Array.from(state.keys());
|
||||
},
|
||||
getAttributes(inp: string[] | string): string[] {
|
||||
if (!entities.ready) {
|
||||
return [];
|
||||
}
|
||||
let entityIds: string[] = [];
|
||||
if (typeof inp === "string") {
|
||||
entityIds = [inp];
|
||||
} else if (Array.isArray(inp)) {
|
||||
entityIds = inp;
|
||||
}
|
||||
let attributes: Set<string> = new Set();
|
||||
entityIds.forEach((entityId) => {
|
||||
const thisAttrs = new Set(
|
||||
Object.keys(entities.collection[entityId]?.attributes ?? {})
|
||||
);
|
||||
if (attributes.size === 0) {
|
||||
attributes = thisAttrs;
|
||||
} else {
|
||||
attributes = new Set([...attributes].filter((a) => thisAttrs.has(a)));
|
||||
}
|
||||
});
|
||||
return Array.from(attributes.keys());
|
||||
},
|
||||
getDomainList(): string[] {
|
||||
return entities.additional?.domains ?? [];
|
||||
},
|
||||
validateOptions(
|
||||
options: string[],
|
||||
restrictedDomains?: string[],
|
||||
restrictedIntegrations?: string[]
|
||||
): null | string[] {
|
||||
let out = options;
|
||||
if (restrictedDomains) {
|
||||
const domains = restrictedDomains.map((x) => x.toLowerCase());
|
||||
const domainsStr =
|
||||
domains.length > 1
|
||||
? `one of "${domains.join(", ")}"`
|
||||
: `"${domains[0]}"`;
|
||||
out = out.reduce<string[]>((all = [], key) => {
|
||||
if (!domains.includes(key.toLowerCase().split(".")[0])) {
|
||||
return [...all, `${methods.getLabel(key)} is not ${domainsStr}`];
|
||||
}
|
||||
return all;
|
||||
}, []);
|
||||
}
|
||||
if (restrictedIntegrations && entitySource.ready) {
|
||||
const domains = restrictedIntegrations.map((x) => x.toLowerCase());
|
||||
const domainsStr =
|
||||
domains.length > 1
|
||||
? `one of "${domains.join(", ")}"`
|
||||
: `"${domains[0]}"`;
|
||||
out = out.reduce<string[]>((all = [], key) => {
|
||||
const integration = entitySource.collection[key].domain;
|
||||
if (!domains.includes(integration.toLowerCase())) {
|
||||
return [...all, `${methods.getLabel(key)} is not ${domainsStr}`];
|
||||
}
|
||||
return all;
|
||||
}, []);
|
||||
}
|
||||
if (out.length > 0) {
|
||||
return out;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
getOptions(
|
||||
restrictToDomain?: string[],
|
||||
restrictedIntegrations?: string[],
|
||||
restrictedDeviceClass?: string[],
|
||||
mode: "and" | "or" = "and"
|
||||
): EntityOption[] {
|
||||
if (!entities.ready) {
|
||||
return [];
|
||||
}
|
||||
const deviceClasses = (restrictedDeviceClass ?? []).map((x) =>
|
||||
x.toLowerCase()
|
||||
);
|
||||
const domains = (restrictToDomain ?? []).map((x) => x.toLowerCase());
|
||||
const integrations = (restrictedIntegrations ?? []).map((x) =>
|
||||
x.toLowerCase()
|
||||
);
|
||||
return Object.keys(entities.collection)
|
||||
.filter((entityId) => {
|
||||
if (mode === "and") {
|
||||
let keep = true;
|
||||
if (domains.length > 0) {
|
||||
keep =
|
||||
keep && domains.includes(entityId.toLowerCase().split(".")[0]);
|
||||
}
|
||||
if (entitySource.ready && integrations.length > 0) {
|
||||
keep =
|
||||
keep &&
|
||||
integrations.includes(
|
||||
entitySource.collection[entityId]?.domain ?? ""
|
||||
);
|
||||
}
|
||||
if (deviceClasses.length > 0) {
|
||||
keep =
|
||||
keep &&
|
||||
deviceClasses.includes(
|
||||
entities.collection[
|
||||
entityId
|
||||
].attributes.device_class?.toLowerCase() ?? ""
|
||||
);
|
||||
}
|
||||
return keep;
|
||||
} else {
|
||||
if (
|
||||
!entitySource.ready &&
|
||||
deviceClasses.length === 0 &&
|
||||
domains.length === 0 &&
|
||||
integrations.length === 0
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
let keep = false;
|
||||
keep =
|
||||
keep || domains.includes(entityId.toLowerCase().split(".")[0]);
|
||||
if (entitySource.ready) {
|
||||
keep =
|
||||
keep ||
|
||||
integrations.includes(
|
||||
entitySource.collection[entityId]?.domain ?? ""
|
||||
);
|
||||
}
|
||||
keep =
|
||||
keep ||
|
||||
deviceClasses.includes(
|
||||
entities.collection[
|
||||
entityId
|
||||
].attributes.device_class?.toLowerCase() ?? ""
|
||||
);
|
||||
return keep;
|
||||
}
|
||||
})
|
||||
.map((key) => ({
|
||||
id: key,
|
||||
label: entities.collection[key].attributes.friendly_name ?? key,
|
||||
domain: key.split(".")[0] ?? "n/a",
|
||||
integration: entitySource.ready
|
||||
? (entitySource.collection[key] ?? {}).domain ?? "n/a"
|
||||
: "...",
|
||||
}));
|
||||
},
|
||||
getLabel: (opt: EntityOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
if (entities.ready) {
|
||||
return entities.collection[opt]?.attributes.friendly_name ?? opt;
|
||||
}
|
||||
return opt;
|
||||
}
|
||||
return opt.label ?? opt.id;
|
||||
},
|
||||
getID: (opt: EntityOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
return opt;
|
||||
}
|
||||
return opt.id;
|
||||
},
|
||||
};
|
||||
return {
|
||||
...entities,
|
||||
...methods,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Connection, getCollection } from "home-assistant-js-websocket";
|
||||
import {
|
||||
DeviceRegistryItem,
|
||||
EntitySource,
|
||||
HassDevices,
|
||||
HassEntitiesRegistry,
|
||||
} from "./types";
|
||||
|
||||
export const fetchDeviceRegistry = (
|
||||
conn: Connection
|
||||
): Promise<Record<string, DeviceRegistryItem>> =>
|
||||
conn
|
||||
.sendMessagePromise<HassDevices>({
|
||||
type: "config/device_registry/list",
|
||||
})
|
||||
.then((data) =>
|
||||
data
|
||||
.filter(({ disabled_by }) => !disabled_by)
|
||||
.reduce<Record<string, DeviceRegistryItem>>((all, n) => {
|
||||
all[n.id] = n;
|
||||
return all;
|
||||
}, {})
|
||||
);
|
||||
export const deviceRegistryColl = (conn: Connection) =>
|
||||
getCollection<Record<string, DeviceRegistryItem>>(
|
||||
conn,
|
||||
"_$drc",
|
||||
fetchDeviceRegistry
|
||||
);
|
||||
|
||||
export const fetchEntityRegistry = (conn: Connection) =>
|
||||
conn
|
||||
.sendMessagePromise<HassEntitiesRegistry>({
|
||||
type: "config/entity_registry/list",
|
||||
})
|
||||
.then((data) => data.filter(({ disabled_by }) => !disabled_by));
|
||||
export const entityRegistryColl = (conn: Connection) =>
|
||||
getCollection<HassEntitiesRegistry>(conn, "_$erc", fetchEntityRegistry);
|
||||
|
||||
export const fetchEntitySource = (conn: Connection) =>
|
||||
conn.sendMessagePromise<Record<string, EntitySource>>({
|
||||
type: "entity/source",
|
||||
});
|
||||
export const entitySourceColl = (conn: Connection) =>
|
||||
getCollection<Record<string, EntitySource>>(conn, "_$esc", fetchEntitySource);
|
||||
@@ -0,0 +1,88 @@
|
||||
import React, { FC, useEffect, useState } from "react";
|
||||
import { makeStory } from "devUtils";
|
||||
import { useHA } from "services/haService";
|
||||
import InputYaml from "components/Inputs/Base/InputYaml";
|
||||
import { InputList } from "components/Inputs/InputList";
|
||||
import { Button } from "components/Inputs/Buttons/Button";
|
||||
import { ServiceEditor } from "components/ServiceEditor";
|
||||
|
||||
const Test: FC = () => {
|
||||
const { services, callService, entities } = useHA();
|
||||
|
||||
const data = services.collection ?? {};
|
||||
|
||||
const domain = "automation";
|
||||
|
||||
const domains = Object.keys(data[domain] ?? "").sort();
|
||||
|
||||
const [service, setService] = useState(domains[0] ?? "");
|
||||
const serviceDefn = (data[domain] ?? {})[service] ?? {};
|
||||
|
||||
const [serviceData, setServiceData] = useState({ field: {}, target: {} });
|
||||
|
||||
useEffect(() => {
|
||||
setService(domains[0] ?? "");
|
||||
setServiceData({ field: {}, target: {} });
|
||||
}, [domain, setService]);
|
||||
|
||||
let serviceEditElm = <>Failed to load</>;
|
||||
|
||||
try {
|
||||
if (service) {
|
||||
serviceEditElm = (
|
||||
<div
|
||||
style={{
|
||||
border: "1px solid var(--mui-grey-400)",
|
||||
maxWidth: "100vw",
|
||||
padding: "2.5em",
|
||||
margin: "2.5em",
|
||||
}}
|
||||
>
|
||||
<ServiceEditor
|
||||
service={serviceDefn}
|
||||
serviceId={`${domain}.${service}`}
|
||||
data={serviceData}
|
||||
onUpdate={setServiceData}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
serviceEditElm = <>{JSON.stringify(err)}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ overflow: "auto", maxHeight: "100vh" }}>
|
||||
<InputList
|
||||
label="Services"
|
||||
current={service}
|
||||
onChange={setService}
|
||||
options={domains}
|
||||
/>
|
||||
<Button
|
||||
onClick={() =>
|
||||
callService(domain, service, serviceData.field, serviceData.target)
|
||||
}
|
||||
>
|
||||
Call
|
||||
</Button>
|
||||
{serviceEditElm}
|
||||
<InputYaml label="Service Data" value={serviceDefn} onChange={() => {}} />
|
||||
{(((serviceData.target ?? {}) as any).entity_id ?? []).map((eid: any) => (
|
||||
<span>
|
||||
{eid}: {entities.getStates([eid])}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const { make, componentMeta } = makeStory({
|
||||
Component: Test,
|
||||
meta: {
|
||||
title: "Services/HA Service",
|
||||
},
|
||||
});
|
||||
|
||||
export default componentMeta;
|
||||
export const AutomationCall = make({});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
ERR_HASS_HOST_REQUIRED,
|
||||
createLongLivedTokenAuth,
|
||||
Connection,
|
||||
ERR_CANNOT_CONNECT,
|
||||
ERR_CONNECTION_LOST,
|
||||
ERR_INVALID_AUTH,
|
||||
ERR_INVALID_HTTPS_TO_HTTP,
|
||||
createConnection as _createConnection,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { wsURL } from "services/apiService";
|
||||
|
||||
export type HAConnection =
|
||||
| {
|
||||
status: "loading";
|
||||
}
|
||||
| {
|
||||
status: "loaded";
|
||||
connection: Connection;
|
||||
}
|
||||
| {
|
||||
status: "error";
|
||||
error: any;
|
||||
};
|
||||
let haConnection: HAConnection = {
|
||||
status: "loading",
|
||||
};
|
||||
|
||||
const translateErrorCodes = (errorCode: number) => {
|
||||
if (errorCode === ERR_HASS_HOST_REQUIRED) {
|
||||
return "Missing HASS host";
|
||||
}
|
||||
if (errorCode === ERR_CANNOT_CONNECT) {
|
||||
return "Failed to connect";
|
||||
}
|
||||
if (errorCode === ERR_CONNECTION_LOST) {
|
||||
return "Connection Lost";
|
||||
}
|
||||
if (errorCode === ERR_INVALID_AUTH) {
|
||||
return "Invalid Host";
|
||||
}
|
||||
if (errorCode === ERR_INVALID_HTTPS_TO_HTTP) {
|
||||
return "Invalid https to http";
|
||||
}
|
||||
return errorCode;
|
||||
};
|
||||
|
||||
const createConnection = async () => {
|
||||
try {
|
||||
return _createConnection({
|
||||
auth: createLongLivedTokenAuth(wsURL, "xxx"),
|
||||
});
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line
|
||||
throw {
|
||||
originalError: JSON.stringify(error),
|
||||
message: translateErrorCodes(error as any),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
async function startHAConnection() {
|
||||
let connection: Connection;
|
||||
try {
|
||||
connection = await createConnection();
|
||||
} catch (error) {
|
||||
haConnection = {
|
||||
status: "error",
|
||||
error: {
|
||||
originalError: JSON.stringify(error),
|
||||
message: translateErrorCodes(error as any),
|
||||
},
|
||||
};
|
||||
throw error;
|
||||
}
|
||||
haConnection = {
|
||||
status: "loaded",
|
||||
connection,
|
||||
};
|
||||
return haConnection;
|
||||
}
|
||||
|
||||
startHAConnection().then(console.info).catch(console.error);
|
||||
export const useHAConnection = (): HAConnection => {
|
||||
const [conn, setConn] = useState<HAConnection>(haConnection);
|
||||
const timeID = useRef<number | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
if (conn.status !== haConnection.status) {
|
||||
setConn(haConnection);
|
||||
}
|
||||
const waiter = () => {
|
||||
if (conn.status !== haConnection.status) {
|
||||
setConn(haConnection);
|
||||
}
|
||||
timeID.current = window.setTimeout(
|
||||
() => {
|
||||
waiter();
|
||||
},
|
||||
conn.status === "loading" ? 500 : 5000
|
||||
);
|
||||
};
|
||||
waiter();
|
||||
return () => window.clearTimeout(timeID.current);
|
||||
}, [conn, setConn]);
|
||||
return conn;
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import React, { FC } from "react";
|
||||
import { useHADeviceRegistry } from "services/haService";
|
||||
import InputYaml from "components/Inputs/Base/InputYaml";
|
||||
import { makeStory } from "devUtils";
|
||||
|
||||
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
|
||||
const conn = useHADeviceRegistry();
|
||||
onRender && onRender();
|
||||
if (conn.ready) {
|
||||
return (
|
||||
<div>
|
||||
{Object.keys(conn.collection).length} items
|
||||
<ul
|
||||
style={{
|
||||
maxHeight: "100vh",
|
||||
overflow: "auto",
|
||||
}}
|
||||
>
|
||||
{Object.keys(conn.collection).map((k) => (
|
||||
<li key={k}>
|
||||
<b>{k}</b>
|
||||
{/* <u>{conn.collection[k].length > 1 ? conn.collection[k].length : ''}</u> */}
|
||||
<InputYaml
|
||||
value={conn.collection[k]}
|
||||
onChange={() => {}}
|
||||
label={k}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <code>Loading...</code>;
|
||||
};
|
||||
|
||||
const { make, componentMeta } = makeStory({
|
||||
Component: Test,
|
||||
meta: {
|
||||
title: "Services/Device Registry",
|
||||
},
|
||||
});
|
||||
|
||||
export default componentMeta;
|
||||
export const Basic = make({});
|
||||
@@ -0,0 +1,57 @@
|
||||
import React, { FC, useState } from "react";
|
||||
import { ComponentMeta, ComponentStory } from "@storybook/react";
|
||||
import { MockPage } from "components/Page";
|
||||
import { useHAEntities } from "services/haService/HAEntities";
|
||||
|
||||
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
|
||||
const [searchTerm, setSearch] = useState("");
|
||||
const conn = useHAEntities();
|
||||
onRender && onRender();
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
key="text"
|
||||
type="text"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearch(e.target.value.toLowerCase())}
|
||||
/>
|
||||
<ul
|
||||
key="list"
|
||||
style={{
|
||||
maxHeight: "60vh",
|
||||
overflow: "auto",
|
||||
}}
|
||||
>
|
||||
{Object.entries(conn.collection ?? {})
|
||||
.filter(([key, _]) => key.toLowerCase().includes(searchTerm))
|
||||
.map(([key, value]) => {
|
||||
return (
|
||||
<li key={key}>
|
||||
<b>{key}</b> <br />
|
||||
Context: {JSON.stringify(value.context)} <br />
|
||||
Attributes: {JSON.stringify(value.attributes)} <br />
|
||||
State: {JSON.stringify(value.state)} <br />
|
||||
Updated at: {JSON.stringify(value.last_updated)} <br />
|
||||
Changed at: {JSON.stringify(value.last_changed)} <br />
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default {
|
||||
title: "Services/HA Entities",
|
||||
component: Test,
|
||||
parameters: { actions: { argTypesRegex: "^on.*" } },
|
||||
args: {},
|
||||
} as ComponentMeta<typeof Test>;
|
||||
|
||||
export const Base: ComponentStory<typeof Test> = (props) => {
|
||||
return (
|
||||
<MockPage>
|
||||
<Test {...props} />
|
||||
</MockPage>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import React, { FC } from "react";
|
||||
import { ComponentMeta, ComponentStory } from "@storybook/react";
|
||||
import { MockPage } from "components/Page";
|
||||
import { useHAEntityRegistry } from "services/haService";
|
||||
|
||||
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
|
||||
const conn = useHAEntityRegistry();
|
||||
onRender && onRender();
|
||||
if (conn.ready) {
|
||||
return (
|
||||
<div>
|
||||
{conn.collection.length}
|
||||
<ul
|
||||
style={{
|
||||
maxHeight: "100vh",
|
||||
overflow: "auto",
|
||||
}}
|
||||
>
|
||||
{conn.collection.map((row, i) => (
|
||||
<li key={i}>
|
||||
{row.entity_id}
|
||||
{/* {Object.keys(row).map(k => <>
|
||||
<span key={k}>
|
||||
<b>{k}</b>: {JSON.stringify(row[k] as any)}
|
||||
</span><br key={`${k}-br`} />
|
||||
</>)} */}
|
||||
{/* <InputYaml label={String(i)} value={row} onChange={() => { }} /> */}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <code>Loading...</code>;
|
||||
};
|
||||
|
||||
export default {
|
||||
title: "Services/Entity Registry",
|
||||
component: Test,
|
||||
parameters: { actions: { argTypesRegex: "^on.*" } },
|
||||
args: {},
|
||||
} as ComponentMeta<typeof Test>;
|
||||
|
||||
export const Base: ComponentStory<typeof Test> = (props) => {
|
||||
return (
|
||||
<MockPage>
|
||||
<Test {...props} />
|
||||
</MockPage>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,146 @@
|
||||
import { BaseOption } from "components/Inputs/AutoComplete/InputAutoComplete";
|
||||
import { MessageBase } from "home-assistant-js-websocket";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { prettyName } from "utils/formatting";
|
||||
import {
|
||||
DeviceConditionType,
|
||||
DeviceTriggerType,
|
||||
DeviceTypeAction,
|
||||
DeviceTypeCapability,
|
||||
HASendMessage,
|
||||
} from "./types";
|
||||
|
||||
export const makeCreateUseThing = (callHA: HASendMessage) =>
|
||||
function <Args, HAData, STData>(
|
||||
convertArgsToMessage: (a: Args) => MessageBase,
|
||||
transformHAData: (ha: HAData) => STData,
|
||||
defaultSTData: STData
|
||||
) {
|
||||
return function useThis(args?: Args) {
|
||||
const lastThing = useRef<string | null>(null);
|
||||
const [stData, setStData] = useState<STData>(defaultSTData);
|
||||
useEffect(() => {
|
||||
const currentThing = JSON.stringify(args);
|
||||
if (args && currentThing && lastThing.current !== currentThing) {
|
||||
lastThing.current = currentThing;
|
||||
const msg = convertArgsToMessage(args);
|
||||
callHA(msg)
|
||||
.then((raw: HAData) => {
|
||||
if (lastThing.current === currentThing) {
|
||||
setStData(transformHAData(raw));
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn({ msg, args, currentThing, error });
|
||||
});
|
||||
} else if (lastThing.current !== currentThing) {
|
||||
lastThing.current = currentThing;
|
||||
setStData(defaultSTData);
|
||||
}
|
||||
}, [args]);
|
||||
return stData;
|
||||
};
|
||||
};
|
||||
|
||||
export const getDeviceExtraWsCalls = (callHA: HASendMessage) => {
|
||||
const createUseThing = makeCreateUseThing(callHA);
|
||||
const reduceDeviceThings = function <
|
||||
Raw extends { type: string; subtype?: string; entity_id?: string }
|
||||
>(raw: Raw[]) {
|
||||
return raw.reduce<Record<string, BaseOption<{ data: Raw[] }>>>(
|
||||
(all, opt: Raw) => {
|
||||
const id = opt.type + (opt.subtype ?? "");
|
||||
if (!all[id]) {
|
||||
return {
|
||||
...all,
|
||||
[id]: {
|
||||
id,
|
||||
label:
|
||||
prettyName(opt.type) + (opt.subtype ? ` ${opt.subtype}` : ""),
|
||||
data: [opt],
|
||||
},
|
||||
};
|
||||
} else {
|
||||
all[id].data.push(opt);
|
||||
return all;
|
||||
}
|
||||
},
|
||||
{}
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
useDeviceActions: createUseThing<
|
||||
{ deviceId: string },
|
||||
DeviceTypeAction[],
|
||||
Record<string, BaseOption<{ data: DeviceTypeAction[] }>>
|
||||
>(
|
||||
({ deviceId }) => ({
|
||||
type: "device_automation/action/list",
|
||||
device_id: deviceId,
|
||||
}),
|
||||
reduceDeviceThings,
|
||||
{}
|
||||
),
|
||||
useDeviceCapalities: createUseThing<
|
||||
DeviceTypeAction,
|
||||
DeviceTypeCapability,
|
||||
Partial<DeviceTypeCapability>
|
||||
>(
|
||||
(action) => ({
|
||||
type: "device_automation/action/capabilities",
|
||||
action,
|
||||
}),
|
||||
(data) => data,
|
||||
{}
|
||||
),
|
||||
useDeviceTriggerCapalities: createUseThing<
|
||||
DeviceTypeAction,
|
||||
DeviceTypeCapability,
|
||||
Partial<DeviceTypeCapability>
|
||||
>(
|
||||
(trigger) => ({
|
||||
type: "device_automation/trigger/capabilities",
|
||||
trigger,
|
||||
}),
|
||||
(data) => data,
|
||||
{}
|
||||
),
|
||||
useDeviceTriggers: createUseThing<
|
||||
{ deviceId: string },
|
||||
DeviceTriggerType[],
|
||||
Record<string, BaseOption<{ data: DeviceTriggerType[] }>>
|
||||
>(
|
||||
({ deviceId }) => ({
|
||||
type: "device_automation/trigger/list",
|
||||
device_id: deviceId,
|
||||
}),
|
||||
reduceDeviceThings,
|
||||
{}
|
||||
),
|
||||
useDeviceConditionCapalities: createUseThing<
|
||||
DeviceTypeAction,
|
||||
DeviceTypeCapability,
|
||||
Partial<DeviceTypeCapability>
|
||||
>(
|
||||
(condition) => ({
|
||||
type: "device_automation/condition/capabilities",
|
||||
condition,
|
||||
}),
|
||||
(data) => data,
|
||||
{}
|
||||
),
|
||||
useDeviceConditions: createUseThing<
|
||||
{ deviceId: string },
|
||||
DeviceConditionType[],
|
||||
Record<string, BaseOption<{ data: DeviceConditionType[] }>>
|
||||
>(
|
||||
({ deviceId }) => ({
|
||||
type: "device_automation/condition/list",
|
||||
device_id: deviceId,
|
||||
}),
|
||||
reduceDeviceThings,
|
||||
{}
|
||||
),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
export interface TypedHassService {
|
||||
name?: string;
|
||||
description: string;
|
||||
fields: Fields;
|
||||
target?: Targets | null | undefined;
|
||||
}
|
||||
|
||||
export type Fields = Record<string, FieldData>;
|
||||
export interface Targets {
|
||||
device?: TargetData;
|
||||
entity?: TargetData;
|
||||
}
|
||||
export interface TargetData {
|
||||
domain?: string;
|
||||
integration?: string;
|
||||
}
|
||||
|
||||
export interface FieldData {
|
||||
name?: string | undefined;
|
||||
description: string;
|
||||
required?: boolean;
|
||||
example?: any;
|
||||
selector?: FieldSelector;
|
||||
advanced?: boolean;
|
||||
default?: any;
|
||||
}
|
||||
|
||||
export interface FieldSelector {
|
||||
text?: SelectorText | null;
|
||||
select?: SelectorSelect;
|
||||
number?: SelectorNumber;
|
||||
boolean?: null;
|
||||
object?: null;
|
||||
theme?: null;
|
||||
addon?: null;
|
||||
entity?: TargetData;
|
||||
icon?: null;
|
||||
color_rgb?: null;
|
||||
color_temp?: SelectorColorTemp | null;
|
||||
time?: null;
|
||||
}
|
||||
|
||||
export interface SelectorColorTemp {
|
||||
min_mireds: number;
|
||||
max_mireds: number;
|
||||
}
|
||||
|
||||
export interface SelectorNumber {
|
||||
min: number;
|
||||
max: number;
|
||||
unit_of_measurement?: string;
|
||||
mode?: "box";
|
||||
step?: number;
|
||||
}
|
||||
|
||||
interface SelectorSelect {
|
||||
options: OptionElement[];
|
||||
}
|
||||
|
||||
type OptionElement = OptionClass | string;
|
||||
|
||||
interface OptionClass {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface SelectorText {
|
||||
multiline: boolean;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import { servicesColl } from "home-assistant-js-websocket";
|
||||
import { Namer } from "utils/formatting";
|
||||
import {
|
||||
deviceRegistryColl,
|
||||
entityRegistryColl,
|
||||
} from "./additionalCollections";
|
||||
import { DeviceRegistryItem, HASendMessage } from "./types";
|
||||
import { useHassCollection } from "./useHassCollection";
|
||||
import { useHAConnection } from "./connection";
|
||||
import { useSnackbar } from "notistack";
|
||||
import { TypedHassService } from "./fieldTypes";
|
||||
import { Option } from "components/Inputs/AutoComplete/InputAutoComplete";
|
||||
import { getDeviceExtraWsCalls } from "./extras";
|
||||
import { useHAEntities } from "./HAEntities";
|
||||
import { useLang } from "services/lang";
|
||||
|
||||
export type ServiceOption = Option<{
|
||||
domain: string;
|
||||
action: string;
|
||||
description: string;
|
||||
data: TypedHassService;
|
||||
}>;
|
||||
export type HAServicesState = ReturnType<typeof useHAServices>;
|
||||
export const useHAServices = () => {
|
||||
const services = useHassCollection(servicesColl);
|
||||
const methods = {
|
||||
getOption(name: string): TypedHassService | null {
|
||||
if (!services.ready) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const [domain, action] = name.split(".");
|
||||
return {
|
||||
name:
|
||||
services.collection[domain][action].name ?? `${domain}.${action}`,
|
||||
description: services.collection[domain][action].description ?? "",
|
||||
target: services.collection[domain][action].target,
|
||||
fields: services.collection[domain][action].fields,
|
||||
};
|
||||
} catch (err: any) {
|
||||
console.warn(err);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
getOptions(): ServiceOption[] {
|
||||
if (!services.ready) {
|
||||
return [];
|
||||
}
|
||||
return Object.keys(services.collection).reduce<ServiceOption[]>(
|
||||
(all, domain) => {
|
||||
const opts = Object.keys(
|
||||
services.collection[domain]
|
||||
).map<ServiceOption>((action) => ({
|
||||
id: `${domain}.${action}`,
|
||||
label:
|
||||
services.collection[domain][action].name ?? `${domain}.${action}`,
|
||||
description: services.collection[domain][action].description ?? "",
|
||||
domain,
|
||||
action,
|
||||
data: {
|
||||
name:
|
||||
services.collection[domain][action].name ??
|
||||
`${domain}.${action}`,
|
||||
description:
|
||||
services.collection[domain][action].description ?? "",
|
||||
target: services.collection[domain][action].target,
|
||||
fields: services.collection[domain][action].fields,
|
||||
},
|
||||
}));
|
||||
return all.concat(opts);
|
||||
},
|
||||
[]
|
||||
);
|
||||
},
|
||||
getLabel: (opt: ServiceOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
if (services.ready) {
|
||||
try {
|
||||
const [domain, action] = opt.split(".");
|
||||
return services.collection[domain][action].name ?? opt;
|
||||
} catch (_) {}
|
||||
}
|
||||
return opt;
|
||||
}
|
||||
return opt.label ?? opt.id;
|
||||
},
|
||||
getID: (opt: ServiceOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
return opt;
|
||||
}
|
||||
return opt.id;
|
||||
},
|
||||
};
|
||||
|
||||
return { ...services, ...methods };
|
||||
};
|
||||
|
||||
export type DeviceRegistryOption = Option<{ manufacturer: string }>;
|
||||
export type HADeviceRegistry = ReturnType<typeof useHADeviceRegistry>;
|
||||
export const useHADeviceRegistry = () => {
|
||||
const dr = useHassCollection(deviceRegistryColl);
|
||||
const getLabelForItem = (item: DeviceRegistryItem) =>
|
||||
item ? item.name_by_user ?? item.name ?? item.id : "";
|
||||
const methods = {
|
||||
getOptions(): DeviceRegistryOption[] {
|
||||
if (!dr.ready) {
|
||||
return [];
|
||||
}
|
||||
const keys = Object.keys(dr.collection);
|
||||
return keys.map((key) => ({
|
||||
id: key,
|
||||
label: getLabelForItem(dr.collection[key]) ?? key,
|
||||
manufacturer: dr.collection[key].manufacturer ?? "",
|
||||
}));
|
||||
},
|
||||
getLabel: (opt: DeviceRegistryOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
if (dr.ready) {
|
||||
return getLabelForItem(dr.collection[opt]) ?? opt;
|
||||
}
|
||||
return opt;
|
||||
}
|
||||
return opt.label ?? opt.id;
|
||||
},
|
||||
getID: (opt: DeviceRegistryOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
return opt;
|
||||
}
|
||||
return opt.id;
|
||||
},
|
||||
};
|
||||
return { ...dr, ...methods };
|
||||
};
|
||||
export const useHAEntityRegistry = () => {
|
||||
const dr = useHassCollection(entityRegistryColl);
|
||||
return dr;
|
||||
};
|
||||
|
||||
export type HAService = ReturnType<typeof useHA>;
|
||||
export const useHA = () => {
|
||||
const langStore = useLang();
|
||||
const entities = useHAEntities();
|
||||
const devices = useHADeviceRegistry();
|
||||
const services = useHAServices();
|
||||
const conn = useHAConnection();
|
||||
const snackbr = useSnackbar();
|
||||
|
||||
const callService = async (
|
||||
domain: string,
|
||||
service: string,
|
||||
data: any = {},
|
||||
target: any = {}
|
||||
) => {
|
||||
if (conn.status === "loaded") {
|
||||
try {
|
||||
const result = await conn.connection.sendMessagePromise({
|
||||
type: "call_service",
|
||||
domain,
|
||||
service,
|
||||
target,
|
||||
service_data: data,
|
||||
});
|
||||
snackbr.enqueueSnackbar(
|
||||
langStore.get("INFO_SUCCESS_CALL", {
|
||||
entityId: `${domain}.${service}`,
|
||||
}),
|
||||
{
|
||||
variant: "success",
|
||||
}
|
||||
);
|
||||
return result;
|
||||
} catch (err: any) {
|
||||
let msg = JSON.stringify(err);
|
||||
if ("message" in err) {
|
||||
msg = err.message;
|
||||
}
|
||||
snackbr.enqueueSnackbar(
|
||||
langStore.get("ERROR_FAILED_CALLING", {
|
||||
entityId: `${domain}.${service}`,
|
||||
msg,
|
||||
}),
|
||||
{
|
||||
variant: "error",
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (conn.status === "error") {
|
||||
snackbr.enqueueSnackbar(
|
||||
langStore.get("ERROR_FAILED_CALLING_BC_CONNECTION", {
|
||||
connStatus: conn.status,
|
||||
connError: conn.error,
|
||||
}),
|
||||
{
|
||||
variant: "error",
|
||||
}
|
||||
);
|
||||
} else {
|
||||
snackbr.enqueueSnackbar(
|
||||
langStore.get("ERROR_FAILED_CALLING_BC_CONNECTION", {
|
||||
connStatus: conn.status,
|
||||
connError: "",
|
||||
}),
|
||||
{
|
||||
variant: "error",
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const callHA: HASendMessage = async (sendMsg) => {
|
||||
if (conn.status === "loaded") {
|
||||
return await conn.connection.sendMessagePromise(sendMsg);
|
||||
}
|
||||
};
|
||||
|
||||
const namer: Namer = {
|
||||
getDeviceName(device_id) {
|
||||
return devices.getLabel(device_id);
|
||||
},
|
||||
getEntityName(entity_id, maxEntities = 1) {
|
||||
if (Array.isArray(entity_id)) {
|
||||
const out = entity_id
|
||||
.slice(0, maxEntities)
|
||||
.map(entities.getLabel)
|
||||
.join(", ");
|
||||
if (entity_id.length > maxEntities) {
|
||||
return out + " " + langStore.get("AND_MORE");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return entities.getLabel(entity_id);
|
||||
},
|
||||
getServiceName(service) {
|
||||
return services.getLabel(service);
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
entities,
|
||||
devices,
|
||||
services,
|
||||
namer,
|
||||
callService,
|
||||
callHA,
|
||||
deviceExtras: getDeviceExtraWsCalls(callHA),
|
||||
reloadAutomations: () =>
|
||||
conn.status === "loaded"
|
||||
? callService("automation", "reload")
|
||||
: Promise.resolve(),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,96 @@
|
||||
import React, { FC, useEffect, useState } from "react";
|
||||
import { ComponentMeta, ComponentStory } from "@storybook/react";
|
||||
import { MockPage } from "components/Page";
|
||||
import { useHA } from "services/haService";
|
||||
import InputYaml from "components/Inputs/Base/InputYaml";
|
||||
import { InputList } from "components/Inputs/InputList";
|
||||
import { Button } from "components/Inputs/Buttons/Button";
|
||||
import { ServiceEditor } from "components/ServiceEditor";
|
||||
|
||||
const Test: FC = () => {
|
||||
const { services, callService } = useHA();
|
||||
|
||||
const data = services.collection ?? {};
|
||||
const options = Object.keys(data).sort();
|
||||
|
||||
const [domain, setDomain] = useState(options[0] ?? "");
|
||||
|
||||
const domains = Object.keys(data[domain] ?? "").sort();
|
||||
|
||||
const [service, setService] = useState(domains[0] ?? "");
|
||||
const serviceDefn = (data[domain] ?? {})[service] ?? {};
|
||||
|
||||
const [serviceData, setServiceData] = useState({ field: {}, target: {} });
|
||||
|
||||
useEffect(() => {
|
||||
setService(domains[0] ?? "");
|
||||
setServiceData({ field: {}, target: {} });
|
||||
}, [domain, setService]);
|
||||
|
||||
let serviceEditElm = <>Failed to load</>;
|
||||
|
||||
try {
|
||||
if (service) {
|
||||
serviceEditElm = (
|
||||
<div
|
||||
style={{
|
||||
border: "1px solid var(--mui-grey-400)",
|
||||
maxWidth: "100vw",
|
||||
padding: "2.5em",
|
||||
margin: "2.5em",
|
||||
}}
|
||||
>
|
||||
<ServiceEditor
|
||||
service={serviceDefn}
|
||||
serviceId={`${domain}.${service}`}
|
||||
data={serviceData}
|
||||
onUpdate={setServiceData}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
serviceEditElm = <>{JSON.stringify(err)}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ overflow: "auto", maxHeight: "100vh" }}>
|
||||
<InputList
|
||||
label="Domains"
|
||||
current={domain}
|
||||
onChange={setDomain}
|
||||
options={options}
|
||||
/>
|
||||
<InputList
|
||||
label="Services"
|
||||
current={service}
|
||||
onChange={setService}
|
||||
options={domains}
|
||||
/>
|
||||
<Button
|
||||
onClick={() =>
|
||||
callService(domain, service, serviceData.field, serviceData.target)
|
||||
}
|
||||
>
|
||||
Call
|
||||
</Button>
|
||||
{serviceEditElm}
|
||||
<InputYaml label="Service Data" value={serviceDefn} onChange={() => {}} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default {
|
||||
title: "Services/HA Service",
|
||||
component: Test,
|
||||
parameters: { actions: { argTypesRegex: "^on.*" } },
|
||||
args: {},
|
||||
} as ComponentMeta<typeof Test>;
|
||||
|
||||
export const ServiceCall: ComponentStory<typeof Test> = (props) => {
|
||||
return (
|
||||
<MockPage>
|
||||
<Test {...props} />
|
||||
</MockPage>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
import { MessageBase } from "home-assistant-js-websocket";
|
||||
import { AutomationDeviceState } from "types/automations/common";
|
||||
|
||||
export type EntityRegisteryItem = {
|
||||
area_id: null | string;
|
||||
config_entry_id: null | string;
|
||||
device_id: null | string;
|
||||
disabled_by: "integration" | "user" | "config_entry" | string | null;
|
||||
entity_category: "diagnostic" | "config" | string | null;
|
||||
hidden_by: "integration" | "user" | string | null;
|
||||
entity_id: string;
|
||||
icon: null | string;
|
||||
name: null | string;
|
||||
platform: string;
|
||||
};
|
||||
|
||||
export type DeviceRegistryItem = {
|
||||
id: string;
|
||||
name: string;
|
||||
name_by_user: string | null;
|
||||
manufacturer: string | null;
|
||||
entry_type: "service" | string | null;
|
||||
disabled_by: EntityRegisteryItem["disabled_by"];
|
||||
area_id: string | null;
|
||||
};
|
||||
|
||||
export type HassDevices = Array<DeviceRegistryItem>;
|
||||
export type HassEntitiesRegistry = Array<EntityRegisteryItem>;
|
||||
export type HASendMessage = (sendMsg: MessageBase) => Promise<any>;
|
||||
|
||||
export type DeviceBaseType = AutomationDeviceState & {
|
||||
metadata: Record<string, any>;
|
||||
} & Record<string, any>;
|
||||
export type DeviceTypeAction = DeviceBaseType;
|
||||
export type DeviceTriggerType = DeviceBaseType & {
|
||||
platform: "device";
|
||||
};
|
||||
export type DeviceConditionType = DeviceBaseType & {
|
||||
condition: "device";
|
||||
};
|
||||
export type DeviceTypeCapability = {
|
||||
extra_fields: Array<HaFormSchema>;
|
||||
};
|
||||
|
||||
export type HaFormSchema =
|
||||
| HaFormConstantSchema
|
||||
| HaFormStringSchema
|
||||
| HaFormIntegerSchema
|
||||
| HaFormFloatSchema
|
||||
| HaFormBooleanSchema
|
||||
| HaFormSelectSchema
|
||||
| HaFormMultiSelectSchema
|
||||
| HaFormTimeSchema
|
||||
| HaFormGridSchema;
|
||||
|
||||
export interface HaFormBaseSchema {
|
||||
name: string;
|
||||
default?: any;
|
||||
required?: boolean;
|
||||
description?: {
|
||||
suffix?: string;
|
||||
suggested_value?: any;
|
||||
};
|
||||
}
|
||||
|
||||
export interface HaFormGridSchema extends HaFormBaseSchema {
|
||||
type: "grid";
|
||||
name: "";
|
||||
column_min_width?: string;
|
||||
schema: HaFormSchema[];
|
||||
}
|
||||
|
||||
export interface HaFormConstantSchema extends HaFormBaseSchema {
|
||||
type: "constant";
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export interface HaFormIntegerSchema extends HaFormBaseSchema {
|
||||
type: "integer";
|
||||
valueMin?: number;
|
||||
valueMax?: number;
|
||||
}
|
||||
|
||||
export interface HaFormSelectSchema extends HaFormBaseSchema {
|
||||
type: "select";
|
||||
options: Array<[string, string]>;
|
||||
}
|
||||
|
||||
export interface HaFormMultiSelectSchema extends HaFormBaseSchema {
|
||||
type: "multi_select";
|
||||
options: Record<string, string> | string[] | Array<[string, string]>;
|
||||
}
|
||||
|
||||
export interface HaFormFloatSchema extends HaFormBaseSchema {
|
||||
type: "float";
|
||||
}
|
||||
|
||||
export interface HaFormStringSchema extends HaFormBaseSchema {
|
||||
type: "string";
|
||||
format?: string;
|
||||
}
|
||||
|
||||
export interface HaFormBooleanSchema extends HaFormBaseSchema {
|
||||
type: "boolean";
|
||||
}
|
||||
|
||||
export interface HaFormTimeSchema extends HaFormBaseSchema {
|
||||
type: "positive_time_period_dict";
|
||||
}
|
||||
|
||||
export interface EntitySource {
|
||||
domain: string;
|
||||
custom_component: boolean;
|
||||
source: "config_entry" | "platform_config";
|
||||
config_entry?: string;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Collection, Connection } from "home-assistant-js-websocket";
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useDelayedFunction } from "utils/useDelay";
|
||||
import { useHAConnection } from "./connection";
|
||||
|
||||
type _HACollectionState<T> =
|
||||
| {
|
||||
ready: false;
|
||||
collection?: undefined;
|
||||
error?: string;
|
||||
}
|
||||
| {
|
||||
ready: true;
|
||||
collection: T;
|
||||
};
|
||||
export type HACollectionState<T, D = {}> = _HACollectionState<T> & {
|
||||
additional: Partial<D>;
|
||||
};
|
||||
export const useHassCollection = <T, D extends {} = {}>(
|
||||
getHACollection: (c: Connection) => Collection<T>,
|
||||
updateAdditionalProps?: (n: T | {}) => D
|
||||
): HACollectionState<T, D> => {
|
||||
const [state, _setState] = useState<_HACollectionState<T>>({
|
||||
ready: false,
|
||||
});
|
||||
const setState = useDelayedFunction(_setState, 500);
|
||||
const conn = useHAConnection();
|
||||
const collection = useMemo(() => {
|
||||
if (conn.status === "loaded") {
|
||||
return getHACollection(conn.connection);
|
||||
}
|
||||
}, [conn, getHACollection]);
|
||||
|
||||
useEffect(() => {
|
||||
if (collection) {
|
||||
if (collection.state) {
|
||||
setState({
|
||||
ready: true,
|
||||
collection: collection.state,
|
||||
});
|
||||
}
|
||||
const unsub = collection.subscribe((d) => {
|
||||
if (d) {
|
||||
setState({
|
||||
ready: true,
|
||||
collection: d,
|
||||
});
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
unsub();
|
||||
};
|
||||
}
|
||||
// eslint-disable-next-line
|
||||
}, [collection, state.ready]);
|
||||
|
||||
useEffect(() => {
|
||||
if (conn.status === "error") {
|
||||
if (!state.ready && conn.error !== state.error) {
|
||||
setState({
|
||||
ready: false,
|
||||
error: conn.error,
|
||||
});
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line
|
||||
}, [conn, state]);
|
||||
|
||||
if (state.ready) {
|
||||
if (!state.collection) {
|
||||
throw Error("What?");
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
get additional(): Partial<D> {
|
||||
if (state.ready && updateAdditionalProps) {
|
||||
return updateAdditionalProps(state.collection ?? {});
|
||||
}
|
||||
return {};
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
{
|
||||
"ADD": "Add",
|
||||
"AREA": "Area",
|
||||
"ALIAS": "Alias",
|
||||
"ATTRIBUTE": "Attribute",
|
||||
"ABOVE": "Above",
|
||||
"BELOW": "Below",
|
||||
"ID": "Id",
|
||||
"NAME": "Name",
|
||||
"TAG": "Tag",
|
||||
"TAGS": "Tags",
|
||||
"DEVICE": "Device",
|
||||
"ACTION": "Action",
|
||||
"TAG_NAME": "Tag Name",
|
||||
"TAG_VALUE": "Tag Value",
|
||||
"TITLE": "Title",
|
||||
"TYPE": "Type",
|
||||
"TRIGGER_ID": "Trigger ID",
|
||||
"TEMPLATE": "Template",
|
||||
"MODE": "Mode",
|
||||
"CLOSE": "Close",
|
||||
"DESCRIPTION": "Description",
|
||||
"TRIGGER": "Trigger",
|
||||
"CONDITION": "Condition",
|
||||
"DELETE": "Delete",
|
||||
"METADATA": "Metadata",
|
||||
"UNDO": "Undo",
|
||||
"RAW": "Raw",
|
||||
"SAVE": "Save",
|
||||
"STATE": "State",
|
||||
"SEARCH": "Search",
|
||||
"FLIPP": "Flip",
|
||||
"CANCEL": "Cancel",
|
||||
"CREATE": "Create",
|
||||
"OR": "Or",
|
||||
"ZONE": "Zone",
|
||||
"ENTITY": "Entity",
|
||||
"ENTITY_ID": "Entity ID",
|
||||
"ENABLED": "Enabled",
|
||||
"ENTITY_WITH_LOCATION": "Entity with Location",
|
||||
"TIME_ENTITY": "Time Entity",
|
||||
"AND_MORE": "and more",
|
||||
"YES": "Yes",
|
||||
"NO": "No",
|
||||
|
||||
"SERVICE": "Service",
|
||||
"REPEAT": "Repeat",
|
||||
"WAIT": "Wait",
|
||||
"WAIT_TYPE": "Wait Type",
|
||||
"STOP": "Stop",
|
||||
"STOP_REASON": "Stop Reason",
|
||||
"CHOOSE": "Choose",
|
||||
"PARALLEL": "Parallel",
|
||||
"SCENE": "Scene",
|
||||
|
||||
"TIME_UNITS_HOURS": "hours",
|
||||
"TIME_UNITS_MINUTES": "minutes",
|
||||
"TIME_UNITS_SECONDS": "seconds",
|
||||
"TIME_UNITS_MILISECONDS": "milliseconds",
|
||||
|
||||
"TIMEOUT": "Timeout",
|
||||
"CONTINUTE_ON_TIMEOUT": "Continue on Timeout",
|
||||
|
||||
"FOR": "For",
|
||||
"AND": "and",
|
||||
"NOT": "not",
|
||||
"NUMERIC_STATE": "Numeric State",
|
||||
"TIME": "Time",
|
||||
"EVENT": "Event",
|
||||
"EVENT_DATA": "Event Data",
|
||||
"HOMEASSISTANT": "Home Assistant",
|
||||
"CALENDAR": "Calendar",
|
||||
"WEBHOOK": "Webhook",
|
||||
"SUN": "Sun",
|
||||
"MQTT": "MQTT",
|
||||
|
||||
"CONNECTED": "Connected",
|
||||
"FAILED": "Failed",
|
||||
"LOADING": "Loading",
|
||||
|
||||
"DAY_MON": "Monday",
|
||||
"DAY_TUE": "Tuesday",
|
||||
"DAY_WED": "Wednesday",
|
||||
"DAY_THU": "Thursday",
|
||||
"DAY_FRI": "Friday",
|
||||
"DAY_SAT": "Saturday",
|
||||
"DAY_SUN": "Sunday",
|
||||
|
||||
"WEEKDAY": "Weekday",
|
||||
"OPTION": "Option",
|
||||
|
||||
"THEME": "Theme",
|
||||
"LANGUAGE": "Language",
|
||||
|
||||
"USER_PRERENCES": "Settings",
|
||||
|
||||
"SELECT_AUTOMATION": "Select automation",
|
||||
"TRIGGER_AUTOMATION": "Trigger automation",
|
||||
"DELETE_AUTOMATION": "Delete automation",
|
||||
|
||||
"CONFIRMATION_DELETE_THIS_AUTOMATION": "Are you sure you want to delete this automation?",
|
||||
"CONFIRMATION_DELETE_THIS_NODE": "Are you sure you want to delete this node?",
|
||||
|
||||
"DELETED": "Deleted.",
|
||||
"NOT_DELETED_NODE": "Did not delete node.",
|
||||
"NOT_DELETED_THING": "Did not delete {{item}}.",
|
||||
|
||||
"MISSING_TEXT": "MISSING TEXT -- {{langId}}",
|
||||
|
||||
"AUTOMATION_METADATA_TOOLTIP_TEXT": "This automation is located in the file {{source_file}}. It's currently '{{state}}', it's entity id is '{{entityId}}' and it's automation id is '{{id}}'",
|
||||
"AUTOMATION_METADATA_TOOLTIP_SIMPLE": "ID={{id}}, EntityID={{entityId}}",
|
||||
|
||||
"ERROR_FAILED_TO_SAVE": "Failed to save automation \"{{aid}}\" contents - {{contents}} -- not found in `/config`",
|
||||
"ERROR_INVALID_AUTOMATION_STATE": "Invalid state",
|
||||
"ERROR_INVALID_AUTOMATION_DETECTED": "Invalid Automations detected!",
|
||||
"ERROR_FAILED_CONNECTION_TO_HA": "Failed to connect to websocket, please check that your access token is properly setup.",
|
||||
"ERROR_FAILED_CALLING": "Failed to call {{entityId}} because '{{msg}}'",
|
||||
"ERROR_FAILED_CALLING_BC_CONNECTION": "Failed to call service because connection is '{{connStatus}}' -- {{connError}}",
|
||||
"ERROR_INVALID_YAML": "! Invalid Yaml !",
|
||||
|
||||
"AUTOMATION_STATE_IS": "Automation is {{state}}",
|
||||
|
||||
"ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK": "Failed to find an automation on disk with id = {{id}}",
|
||||
"ISSUES_INVALID_STATE": "Recived invalid state '{{state}}', this could be because you have a lingering automation that was not cleared by homeassistant, try to reboot HA or manually clear this automation from HA Database.",
|
||||
"ISSUES_FIND_AUTOMATION_IN_CONFIG": "failed to find this automation in '/config' folder",
|
||||
"ISSUES_NO_LOAD_AUTOMATION": "homeassistant did not load this automation, try to manually reload automations or restart homeassistant.",
|
||||
"ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT": "In order to modify an automation you have specify a unique id. Please go to the file '{{sourceFile}}' and add an `id` field to the automation.",
|
||||
|
||||
"AUTOMATION_STATE_UNREGISTERED": "unregistered",
|
||||
"AUTOMATION_STATE_ON": "On",
|
||||
"AUTOMATION_STATE_OFF": "Off",
|
||||
|
||||
"AUTOMATION_MANAGER_STATE_CHANGE": "changing automation state",
|
||||
"AUTOMATION_MANAGER_STATE_CHANGE_FAIL": "Failed to toggle automation due to \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_REFRESH": "refreshing automations",
|
||||
"AUTOMATION_MANAGER_REFRESH_FAIL": "Failed refreshing automations due to \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_DELETE": "deleting automation",
|
||||
"AUTOMATION_MANAGER_DELETE_FAIL": "Failed delete due to \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_TRIGGER": "triggering automation",
|
||||
"AUTOMATION_MANAGER_TRIGGER_FAIL": "Failed trigger due to \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_ADD": "adding automation",
|
||||
"AUTOMATION_MANAGER_ADD_FAIL": "Failed adding automation due to \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_UPDATE": "updating automation",
|
||||
"AUTOMATION_MANAGER_UPDATE_FAIL": "Failed updating automation due to \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_UPDATE_TAGS": "updating automation tags",
|
||||
"AUTOMATION_MANAGER_UPDATE_TAGS_FAIL": "Failed updating automation tags due to \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_DELETE_LIGHT": "Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant",
|
||||
|
||||
"NEW_AUTOMATION": "New Automation",
|
||||
"SWITCH_AUTOMATION": "Switch Automation",
|
||||
|
||||
"N/A": "n/a",
|
||||
|
||||
"VALIDATION_AUTOMATION_NAME": "Name must be at least 1 character long",
|
||||
"VALIDATION_MAX_TAG_SELECTION": "Can only select up to {{count}} tags",
|
||||
"VALIDATION_TAG_EXISTS": "The tag '{{name}}' already exists",
|
||||
"VALIDATION_PLEASE_CORRECT_FILE": "Please correct the automation file manually and then continue!",
|
||||
"VALIDATION_MISSING_VALUES_FOR_NODE": "This node is missing some values",
|
||||
"VALIDATION_ERROR_VALUES_IN_NODE": "This node contains errors",
|
||||
"VALIDATION_UNSAVED_WORK_IN_NODE": "This node is has some unsaved work",
|
||||
"VALIDATION_NOT_ALL_FIELD_FILLED_IN": "Some fields have not been properly filled up",
|
||||
|
||||
"CONFIRM_EXIT": "Are you sure you want to {{what}}?",
|
||||
|
||||
"MODE_SIGNLE_LABEL": "Do not start a new run. Issue a warning.",
|
||||
"MODE_SIGNLE_PARALLEL": "Start a new, independent run in parallel with previous runs.",
|
||||
"MODE_SIGNLE_QUEUED": "Start a new run after all previous runs complete. Runs are guaranteed to execute in the order they were queued.",
|
||||
"MODE_SIGNLE_RESTART": "Start a new run after first stopping previous run.",
|
||||
|
||||
"WARNING_SWITCHING_FROM_NONE_SAVE": "Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.",
|
||||
"WARNING_DEVICE_NO_TYPES": "This device has no {{type}}.",
|
||||
|
||||
"INFO_SUCCESS_CALL": "Successfully called {{entityId}}",
|
||||
|
||||
"HOW_MANY_TIMES": "How many times?",
|
||||
|
||||
"READONLY_MODE": "Read Only Mode",
|
||||
"READONLY_CANNOT_UPDATE": "Cannot update in readonly mode"
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
{
|
||||
"ADD": "Ajouter",
|
||||
"AREA": "Zone",
|
||||
"ALIAS": "Alias",
|
||||
"ATTRIBUTE": "Attribuer",
|
||||
"ABOVE": "Plus grand que",
|
||||
"BELOW": "Plus petit que",
|
||||
"ID": "Id",
|
||||
"NAME": "Nom",
|
||||
"TAG": "Étiquette",
|
||||
"TAGS": "Étiquettes",
|
||||
"DEVICE": "Dispositif",
|
||||
"ACTION": "Opération",
|
||||
"ACTIONS": "Opérations",
|
||||
"TAG_NAME": "Nom de l'étiquette",
|
||||
"TAG_VALUE": "Valeur de l'étiquette",
|
||||
"TYPE": "Taper",
|
||||
"TITLE": "Titre",
|
||||
"TRIGGER_ID": "ID déclencheur",
|
||||
"TEMPLATE": "Modèle",
|
||||
"MODE": "Mode",
|
||||
"CLOSE": "Fermer",
|
||||
"DESCRIPTION": "Description",
|
||||
"TRIGGER": "Déclencheur",
|
||||
"TRIGGERS": "Déclencheurs",
|
||||
"CONDITION": "Condition",
|
||||
"CONDITIONS": "Les conditions",
|
||||
"DELETE": "Supprimer",
|
||||
"METADATA": "Métadonnées",
|
||||
"UNDO": "Annuler",
|
||||
"RAW": "Brut",
|
||||
"SAVE": "Enregistrer",
|
||||
"STATE": "Statut",
|
||||
"SEARCH": "Chercher",
|
||||
"FLIPP": "Retourner",
|
||||
"CANCEL": "Annuler",
|
||||
"CREATE": "Créer",
|
||||
"OR": "Ou",
|
||||
"ZONE": "Zone",
|
||||
"ENTITY": "Entité",
|
||||
"ENTITY_ID": "ID d'entité",
|
||||
"ENABLED": "Activé",
|
||||
"ENTITY_WITH_LOCATION": "Entité avec emplacement",
|
||||
"TIME_ENTITY": "Entité temporelle",
|
||||
"AND_MORE": "et plus",
|
||||
"YES": "Oui",
|
||||
"NO": "Non",
|
||||
|
||||
"SERVICE": "Service",
|
||||
"REPEAT": "Répéter",
|
||||
"WAIT": "Attendre",
|
||||
"WAIT_TYPE": "Type d'attente",
|
||||
"STOP": "Arrêt",
|
||||
"STOP_REASON": "Raison d'arrêt",
|
||||
"CHOOSE": "Choisir",
|
||||
"PARALLEL": "Parallèle",
|
||||
"SCENE": "Scène",
|
||||
"EVENT": "Événement",
|
||||
"EVENT_DATA": "Données d'événement",
|
||||
"HOMEASSISTANT": "Home Assistant",
|
||||
"CALENDAR": "Calendrier",
|
||||
"WEBHOOK": "Webhook",
|
||||
"SUN": "Soleil",
|
||||
"MQTT": "MQTT",
|
||||
|
||||
"TIME_UNITS_HOURS": "heures",
|
||||
"TIME_UNITS_MINUTES": "minutes",
|
||||
"TIME_UNITS_SECONDS": "secondes",
|
||||
"TIME_UNITS_MILISECONDS": "millisecondes",
|
||||
|
||||
"TIMEOUT": "Temps libre",
|
||||
"CONTINUTE_ON_TIMEOUT": "Continuer sur Timeout",
|
||||
|
||||
"CONNECTED": "Connecté",
|
||||
"FAILED": "Échoué",
|
||||
"LOADING": "Chargement",
|
||||
|
||||
"FOR": "Pour",
|
||||
"AND": "et",
|
||||
"NOT": "non",
|
||||
"NUMERIC_STATE": "État numérique",
|
||||
"TIME": "Temps",
|
||||
|
||||
"DAY_MON": "Lundi",
|
||||
"DAY_TUE": "Mardi",
|
||||
"DAY_WED": "Mercredi",
|
||||
"DAY_THU": "Jeudi",
|
||||
"DAY_FRI": "Vendredi",
|
||||
"DAY_SAT": "Samedi",
|
||||
"DAY_SUN": "Dimanche",
|
||||
|
||||
"WEEKDAY": "Jour de la semaine",
|
||||
"OPTION": "Option",
|
||||
|
||||
"THEME": "Thème",
|
||||
"LANGUAGE": "Langue",
|
||||
|
||||
"USER_PRERENCES": "Préférences de l'utilisateur",
|
||||
|
||||
"SELECT_AUTOMATION": "Sélectionnez l'automatisation",
|
||||
"TRIGGER_AUTOMATION": "Déclencher l'automatisation",
|
||||
"DELETE_AUTOMATION": "Supprimer l'automatisation",
|
||||
|
||||
"CONFIRMATION_DELETE_THIS_AUTOMATION": "Voulez-vous vraiment supprimer cette automatisation ?",
|
||||
"CONFIRMATION_DELETE_THIS_NODE": "Voulez-vous vraiment supprimer ce nœud ?",
|
||||
|
||||
"DELETED": "Supprimé.",
|
||||
"NOT_DELETED_NODE": "N'a pas supprimé le nœud.",
|
||||
"NOT_DELETED_THING": "{{item}} n'a pas été supprimé.",
|
||||
|
||||
"MISSING_TEXT": "TEXTE MANQUANT --{{langId}}",
|
||||
|
||||
"AUTOMATION_METADATA_TOOLTIP_TEXT": "Cette automatisation se trouve dans le fichier {{source_file}}. Elle est actuellement '{{state}}', son identifiant d'entité est '{{entityId}}' et son identifiant d'automatisation est '{{id}}'",
|
||||
|
||||
"ERROR_FAILED_TO_SAVE": "Échec de l'enregistrement du contenu de l'automatisation \"{{aid}}\" - {{contents}} -- introuvable dans `/config`",
|
||||
"ERROR_INVALID_AUTOMATION_STATE": "Etat non valide",
|
||||
"ERROR_INVALID_AUTOMATION_DETECTED": "Automatisations invalides détectées !",
|
||||
"ERROR_FAILED_CONNECTION_TO_HA": "Échec de la connexion au websocket, veuillez vérifier que votre jeton d'accès est correctement configuré.",
|
||||
"ERROR_FAILED_CALLING": "Échec de l'appel de {{entityId}} car '{{msg}}'",
|
||||
"ERROR_FAILED_CALLING_BC_CONNECTION": "Impossible d'appeler le service car la connexion est '{{connStatus}}' -- {{connError}}",
|
||||
"ERROR_INVALID_YAML": "! Yaml invalide !",
|
||||
|
||||
"AUTOMATION_STATE_IS": "L'automatisation est {{state}}",
|
||||
|
||||
"ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK": "Impossible de trouver une automatisation sur le disque avec id = {{id}}",
|
||||
"ISSUES_INVALID_STATE": "État invalide reçu '{{state}}', cela peut être dû au fait que vous avez une automatisation persistante qui n'a pas été effacée par Home Assistant, essayez de redémarrer Home Assistant ou effacez manuellement cette automatisation de la base de données HA.",
|
||||
"ISSUES_FIND_AUTOMATION_IN_CONFIG": "impossible de trouver cette automatisation dans le dossier '/config'",
|
||||
"ISSUES_NO_LOAD_AUTOMATION": "homeassistant n'a pas chargé cette automatisation, essayez de recharger manuellement les automatisations ou redémarrez Home Assistant.",
|
||||
"ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT": "Pour modifier une automatisation, vous devez spécifier un identifiant unique. Veuillez aller dans le fichier '{{sourceFile}}' et ajouter un champ `id` à l'automatisation.",
|
||||
|
||||
"AUTOMATION_STATE_UNREGISTERED": "non enregistré",
|
||||
"AUTOMATION_STATE_ON": "Activé",
|
||||
"AUTOMATION_STATE_OFF": "Désactivé",
|
||||
|
||||
"AUTOMATION_MANAGER_STATE_CHANGE": "modification de l'état de l'automatisation",
|
||||
"AUTOMATION_MANAGER_STATE_CHANGE_FAIL": "Impossible de basculer l'automatisation en raison de \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_REFRESH": "Actualisation des automatisations",
|
||||
"AUTOMATION_MANAGER_REFRESH_FAIL": "Échec de l'actualisation des automatisations en raison de \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_DELETE": "suppression des automatisation",
|
||||
"AUTOMATION_MANAGER_DELETE_FAIL": "Échec de la suppression en raison de \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_TRIGGER": "déclenchement de l'automatisation",
|
||||
"AUTOMATION_MANAGER_TRIGGER_FAIL": "Échec du déclencheur dû à \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_ADD": "ajouter des automatisations",
|
||||
"AUTOMATION_MANAGER_ADD_FAIL": "Échec de l'ajout de l'automatisation en raison de \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_UPDATE": "mise à jour de l'automatisation",
|
||||
"AUTOMATION_MANAGER_UPDATE_FAIL": "Échec de la mise à jour de l'automatisation en raison de \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_UPDATE_TAGS": "mise à jour des balises d'automatisation",
|
||||
"AUTOMATION_MANAGER_UPDATE_TAGS_FAIL": "Échec de la mise à jour des balises d'automatisation en raison de \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_DELETE_LIGHT": "Échec de la suppression de l'automatisation, cela peut être résolu par une actualisation ou un redémarrage de Home Assistant",
|
||||
|
||||
"NEW_AUTOMATION": "Nouvelle automatisation",
|
||||
"SWITCH_AUTOMATION": "Automatisation des commutateurs",
|
||||
|
||||
"N/A": "n/a",
|
||||
|
||||
"VALIDATION_AUTOMATION_NAME": "Le nom doit comporter au moins 1 caractère",
|
||||
"VALIDATION_MAX_TAG_SELECTION": "Ne peut sélectionner que {{count}} étiquettes maximum",
|
||||
"VALIDATION_TAG_EXISTS": "L'étiquette \"{{name}}\" existe déjà",
|
||||
"VALIDATION_PLEASE_CORRECT_FILE": "Veuillez corriger le fichier d'automatisation manuellement, puis continuer !",
|
||||
"VALIDATION_MISSING_VALUES_FOR_NODE": "Il manque certaines valeurs à ce nœud",
|
||||
"VALIDATION_ERROR_VALUES_IN_NODE": "Ce nœud contient des erreurs",
|
||||
"VALIDATION_UNSAVED_WORK_IN_NODE": "Ce nœud contient du travail non enregistré",
|
||||
"VALIDATION_NOT_ALL_FIELD_FILLED_IN": "Certains champs n'ont pas été correctement remplis",
|
||||
|
||||
"CONFIRM_EXIT": "Êtes-vous sûr de vouloir {{what}}?",
|
||||
|
||||
"MODE_SIGNLE_LABEL": "Ne pas démarrer une nouvelle exécution. Émettre un avertissement.",
|
||||
"MODE_SIGNLE_PARALLEL": "Démarrer une nouvelle exécution indépendante en parallèle avec les exécutions précédentes.",
|
||||
"MODE_SIGNLE_QUEUED": "Démarrer une nouvelle exécution une fois toutes les exécutions précédentes terminées. Les exécutions sont garanties de s'exécuter dans l'ordre dans lequel elles ont été mises en file d'attente.",
|
||||
"MODE_SIGNLE_RESTART": "Démarrer une nouvelle exécution après avoir arrêté l'exécution précédente.",
|
||||
|
||||
"WARNING_SWITCHING_FROM_NONE_SAVE": "La sélection d'une autre automatisation vous fera perdre tout le travail effectué sur cette nouvelle automatisation. Veuillez d'abord enregistrer votre travail sur cette automatisation.",
|
||||
"WARNING_DEVICE_NO_TYPES": "Cet appareil n'a pas de {{type}}.",
|
||||
|
||||
"INFO_SUCCESS_CALL": "{{entityId}} a été appelé avec succès",
|
||||
|
||||
"HOW_MANY_TIMES": "Données d'événementaCombien de fois?",
|
||||
|
||||
"READONLY_MODE": "Mode lecture seule",
|
||||
"READONLY_CANNOT_UPDATE": "Impossible de mettre à jour en mode lecture seule"
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useApiState } from "services/apiService";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
const MISSING_TEXT = "<<MISSING TEXT -- {{langId}}>>";
|
||||
const LOADING_TEXT = "...";
|
||||
|
||||
export type LangStore = ReturnType<typeof useLang>;
|
||||
export const useLang = () => {
|
||||
const apiState = useApiState();
|
||||
const [langStore, setLangStore] =
|
||||
useState<Record<string, string> | null>(null);
|
||||
const [langEngStore, setLangEngStore] =
|
||||
useState<Record<string, string> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
import("./eng.json").then((data) => {
|
||||
setLangEngStore(data.default);
|
||||
});
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (apiState.userProfile.ready && apiState.userProfile.ok) {
|
||||
import(`./${apiState.userProfile.data.lang}.json`).then((data) => {
|
||||
setLangStore(data.default);
|
||||
});
|
||||
}
|
||||
}, [apiState.userProfile]);
|
||||
|
||||
const updateParams = (
|
||||
textTemplate: string,
|
||||
replacements: Record<string, string> = {}
|
||||
) => {
|
||||
let text = textTemplate;
|
||||
Object.keys(replacements).forEach((k) => {
|
||||
const v = replacements[k];
|
||||
text = text.replace(`{{${k}}}`, v);
|
||||
});
|
||||
return text;
|
||||
};
|
||||
|
||||
return {
|
||||
get: (langId: string, replacements: Record<string, string> = {}) => {
|
||||
let out = LOADING_TEXT;
|
||||
if (langStore !== null) {
|
||||
out =
|
||||
langStore[langId.toLocaleUpperCase()] ??
|
||||
`<<${langStore.MISSING_TEXT}>>` ??
|
||||
MISSING_TEXT;
|
||||
} else if (langEngStore !== null) {
|
||||
out =
|
||||
langEngStore[langId.toLocaleUpperCase()] ??
|
||||
`<<${langEngStore.MISSING_TEXT}>>` ??
|
||||
MISSING_TEXT;
|
||||
}
|
||||
return updateParams(out, { ...replacements, langId });
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
{
|
||||
"ADD": "Aggiungi",
|
||||
"AREA": "La zona",
|
||||
"ALIAS": "Alias",
|
||||
"ATTRIBUTE": "Attributo",
|
||||
"ABOVE": "Above",
|
||||
"BELOW": "Below",
|
||||
"ID": "Id",
|
||||
"NAME": "Nome",
|
||||
"TAG": "Tag",
|
||||
"TAGS": "Tags",
|
||||
"DEVICE": "Dispositivo",
|
||||
"ACTION": "Azione",
|
||||
"TAG_NAME": "Nome Tag",
|
||||
"TAG_VALUE": "Valore Tag",
|
||||
"TITLE": "Titolo",
|
||||
"TYPE": "Tipo",
|
||||
"TRIGGER_ID": "ID Attivazione",
|
||||
"TEMPLATE": "Modello",
|
||||
"MODE": "Modalità",
|
||||
"CLOSE": "Chiudi",
|
||||
"DESCRIPTION": "Descrizione",
|
||||
"TRIGGER": "Attivazione",
|
||||
"CONDITION": "Condizione",
|
||||
"DELETE": "Elimina",
|
||||
"METADATA": "Metadata",
|
||||
"UNDO": "Annulla",
|
||||
"RAW": "Raw",
|
||||
"SAVE": "Salva",
|
||||
"STATE": "Stato",
|
||||
"SEARCH": "Cerca",
|
||||
"FLIPP": "Flip",
|
||||
"CANCEL": "Cancella",
|
||||
"CREATE": "Crea",
|
||||
"OR": "Oppure",
|
||||
"ZONE": "Zona",
|
||||
"ENTITY": "Entità",
|
||||
"ENTITY_ID": "ID entità",
|
||||
"ENABLED": "A",
|
||||
"ENTITY_WITH_LOCATION": "Entità con posizione",
|
||||
"TIME_ENTITY": "Entità Tempo",
|
||||
"AND_MORE": "e altro",
|
||||
"YES": "Sì",
|
||||
"NO": "No",
|
||||
|
||||
"SERVICE": "Chiama Servizio",
|
||||
"REPEAT": "Ripeti",
|
||||
"WAIT": "Attesa",
|
||||
"WAIT_TYPE": "Tipo di attesa",
|
||||
"STOP": "Ferma",
|
||||
"STOP_REASON": "Ferma la ragione",
|
||||
"CHOOSE": "Scegli",
|
||||
"PARALLEL": "Eseguire in parallelo",
|
||||
"SCENE": "Scena",
|
||||
|
||||
"TIME_UNITS_HOURS": "ore",
|
||||
"TIME_UNITS_MINUTES": "minuti",
|
||||
"TIME_UNITS_SECONDS": "secondi",
|
||||
"TIME_UNITS_MILISECONDS": "millisecondi",
|
||||
|
||||
"TIMEOUT": "Tempo scaduto",
|
||||
"CONTINUTE_ON_TIMEOUT": "Continua su Timeout",
|
||||
|
||||
"FOR": "Per",
|
||||
"AND": "e",
|
||||
"NOT": "non",
|
||||
"NUMERIC_STATE": "Valore Numerico",
|
||||
"TIME": "Ora",
|
||||
"EVENT": "Evento",
|
||||
"EVENT_DATA": "Dati dell'evento",
|
||||
"HOMEASSISTANT": "Home Assistant",
|
||||
"CALENDAR": "Calendario",
|
||||
"WEBHOOK": "Webhook",
|
||||
"SUN": "Sole",
|
||||
"MQTT": "MQTT",
|
||||
|
||||
"CONNECTED": "Connesso",
|
||||
"FAILED": "Fallito",
|
||||
"LOADING": "Caricamento",
|
||||
|
||||
"DAY_MON": "Lunedì",
|
||||
"DAY_TUE": "Martedì",
|
||||
"DAY_WED": "Mercoledì",
|
||||
"DAY_THU": "Giovedì",
|
||||
"DAY_FRI": "Venerdì",
|
||||
"DAY_SAT": "Sabato",
|
||||
"DAY_SUN": "Domenica",
|
||||
|
||||
"WEEKDAY": "Giorno della settimana",
|
||||
"OPTION": "Opzione",
|
||||
|
||||
"THEME": "Tema",
|
||||
"LANGUAGE": "Lingua",
|
||||
|
||||
"USER_PRERENCES": "Impostazioni",
|
||||
|
||||
"SELECT_AUTOMATION": "Seleziona automazione",
|
||||
"TRIGGER_AUTOMATION": "Innesca Automazione",
|
||||
"DELETE_AUTOMATION": "Elimina automazione",
|
||||
|
||||
"CONFIRMATION_DELETE_THIS_AUTOMATION": "Sei sicuro di voler eliminare questa automazione?",
|
||||
"CONFIRMATION_DELETE_THIS_NODE": "Sei sicuro di voler eliminare questo nodo?",
|
||||
|
||||
"DELETED": "Eliminato.",
|
||||
"NOT_DELETED_NODE": "Il nodo non è stato eliminato.",
|
||||
"NOT_DELETED_THING": "{{item}} non è stato eliminato.",
|
||||
|
||||
"MISSING_TEXT": "TESTO MANCANTE -- {{langId}}",
|
||||
|
||||
"AUTOMATION_METADATA_TOOLTIP_TEXT": "Questa automazione si trova nel file {{source_file}}. It's currently '{{state}}', it's entity id is '{{entityId}}' and it's automation id is '{{id}}'",
|
||||
"AUTOMATION_METADATA_TOOLTIP_SIMPLE": "ID={{id}}, ID Entità={{entityId}}",
|
||||
|
||||
"ERROR_FAILED_TO_SAVE": "Salvataggio dell'automazione fallito \"{{aid}}\" contents - {{contents}} -- non trovato in `/config`",
|
||||
"ERROR_INVALID_AUTOMATION_STATE": "Stato Non Valido",
|
||||
"ERROR_INVALID_AUTOMATION_DETECTED": "Rilevate Automazioni Non Valide!",
|
||||
"ERROR_FAILED_CONNECTION_TO_HA": "Connessione al websocket fallita, perfavore controlla che il tuo token di accesso sia impostato correttamente.",
|
||||
"ERROR_FAILED_CALLING": "Chiamata di {{entityId}} fallita perchè '{{msg}}'",
|
||||
"ERROR_FAILED_CALLING_BC_CONNECTION": "Chiamata al servizio fallita perchè la connessione è '{{connStatus}}' -- {{connError}}",
|
||||
"ERROR_INVALID_YAML": "! Yaml non valido !",
|
||||
|
||||
"AUTOMATION_STATE_IS": "L'automazione è {{state}}",
|
||||
|
||||
"ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK": "Rcierca sul disco dell'automazione con id = {{id}} fallita ",
|
||||
"ISSUES_INVALID_STATE": "Ricevuto uno stato non valido '{{state}}', questo potrebbe essere causato da una automazione persistente che non è stata cancellata da homeassistant, prova a riavviare HA o ad eliminare manualmente questa automazione dal database di HA.",
|
||||
"ISSUES_FIND_AUTOMATION_IN_CONFIG": "ricerca dell'automazione fallita nella cartella '/config' ",
|
||||
"ISSUES_NO_LOAD_AUTOMATION": "homeassistant non ha caricato questa automazione, prova a ricaricare manualmente le automazioni o riavvia homeassistant.",
|
||||
"ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT": "Per modificare un'automazione è necessario specificare un ID univoco. Vai al file '{{sourceFile}}' e aggiungi un campo `id` all'automazione.",
|
||||
|
||||
"AUTOMATION_STATE_UNREGISTERED": "Non registrata",
|
||||
"AUTOMATION_STATE_ON": "On",
|
||||
"AUTOMATION_STATE_OFF": "Off",
|
||||
|
||||
"AUTOMATION_MANAGER_STATE_CHANGE": "cambiando lo stato dell'automazione",
|
||||
"AUTOMATION_MANAGER_STATE_CHANGE_FAIL": "Failed to toggle automation due to \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_REFRESH": "aggiornamento automazioni",
|
||||
"AUTOMATION_MANAGER_REFRESH_FAIL": "Aggiornamento delle automazioni fallito a causa di \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_DELETE": "eliminando l'automazione",
|
||||
"AUTOMATION_MANAGER_DELETE_FAIL": "Eliminazione fallita a causa di \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_TRIGGER": "attivando l'automazione",
|
||||
"AUTOMATION_MANAGER_TRIGGER_FAIL": "Attivazione fallita a causa di \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_ADD": "aggiungendo l'automazione",
|
||||
"AUTOMATION_MANAGER_ADD_FAIL": "Aggiunta delle automazioni fallito a causa di \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_UPDATE": "aggironando l'automazione",
|
||||
"AUTOMATION_MANAGER_UPDATE_FAIL": "Aggiornamento delle automazioni fallito a causa di \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_UPDATE_TAGS": "Aggiornando i tag delle automazioni",
|
||||
"AUTOMATION_MANAGER_UPDATE_TAGS_FAIL": "Aggiornamento dei tag delle automazioni fallito a causa di \"{{err}}\"",
|
||||
"AUTOMATION_MANAGER_DELETE_LIGHT": "Eliminazione dell'automazione fallita, potresti risolvere aggiornando o riavviando Home Assistant",
|
||||
|
||||
"NEW_AUTOMATION": "Nuova Automazione",
|
||||
"SWITCH_AUTOMATION": "Cambia Automazione",
|
||||
|
||||
"N/A": "n/d",
|
||||
|
||||
"VALIDATION_AUTOMATION_NAME": "Il nome deve essere lungo almeno un 1 carattere",
|
||||
"VALIDATION_MAX_TAG_SELECTION": "Puoi selezionare massimo {{count}} tag",
|
||||
"VALIDATION_TAG_EXISTS": "Il tag '{{name}}' esiste già",
|
||||
"VALIDATION_PLEASE_CORRECT_FILE": "Perfavore correggi il file dell'automazione manualmente e poi continua !",
|
||||
"VALIDATION_MISSING_VALUES_FOR_NODE": "Questo nodo contiene dei valori mancanti",
|
||||
"VALIDATION_ERROR_VALUES_IN_NODE": "Questo nodo contiene errori",
|
||||
"VALIDATION_UNSAVED_WORK_IN_NODE": "Questo nodo ha delle modifiche non salvate",
|
||||
"VALIDATION_NOT_ALL_FIELD_FILLED_IN": "Alcuni campi non sono stati compilati correttamente",
|
||||
|
||||
"CONFIRM_EXIT": "Sei sicuro di voler {{what}}?",
|
||||
|
||||
"MODE_SIGNLE_LABEL": "Non avviare una nuova esecuzione. Fornisci un avvertimento.",
|
||||
"MODE_SIGNLE_PARALLEL": "Avvia una nuova e indipendente esecuzione in parallelo con le esecuzioni precedenti.",
|
||||
"MODE_SIGNLE_QUEUED": "Avvia una nuova esecuzione dopo che tutte le altre sono state completate. Le esecuzioni partiranno nell'ordine in cui sono state accodate.",
|
||||
"MODE_SIGNLE_RESTART": "Avvia una nuova esecuzione dopo aver fermato quella precedente.",
|
||||
|
||||
"WARNING_SWITCHING_FROM_NONE_SAVE": "Selezionando un'altra automazione perderai tutte le modifiche effettuate a questa nuova automazione. Salva prima le modifiche.",
|
||||
"WARNING_DEVICE_NO_TYPES": "Questo dispositivo non ha {{type}}.",
|
||||
|
||||
"INFO_SUCCESS_CALL": "{{entityId}} chiamata con successo",
|
||||
|
||||
"HOW_MANY_TIMES": "Dati eventoaQuante volte?",
|
||||
|
||||
"READONLY_MODE": "Modalità di sola lettura",
|
||||
"READONLY_CANNOT_UPDATE": "Impossibile aggiornare in modalità di sola lettura"
|
||||
}
|
||||
Reference in new issue
Block a user