-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryBuilder.jsx
More file actions
253 lines (234 loc) · 8.21 KB
/
QueryBuilder.jsx
File metadata and controls
253 lines (234 loc) · 8.21 KB
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
177
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import React, { useState, useContext } from 'react';
import { useHistory } from 'react-router-dom';
import Button from '@material-ui/core/Button';
import { withStyles } from '@material-ui/core';
import { blue } from '@material-ui/core/colors';
import { set as idbSet } from 'idb-keyval';
import { useAuth0 } from '@auth0/auth0-react';
import API from '~/API';
import ARAs from '~/API/services';
import QueryBuilderContext from '~/context/queryBuilder';
import AlertContext from '~/context/alert';
import queryGraphUtils from '~/utils/queryGraph';
import { defaultQuestion } from '~/utils/cache';
import usePageStatus from '~/stores/usePageStatus';
import useQueryBuilder from './useQueryBuilder';
import GraphEditor from './graphEditor/GraphEditor';
import TextEditor from './textEditor/TextEditor';
import JsonEditor from './jsonEditor/JsonEditor';
import TemplatedQueriesModal from './templatedQueries/TemplatedQueriesModal';
import DownloadDialog from '~/components/DownloadDialog';
import './queryBuilder.css';
const SubmitButton = withStyles((theme) => ({
root: {
marginLeft: 'auto',
color: theme.palette.getContrastText(blue[600]),
backgroundColor: blue[600],
'&:hover': {
backgroundColor: blue[700],
},
},
}))(Button);
/**
* Query Builder parent component
*
* Displays the text, graph, and json editors
*/
export default function QueryBuilder() {
const queryBuilder = useQueryBuilder();
const pageStatus = usePageStatus(false);
const [showJson, toggleJson] = useState(false);
const [downloadOpen, setDownloadOpen] = useState(false);
const [ara] = useState(ARAs[0]);
const displayAlert = useContext(AlertContext);
const history = useHistory();
const { isAuthenticated, getAccessTokenSilently } = useAuth0();
const [exampleQueriesOpen, setExampleQueriesOpen] = useState(false);
/**
* Submit this query directly to an ARA and then navigate to the answer page
*/
async function onQuickSubmit() {
pageStatus.setLoading('Fetching answer, this may take a while');
const prunedQueryGraph = queryGraphUtils.prune(queryBuilder.query_graph);
const response = await API.ara.getQuickAnswer(ara, { message: { query_graph: prunedQueryGraph } });
if (response.status === 'error') {
const failedToAnswer = 'Please try asking this question later.';
displayAlert('error', `${response.message}. ${failedToAnswer}`);
// go back to rendering query builder
pageStatus.setSuccess();
} else {
// stringify to stay consistent with answer page json parsing
idbSet('quick_message', JSON.stringify(response))
.then(() => {
displayAlert('success', 'Your answer is ready!');
// once message is stored, navigate to answer page to load and display
history.push('/answer');
})
.catch((err) => {
displayAlert('error', `Failed to locally store this answer. Please try again later. Error: ${err}`);
pageStatus.setSuccess();
});
}
}
/**
* Get new answer for stored question id
* @param {string} questionId - question id
* @returns {object} response
*/
async function fetchAnswer(questionId, accessToken) {
let response = await API.ara.getAnswer(ara, questionId, accessToken);
if (response.status === 'error') {
return response;
}
const answerId = response.id;
response = await API.cache.getQuestion(questionId, accessToken);
if (response.status === 'error') {
return response;
}
// Set hasAnswers in metadata to true
const questionMeta = response;
questionMeta.metadata.hasAnswers = true;
response = await API.cache.updateQuestion(questionMeta, accessToken);
if (response.status === 'error') {
return response;
}
return { status: 'success', answerId };
}
/**
* Handle user question submission
*
* - Uploads a question to Robokache
* - Fetches an answer from an ARA and stores in Robokache
* - Notifies the user when the answer is ready
*/
async function onSubmit() {
let accessToken;
if (isAuthenticated) {
try {
accessToken = await getAccessTokenSilently();
} catch (err) {
displayAlert('error', `Failed to authenticate user: ${err}`);
return;
}
}
let response;
response = await API.cache.createQuestion(defaultQuestion, accessToken);
if (response.status === 'error') {
displayAlert('error', response.message);
return;
}
const questionId = response.id;
// Strip labels from nodes
const prunedQueryGraph = queryGraphUtils.prune(queryBuilder.query_graph);
// Upload question data
const questionData = JSON.stringify({ message: { query_graph: prunedQueryGraph } }, null, 2);
response = await API.cache.setQuestionData(questionId, questionData, accessToken);
if (response.status === 'error') {
displayAlert('error', response.message);
return;
}
pageStatus.setLoading('Fetching answer, this may take a while');
// Start the process of getting an answer and display to user when done
response = await fetchAnswer(questionId, accessToken);
if (response.status === 'error') {
const failedToAnswer = 'Please try asking this question later.';
displayAlert('error', `${response.message}. ${failedToAnswer}`);
// go back to rendering query builder
pageStatus.setSuccess();
} else {
const alertText = 'Your answer is ready!';
const { answerId } = response;
// User has navigated away, display a button to go to the answer
if (history.location.pathname !== '/') {
displayAlert(
response.status,
<>
<h4>{alertText}</h4>
{answerId && (
<Button
onClick={() => history.push(`/answer/${answerId}`)}
variant="contained"
>
View Answer
</Button>
)}
</>,
);
} else {
displayAlert(response.status, alertText);
// Redirect to answer
history.push(`/answer/${answerId}`);
}
}
}
return (
<>
<pageStatus.Display />
{pageStatus.displayPage && (
<div id="queryBuilderContainer">
<div id="queryEditorContainer">
<QueryBuilderContext.Provider value={queryBuilder}>
<div style={{ flex: 1 }}>
<TextEditor
rows={queryBuilder.textEditorRows}
/>
</div>
<div>
<GraphEditor />
<div id="queryBuilderButtons">
<Button
onClick={() => setExampleQueriesOpen(true)}
variant="outlined"
>
Load Example
</Button>
<TemplatedQueriesModal
open={exampleQueriesOpen}
setOpen={setExampleQueriesOpen}
/>
<Button
onClick={() => toggleJson(true)}
variant="outlined"
>
Edit JSON
</Button>
<Button
onClick={() => setDownloadOpen(true)}
variant="outlined"
>
Download Query
</Button>
<SubmitButton
onClick={onQuickSubmit}
variant="contained"
>
Submit
</SubmitButton>
{isAuthenticated && (
<Button
onClick={onSubmit}
variant="contained"
color="primary"
>
Submit Query
</Button>
)}
</div>
</div>
<JsonEditor
show={showJson}
close={() => toggleJson(false)}
/>
<DownloadDialog
open={downloadOpen}
setOpen={setDownloadOpen}
message={queryBuilder.query_graph}
download_type="all_queries"
/>
</QueryBuilderContext.Provider>
</div>
</div>
)}
</>
);
}