-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.js
More file actions
213 lines (191 loc) · 7.02 KB
/
Copy pathmain.js
File metadata and controls
213 lines (191 loc) · 7.02 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
// main.js
// Orchestrates components: state manager, code editors, database querying, and table rendering
import './bootstrap.js'
import 'jquery-ui/dist/jquery-ui.js';
import state from './components/state.js';
import CodeEditor from './components/CodeEditor.js';
import DB from './components/db.js';
import ResultTable from './components/ResultTable.js';
import ErrorMessage from './components/ErrorMessage.js';
import ResizeHandle from './components/ResizeHandle.js';
import { toggleFavicon } from './components/favicons.js';
import SAMPLE_QUERIES from './static/sample-queries.json';
import { copyToClipboard } from '/util.js'
const app = {};
// Date of the last cloudspecs.duckdb refresh; bump when the database is updated.
const LAST_UPDATED = '2026-07-25';
//////////////////////// SQL Editor ///////////////////////
// Run query based on current state.sqlQuery
async function runQuery() {
state.setState({ sqlError: 'loading' });
const query = state.getState().sqlQuery;
let result;
try {
result = await app.db.query(query);
} catch (err) {
result = { error: err.toString() };
}
if (result.error) {
state.setState({ result: { columns: [], rows: [], query }, sqlError: result.error });
} else {
let newState = { result: { columns: result.columns, rows: result.rows, query }, sqlError: '' };
state.setState('warning' in result ? { ...newState, sqlWarning: result.warning } : newState);
}
}
document.addEventListener('DOMContentLoaded', async () => {
// SQL Code Editor
app.sqlEditor = new CodeEditor('#sql-editor', {
mode: 'text/x-sql',
stateKey: 'sqlQuery',
// handled in global ctrlenter listener below
// extraKeys: { 'Ctrl-Enter': runQuery }
});
// error message for SQL
app.sqlError = new ErrorMessage('#sql-status', ['sqlError', 'sqlWarning']);
// Initialize database and result table
app.db = await DB.create();
app.resultTable = new ResultTable('#sql-output');
// Handle state updates for query results
state.subscribe((newState, updates) => {
const { columns, rows, query } = newState.result;
app.resultTable.render(columns, rows, query);
}, ['result', 'viewsize', 'layout']);
// Load table button
document.getElementById('load-table').addEventListener('click', async (e) => {
e.preventDefault();
await runQuery();
});
// Fallback Ctrl+Enter
document.addEventListener('keydown', (event) => {
if (event.ctrlKey && event.key === 'Enter') {
runQuery();
}
});
await runQuery();
});
//////////////////////// R module ///////////////////////
document.addEventListener('DOMContentLoaded', async () => {
const RRepl = await import('./components/RRepl.js');
// error message for R
app.rError = new ErrorMessage('#r-status', 'rError');
// Prepare R evaluation area
app.rEditor = new CodeEditor("#r-editor", {
mode: 'text/x-rsrc',
stateKey: 'rCode',
// handled in global ctrlenter listener
// extraKeys: { 'Ctrl-Enter': () => evalR() },
overrides: { lineNumbers: false }
});
// Initialize R environment
const outputElem = 'r-output';
app.repl = await RRepl.default.initialize(outputElem);
async function evalR(viewOnly = false) {
state.setState({ rError: 'loading' });
const { rCode, result } = state.getState();
const res = await app.repl.eval(rCode, result, viewOnly);
if (res.error) {
state.setState({ rError: res.error });
} else {
state.setState({ rError: '', rOutput: res.svg });
document.getElementById(outputElem).innerHTML = res.svg;
}
}
// 'Execute R' button
// document.getElementById('execute-r').addEventListener('click', async (e) => {await evalR();});
// evaluate R when sql state changes
state.subscribe((newState, updates) => {
if (newState.sqlError) { return; }
if ('layout' in updates) {
app.rEditor.refresh();
}
if (!('runningQuery' in updates)) {
evalR(!('result' in updates) /* viewOnly */);
}
}, ['result', 'viewsize', 'layout']);
// Initial query to populate table based on URL/state
await evalR();
});
//////////////////////// Window Resizing, Global Buttons, etc. ///////////////////////
document.addEventListener('DOMContentLoaded', () => {
state.subscribe((newState, updates) => {
// don't save when there are errors is empty
if (newState.sqlError || newState.rError) { return; }
if ('result' in updates || 'rOutput' in updates) {
state.saveState();
}
if ('rOutput' in updates) {
// button for downloading svg
const dl = $('#svg-dl-btn');
const blob = new Blob([newState.rOutput], { type: 'image/svg+xml' });
const newUrl = URL.createObjectURL(blob);
const oldUrl = dl.attr('href');
if (!!oldUrl) { URL.revokeObjectURL(oldUrl); }
dl.attr('download', 'cloudspecs-plot.svg').attr('href', newUrl);
}
}, ['result', 'rOutput']);
// button for sharing url
$('#share-btn').click(() => {
// state.saveState();
copyToClipboard(window.location.href, "Link copied to clipboard!");
});
// footer database info + schema dialog
document.getElementById('last-updated').textContent = LAST_UPDATED;
const schemaDialog = document.getElementById('schema-dialog');
$('#schema-btn').click((e) => {
e.preventDefault();
schemaDialog.showModal();
});
$('#schema-close-btn').click(() => schemaDialog.close());
schemaDialog.addEventListener('click', (e) => {
if (e.target === schemaDialog) { schemaDialog.close(); }
});
// logo resets the page
$('#logo-link').click((e) => {
e.preventDefault();
const newUrl = window.location.origin + window.location.pathname;
window.location = newUrl;
});
// parse sample queries
const samplesTable = {};
SAMPLE_QUERIES.forEach(item => {
let sqlProcessed = item.sql_code;
let rProcessed = item.r_code;
if (Array.isArray(sqlProcessed)) {
sqlProcessed = sqlProcessed.join('\n');
}
if (Array.isArray(rProcessed)) {
rProcessed = rProcessed.join('\n');
}
samplesTable[item.description] = {
sql_code: sqlProcessed,
r_code: rProcessed,
layout: item.layout || (!!rProcessed ? 'split' : 'table')
};
});
const $dropdown = $('#sample-queries');
for (const description in samplesTable) {
if (description) {
$dropdown.append(
$('<option></option>')
.attr('value', description)
.text(description)
);
}
}
$dropdown.on('change', () => {
const selectedDescription = $('#sample-queries :selected').val();
const data = samplesTable[selectedDescription];
if (!data) { return; }
const updates = { sqlQuery: data.sql_code, rCode: data.r_code, layout: { type: data.layout }, runningQuery: true };
if (!data.r_code && 'repl' in app) {
updates.rCode = app.repl.minimalRCode();
updates.layout = updates.layout || { type: 'table' };
}
console.log(data);
state.setState(updates);
toggleFavicon(false); // Using sample queries is not cracked
runQuery();
});
// grid resize drag handler
app.resizeHandle = new ResizeHandle('#app', '#grid-resize', '#toggle-viz-btn');
});