colouring-montreal/app/src/frontend/building/data-components/data-entry-input.tsx

59 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-01-06 14:48:47 -05:00
import React, { useState } from 'react';
import { AutofillDropdown } from './autofill-dropdown/autofill-dropdown';
2020-01-06 11:21:44 -05:00
export interface TextDataEntryInputProps {
slug: string;
2020-01-06 14:48:47 -05:00
name?: string;
2020-01-07 14:06:42 -05:00
id?: string;
2020-01-06 14:48:47 -05:00
onChange?: (key: string, val: any) => void;
2020-01-06 11:21:44 -05:00
maxLength?: number;
disabled?: boolean;
placeholder?: string;
valueTransform?: (val: string) => string;
2020-01-06 14:48:47 -05:00
autofill?: boolean;
2020-01-06 11:21:44 -05:00
}
2020-01-06 14:48:47 -05:00
export const DataEntryInput: React.FC<TextDataEntryInputProps & {value?: string}> = props => {
const [isEditing, setEditing] = useState(false);
2020-01-07 14:06:42 -05:00
const nameAttr = props.name || props.slug;
const idAttr = props.id || props.slug;
2020-01-06 14:48:47 -05:00
const handleChange = (value: string) => {
console.log(value);
const transform = props.valueTransform || (x => x);
const transformedValue = value === '' ?
null :
transform(value);
props.onChange(props.slug, transformedValue);
};
2020-01-06 11:21:44 -05:00
return (
2020-01-07 14:06:42 -05:00
<>
2020-01-06 14:48:47 -05:00
<input className="form-control" type="text"
2020-01-07 14:06:42 -05:00
id={idAttr}
name={nameAttr}
2020-01-06 14:48:47 -05:00
value={props.value || ''}
maxLength={props.maxLength}
disabled={props.disabled}
placeholder={props.placeholder}
onChange={e => handleChange(e.target.value)}
2020-01-07 14:06:42 -05:00
onInput={e => setEditing(true)}
onFocus={e => setEditing(true)}
onBlur={e => setEditing(false)}
2020-01-06 14:48:47 -05:00
/>
{
props.autofill &&
<AutofillDropdown
editing={isEditing}
onSelect={value => handleChange(value)}
onClose={() => setEditing(false)}
fieldName={props.slug}
fieldValue={props.value}
/>
}
2020-01-07 14:06:42 -05:00
</>
2020-01-06 11:21:44 -05:00
);
};