InsertObjectModal.jsx 10.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// @flow
import * as React from 'react';
import {
	Container,
	Row,
	Col,
	TabContent, TabPane,
	Alert,
	Badge,
	Modal, ModalBody, ModalHeader, ModalFooter,
	Table,
	Input,
	Button,
	ButtonGroup,
	FormGroup,
	ListGroup,
	ListGroupItem,
} from 'reactstrap';

import type { FlattenedDatabaseEntry } from '@store/selectors';

22
import type { ConnectionType } from '@helpers/toolchainTypes';
23
24
25
26
27
28
import type { Protocol, Set as ProtocolSet } from '../database/DatabaseEditor.jsx';
import type { BeatObject } from '@helpers/beat';
import { generateNewKey } from '@helpers';

import SearchWorker from '@helpers/search.worker.js';

29
type ObjectTypeOption = 'toolchains' | 'protocols' | 'sets' | 'normalAlgorithms' | 'analyzerAlgorithms';
30
31
32
33
34
35
36
37
38
39

type Props = {
	// func to close modal
	toggle: () => any,
	// is the modal active?
	active: boolean,
	// user selected a search result
	addNewBlocks: (type: ObjectTypeOption, newBlocksData: any[], newConnections?: ConnectionType[]) => any,
	// all toolchains
	toolchains: BeatObject[],
40
41
42
	// all database protocols
	protocols: BeatObject[],
	// sets of protocols of protocols
43
44
45
46
47
48
49
50
	sets: FlattenedDatabaseEntry[],
	// algorithms for normal blocks (inputs & outputs)
	normalAlgorithms: BeatObject[],
	// algorithms for analyzer blocks (inputs & results)
	analyzerAlgorithms: BeatObject[],
	usedNames: string[],
};

51
52
type Res = BeatObject[] | FlattenedDatabaseEntry[] | any;

53
type State = {
54
	searchResults: ?Res,
55
56
57
	searchFilter: ObjectTypeOption,
};

58
const options: ObjectTypeOption[] = ['toolchains', 'protocols', 'sets', 'normalAlgorithms', 'analyzerAlgorithms'];
59
60
const optionText = {
	toolchains: 'Toolchain',
61
	protocols: 'Protocol',
62
63
64
65
66
67
68
69
70
71
72
	sets: 'Dataset',
	normalAlgorithms: 'Block Algorithm',
	analyzerAlgorithms: 'Analyzer Algorithm',
};

class InsertObjectModal extends React.PureComponent<Props, State> {
	constructor(props: Props){
		super(props);
	}

	state = {
73
		searchResults: this.props[options[0]],
74
75
76
77
78
79
80
81
82
83
84
85
86
		searchFilter: options[0],
	}

	searchWorker = null;

	componentDidMount = () => {
		this.searchWorker = new SearchWorker();
		this.searchWorker.onmessage = (m) => {
			this.setState(prevState => ({ searchResults: m.data }));
		};
		this.updateFuseInstance();
	}

87
88
89
90
	componentDidUpdate = (prevProps: Props) => {
		if(this.props[this.state.searchFilter] !== prevProps[this.state.searchFilter]){
			this.updateFuseInstance(this.props[this.state.searchFilter]);
		}
91
92
93
94
95
	}

	updateFuseInstance = (data: any[] = this.props[this.state.searchFilter]) => {
		if(!this.searchWorker)
			throw new Error(`searchWorker is not instantiated!`);
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
		this.searchWorker.postMessage(
			{
				type: 'dataChanged',
				payload: {
					data,
					options: {
						shouldSort: true,
						threshold: 0.6,
						location: 0,
						distance: 100,
						maxPatternLength: 32,
						minMatchCharLength: 1,
						keys: Object.keys(data.length > 0 ? data[0] : {}),
					}
				}
			}
		);
	}

	search = (str: string) => {
		if(!this.searchWorker)
			throw new Error(`searchWorker is not instantiated!`);
		this.searchWorker.postMessage(
			{
				type: 'search',
				payload: str
			}
		);
	}

