Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autocomplete - Allow creation of new entries #1905

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,12 @@ import SelectInfiniteScroll from '@js/components/SelectInfiniteScroll/SelectInfi

const Autocomplete = ({
className,
clearable = false,
id,
labelKey,
multi = false,
name,
title,
value,
valueKey,
placeholder,
onChange,
onLoadOptions,
...props
}) => {
const getValue = () => {
Expand All @@ -39,36 +34,37 @@ const Autocomplete = ({
}
return value;
};

const defaultNewOptionCreator = (option) => ({
[valueKey]: option.label,
[labelKey]: option.label
});

return (
<div className={`autocomplete${className ? " " + className : ""}`}>
<label className="control-label" htmlFor={id}>{title || name}</label>
<SelectInfiniteScroll
{...props}
id={id}
value={getValue()}
multi={multi}
clearable={clearable}
placeholder={placeholder}
loadOptions={onLoadOptions}
onChange={onChange}
valueKey={valueKey}
labelKey={labelKey}
{...props.creatable && {
newOptionCreator: props.newOptionCreator ?? defaultNewOptionCreator
}}
/>
</div>
);
};

Autocomplete.propTypes = {
className: PropTypes.string,
clearable: PropTypes.bool,
id: PropTypes.string.isRequired,
labelKey: PropTypes.string,
multi: PropTypes.bool,
name: PropTypes.string,
title: PropTypes.string,
value: PropTypes.any.isRequired,
valueKey: PropTypes.string,
placeholder: PropTypes.string,
onChange: PropTypes.func.isRequired,
onLoadOptions: PropTypes.func.isRequired
valueKey: PropTypes.string
};

export default Autocomplete;
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import React, { useRef, useState, useEffect } from 'react';
import axios from '@mapstore/framework/libs/ajax';
import debounce from 'lodash/debounce';
import isEmpty from 'lodash/isEmpty';
import ReactSelect from 'react-select';
import localizedProps from '@mapstore/framework/components/misc/enhancers/localizedProps';

Expand All @@ -18,6 +19,9 @@ function SelectInfiniteScroll({
loadOptions,
pageSize = 20,
debounceTime = 500,
labelKey,
valueKey,
newOptionPromptText = "Create option",
...props
}) {

Expand All @@ -40,6 +44,23 @@ function SelectInfiniteScroll({
source.current = cancelToken.source();
};

const updateNewOption = (newOptions, query) => {
if (props.creatable && !isEmpty(query)) {
const isValueExist = props.value?.some(v => v[labelKey] === query);
const isOptionExist = newOptions.some((o) => o[labelKey] === query);

// Add new option if it doesn't exist and `creatable` is enabled
if (!isValueExist && !isOptionExist) {
return [{
[labelKey]: `${newOptionPromptText} "${query}"`, value: query,
result: { [valueKey]: query, [labelKey]: query }
}].concat(newOptions);
}
return newOptions;
}
return newOptions;
};

const handleUpdateOptions = useRef();
handleUpdateOptions.current = (args = {}) => {
createToken();
Expand All @@ -56,8 +77,10 @@ function SelectInfiniteScroll({
}
})
.then((response) => {
const newOptions = response.results.map(({ selectOption }) => selectOption);
setOptions(newPage === 1 ? newOptions : [...options, ...newOptions]);
let newOptions = response.results.map(({ selectOption }) => selectOption);
newOptions = newPage === 1 ? newOptions : [...options, ...newOptions];
newOptions = updateNewOption(newOptions, query);
setOptions(newOptions);
setIsNextPageAvailable(response.isNextPageAvailable);
setLoading(false);
source.current = undefined;
Expand Down Expand Up @@ -89,7 +112,7 @@ function SelectInfiniteScroll({
handleUpdateOptions.current({ q: value, page: 1 });
}
}, debounceTime);
}, []);
}, [text]);

useEffect(() => {
if (open) {
Expand All @@ -106,16 +129,21 @@ function SelectInfiniteScroll({
}
}, [page]);

const filterOptions = (currentOptions) => {
return currentOptions.map(option=> {
const match = /\"(.*?)\"/.exec(text);
return match ? match[1] : option;
});
};

return (
<SelectSync
{...props}
isLoading={loading}
options={options}
onOpen={() => setOpen(true)}
onClose={() => setOpen(false)}
filterOptions={(currentOptions) => {
return currentOptions;
}}
filterOptions={filterOptions}
onInputChange={(q) => handleInputChange(q)}
onMenuScrollToBottom={() => {
if (!loading && isNextPageAvailable) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,20 @@ const SchemaField = (props) => {
const valueKey = autocompleteOptions?.valueKey || 'id';
const labelKey = autocompleteOptions?.labelKey || 'label';
const placeholder = autocompleteOptions?.placeholder ?? '...';
const creatable = !!autocompleteOptions?.creatable;

let autoCompleteProps = {
className: "form-group gn-metadata-autocomplete",
clearable: !isMultiSelect,
creatable,
id: idSchema.$id,
labelKey,
multi: isMultiSelect,
name,
placeholder,
title: schema.title,
value: formData,
valueKey,
labelKey,
placeholder,
multi: isMultiSelect,
clearable: !isMultiSelect,
onChange: (selected) => {
let _selected = selected?.result ?? null;
if (isMultiSelect) {
Expand All @@ -67,39 +70,34 @@ const SchemaField = (props) => {
});
}
onChange(_selected);
},
loadOptions: ({ q, config, ...params }) => {
return axios.get(autocompleteUrl, {
...config,
params: {
...params,
...(q && { [queryKey]: q }),
page: params.page
}
})
.then(({ data }) => {
return {
isNextPageAvailable: !!data.pagination?.more,
results: data?.[resultsKey].map((result) => {
return {
selectOption: {
result,
value: result[valueKey],
label: result[labelKey]
}
};
})
};
});
}
};

return (
<Autocomplete
{...autoCompleteProps}
className={"form-group gn-metadata-autocomplete"}
onLoadOptions={({ q, config, ...params }) => {
return axios.get(autocompleteUrl, {
...config,
params: {
...params,
...(q && { [queryKey]: q }),
page: params.page
}
})
.then(({ data }) => {
return {
isNextPageAvailable: !!data.pagination?.more,
results: data?.[resultsKey].map((result) => {
return {
selectOption: {
result,
value: result[valueKey],
label: result[labelKey]
}
};
})
};
});
}}
/>
);
return <Autocomplete {...autoCompleteProps}/>;
}
return <DefaultSchemaField {...props}/>;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@
padding: 0.75rem;
border: 1px solid transparent;
border-radius: 8px;
margin: 0.75rem;
}
legend {
font-weight: bold;
Expand Down