input entities

This commit is contained in:
ari committed 2022-05-30 15:05:54 -04:00
1 parent 878035e748
commit 996626f9af
27 files changed
+596 -92

No files matched your search

@@ -0,0 +1,35 @@
.input-entities .BaseBadge-root {
max-width: 100%;
}
.input-entities--list, .input-entities--chip>span {
display: flex;
flex-direction: row;
gap: 0.15em;
}
.input-entities--list>small::before, .input-entities--chip>span>small::before {
content: "/ ";
}
.input-entities--chip>span>small {
size: 0.15em;
}
.input-entities--errors {
margin-top: 0.75em;
}
.input-entities--errors ul {
padding: 0 0 0 1em;
margin: 0;
max-height: 2.5em;
overflow-y: auto;
overflow-x: hidden;
}
.input-entities--tags {
max-height: 5em;
max-width: 100%;
overflow: auto;
}
@@ -0,0 +1,181 @@
import "./InputEntities.css";
import { FC } from "react";
import { useHAEntities } from 'haService';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Chip from '@mui/material/Chip';
import { prettyName } from "utils/formatting";
import parse from 'autosuggest-highlight/parse';
import match from 'autosuggest-highlight/match';
import { EntityId } from 'types/automations/common';
import { Badge } from "@mui/material";
export type InputEntityProps = {
restrictToDomain?: string[],
label?: string,
} & ({
value: string | null;
multiple?: false;
onChange: (v: string | null) => void;
} | {
value: EntityId;
multiple: true;
onChange: (v: string[]) => void;
})
export const InputEntity: FC<InputEntityProps> = props => {
// state
const entities = useHAEntities();
// processing of inputs
const options = entities.getOptions(props.restrictToDomain);
const value = Array.isArray(props.value) ? props.value : !!props.value ? [props.value] : [];
const errors = entities.validateOptions(value, props.restrictToDomain);
// processing of errors
let helperText = <></>;
let error: boolean = false;
if (errors !== null) {
error = true
if (errors.length > 0) {
helperText = <Badge
className="input-entities--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-entities"
multiple={true}
freeSolo
value={value}
options={options}
onChange={onChange}
getOptionLabel={entities.getLabel}
filterOptions={(opts, s) => {
const searchTerm = s.inputValue.toLocaleLowerCase();
return opts.map(opt => {
let similarityScore = 0;
const eid = entities.getID(opt);
if (eid.toLocaleLowerCase().includes(searchTerm)) {
similarityScore = Math.abs(eid.length - searchTerm.length)
}
const name = entities.getLabel(opt);
if (name.toLocaleLowerCase().includes(searchTerm)) {
similarityScore = Math.abs(eid.length - searchTerm.length)
}
return {
label: name,
id: eid,
domain: (typeof opt === 'string') ? '' : opt.domain,
similarityScore
}
}).filter(opt => opt.similarityScore > 0).sort((a, b) => {
return (a.similarityScore > b.similarityScore) ? 1 : -1
})
}}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''}
renderOption={(prop, option, { inputValue }) => {
const label = entities.getLabel(option);
const id = entities.getID(option);
return <SearchItem
listProps={prop}
id={id}
label={label}
searchTerm={inputValue}
/>
}}
renderInput={params => <TextField
{...params}
variant="filled"
label={props.label ?? "Entity ID"}
helperText={helperText}
error={error}
/>}
renderTags={(tagValue, getTagProps) => <Badge badgeContent={tagValue.length} color="info">
<div className="input-entities--tags">
{tagValue.map((option, index) => {
const label = entities.getLabel(option);
const id = entities.getID(option);
const props = getTagProps({ index });
props.className += ' input-entities--chip'
return (
<Chip
size="medium"
label={<>
{(id === label) ? <span>{label}</span> : <b>{label}</b>}
{(id !== label) && <small>{id}</small>}
</>}
{...props}
/>
)
})}
</div>
</Badge>
}
/>
}
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,
}> = ({
listProps,
label,
id,
searchTerm
}) => <li {...listProps} className={[listProps.className ?? "", 'input-entities--list'].join(' ')}>
<b><HighlightElm text={label} searchTerm={searchTerm} /></b> <small>
<HighlightElm text={id} searchTerm={searchTerm} />
</small>
</li>
@@ -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,28 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { SearchItem } from "./InputEntities";
export default {
title: 'Inputs/InputEntity/SearchItem',
component: SearchItem,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof SearchItem>;
const Template: ComponentStory<typeof SearchItem> = args => {
return <Page>
<SearchItem {...args} />
</Page>
}
export const Simple = Template.bind({})
Simple.args = {
id: "sensor.humidity_main_bedroom",
label: 'Main Bedroom Humidity',
searchTerm: "bedroom",
listProps: {},
} as any
@@ -49,26 +49,4 @@ export const InputList: FC<Props<any>> = ({
</Select>
<FormHelperText>{invalidCurrent ? `'${current}' is not a valid selection` : ''}</FormHelperText>
</FormControl>
// return <InputWrapper label={label} labelSize={'small'} noMargin error={invalidCurrent ? "Invalid Selection" : undefined}>
// <select
// title={invalidCurrent ? "Invalid Selection" : ""}
// className={classes.input}
// {...selattr} value={current}
// onChange={e => {
// e.preventDefault();
// if (e.currentTarget.id === 'invalid') {
// onChange(options[0])
// } else {
// onChange(e.currentTarget.value as any);
// }
// }}
// >
// {options.map((t, i) => <option id={String(i)} key={i} value={t}>{t}</option>)}
// {invalidCurrent ? <option
// id={'invalid'}
// value={current}
// style={{ display: 'none' }}
// >!{current}!</option> : <></>}
// </select>
// </InputWrapper>
}
@@ -2,7 +2,7 @@ import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import InputTextBubble, { InputEntity } from "./InputTextBubble";
import InputTextBubble from "./InputTextBubble";
export default {
title: 'Inputs/InputTextBubble',
@@ -34,16 +34,6 @@ export const JustText: ComponentStory<typeof InputTextBubble> = args => {
</Page>
}
export const EntityId: ComponentStory<typeof InputTextBubble> = args => {
const [value, setValue] = useState<string | string[]>(['sensor.bathroom'])
return <Page>
<InputEntity value={value} onChange={setValue} />
</Page>
}
export const ManyOptions: ComponentStory<typeof InputTextBubble> = args => {
const [value, setValue] = useState<string | string[]>('hello')
@@ -5,28 +5,36 @@ import { FC } from "react";
export interface Props {
label: string;
value: string | string[];
value?: string | string[];
options?: string[];
onChange: (v: string[]) => void;
maxAllowed?: number;
}
export default function InputTextBubble({
value = "",
label,
options = [],
onChange,
maxAllowed,
}: Props) {
const selected = Array.isArray(value) ? value : [value];
const selected = Array.isArray(value) ? value : value ? [value] : [];
return <Autocomplete
multiple
freeSolo
value={selected}
options={options}
onChange={(_e, v) => onChange(
v === null ? [] :
onChange={(_e, v) => {
let cleanValue = v === null ? [] :
Array.isArray(v) ? v : [v]
)}
if (maxAllowed) {
cleanValue = cleanValue.slice(0, maxAllowed);
}
onChange(cleanValue)
}}
renderInput={params => <TextField
{...params}
variant="filled"
@@ -42,15 +50,3 @@ export default function InputTextBubble({
}
/>
}
export const InputEntity: FC<{
value: string | string[];
onChange: (v: string[]) => void;
}> = ({
value,
onChange,
}) => <InputTextBubble
value={value}
onChange={onChange}
label="Entity ID"
/>