	updateSearchFilter = (filter: ObjectTypeOption) => {
128
129
130
131
		this.setState(prevState => ({
			searchFilter: filter,
			searchResults:this.props[filter],
		}));
132
133
134
		this.updateFuseInstance(this.props[filter]);
	}

135
	stringifyResult = (obj: any, type: ObjectTypeOption): string => {
136
137
		if(!obj)
			return '';
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
		switch(type){
			case 'toolchains':
				// tc obj
				return `datasets: ${ obj.contents.datasets.length }, blocks: ${ obj.contents.blocks.length }`;
			case 'protocols':
				// protocol obj w "database" field for db name
				return `sets: ${ obj.sets.length }`;
			case 'sets':
				// set w protocol & db
				return `outputs: ${ Object.keys(obj.outputs).length }`;
			case 'normalAlgorithms':
				// alg obj
				return `inputs: ${
					obj.contents.groups.reduce((iNum, g) => g.inputs ? iNum + Object.keys(g.inputs).length : iNum, 0)
				}, outputs: ${
					obj.contents.groups.reduce((iNum, g) => g.outputs ? iNum + Object.keys(g.outputs).length : iNum, 0)
				}`;
			case 'analyzerAlgorithms':
				// alg obj
				return `inputs: ${
					obj.contents.groups.reduce((iNum, g) => g.inputs ? iNum + Object.keys(g.inputs).length : iNum, 0)
				}`;
			default:
				return obj.name;
		}
	}

