-
Notifications
You must be signed in to change notification settings - Fork 3
/
DatasetSearchBox.tsx
176 lines (161 loc) · 7.04 KB
/
DatasetSearchBox.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import React from 'react';
import {RestBaseUtils, IdTextPair, Select3Utils} from 'tdp_core';
import {components, FormatOptionLabelMeta} from 'react-select';
import {AsyncPaginate} from 'react-select-async-paginate';
import Highlighter from 'react-highlight-words';
import {GeneUtils, IDataSourceConfig} from '../common';
import {IACommonListOptions} from 'tdp_gene';
interface IDatasetSearchOption {
id: any;
text: string;
invalid?: boolean;
}
interface IDatasetSearchBoxParams {
[key: string]: any;
}
interface IDatasetSearchBoxProps {
placeholder: string;
dataSource: IDataSourceConfig;
onSaveAsNamedSet: (items: IdTextPair[]) => void;
onOpen: (event: React.MouseEvent<HTMLElement>, search: Partial<IACommonListOptions>) => void;
/**
* Extra parameters when querying the options of the searchbox,
*/
params?: IDatasetSearchBoxParams;
tokenSeparators?: RegExp;
}
export function DatasetSearchBox({placeholder, dataSource, onOpen, onSaveAsNamedSet, params = {}, tokenSeparators = /[\s;,]+/gm}: IDatasetSearchBoxProps) {
const [items, setItems] = React.useState<IDatasetSearchOption[]>([]);
const [inputValue, setInputValue] = React.useState('');
const loadOptions = async (query: string, _, {page}: {page: number}) => {
const {db, base, dbViewSuffix, entityName} = dataSource;
return RestBaseUtils.getTDPLookup(db, base + dbViewSuffix, {
column: entityName,
...params,
query,
page,
limit: 10
}).then(({items, more}) => ({
options: items,
hasMore: more,
additional: {
page: page + 1
}
}));
};
const formatOptionLabel = (option: IDatasetSearchOption, ctx: FormatOptionLabelMeta<IDatasetSearchOption, true>) => {
// do not highlight selected elements
if (ctx.selectValue?.some((o) => o.id === option.id)) {
return option.text;
}
return (
<>
<Highlighter
searchWords={[ctx.inputValue]}
autoEscape={true}
textToHighlight={option.text}
/>
{option.text !== option.id &&
<span className="small text-muted ms-1">{option.id}</span>}
</>
);
};
React.useEffect(() => {
setInputValue('');
}, [items]);
const onPaste = async (event: React.ClipboardEvent) => {
const pastedData = event.clipboardData.getData('text')?.toLocaleLowerCase();
const splitData = Select3Utils.splitEscaped(pastedData, tokenSeparators, false).map((d) => d.trim()).filter((d) => d !== '');
const validData = await GeneUtils.validateGeneric(dataSource, splitData);
const invalidData = splitData
.filter((s) => !validData.length || validData.every((o) => o.id.toLocaleLowerCase() !== s.toLocaleLowerCase() && o.text.toLocaleLowerCase() !== s.toLocaleLowerCase()))
.map((s) => ({id: s, text: s, invalid: true}));
setItems([...validData, ...invalidData]);
};
const validItems = items?.filter((i) => !i.invalid);
const searchResults = {
search: {
ids: validItems.map((i) => i.id),
type: dataSource.tableName
}
};
return (
<div className="hstack gap-3 ordino-dataset-searchbox" data-testid="ordino-dataset-searchbox">
<AsyncPaginate
className="flex-fill"
onPaste={onPaste}
placeholder={placeholder}
noOptionsMessage={() => 'No results found'}
isMulti={true}
loadOptions={loadOptions}
inputValue={inputValue}
value={items}
onChange={setItems}
onInputChange={setInputValue}
formatOptionLabel={formatOptionLabel}
hideSelectedOptions
getOptionLabel={(option) => option.text}
getOptionValue={(option) => option.id}
captureMenuScroll={false}
additional={{
page: 0 // page starts from index 0
}}
components={{Input}}
styles={{
multiValue: (styles, {data}) => ({
...styles,
border: `1px solid #CCC`,
borderRadius: '3px'
}),
multiValueLabel: (styles, {data}) => ({
...styles,
textDecoration: data.invalid ? 'line-through' : 'none',
color: data.color,
backgroundColor: 'white',
order: 2,
paddingLeft: '0',
paddingRight: '6px'
}),
multiValueRemove: (styles, {data}) => ({
...styles,
color: data.invalid ? 'red' : '#999',
backgroundColor: 'white',
order: 1,
':hover': {
color: '#333',
cursor: 'pointer'
},
}),
placeholder: (provided) => ({
...provided,
// disable placeholder mouse events
pointerEvents: 'none',
userSelect: 'none',
}),
input: (css) => ({
...css,
//expand the Input Component div
flex: '1 1 auto',
// expand the Input Component child div
'> div': {
width: '100%'
},
// expand the Input Component input
input: {
width: '100% !important',
textAlign: 'left'
}
})
}}
/>
<button className="btn btn-secondary" data-testid="open-button" disabled={!validItems?.length} onClick={(event) => onOpen(event, searchResults)}>Open</button>
<button className="btn btn-outline-secondary" data-testid="save-button" disabled={!validItems?.length} onClick={() => onSaveAsNamedSet(validItems)}>Save as set</button>
</div>
);
}
function Input(props: any) {
const {onPaste} = props.selectProps;
const modifiedProps = Object.assign({'data-testid': 'async-paginate-input-component'}, props);
delete modifiedProps.popoverType; // remove the "illegal" prop from the copy
return (<components.Input onPaste={onPaste} { ...modifiedProps } />);
}