refactor inputs

This commit is contained in:
ari committed 2022-08-05 22:04:31 -04:00
1 parent 2c5d64ab86
commit 549f52655b
45 files changed
+301 -256

No files matched your search

@@ -0,0 +1,26 @@
import { FC } from "react";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { useHAAreas } from "haService/AreaRegistry";
export type InputAreaProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[];
restrictedIntegrations?: string[];
};
export const InputArea: FC<InputAreaProps> = (props) => {
// state
const areas = useHAAreas();
return (
<InputAutoComplete
{...props}
label={props.label ?? "Area"}
getID={areas.getID}
getLabel={areas.getLabel}
options={areas.getOptions()}
onlyShowLabel
/>
);
};
@@ -0,0 +1,47 @@
.input-autocomplete .BaseBadge-root {
max-width: 100%;
}
.input-autocomplete--chip>span {
display: flex;
flex-direction: row;
gap: 0.15em;
}
.input-autocomplete--chip>span>small::before {
content: "/ ";
}
.input-autocomplete--chip>span>small {
size: 0.15em;
}
.input-autocomplete--errors {
margin-top: 0.75em;
}
.input-autocomplete--errors ul {
padding: 0 0 0 1em;
margin: 0;
max-height: 2.5em;
overflow-y: auto;
overflow-x: hidden;
}
.input-autocomplete--tags {
max-height: 5em;
width: fit-content;
max-width: 100%;
overflow: auto;
text-overflow: ellipsis;
}
.input-autocomplete--chip small {
max-width: 7em;
text-overflow: ellipsis;
overflow: hidden;
}
.input-autocomplete--popper {
min-width: fit-content;
}
@@ -0,0 +1,23 @@
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());
});
test("similarity score #2", () => {
expect(
computeSimilarity(
"li",
"6592b3d6d05d3de6fa26c3dbd2edecc2",
"Balcony Lights"
)
).toBeGreaterThan(0);
});
@@ -0,0 +1,269 @@
import "./InputAutoComplete.css";
import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
import Chip from "@mui/material/Chip";
import Badge from "@mui/material/Badge";
import Popper from "@mui/material/Popper";
import { SearchItem } from "./extras";
import { ReactNode } from "react";
import { prettyName } from "utils/formatting";
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;
options: T[];
getLabel?: (opt: T) => string;
getID?: (opt: T) => string;
} & InputAutoCompletePropsBase;
export type InputAutoCompletePropsBase = {
label?: string;
className?: string;
disabled?: boolean;
required?: boolean;
onlyShowLabel?: boolean;
helperText?: ReactNode;
endAdornment?: ReactNode;
onEnter?: () => void;
disableChips?: boolean;
} & (
| {
value: string | null;
multiple?: false;
onChange: (v: string | null) => void;
}
| {
value: string | string[];
multiple: true;
onChange: (v: string[]) => void;
}
);
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 (lowCaseLabel.includes(segment)) {
similarityScore += lowCaseLabel.length / lowCaseLabel.length;
}
}
return similarityScore;
}
export function InputAutoComplete<T extends Option>(
props: InputAutoCompleteProps<T>
) {
// aliases
const getID = (opt: T): string => {
if (props.getID) {
return props.getID(opt);
}
if (typeof opt === "string") {
return opt;
}
return opt.id;
};
const getLabel = (opt: T): string => {
if (props.getLabel) {
return props.getLabel(opt);
}
if (typeof opt === "string") {
return opt;
}
return opt.label;
};
// processing of inputs
const value = Array.isArray(props.value)
? props.value
: !!props.value
? [props.value]
: [];
const errors = props.validateOption ? props.validateOption(value) : null;
const options = props.options
.filter((opt) => !value.includes(getID(opt)))
.sort((a, b) => {
return getID(a) > getID(b) ? 1 : -1;
});
// processing of errors
let helperText = props.helperText ?? <></>;
let error: boolean = false;
if (errors !== null) {
error = true;
if (errors.length > 0) {
helperText = (
<Badge
className="input-autocomplete--errors"
badgeContent={errors.length}
color="error"
>
<ul title={errors.join(", and")}>
{errors.map((msg, i) => (
<li key={i}>{msg}</li>
))}
</ul>
</Badge>
);
}
}
// events
const onChange = (_e: any, v: any) => {
const cleanValue: string[] =
v === null
? []
: Array.isArray(v)
? v.map((opt) => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
})
: [v];
if (props.multiple) {
props.onChange(cleanValue);
} else {
props.onChange(cleanValue[cleanValue.length - 1]);
}
};
return (
<Autocomplete
className={["input-autocomplete", props.className ?? ""].join(" ")}
multiple={true}
freeSolo
value={value}
options={options}
onChange={onChange}
getOptionLabel={getLabel as any}
disabled={props.disabled}
PopperComponent={(props) => {
return (
<Popper
key={Math.random().toString()}
{...props}
className={[props.className, "input-autocomplete--popper"].join(
" "
)}
/>
);
}}
filterOptions={(opts, s) => {
const searchTerm = s.inputValue;
if (!searchTerm) {
return opts;
}
return opts
.map((opt) => {
return {
opt,
similarityScore: computeSimilarity(
searchTerm,
getID(opt),
getLabel(opt)
),
};
})
.filter((opt) => opt.similarityScore > 0)
.sort((a, b) => {
return a.similarityScore < b.similarityScore ? 1 : -1;
})
.map(({ opt }) => opt);
}}
groupBy={props.groupBy}
renderOption={(listProps, option, { inputValue }) => {
const label = getLabel(option);
const id = getID(option);
return (
<>
<SearchItem
key={label + id}
listProps={listProps}
id={id}
label={label}
searchTerm={inputValue}
onlyShowLabel={props.onlyShowLabel}
/>
</>
);
}}
renderInput={(params) => (
<TextField
{...params}
InputProps={{
...params.InputProps,
endAdornment: props.endAdornment ?? params.InputProps.endAdornment,
}}
onKeyDown={(e) => {
if (e.key === "Enter" && props.onEnter) {
props.onEnter();
}
}}
variant="filled"
required={props.required}
label={props.label ?? "Entity ID"}
helperText={helperText}
disabled={props.disabled}
error={error}
placeholder={
props.disableChips && !props.multiple ? props.value ?? "" : ""
}
/>
)}
renderTags={(tagValue, getTagProps) => {
const inner = (
<div className="input-autocomplete--tags">
{tagValue.map((option, index) => {
const label = getLabel(option);
const id = getID(option);
const tagProps = getTagProps({ index });
tagProps.className += " input-autocomplete--chip";
return (
<Chip
size="medium"
title={`${label} / ${id}`}
label={
<>
{id === label ? (
<span>{prettyName(label)}</span>
) : (
<b>{label}</b>
)}
{id !== label && !props.onlyShowLabel && (
<small>{id}</small>
)}
</>
}
{...tagProps}
/>
);
})}
</div>
);
if (props.disableChips) {
return <></>;
}
if (props.multiple) {
return (
<Badge badgeContent={tagValue.length} color="info">
{inner}
</Badge>
);
} else {
return inner;
}
}}
/>
);
}
@@ -0,0 +1,36 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { InputDevice } from "./InputDevice";
export default {
title: 'Inputs/InputDevice',
component: InputDevice,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputDevice>;
const Template: ComponentStory<typeof InputDevice> = args => {
const [value, setValue] = useState(args.value)
return <Page>
<div style={{
maxWidth: 200
}}>
<InputDevice {...args} value={value as any} onChange={(v: any) => {
setValue(v)
args.onChange(v as any)
}} />
</div>
</Page>
}
export const Single = Template.bind({})
Single.args = {
...Single.args,
multiple: false,
value: 'sensor.humidity_bathroom'
} as any
@@ -0,0 +1,22 @@
import { FC } from "react";
import { useHADeviceRegistry } from "haService";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
export type InputDeviceProps = InputAutoCompletePropsBase;
export const InputDevice: FC<InputDeviceProps> = (props) => {
// state
const dr = useHADeviceRegistry();
return (
<InputAutoComplete
{...props}
label={props.label ?? "Device"}
getID={dr.getID}
getLabel={dr.getLabel}
options={dr.getOptions()}
/>
);
};
@@ -0,0 +1,6 @@
.input-device-caps {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
@@ -0,0 +1,120 @@
import "./InputDeviceCapabilties.css";
import { HaFormSchema } from "haService/types";
import { useSnackbar } from "notistack";
import { useRef } from "react";
import { prettyName } from "utils/formatting";
import { InputAutoComplete, Option } from "./InputAutoComplete";
import InputBoolean from "../InputBoolean";
import { InputTime } from "../InputDayTime";
import InputNumber from "../InputNumber";
import InputText from "../InputText";
export type InputDeviceCapabiltiesProps<T extends Record<string, any>> = {
defn: HaFormSchema[];
state: T;
setState: (s: T) => void;
};
export function InputDeviceCapabilties<T extends Record<string, any>>(
props: InputDeviceCapabiltiesProps<T>
) {
const snackr = useSnackbar();
const msgRef = useRef<Record<string, boolean>>({});
return (
<div className="input-device-caps">
{props.defn.map((def, i) => {
const prop = {
key: String(i),
className: "input-device-cap",
label:
prettyName(def.name) +
" " +
(JSON.stringify(def.description) ?? ""),
required: def.required,
placeholder: def.default,
value: props.state[def.name],
onChange: (v: any) =>
props.setState({
...props.state,
[def.name]: v,
}),
};
if (def.type === "boolean") {
return <InputBoolean {...prop} />;
} else if (def.type === "string") {
return <InputText {...prop} />;
} else if (def.type === "integer") {
return (
<InputNumber
{...prop}
step={1}
max={def.valueMax}
min={def.valueMin}
/>
);
} else if (def.type === "float") {
return <InputNumber {...prop} step={0.01} />;
} else if (def.type === "constant") {
return (
<InputText {...prop} value={def.value ?? props.state[def.name]} />
);
} else if (def.type === "positive_time_period_dict") {
return <InputTime {...prop} />;
} else if (def.type === "select") {
return (
<InputAutoComplete
{...prop}
multiple={false}
options={def.options.map(([value, label]) => ({
id: value,
label: prettyName(label),
}))}
/>
);
} else if (def.type === "multi_select") {
let options: Option[] = [];
if (Array.isArray(def.options)) {
options = def.options.map((opt) =>
Array.isArray(opt)
? {
id: opt[0],
label: prettyName(opt[1]),
}
: {
id: opt,
label: prettyName(opt),
}
);
} else {
options = Object.entries(def.options).map(([id, label]) => ({
id,
label: prettyName(label),
}));
}
return (
<InputAutoComplete {...prop} multiple={true} options={options} />
);
}
if (!msgRef.current[def.name + def.type]) {
msgRef.current[def.name + def.type] = true;
snackr.enqueueSnackbar(
<span>
"{def.name}" is of a unimplemented type "{def.type}"! <br />
Please report this to the maintainers.{" "}
<b>For now, we leave you with a generic textbox!</b> <br />
DEBUG="{JSON.stringify(def)}"
</span>,
{
variant: "warning",
persist: true,
}
);
}
return (
<>
<InputText {...prop} />
</>
);
})}
</div>
);
}
@@ -0,0 +1,62 @@
import { FC } from "react";
import { useHAEntities } from "haService/HAEntities";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { prettyName } from "utils/formatting";
export type InputEntityProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[];
restrictedIntegrations?: string[];
preSelectedEntityIds?: string[];
restrictedDeviceClass?: string[];
restrictMode?: "and" | "or";
};
export const InputEntity: FC<InputEntityProps> = (props) => {
// state
const entities = useHAEntities();
let options = entities.getOptions(
props.restrictToDomain,
props.restrictedIntegrations,
props.restrictedDeviceClass,
props.restrictMode ?? "and"
);
if (props.preSelectedEntityIds) {
options = options.filter((opt) =>
props.preSelectedEntityIds?.includes(entities.getID(opt))
);
}
const validateOptions = (v: string[]): null | string[] => {
const errors: string[] = [];
if (props.preSelectedEntityIds) {
v.forEach((eid) => {
if (!props.preSelectedEntityIds?.includes(eid)) {
errors.push(`"${eid}" is not a valid selection`);
}
});
}
errors.concat(
entities.validateOptions(
v,
props.restrictToDomain,
props.restrictedIntegrations
) ?? []
);
if (errors.length > 0) {
return errors;
}
return null;
};
return (
<InputAutoComplete
{...props}
validateOption={validateOptions}
options={options}
getID={entities.getID}
getLabel={entities.getLabel}
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
/>
);
};
@@ -0,0 +1,84 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { InputEntity } from "./InputEntities";
export default {
title: 'Inputs/InputEntity',
component: InputEntity,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputEntity>;
const Template: ComponentStory<typeof InputEntity> = args => {
const [value, setValue] = useState(args.value)
return <Page>
<div style={{
maxWidth: 200
}}>
<InputEntity {...args} value={value as any} onChange={(v: any) => {
setValue(v)
args.onChange(v as any)
}} />
</div>
</Page>
}
export const Single = Template.bind({})
Single.args = {
...Single.args,
multiple: false,
value: 'sensor.bathroom'
} as any
export const Many = Template.bind({})
Many.args = {
...Many.args,
multiple: true,
value: ['sensor.bathroom', 'person.ari']
} as any
export const ManyEmpty = Template.bind({})
ManyEmpty.args = {
...ManyEmpty.args,
multiple: true,
value: []
} as any
export const ManyButGotSingle = Template.bind({})
ManyButGotSingle.args = {
...ManyButGotSingle.args,
multiple: true,
value: 'sensor.bathroom'
} as any
export const InvalidDomain = Template.bind({})
InvalidDomain.args = {
...InvalidDomain.args,
multiple: true,
value: 'sensor.bathroom',
restrictToDomain: ['zone'],
} as any
export const InvalidManyDomain = Template.bind({})
InvalidManyDomain.args = {
...InvalidManyDomain.args,
multiple: true,
value: 'sensor.bathroom',
restrictToDomain: ['zone', 'switch'],
} as any
export const InvalidLots = Template.bind({})
InvalidLots.args = {
...InvalidLots.args,
multiple: true,
value: ['person.ari', 'sensor.bathroom', 'binary_sensor.ping_tv', 'device_tracker.phone'],
restrictToDomain: ['zone', 'switch'],
} as any
@@ -0,0 +1,36 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { InputService } from "./InputService";
export default {
title: 'Inputs/InputService',
component: InputService,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputService>;
const Template: ComponentStory<typeof InputService> = args => {
const [value, setValue] = useState(args.value)
return <Page>
<div style={{
maxWidth: 200
}}>
<InputService {...args} value={value as any} onChange={(v: any) => {
setValue(v)
args.onChange(v as any)
}} />
</div>
</Page>
}
export const Single = Template.bind({})
Single.args = {
...Single.args,
multiple: false,
value: ''
} as any
@@ -0,0 +1,19 @@
import { FC } from "react";
import { useHAServices } from 'haService';
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete';
import { prettyName } from 'utils/formatting';
export type InputServiceProps = InputAutoCompletePropsBase & { multiple?: false };
export const InputService: FC<InputServiceProps> = props => {
const services = useHAServices();
return <InputAutoComplete
{...props}
label={props.label ?? "Service"}
options={services.getOptions()}
getID={services.getID}
getLabel={services.getLabel}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''}
/>
}
@@ -0,0 +1,21 @@
.input-time-entity {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
gap: 0.5em;
}
.input-time-entity button.MuiButtonBase-root {
border-color: var(--mui-info-light);
background-color: var(--mui-info-main);
color: var(--mui-info-contrastText);
}
.input-time-entity button.MuiButtonBase-root:hover {
background-color: var(--mui-info-light);
}
.input-time-entity .input-autocomplete {
min-width: 10em;
}
@@ -0,0 +1,35 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { InputTimeEntity } from "./InputTimeEntity";
export default {
title: "Inputs/InputTimeEntity",
component: InputTimeEntity,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof InputTimeEntity>;
const Template: ComponentStory<typeof InputTimeEntity> = (args) => {
const [value, setValue] = useState("");
return (
<Page>
<div
style={{
padding: "1em",
}}
>
<InputTimeEntity
{...args}
value={value}
onChange={(t) => {
setValue(t);
args.onChange(t);
}}
/>
</div>
</Page>
);
};
export const SimpleText = Template.bind({});
@@ -0,0 +1,68 @@
import "./InputTimeEntity.css";
import { FC, ReactNode } from "react";
import AccessTimeOutlinedIcon from "@mui/icons-material/AccessTimeOutlined";
import MoreTimeOutlinedIcon from "@mui/icons-material/MoreTimeOutlined";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import {
convertObjectToAutomationTimeString,
isAutomationTimeString24Hours,
} from "utils/time";
import { InputEntity } from "./InputEntities";
import { InputTime } from "../InputTime";
export type InputTimeEntityProps = {
value: string;
onChange: (v: string) => void;
className?: string;
};
export const InputTimeEntity: FC<InputTimeEntityProps> = ({
value,
onChange,
className = "",
}) => {
const is24Hour = isAutomationTimeString24Hours(value);
let editor: ReactNode;
if (is24Hour) {
editor = (
<InputTime
label=""
value={value ?? "00:00:00"}
restrictEmpty
onChange={(t) =>
onChange(t ? convertObjectToAutomationTimeString(t) : "00:00:00")
}
/>
);
} else {
editor = (
<InputEntity
label="Time Entity"
restrictMode="or"
restrictedDeviceClass={["timestamp"]}
restrictToDomain={["input_datetime"]}
value={value}
multiple={false}
onChange={(t) => onChange(t ?? "")}
/>
);
}
return (
<div className={"input-time-entity " + className}>
{editor}{" "}
<ButtonIcon
icon={is24Hour ? <AccessTimeOutlinedIcon /> : <MoreTimeOutlinedIcon />}
onClick={() => {
if (is24Hour) {
onChange("");
} else {
onChange("00:00:00");
}
}}
/>
</div>
);
};
@@ -0,0 +1,36 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { SearchItem } from "./extras";
export default {
title: "Inputs/Extras/SearchItem",
component: SearchItem,
parameters: { actions: { argTypesRegex: "^on.*" } },
argTypes: {},
} as ComponentMeta<typeof SearchItem>;
const Template: ComponentStory<typeof SearchItem> = (args) => {
return (
<Page>
<div
style={{
width: "15em",
height: "3em",
border: "1px solid var(--mui-grey-400)",
}}
>
<SearchItem {...args} />
</div>
</Page>
);
};
export const Simple = Template.bind({});
Simple.args = {
id: "sensor.humidity_main_bedroom",
label: "Main Bedroom Humidity",
searchTerm: "bedroom",
listProps: {},
onlyShowLabel: false,
};
@@ -0,0 +1,43 @@
.input-extras--search-item--list {
display: flex;
flex-direction: column;
gap: 0;
justify-content: center;
align-items: flex-start !important;
margin: 0;
padding: 0;
min-height: 2em;
max-height: 100%;
height: 100%;
width: 100%;
min-width: 100%;
max-width: 20em;
text-overflow: ellipsis;
overflow: hidden;
}
.input-extras--search-item--list small {
/* max-height: 2em; */
max-width: 100%;
width: fit-content;
overflow: hidden;
text-overflow: ellipsis;
}
.input-extras--search-item--list b {
max-height: 1.5em;
width: fit-content;
max-width: 100%;
padding-right: 0.25em;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
}
/* .input-extras--search-item--list>small::before {
content: "/ ";
} */
@@ -0,0 +1,75 @@
import "./extras.css";
import { FC } from "react";
import parse from "autosuggest-highlight/parse";
import match from "autosuggest-highlight/match";
export const HighlightElm: FC<{
text: string;
searchTerm: string;
}> = ({ text, searchTerm }) => {
const matches = match(text, searchTerm, {
findAllOccurrences: true,
insideWords: true,
});
const parts = parse(text, matches);
return (
<>
{parts.map((part, index) => (
<span
key={index}
style={{
textDecoration: part.highlight ? "underline" : "unset",
}}
>
{part.text}
</span>
))}
</>
);
};
export const SearchItem: FC<{
listProps: React.HTMLAttributes<HTMLLIElement>;
label: string;
id: string;
searchTerm: string;
onlyShowLabel?: boolean;
}> = ({ listProps, label, id, searchTerm, onlyShowLabel = false }) => {
const labelElm = (
<b className="input-extras--search-item--list--label">
<HighlightElm text={label} searchTerm={searchTerm} />
</b>
);
const idElm = (
<small className="input-extras--search-item--list--id">
<HighlightElm text={id} searchTerm={searchTerm} />
</small>
);
let inner = (
<>
{labelElm}
{idElm}
</>
);
if (onlyShowLabel) {
if (label) {
inner = labelElm;
} else {
inner = idElm;
}
}
return (
<li
{...listProps}
className={[
listProps.className ?? "",
"input-extras--search-item--list",
].join(" ")}
>
{inner}
</li>
);
};