	stringifyResultName = (obj: any) => {
		if(!obj)
			return '';
		if(obj.set)
			return `${ obj.protocol }/${ obj.set } (${ obj.database })`;
		if(obj.database)
171
			return `${ obj.name } (${ obj.database })`;
172
173
		if(obj.name)
			return obj.name;
174
		return 'undefined';
175
176
	}

177
	generateNewBlockData = (obj: any): {blocks: any[], connections: ConnectionType[]} | any[] => {
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
		const copiedObj = JSON.parse(JSON.stringify(obj));
		const usedNames = this.props.usedNames;
		const type = this.state.searchFilter;
		switch(type){
			case 'toolchains':
				const rep = copiedObj.contents.representation.blocks;
				// add blocks/connections from a toolchain
				// map all the blocks to new data to give to addBlocks()
				const newBlocksData = [
					...copiedObj.contents.datasets
					.map((blk) => ([generateNewKey(blk.name, usedNames), 'datasets', rep[blk.name].col, rep[blk.name].row, blk])),
					...copiedObj.contents.blocks
					.map((blk) => ([generateNewKey(blk.name, usedNames), 'blocks', rep[blk.name].col, rep[blk.name].row, blk])),
					...copiedObj.contents.analyzers
					.map((blk) => ([generateNewKey(blk.name, usedNames), 'analyzers', rep[blk.name].col, rep[blk.name].row, blk])),
				];

				const nameMap = {};
				for(const b of newBlocksData){
					nameMap[b[4].name] = b[0];
					if(b[1] === 'blocks' || b[1] === 'analyzers')
						b[4].synchronized_channel = nameMap[b[4].synchronized_channel];
				}

				const connections = copiedObj.contents.connections
				.map(({ from, to, channel }) => {
					const fromSplit = from.split('.');
					const toSplit = to.split('.');
					return {
						from: `${ nameMap[fromSplit[0]] }.${ fromSplit[1] }`,
						to: `${ nameMap[toSplit[0]] }.${ toSplit[1] }`,
						channel: nameMap[channel],
					};
				});

				// reset the locations of all these blocks - make sure that the point (0,0) is at the top-left of the toolchain
				const minX = Math.min(...newBlocksData.map(d => d[2]));
				const minY = Math.min(...newBlocksData.map(d => d[3]));
				for(const b of newBlocksData){
					b[2] -= minX;
					b[3] -= minY;
					b[4].name = b[0];
				}

				return {
					blocks: newBlocksData,
					connections,
				};
226
			case 'protocols':
227
				// add a block for each set in each protocol in the database
228
229
230
231
232
233
				const newBlocks = obj.sets
				// compile basic info for the set (the new name & the outputs for the block)
				.map((set, i) => ({
					name: generateNewKey(`${ obj.name }_${ set.name }`, usedNames),
					outputs: Object.keys(set.outputs),
				}))
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
				// convert the set's basic info into data arrs for addBlocks()
				.map((setData, i) => [setData.name, 'datasets', 0, 0, { outputs: setData.outputs }]);

				// shift the y coord of each new block down according to the # of outputs
				// accumulate this change so the blocks will all be x-aligned with 1 row between them
				let yCount = 0;
				for(const i in newBlocks){
					newBlocks[i][3] = yCount;
					yCount += newBlocks[i][4].outputs.length + 3;
				}

				return newBlocks;
			case 'sets':
				// add from database's protocol's set
				const setBlock = [
					generateNewKey(`${ obj.protocol }_${ obj.set }`, usedNames),
					'datasets',
					0,
					0,
					{ outputs: Object.keys(obj.outputs) }
				];

				return [setBlock];
			case 'normalAlgorithms':
				// create a block compatible with the alg
				const normalBlock = [
					generateNewKey(obj.name.replace(/\//g, '_'), usedNames),
					'blocks',
					0,
					0,
					{
						outputs: Object.keys(obj.contents.groups[0].outputs),
						inputs: obj.contents.groups
						.map(g => Object.keys(g.inputs))
268
269
						.reduce((arr, is) => [...arr, ...is], []),
						synchronized_channel: '',
270
271
272
273
274
275
276
277
278
279
280
281
282
283
					}
				];

				return [normalBlock];
			case 'analyzerAlgorithms':
				// create a block compatible with the alg
				const analyzerBlock = [
					generateNewKey(obj.name.replace(/\//g, '_'), usedNames),
					'analyzers',
					0,
					0,
					{
						inputs: obj.contents.groups
						.map(g => Object.keys(g.inputs))
284
285
						.reduce((arr, is) => [...arr, ...is], []),
						synchronized_channel: '',
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
					}
				];

				return [analyzerBlock];
			default:
				return [];
		}
	}

	render = () => {
		return (
			<Modal
				size='lg'
				isOpen={this.props.active}
				toggle={this.props.toggle}
				fade={true}
				onOpened={e => {
					/*
					const f = document.querySelector('#tcModalInitFocus');
					if(f && f.focus)
						f.focus();
						*/
				}}
			>
				<ModalHeader toggle={this.props.toggle}>
					Insert blocks from an existing object
				</ModalHeader>
				<ModalBody>
					<FormGroup row>
						<Col>
						</Col>
						<Col sm='auto'>
							<ButtonGroup>
								{
									options.map((o, i) => {
										const isCurrentOption = this.state.searchFilter === o;
										return (
											<Button
												key={i}
												onClick={e => this.updateSearchFilter(o)}
												color={isCurrentOption ? 'primary' : 'secondary'}
											>
												{ optionText[o] }
											</Button>
										);
									})
								}

							</ButtonGroup>
						</Col>
						<Col>
						</Col>
					</FormGroup>
					<FormGroup row>
						<Col sm={12}>
							<Input
								type='text'
								placeholder='Search...'
								onChange={e => this.search(e.target.value)}
								autoFocus
							/>
						</Col>
					</FormGroup>
					<FormGroup row>
						<Col sm={12}>
							<ListGroup className='searchResults'>
								{
									this.state.searchResults &&
										this.state.searchResults.map((res, i) =>
											<ListGroupItem
												key={i}
												tag='button'
												action
												onClick={e => {
													const newData = this.generateNewBlockData(res);
													if(Array.isArray(newData))
														this.props.addNewBlocks(
															this.state.searchFilter,
															newData,
														);
													else
														this.props.addNewBlocks(
															this.state.searchFilter,
															newData.blocks,
															newData.connections,
														);
													this.props.toggle();
												}}
											>
375
376
377
378
379
												{ this.stringifyResultName(res) }
												{' '}
												<small className='text-muted'>
													{ this.stringifyResult(res, this.state.searchFilter) }
												</small>
380
381
382
383
384
385
386
387
388
389
390
391
											</ListGroupItem>
										)
								}
							</ListGroup>
						</Col>
					</FormGroup>
				</ModalBody>
			</Modal>
		);
	}
}

392
export default InsertObjectModal;