-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery_form.js
217 lines (196 loc) · 7.18 KB
/
query_form.js
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
/* global queryStructure */
(function () {
function fetchCSRFToken() {
return fetch('/csrf_token')
.then((response) =>
response.ok ? response.json() : { csrf_token: null }
)
.then((responseJson) => responseJson && responseJson.csrf_token)
.catch((err) => {
console.error('Failed to fetch CSRF token: ', err);
});
}
function createOptionElement(text, value = text) {
const element = document.createElement('option');
return Object.assign(element, { text, value });
}
function getSourceDestinationMapForDatatype(datatype) {
return queryStructure && queryStructure[datatype.replace(/_/g, ' ')];
}
function getAvailableSourcesForDatatype(datatype) {
const map = getSourceDestinationMapForDatatype(datatype);
return map && Object.keys(map);
}
function getAvailableDestinationsForSource({ datatype, source }) {
const map = getSourceDestinationMapForDatatype(datatype);
return map && map[source];
}
function safelySetSessionStorageItem(key, item) {
try {
sessionStorage.setItem(key, item);
} catch (e) {
console.error('Failed to set sessionStorage item', e);
}
}
function safelyGetSessionStorageItem(key) {
try {
return sessionStorage.getItem(key);
} catch (e) {
console.error('Failed to get sessionStorage item', e);
return null;
}
}
// query_form.js handles populating the query form dropdowns on index.html,
// as well as saving form state to session storage to smooth the user experience.
// Dropdowns are filled based on selections so far, rather than show all options
// some of which are invalid for the content type chosen.
function createDropdownValuesSetter({
dropdownElement,
placeholder = 'Select an option',
}) {
return function setDropdownValues(possibleValues) {
dropdownElement.innerHTML = '';
const uniqueValues = Array.from(new Set(possibleValues));
const optionElements = [createOptionElement(placeholder, '')].concat(
uniqueValues.map((value) => createOptionElement(value))
);
dropdownElement.append(...optionElements);
dropdownElement.disabled = uniqueValues.length === 0;
};
}
document.addEventListener('DOMContentLoaded', function () {
const hidden_form_items =
document.getElementsByClassName('formstarthidden');
for (let item of hidden_form_items) {
item.style.display = 'none';
}
const query_form = document.forms['query_form'];
const sourceDropdown = document.getElementById('id_datasource');
const destDropdown = document.getElementById('id_datadest');
const submitButton = document.getElementById('query-form-submit-button');
const setSourceValues = createDropdownValuesSetter({
dropdownElement: sourceDropdown,
placeholder: 'Select a source',
});
const setDestinationValues = createDropdownValuesSetter({
dropdownElement: destDropdown,
placeholder: 'Select a destination',
});
function getSelectedDatatype() {
const selectedRadioItem = query_form.querySelector(
'input[name="datatype"]:checked'
);
return selectedRadioItem && selectedRadioItem.value;
}
if (!(sourceDropdown && destDropdown)) {
console.error(
'Missing expected form elements - id_datasource and id_datadest'
);
return;
}
function populateSourceListForDatatype(datatype) {
for (let item of hidden_form_items) {
item.style.display = 'block';
}
setSourceValues(getAvailableSourcesForDatatype(datatype));
setDestinationValues([]);
submitButton.removeAttribute('disabled');
}
function populateDestinationListForSource(source) {
setDestinationValues(
getAvailableDestinationsForSource({
datatype: getSelectedDatatype(),
source,
})
);
}
function restoreFormState(datatype) {
const typeRadioItem = query_form.querySelector(
`input[value=${datatype}]`
);
if (!typeRadioItem) {
return;
}
typeRadioItem.checked = true;
populateSourceListForDatatype(datatype);
const storedSource = safelyGetSessionStorageItem('selectedSource');
if (!storedSource) {
return;
}
const sources = getAvailableSourcesForDatatype(datatype);
if (!sources.includes(storedSource)) {
// The stored source doesn't match what's available for this datatype
return;
}
sourceDropdown.value = storedSource;
populateDestinationListForSource(storedSource);
const storedDest = safelyGetSessionStorageItem('selectedDest');
if (!storedDest) {
return;
}
const destinations = getAvailableDestinationsForSource({
datatype,
source: storedSource,
});
if (destinations.includes(storedDest)) {
destDropdown.value = storedDest;
}
}
// If there's a data type already selected (like after a refresh),
// populate the dropdowns
let lastDatatype =
getSelectedDatatype() || safelyGetSessionStorageItem('selectedType');
if (lastDatatype) {
restoreFormState(lastDatatype);
}
// Add an event listener so that when the content type is chosen, a list of known sources is populated
// for the next step
query_form.addEventListener('change', function () {
const newDatatype = getSelectedDatatype();
if (newDatatype !== null && newDatatype !== lastDatatype) {
lastDatatype = newDatatype;
populateSourceListForDatatype(newDatatype);
safelySetSessionStorageItem('selectedType', newDatatype);
sourceDropdown.scrollIntoView({ behavior: 'smooth' });
}
});
// Then when the source for data is chosen, a list of destinations
sourceDropdown.addEventListener('change', function () {
populateDestinationListForSource(sourceDropdown.value);
safelySetSessionStorageItem('selectedSource', sourceDropdown.value);
});
destDropdown.addEventListener('change', function () {
safelySetSessionStorageItem('selectedDest', destDropdown.value);
});
const askForArticle = document.getElementById('askforarticle');
askForArticle.style.display = 'none';
const didNotFind = document.getElementById('didnotfind');
didNotFind.addEventListener('click', function () {
didNotFind.remove();
askForArticle.style.display = 'inline';
});
// When this page is statically generated, a CSRF token won't be provided.
// In that case, we fetch one and insert it ourselves.
const feedbackForm = document.getElementById(
'multiple_option_feedback_form'
);
const hasCSRFToken = Boolean(
feedbackForm.querySelector('input[name=csrfmiddlewaretoken]')
);
if (!hasCSRFToken) {
fetchCSRFToken().then((token) => {
if (!token) {
return;
}
const tokenInputElement = document.createElement('input');
tokenInputElement.type = 'hidden';
tokenInputElement.name = 'csrfmiddlewaretoken';
tokenInputElement.value = token;
feedbackForm.prepend(tokenInputElement);
document
.getElementById('usecase_submit_button')
.removeAttribute('disabled');
});
}
});
})();