input area

This commit is contained in:
ari committed 2022-06-16 17:24:31 -04:00
1 parent 0fc3ea6146
commit 15c97b81b4
16 files changed
+699 -416

No files matched your search

@@ -0,0 +1,25 @@
import { FC } from "react";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { useHAAreas } from "haService/AreaRegistry";
export type InputAreaProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[];
};
export const InputArea: FC<InputAreaProps> = (props) => {
// state
const areas = useHAAreas();
return (
<InputAutoComplete
{...props}
validateOption={(v) => areas.validateOptions(v, props.restrictToDomain)}
options={areas.getOptions(props.restrictToDomain)}
getID={areas.getID}
getLabel={areas.getLabel}
onlyShowLabel
/>
);
};
@@ -32,4 +32,10 @@
max-height: 5em;
max-width: 100%;
overflow: auto;
}
.input-autocomplete--chip small {
max-width: 7em;
text-overflow: ellipsis;
overflow: hidden;
}
@@ -0,0 +1,13 @@
import { computeSimilarity } from "./InputAutoComplete";
test("similarity score", () => {
const searchTerms = [
"lught",
"light",
"light balcn",
"light bal",
"light balcony",
"Balcony lig",
].map((x) => computeSimilarity(x, "light.balcony", "Balcony Light"));
expect(searchTerms).toStrictEqual(searchTerms.sort());
});
@@ -1,5 +1,4 @@
import "./InputAutoComplete.css";
import { Option } from "haService";
import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
import Chip from "@mui/material/Chip";
@@ -7,6 +6,11 @@ import { Badge } from "@mui/material";
import { SearchItem } from "./extras";
import { ReactNode } from "react";
export type BaseOption<T = {}> = {
id: string;
label: string;
} & T;
export type Option<T = {}> = string | BaseOption<T>;
export type InputAutoCompleteProps<T extends Option<any>> = {
validateOption?: (v: string[]) => string[] | null;
groupBy?: (opt: T) => string;
@@ -18,7 +22,6 @@ export type InputAutoCompleteProps<T extends Option<any>> = {
required?: boolean;
onlyShowLabel?: boolean;
} & InputAutoCompletePropsBase;
export type InputAutoCompletePropsBase = {
label?: string;
className?: string;
@@ -35,6 +38,25 @@ export type InputAutoCompletePropsBase = {
}
);
export function computeSimilarity(
text: string,
optId: string,
optLabel: string
) {
let similarityScore = 0;
const lowCaseId = optId.toLocaleLowerCase();
const lowCaseLabel = optLabel.toLocaleLowerCase();
for (const segment of text.toLocaleLowerCase().split(" ")) {
if (lowCaseId.includes(segment)) {
similarityScore += lowCaseId.length / lowCaseId.length;
}
if (lowCaseId.includes(segment)) {
similarityScore += lowCaseLabel.length / lowCaseLabel.length;
}
}
return similarityScore;
}
export function InputAutoComplete<T extends Option>(
props: InputAutoCompleteProps<T>
) {
@@ -120,32 +142,26 @@ export function InputAutoComplete<T extends Option>(
onChange={onChange}
getOptionLabel={getLabel as any}
filterOptions={(opts, s) => {
const searchTerm = s.inputValue.toLocaleLowerCase().trim();
const searchTerm = s.inputValue;
if (!searchTerm) {
return opts;
}
return opts
.map((opt) => {
let similarityScore = 0;
const eid = getID(opt);
if (eid.toLocaleLowerCase().includes(searchTerm)) {
similarityScore = Math.abs(eid.length - searchTerm.length);
}
const name = getLabel(opt);
if (name.toLocaleLowerCase().includes(searchTerm)) {
similarityScore = Math.abs(eid.length - searchTerm.length);
}
return {
label: name,
id: eid,
domain: typeof opt === "string" ? "" : (opt as any).domain,
similarityScore,
opt,
similarityScore: computeSimilarity(
searchTerm,
getID(opt),
getLabel(opt)
),
};
})
.filter((opt) => opt.similarityScore > 0)
.sort((a, b) => {
return a.similarityScore > b.similarityScore ? 1 : -1;
}) as any;
return a.similarityScore < b.similarityScore ? 1 : -1;
})
.map(({ opt }) => opt);
}}
groupBy={props.groupBy}
renderOption={(listProps, option, { inputValue }) => {
@@ -153,14 +169,16 @@ export function InputAutoComplete<T extends Option>(
const id = getID(option);
return (
<SearchItem
key={label + id}
listProps={listProps}
id={id}
label={label}
searchTerm={inputValue}
onlyShowLabel={props.onlyShowLabel}
/>
<>
<SearchItem
key={label + id}
listProps={listProps}
id={id}
label={label}
searchTerm={inputValue}
onlyShowLabel={props.onlyShowLabel}
/>
</>
);
}}
renderInput={(params) => (
@@ -22,7 +22,6 @@ export default function InputAutoText({
endAdornment,
error,
}: InputAutoTextProps) {
console.log(options);
return (
<Autocomplete
freeSolo
+18 -13
View File
@@ -1,18 +1,23 @@
import { FC } from "react";
import { useHADeviceRegistry } from 'haService';
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete';
import { useHADeviceRegistry } from "haService";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
export type InputDeviceProps = InputAutoCompletePropsBase & { multiple?: false };
export type InputDeviceProps = InputAutoCompletePropsBase;
export const InputDevice: FC<InputDeviceProps> = props => {
// state
const dr = useHADeviceRegistry();
export const InputDevice: FC<InputDeviceProps> = (props) => {
// state
const dr = useHADeviceRegistry();
return <InputAutoComplete
{...props}
label={props.label ?? "Device ID"}
getID={dr.getID}
getLabel={dr.getLabel}
options={dr.getOptions()}
return (
<InputAutoComplete
{...props}
label={props.label ?? "Device ID"}
getID={dr.getID}
getLabel={dr.getLabel}
options={dr.getOptions()}
/>
}
);
};
@@ -226,7 +226,7 @@ const computeInvalidYaml = (
) => {
const errors = validateNode(node, allowedNodeTypes);
if (errors) {
console.log({ errors });
console.warn({ errors });
return {
node,
isErrored: true,
@@ -5,10 +5,7 @@ import InputText from "components/Inputs/InputText";
import InputNumber from "components/Inputs/InputNumber";
import { IconButton } from "@mui/material";
import { RemoveCircle } from "@mui/icons-material";
import { InputEntity } from "components/Inputs/InputEntities";
import InputAutoText from "components/Inputs/InputAutoText";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { Option } from "haService";
import { InputAutoComplete, Option } from "components/Inputs/InputAutoComplete";
import { prettyName } from "utils/formatting";
export type ServiceEditorFieldProps = {
@@ -45,85 +42,67 @@ export const ServiceEditorField: FC<ServiceEditorFieldProps> = ({
required={isRequired}
/>
);
if (option.type === "field") {
example = option.data.example ? `Example: ${option.data.example}` : "";
if (option.data.selector?.number) {
return (
<InputNumber
className="service-editor--field"
label={label}
value={value ?? option.data.default}
min={option.data.selector.number.min}
max={option.data.selector.number.max}
step={option.data.selector.number.step}
unit={option.data.selector.number.unit_of_measurement}
onChange={onChange}
required={isRequired}
placeholder={example}
/>
);
}
if (option.data.selector?.select) {
return (
<InputAutoComplete
className="service-editor--field"
label={label}
value={value}
onChange={onChange}
endAdornment={removeIcon}
required={isRequired}
options={option.data.selector.select.options.map<Option>((opt) => {
if (typeof opt === "string") {
return {
id: opt,
label: prettyName(opt),
};
}
return {
id: opt.value,
label: opt.label,
};
})}
getLabel={(opt) => {
if (typeof opt === "string") {
return prettyName(opt);
}
return opt.label;
}}
onlyShowLabel
/>
);
}
example = option.data.example ? `Example: ${option.data.example}` : "";
if (option.data.selector?.number) {
return (
<InputText
<InputNumber
className="service-editor--field"
label={label}
title={description}
helperText={description}
value={value ?? option.data.default}
min={option.data.selector.number.min}
max={option.data.selector.number.max}
step={option.data.selector.number.step}
unit={option.data.selector.number.unit_of_measurement}
onChange={onChange}
placeholder={example}
required={isRequired}
endAdornment={removeIcon}
placeholder={example}
/>
);
} else {
if (option.id === "entity") {
if ("domain" in option.data) {
return (
<InputEntity
value={value}
onChange={onChange}
className="service-editor--field"
multiple
restrictToDomain={
option.data.domain ? [option.data.domain] : undefined
}
/>
);
}
}
}
if (option.data.selector?.select) {
return (
<InputAutoComplete
className="service-editor--field"
label={label}
value={value}
onChange={onChange}
endAdornment={removeIcon}
required={isRequired}
options={option.data.selector.select.options.map<Option>((opt) => {
if (typeof opt === "string") {
return {
id: opt,
label: prettyName(opt),
};
}
return {
id: opt.value,
label: opt.label,
};
})}
getLabel={(opt) => {
if (typeof opt === "string") {
return prettyName(opt);
}
return opt.label;
}}
onlyShowLabel
/>
);
}
return (
<InputText
className="service-editor--field"
label={label}
title={description}
helperText={description}
value={value ?? option.data.default}
onChange={onChange}
placeholder={example}
required={isRequired}
endAdornment={removeIcon}
/>
);
return input;
};
@@ -0,0 +1,10 @@
.service-editor--targets {
display: flex;
flex-direction: row;
gap: 1em;
padding-bottom: 0.5em;
}
.service-editor--targets>div {
flex: 1;
}
@@ -0,0 +1,89 @@
import "./ServiceEditorTarget.css";
import { InputDevice } from "components/Inputs/InputDevice";
import { InputEntity } from "components/Inputs/InputEntities";
import { Targets } from "haService/fieldTypes";
import { FC } from "react";
import { InputArea } from "components/Inputs/InputArea";
type RawTargetData = {
entity_id?: string[] | string;
area_id?: string[] | string;
device_id?: string[] | string;
};
type CleanTargetData = {
entity_id: string[];
area_id: string[];
device_id: string[];
};
export type ServiceEditorTargetProps = {
defn: Targets;
value: RawTargetData | null | undefined;
onChange: (v: any) => void;
};
export const ServiceEditorTarget: FC<ServiceEditorTargetProps> = (props) => {
const value = cleanUpValue(props.value ?? {});
const domainRestrictions: string[] = [];
if (props.defn.entity) {
if (typeof props.defn.entity.domain === "string") {
domainRestrictions.push(props.defn.entity.domain);
}
}
return (
<div className="service-editor--targets">
<InputEntity
label="Target Entities"
value={value.entity_id}
onChange={(entity_id) =>
props.onChange({
...(props.value || {}),
entity_id,
})
}
restrictToDomain={domainRestrictions}
multiple
/>
<InputDevice
label="Target Devices"
value={value.device_id}
onChange={(device_id) =>
props.onChange({
...(props.value || {}),
device_id,
})
}
multiple
/>
<InputArea
label="Target Areas"
value={value.area_id}
onChange={(area_id) =>
props.onChange({
...(props.value || {}),
area_id,
})
}
multiple
/>
</div>
);
};
const cleanUpValue = (value: RawTargetData): CleanTargetData => {
const cleanOne = (v?: string[] | string): string[] => {
if (typeof v === "string") {
return [v];
}
if (!v || !Array.isArray(v)) {
return [];
}
return v;
};
return {
entity_id: cleanOne(value.entity_id),
device_id: cleanOne(value.device_id),
area_id: cleanOne(value.area_id),
};
};
+17 -30
View File
@@ -7,11 +7,11 @@ import {
ServiceEditorOption,
splitUpOptions,
convertFieldToOption,
convertTargetToOption,
ServiceEditorData,
} from "./options";
import { ServiceEditorField } from "./ServiceEditorField";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { ServiceEditorTarget } from "./ServiceEditorTarget";
export type ServiceEditorProps = {
serviceId: string;
@@ -26,7 +26,6 @@ export const ServiceEditor: FC<ServiceEditorProps> = ({
onUpdate,
}) => {
const options = splitUpOptions(service, data);
console.log(service);
const [additionalFields, setAdditionalFields] = useState<{
field: string[];
optionalList: ServiceEditorOption[];
@@ -60,14 +59,14 @@ export const ServiceEditor: FC<ServiceEditorProps> = ({
<>
{options.required.map((opt) => (
<ServiceEditorField
key={opt.type + opt.id}
key={"field-" + opt.id}
option={opt}
value={data[opt.type][opt.id]}
value={data.field[opt.id]}
onChange={(v) =>
onUpdate({
...data,
[opt.type]: {
...data[opt.type],
field: {
...data.field,
[opt.id]: v,
},
})
@@ -75,28 +74,17 @@ export const ServiceEditor: FC<ServiceEditorProps> = ({
/>
))}
{hasTargets && (
<div className="service-editor--target">
{Object.keys(service.target ?? {}).map((key) => {
const targetData = (service.target as any)[key];
const option = convertTargetToOption(key, targetData);
return (
<ServiceEditorField
key={"fields-" + key}
option={option}
value={data.target[key] ?? ""}
onChange={(v) =>
onUpdate({
...data,
target: {
...data.target,
[key]: v,
},
})
}
/>
);
})}
</div>
<ServiceEditorTarget
key={"target-" + serviceId}
defn={service.target ?? {}}
value={data.target}
onChange={(target) =>
onUpdate({
...data,
target,
})
}
/>
)}
<div className="service-editor--used">
{additionalFields.field.map((key) => {
@@ -154,8 +142,7 @@ export const ServiceEditor: FC<ServiceEditorProps> = ({
...additionalFields,
field: additionalFields.field.concat([newField.id]),
optionalList: additionalFields.optionalList.filter(
(opt) =>
!(opt.type === newField.type && opt.id === newField.id)
(opt) => !(opt.id === newField.id)
),
});
}
+5 -25
View File
@@ -1,41 +1,21 @@
import { BaseOption } from "haService";
import { FieldData, TargetData, TypedHassService } from "haService/fieldTypes";
import { BaseOption } from "components/Inputs/InputAutoComplete";
import { FieldData, TypedHassService } from "haService/fieldTypes";
import { prettyName } from "utils/formatting";
export type ServiceEditorData = {
field: Record<string, any>;
target: Record<string, any>;
};
export type ServiceEditorOption = BaseOption<
| {
type: "field";
data: {
description: string;
} & FieldData;
}
| {
type: "target";
data: {
description: string;
} & TargetData;
}
>;
export type ServiceEditorOption = BaseOption<{
data: FieldData
}>;
export const convertFieldToOption = (id: string, data: FieldData): ServiceEditorOption => ({
id,
label: data.name ?? prettyName(id),
type: "field",
data,
})
export const convertTargetToOption = (id: string, data: TargetData): ServiceEditorOption => ({
id,
type: "target",
label: ((data ?? {}) as any).name ?? prettyName(id),
data: (data as any) ?? {
description: "",
},
})
export const splitUpOptions = (service: TypedHassService, data: ServiceEditorData) => {
const required: ServiceEditorOption[] = [];