added some initial work on intl

This commit is contained in:
ari committed 2022-08-29 12:51:24 -04:00
1 parent 157efa04b1
commit caad458b48
22 files changed
+588 -155

No files matched your search

@@ -1,4 +1,5 @@
import { HassEntities } from "home-assistant-js-websocket";
import { LangStore, useLang } from "lang";
import { useEffect, useState } from "react";
import { AutomationData, BareAutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults";
@@ -10,7 +11,8 @@ export const useAutomationDB = (
configAutomations: AutomationData[],
tagsDB: TagDB
) => {
const autoMap = genMapping(haEntities, configAutomations, tagsDB);
const langStore = useLang();
const autoMap = genMapping(haEntities, configAutomations, tagsDB, langStore);
const [newAuto, setNewAuto] =
useState<
null | [AutomationManagerAuto, AutomationData | BareAutomationData]
@@ -54,13 +56,13 @@ export const useAutomationDB = (
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: "unregistered",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: {},
issue: "New Automation",
issue: langStore.get("NEW_AUTOMATION"),
isNew: true,
source_file: "n/a",
source_file_type: "n/a",
configuration_key: ["n/a"],
source_file: langStore.get("N/A"),
source_file_type: langStore.get("N/A"),
configuration_key: [],
},
auto,
]);
@@ -72,7 +74,8 @@ export const useAutomationDB = (
const genMapping = (
haEntities: HassEntities,
configAutomations: AutomationData[],
tagsDB: TagDB
tagsDB: TagDB,
langStore: LangStore
) => {
const configData: Record<string, AutomationData> = configAutomations.reduce(
(all, n) => ({
@@ -93,7 +96,9 @@ const genMapping = (
let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state)
? undefined
: `recived invalid state "${entityData.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."`;
: langStore.get("ISSUES_INVALID_STATE", {
state: entityData.state,
});
let found: AutomationData | null = null;
let source_file = "n/a";
let source_file_type = "n/a";
@@ -107,7 +112,7 @@ const genMapping = (
configuration_key = found.configuration_key ?? configuration_key;
delete configData[autoId];
} else {
issue = "failed to find this automation in '/config' folder";
issue = langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG");
}
automatioinMap[autoId] = [
@@ -134,13 +139,12 @@ const genMapping = (
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: "unregistered",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: tagsDB.getTags(auto.id),
source_file: auto.source_file,
source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key,
issue:
"homeassistant did not load this automation, try to manually reload automations or restart homeassistant.",
issue: langStore.get("ISSUES_NO_LOAD_AUTOMATION"),
},
auto,
];
@@ -10,6 +10,7 @@ import {
} from "./state";
import Alert from "@mui/material/Alert";
import { useConfirm } from "material-ui-confirm";
import { useLang } from "lang";
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
onAutomationDelete: (aid: string, eid: string) => void;
@@ -17,13 +18,14 @@ export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
export const AutomationManagerLoaded: FC<
PropsWithChildren<AutomationManagerLoadedProps>
> = ({ children, ...args }) => {
const langStore = useLang();
const state = useAutomationManagerState(args);
const confirm = useConfirm();
const onAutomationDelete = async (aid: string, eid: string) =>
confirm({
title: "Are you sure you want to delete this automation?",
confirmationText: "Delete",
title: langStore.get("CONFIRMATION_DELETE_THIS_AUTOMATION"),
confirmationText: langStore.get("DELETE"),
})
.then(() => {
args.onAutomationDelete(aid, eid);
@@ -76,8 +78,9 @@ export const AutomationManagerLoaded: FC<
) : (
<div>
<Alert color="warning">
Failed to find an automation on disk with id{" "}
{state.currentAutomationId}.
{langStore.get("ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK", {
id: state.currentAutomationId,
})}
</Alert>
</div>
)
@@ -7,6 +7,7 @@ import { useAutomationDB } from "./automationDB";
import { useConfirm } from "material-ui-confirm";
import { AutomationManagerAutoUpdatable } from "../types";
import { useSnackbar } from "notistack";
import { useLang } from "lang";
export type UseAutomationManagerStateArgs = {
configAutomations: AutomationData[];
@@ -26,6 +27,7 @@ export const useAutomationManagerState = ({
onAutomationStateChange,
}: UseAutomationManagerStateArgs) => {
// state
const langStore = useLang();
const confirm = useConfirm();
const snackbr = useSnackbar();
const cookies = useAMSCookies();
@@ -44,10 +46,9 @@ export const useAutomationManagerState = ({
const stillHaveNewAreYouSure = async () => {
try {
await confirm({
content:
"Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.",
confirmationText: "Switch Automation",
cancellationText: "Cancel",
content: langStore.get("WARNING_SWITCHING_FROM_NONE_SAVE"),
confirmationText: langStore.get("SWITCH_AUTOMATION"),
cancellationText: langStore.get("CANCEL"),
});
return true;
} catch (_) {
@@ -128,9 +129,10 @@ export const useAutomationManagerState = ({
}
} else {
snackbr.enqueueSnackbar(
`Failed to save automation "${aid}" contents - ${JSON.stringify(
a
)} -- not found in /config`,
langStore.get("ERROR_FAILED_TO_SAVE", {
aid,
contents: JSON.stringify(a),
}),
{ variant: "error" }
);
}
@@ -12,6 +12,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "../TagDB";
import { useLang } from "lang";
export type TagsProps = {
automationId: string;
@@ -29,6 +30,7 @@ export type TagModalState =
};
export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
const langStore = useLang();
const [modalState, setModal] = useState<TagModalState>({ open: false });
const tags = tagsDB.getTags(automationId, true);
const onUpdate = (t: Record<string, string>) =>
@@ -44,7 +46,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText
className="name"
options={tagsDB.getTagNames(Object.keys(tags))}
label="Tag Name"
label={langStore.get("TAG_NAME")}
value={modalState.tag[0]}
onChange={(v) =>
setModal({
@@ -56,7 +58,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText
className="value"
options={tagsDB.getTagValues(modalState.tag[0])}
label="Tag Value"
label={langStore.get("TAG_VALUE")}
value={modalState.tag[1]}
onChange={(v) =>
setModal({
@@ -67,7 +69,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
/>
<div className="buttons">
<Button onClick={() => setModal({ open: false })} color="info">
Close
{langStore.get("CLOSE")}
</Button>
<Button
disabled={!validTag}
@@ -80,7 +82,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
}}
color="success"
>
{modalState.isNew ? "Create" : "Save"}
{modalState.isNew ? langStore.get("CREATE") : langStore.get("SAVE")}
</Button>
</div>
</div>
@@ -15,6 +15,7 @@ import { AutomationManagerAuto } from "../types";
import { Tags } from "./Tags";
import { TagDB } from "../TagDB";
import { Chip, Tooltip } from "@mui/material";
import { useLang } from "lang";
export type MetadataBoxProps = AutomationManagerAuto & {
onDelete: () => void;
@@ -28,6 +29,10 @@ export type MetadataBoxProps = AutomationManagerAuto & {
};
export const MetadataBox: FC<MetadataBoxProps> = (props) => {
const isValidState = ["on", "off"].includes(props.state);
const langStore = useLang();
const prettyState = ["on", "off"].includes(props.state)
? langStore.get(`AUTOMATION_STATE_${props.state}`)
: props.state;
return (
<div
className={[
@@ -38,7 +43,13 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
>
<div
className="metadatabox--switch"
title={!isValidState ? "Invalid state" : `Automation is ${props.state}`}
title={
!isValidState
? langStore.get("ERROR_INVALID_AUTOMATION_STATE")
: langStore.get("AUTOMATION_STATE_IS", {
state: prettyState,
})
}
>
<Switch
checked={props.state !== "off"}
@@ -53,11 +64,16 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
<div className="metadatabox--title">
<span className="metadatabox--title--source">
<Tooltip
title={`This automation is located in the file ${props.source_file}. It's currently '${props.state}', it's entity id is '${props.entityId}' and it's automation id is '${props.id}'`}
title={langStore.get("AUTOMATION_METADATA_TOOLTIP_TEXT", {
source_file: props.source_file,
state: prettyState,
entityId: props.entityId,
id: props.id,
})}
>
<Chip
label={`@${props.source_file} (${props.source_file_type}) - ${
props.entityId ?? "n/a"
props.entityId ?? langStore.get("N/A")
}`}
className="text-ellipsis"
/>
@@ -66,7 +82,7 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
<Tooltip title={`ID=${props.id}, EntityID=${props.entityId}`}>
<InputTextView
className="title"
placeholder="Title"
placeholder={langStore.get("TITLE")}
value={props.title}
onChange={props.onTitleUpdate}
disabled={props.isNew}
@@ -74,7 +90,7 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
</Tooltip>
<InputTextView
className="description"
placeholder="Description"
placeholder={langStore.get("DESCRIPTION")}
value={props.description}
onChange={props.onDescriptionUpdate}
disabled={props.isNew}
@@ -93,19 +109,19 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
className="select"
icon={<SelectIcon />}
onClick={props.onSelect}
title="Select automation"
title={langStore.get("SELECT_AUTOMATION")}
/>
<ButtonIcon
className="run"
icon={<RunIcon />}
onClick={props.onRun}
title="Trigger automation"
title={langStore.get("TRIGGER_AUTOMATION")}
/>
<ButtonIcon
className="delete"
icon={<DeleteForeverIcon />}
onClick={props.onDelete}
title="Delete automation"
title={langStore.get("DELETE_AUTOMATION")}
/>
</div>
</div>
@@ -18,6 +18,7 @@ import {
} from "../types";
import { Button } from "components/Inputs/Buttons/Button";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
export type AutomationManagerSidebarProps = {
tagsDB: TagDB;
@@ -41,6 +42,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
onSelectedAutomationId,
...events
}) => {
const langStore = useLang();
const [searchText, setSearchText] = useState("");
const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>([]);
const [isHidden, setHidden] = useState(false);
@@ -76,9 +78,13 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
].join(" ")}
>
<div className="automation-manager--sidebar-box--nav">
<InputText label="Search" value={searchText} onChange={setSearchText} />
<InputText
label={langStore.get("SEARCH")}
value={searchText}
onChange={setSearchText}
/>
<InputMultiSelect
label="Tags"
label={langStore.get("TAGS")}
selected={selectedTagIdx}
onChange={setSelectedTagIdx}
options={tags}
@@ -109,7 +115,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
color="primary"
className="add-btn"
>
Add
{langStore.get("ADD")}
</Button>
<ButtonIcon
className="hide-btn"
@@ -15,6 +15,7 @@ import * as av from "types/validators/autmation";
import { useConfirm } from "material-ui-confirm";
import InputYaml from "components/Inputs/Base/InputYaml";
import { APIResponse } from "apiService/types";
import { useLang } from "lang";
export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => Promise<any>;
@@ -33,6 +34,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
forceDeleteAutomation: _forceDeleteAutomation,
triggerAutomation: _triggerAutomation,
}) => {
const langStore = useLang();
const snackbr = useSnackbar();
const confirm = useConfirm();
const validationsShown = useRef(false);
@@ -52,9 +54,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
})
.catch((err) => {
console.error(err);
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", String(err)), {
variant: "error",
});
snackbr.enqueueSnackbar(
langStore.get(errorMessage, {
err: String(err),
}),
{
variant: "error",
}
);
setIsSaving(isSaving.filter((k) => k !== name));
});
}
@@ -68,9 +75,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
if (resp.ok) {
refreshAutomations();
} else {
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", resp.error), {
variant: "error",
});
snackbr.enqueueSnackbar(
langStore.get(errorMessage, {
err: resp.error,
}),
{
variant: "error",
}
);
}
}
});
@@ -78,24 +90,26 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
const onAutomationStateChange = (eid: string, on: boolean) =>
wrapPromise(
"changing automation state",
'failed to toggle autonation due to "{{err}}"',
langStore.get("AUTOMATION_MANAGER_STATE_CHANGE"),
"AUTOMATION_MANAGER_STATE_CHANGE_FAIL",
() => _onAutomationStateChange(eid, on)
);
const refreshAutomations = () =>
wrapPromise(
"refreshing automations",
'failed refreshing automations due to "{{err}}"',
langStore.get("AUTOMATION_MANAGER_REFRESH"),
"AUTOMATION_MANAGER_REFRESH_FAIL",
() => _refreshAutomations()
);
const forceDeleteAutomation = (eid: string) =>
wrapPromise("deleting automations", 'failed delete due to "{{err}}"', () =>
_forceDeleteAutomation(eid)
wrapPromise(
langStore.get("AUTOMATION_MANAGER_DELETE"),
"AUTOMATION_MANAGER_DELETE_FAIL",
() => _forceDeleteAutomation(eid)
);
const triggerAutomation = (eid: string) =>
wrapPromise(
"triggering automations",
'failed trigger due to "{{err}}"',
langStore.get("AUTOMATION_MANAGER_TRIGGER"),
"AUTOMATION_MANAGER_TRIGGER_FAIL",
() => _triggerAutomation(eid)
);
@@ -129,7 +143,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
cancellationButtonProps: {
style: { display: "none" },
},
title: "Invalid Automations detected!",
title: langStore.get("ERROR_INVALID_AUTOMATION_DETECTED"),
content: (
<>
<ol className="invalid-automation-modal-list">
@@ -165,6 +179,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
.catch(console.error);
}
}
// eslint-disable-next-line
}, [api.state.automations, confirm]);
// handle bad states
@@ -172,8 +187,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return (
<div className="automation-manager error">
<Alert color="error">
Failed to connect to websocket, please check that your access token is
properly setup
{langStore.get("ERROR_FAILED_CONNECTION_TO_HA")}
</Alert>{" "}
<br />
<code>{JSON.stringify(haEntities.error)}</code>
@@ -205,7 +219,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return (
<div className="automation-manager error">
<Alert color="error">
Failed to load automations from <code>/config</code>
{langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG")}
</Alert>{" "}
<br />
<code>{error}</code>
@@ -237,8 +251,8 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
onAutomationStateChange={onAutomationStateChange}
onAutomationAdd={(auto) =>
wrapApiPromise(
"adding automation",
"Failed to create automation, recieved error: {{err}}!",
langStore.get("AUTOMATION_MANAGER_ADD"),
"AUTOMATION_MANAGER_ADD_FAIL",
() => api.createAutomation(auto) as any
)
}
@@ -258,7 +272,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}
if (!deleteSent) {
snackbr.enqueueSnackbar(
"Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant",
langStore.get("AUTOMATION_MANAGER_DELETE_LIGHT"),
{
variant: "error",
}
@@ -268,15 +282,15 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}}
onAutomationUpdate={(auto) =>
wrapApiPromise(
"updating automation",
"Failed to update automation, recieved error: {{err}}!",
langStore.get("AUTOMATION_MANAGER_UPDATE"),
"AUTOMATION_MANAGER_UPDATE_FAIL",
() => api.updateAutomation(auto) as any
)
}
onUpdateTags={async (aid, t) => {
wrapApiPromise(
"updating tags",
"Failed to update tags, recieved error: {{err}}!",
langStore.get("AUTOMATION_MANAGER_UPDATE_TAGS"),
"AUTOMATION_MANAGER_UPDATE_TAGS_FAIL",
() =>
api.updateTags({
automation_id: aid,