-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathexplorer.js
More file actions
413 lines (348 loc) · 14.2 KB
/
explorer.js
File metadata and controls
413 lines (348 loc) · 14.2 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import $ from 'jquery';
import { EditorView } from "codemirror";
import { explorerSetup } from "./codemirror-config";
import { setUpAssistant } from "./assistant";
import cookie from 'cookiejs';
import List from 'list.js'
import { getCsrfToken } from "./csrf";
import { toggleFavorite } from "./favorites";
import {schemaCompletionSource, StandardSQL} from "@codemirror/lang-sql";
import {StateEffect} from "@codemirror/state";
import {getConnElement, SchemaSvc} from "./schemaService";
function updateSchema() {
SchemaSvc.get().then(schema => {
window.editor.dispatch({
effects: StateEffect.appendConfig.of(
StandardSQL.language.data.of({
autocomplete: schemaCompletionSource({schema: schema})
})
)
});
});
$("#schema_frame").attr("src", `${window.baseUrlPath}schema/${getConnElement().value}`);
}
function editorFromTextArea(textarea) {
let view = new EditorView({
doc: textarea.value,
extensions: [
explorerSetup,
]})
textarea.parentNode.insertBefore(view.dom, textarea)
textarea.style.display = "none"
if (textarea.form) textarea.form.addEventListener("submit", () => {
textarea.value = view.state.doc.toString()
})
return view
}
function selectConnection() {
var urlParams = new URLSearchParams(window.location.search);
var connectionId = urlParams.get('connection');
if (connectionId) {
var connectionSelect = document.getElementById('id_database_connection');
if (connectionSelect) {
connectionSelect.value = connectionId;
}
}
}
function downloadCSVFromTable() {
var table = document.getElementById("preview");
var rows = table.querySelectorAll("tr");
var csv = [];
rows.forEach(function (row) {
var cols = row.querySelectorAll("td, th");
var rowData = [];
cols.forEach(function (col) {
rowData.push(col.innerText);
});
csv.push(rowData.join(","));
});
var csvFile = new Blob([csv.join("\n")], { type: "text/csv" });
var downloadLink = document.createElement("a");
downloadLink.href = URL.createObjectURL(csvFile);
downloadLink.download = "preview.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
export class ExplorerEditor {
constructor(queryId) {
selectConnection();
const aa = document.getElementById('assistant_accordion');
const pa = document.getElementById('nav-preview');
if (aa) {
// Expand the assistant only if a new query is being created
// and no results are yet being shown
const expand = !pa && queryId === 'new';
setUpAssistant(expand);
}
this.queryId = queryId;
this.$rows = $("#rows");
this.$form = $("form");
this.$snapshotField = $("#id_snapshot");
this.docChanged = false;
this.$submit = $("#refresh_play_button, #save_button");
if (!this.$submit.length) {
this.$submit = $("#refresh_button");
}
this.editor = editorFromTextArea(document.getElementById("id_sql"));
window.editor = this.editor;
document.addEventListener('submitEventFromCM', (e) => {
this.$submit.click();
});
document.addEventListener('formatEventFromCM', (e) => {
this.formatSql();
});
document.addEventListener('docChanged', (e) => {
this.docChanged = true;
});
this.bind();
if (cookie.get("schema_sidebar_open") === 'true') {
this.toggleSchema(true, true);
}
}
getParams() {
let o = false;
const params = document.querySelectorAll("form .param");
if (params.length) {
o = {};
params.forEach((param) => {
o[param.dataset.param] = param.value;
});
}
return o;
}
serializeParams(params) {
var args = [];
for(var key in params) {
args.push(key + ":" + params[key]);
}
return encodeURIComponent(args.join("|"));
}
updateQueryString(key, value, url) {
// http://stackoverflow.com/a/11654596/221390
if (!url) url = window.location.href;
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
hash = url.split("#");
if (re.test(url)) {
if (typeof value !== "undefined" && value !== null)
return url.replace(re, "$1" + key + "=" + value + "$2$3");
else {
url = hash[0].replace(re, "$1$3").replace(/(&|\?)$/, "");
if (typeof hash[1] !== "undefined" && hash[1] !== null)
url += "#" + hash[1];
return url;
}
}
else {
if (typeof value !== "undefined" && value !== null) {
var separator = url.indexOf("?") !== -1 ? "&" : "?";
url = hash[0] + separator + key + "=" + value;
if (typeof hash[1] !== "undefined" && hash[1] !== null)
url += "#" + hash[1];
return url;
}
else
return url;
}
}
formatSql() {
let sqlText = this.editor.state.doc.toString();
let editor = this.editor;
var formData = new FormData();
formData.append('sql', sqlText); // Append the SQL text to the form data
// Make the fetch call
fetch(`${window.baseUrlPath}format/`, {
method: "POST",
headers: {
// 'Content-Type': 'application/x-www-form-urlencoded', // Not needed when using FormData, as the browser sets it along with the boundary
'X-CSRFToken': getCsrfToken()
},
body: formData // Use the FormData object as the body
})
.then(response => response.json()) // Parse the JSON response
.then(data => {
editor.dispatch({
changes: {
from: 0,
to: editor.state.doc.length,
insert: data.formatted
}
});
})
.catch(error => console.error('Error:', error));
}
showRows() {
let rows = document.getElementById("rows").value;
let form = document.getElementById("editor");
form.setAttribute("action", this.updateQueryString("rows", rows, window.location.href));
form.submit();
}
toggleSchema(noAutofocus, doShow) {
var schema = document.getElementById("schema");
var queryArea = document.getElementById("query_area");
var toggleBtn = document.getElementById("toggle_schema_button");
if (doShow || schema.style.display === "none" || schema.style.display === "") { // show
if (noAutofocus === true) {
schema.classList.add("no-autofocus");
}
queryArea.classList.remove("col");
queryArea.classList.add("col-9");
schema.classList.add("col-md-3");
schema.style.display = "block";
toggleBtn.innerHTML = "Hide Schema";
cookie.set("schema_sidebar_open", 'true');
} else { // hide
queryArea.classList.remove("col-9");
queryArea.classList.add("col");
schema.classList.remove("col-md-3");
schema.style.display = "none";
toggleBtn.innerHTML = "Show Schema";
cookie.set("schema_sidebar_open", 'false');
}
return false;
}
handleBeforeUnload = (event) => {
if (clientRoute === 'query_detail' && this.docChanged) {
const confirmationMessage = "You have unsaved changes to your query.";
event.returnValue = confirmationMessage;
return confirmationMessage;
}
};
bind() {
window.addEventListener("beforeunload", this.handleBeforeUnload)
document.addEventListener("submit", (event) => {
// Disable unsaved changes warning when submitting the editor form
if (event.target.id === "editor") {
window.removeEventListener("beforeunload", this.handleBeforeUnload);
}
})
document.querySelectorAll('.query_favorite_toggle').forEach(function(element) {
element.addEventListener('click', toggleFavorite);
});
document.getElementById('toggle_schema_button')?.addEventListener('click', this.toggleSchema.bind(this));
document.getElementById('preview-download')?.addEventListener('click', downloadCSVFromTable)
$("#format_button").click(function(e) {
e.preventDefault();
this.formatSql();
}.bind(this));
$("#rows").keyup(function() {
var curUrl = $("#fullscreen").attr("href");
var newUrl = curUrl.replace(/rows=\d+/, "rows=" + $("#rows").val());
$("#fullscreen").attr("href", newUrl);
}.bind(this));
$("#save_button").click(function() {
var params = this.getParams(this);
if(params) {
this.$form.attr("action", "../" + this.queryId + "/?params=" + this.serializeParams(params));
}
this.$snapshotField.hide();
this.$form.append(this.$snapshotField);
}.bind(this));
$("#save_only_button").click(function() {
console.log("here");
var params = this.getParams(this);
if(params) {
this.$form.attr('action', '../' + this.queryId + '/?show=0¶ms=' + this.serializeParams(params));
} else {
this.$form.attr('action', '../' + this.queryId + '/?show=0');
}
this.$snapshotField.hide();
this.$form.append(this.$snapshotField);
}.bind(this));
$("#refresh_button").click(function(e) {
e.preventDefault();
var params = this.getParams();
if(params) {
window.location.href = "../" + this.queryId + "/?params=" + this.serializeParams(params);
} else {
window.location.href = "../" + this.queryId + "/";
}
}.bind(this));
$("#refresh_play_button").click(function() {
this.$form.attr("action", "../play/");
}.bind(this));
$("#playground_button").click(function(e) {
e.preventDefault();
this.$form.attr("action", "../play/?show=0");
this.$form.submit();
}.bind(this));
$("#create_button").click(function() {
this.$form.attr("action", "../new/");
}.bind(this));
$(".download-button").click(function(e) {
var url = "../download?format=" + $(e.target).data("format");
var params = this.getParams();
if(params) {
url = url + "¶ms=" + params;
}
this.$form.attr("action", url);
}.bind(this));
$(".download-query-button").click(function(e) {
var url = "../download?format=" + $(e.target).data("format");
var params = this.getParams();
if(params) {
url = url + "¶ms=" + params;
}
this.$form.attr("action", url);
}.bind(this));
document.querySelectorAll('.stats-expand').forEach(element => {
element.addEventListener('click', function(e) {
e.preventDefault();
document.querySelectorAll('.stats-expand').forEach(el => el.style.display = 'none');
document.querySelectorAll('.stats-wrapper').forEach(el => el.style.display = '');
});
});
let counterToggle = document.getElementById('counter-toggle');
if (counterToggle) {
counterToggle.addEventListener('click', function(e) {
e.preventDefault();
document.querySelectorAll('.counter').forEach(el => {
el.style.display = el.style.display === 'none' ? '' : 'none';
});
});
}
// List.js setup for the preview pane to support sorting
let previewPane = document.querySelector('#preview');
if (previewPane) {
let thElements = previewPane.querySelectorAll('th');
new List('preview', {
valueNames: Array.from(thElements, (_, index) => index)
});
}
document.querySelectorAll('.sort').forEach(sortButton => {
sortButton.addEventListener('click', function(e) {
const target = e.target;
// Reset icons on all sort buttons
document.querySelectorAll('.sort').forEach(btn => {
btn.classList.add('bi-chevron-expand');
btn.classList.remove('bi-chevron-down', 'bi-chevron-up');
});
if ( target.classList.contains('asc') ) {
target.classList.replace('bi-chevron-expand', 'bi-chevron-up');
target.classList.remove('bi-chevron-down');
} else {
target.classList.replace('bi-chevron-expand', 'bi-chevron-down');
target.classList.remove('bi-chevron-up');
}
}.bind(this));
});
const tabEl = document.querySelector('button[data-bs-target="#nav-pivot"]')
if (tabEl) {
tabEl.addEventListener('shown.bs.tab', event => {
import('./pivot-setup').then(({pivotSetup}) => pivotSetup($));
});
}
// Pretty hacky, but at the moment URL hashes are only used for storing pivot state, so this is a safe
// way of checking if we are following a link to a pivot table.
if (window.location.hash) {
document.querySelector('#nav-pivot-tab').click();
}
this.$rows.change(function() { this.showRows(); }.bind(this));
this.$rows.keyup(function(event) {
if(event.keyCode === 13){ this.showRows(); }
}.bind(this));
// Set up schema autocomplete in the editor. When the connection changes, load new schema.
getConnElement().addEventListener('change', updateSchema);
updateSchema();
}
}