Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them.
Page: /drakestapleton/sqlite/blob/master/ext/wasm/fiddle/fiddle.js
# sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
Sign in to star 0 stars 0 watching
About Files History Releases Proposed changes Issues For developers
branch `master` Branches Tags History
`sqlite / ext / wasm / fiddle / fiddle.js`
902 lines ยท 34617 bytes Raw Blame History
1 /*
2 2022-05-20
3
4 The author disclaims copyright to this source code. In place of a
5 legal notice, here is a blessing:
6
7 * May you do good and not evil.
8 * May you find forgiveness for yourself and forgive others.
9 * May you share freely, never taking more than you give.
10
11 ***********************************************************************
12
13 This is the main entry point for the sqlite3 fiddle app. It sets up the
14 various UI bits, loads a Worker for the db connection, and manages the
15 communication between the UI and worker.
16 */
17 (function(){
18 'use strict';
19 /* Recall that the 'self' symbol, except where locally
20 overwritten, refers to the global window or worker object. */
21
22 const storage = (function(NS/*namespace object in which to store this module*/){
23 /* Pedantic licensing note: this code originated in the Fossil SCM
24 source tree, where it has a different license, but the person who
25 ported it into sqlite is the same one who wrote it for fossil. */
26 'use strict';
27 NS = NS||{};
28
29 /**
30 This module provides a basic wrapper around localStorage
31 or sessionStorage or a dummy proxy object if neither
32 of those are available.
33 */
34 const tryStorage = function f(obj){
35 if(!f.key) f.key = 'storage.access.check';
36 try{
37 obj.setItem(f.key, 'f');
38 const x = obj.getItem(f.key);
39 obj.removeItem(f.key);
40 if(x!=='f') throw new Error(f.key+" failed")
41 return obj;
42 }catch(e){
43 return undefined;
44 }
45 };
46
47 /** Internal storage impl for this module. */
48 const $storage =
49 tryStorage(window.localStorage)
50 || tryStorage(window.sessionStorage)
51 || tryStorage({
52 // A basic dummy xyzStorage stand-in
53 $$$:{},
54 setItem: function(k,v){this.$$$[k]=v},
55 getItem: function(k){
56 return this.$$$.hasOwnProperty(k) ? this.$$$[k] : undefined;
57 },
58 removeItem: function(k){delete this.$$$[k]},
59 clear: function(){this.$$$={}}
60 });
61
62 /**
63 For the dummy storage we need to differentiate between
64 $storage and its real property storage for hasOwnProperty()
65 to work properly...
66 */
67 const $storageHolder = $storage.hasOwnProperty('$$$') ? $storage.$$$ : $storage;
68
69 /**
70 A prefix which gets internally applied to all storage module
71 property keys so that localStorage and sessionStorage across the
72 same browser profile instance do not "leak" across multiple apps
73 being hosted by the same origin server. Such cross-polination is
74 still there but, with this key prefix applied, it won't be
75 immediately visible via the storage API.
76
77 With this in place we can justify using localStorage instead of
78 sessionStorage.
79
80 One implication of using localStorage and sessionStorage is that
81 their scope (the same "origin" and client application/profile)
82 allows multiple apps on the same origin to use the same
83 storage. Thus /appA/foo could then see changes made via
84 /appB/foo. The data do not cross user- or browser boundaries,
85 though, so it "might" arguably be called a
86 feature. storageKeyPrefix was added so that we can sandbox that
87 state for each separate app which shares an origin.
88
89 See: https://fossil-scm.org/forum/forumpost/`4afc4d34de`
90
91 Sidebar: it might seem odd to provide a key prefix and stick all
92 properties in the topmost level of the storage object. We do that
93 because adding a layer of object to sandbox each app would mean
94 (de)serializing that whole tree on every storage property change.
95 e.g. instead of storageObject.projectName.foo we have
96 storageObject[storageKeyPrefix+'foo']. That's soley for
97 efficiency's sake (in terms of battery life and
98 environment-internal storage-level effort).
99 */
100 const storageKeyPrefix = (
101 $storageHolder===$storage/*localStorage or sessionStorage*/
102 ? (
103 (NS.config ?
104 (NS.config.projectCode || NS.config.projectName
105 || NS.config.shortProjectName)
106 : false)
107 || window.location.pathname
108 )+'::' : (
109 '' /* transient storage */
110 )
111 );
112
113 /**
114 A proxy for localStorage or sessionStorage or a
115 page-instance-local proxy, if neither one is available.
116
117 Which exact storage implementation is uses is unspecified, and
118 apps must not rely on it.
119 */
120 NS.storage = {
121 storageKeyPrefix: storageKeyPrefix,
122 /** Sets the storage key k to value v, implicitly converting
123 it to a string. */
124 set: (k,v)=>$storage.setItem(storageKeyPrefix+k,v),
125 /** Sets storage key k to JSON.stringify(v). */
126 setJSON: (k,v)=>$storage.setItem(storageKeyPrefix+k,JSON.stringify(v)),
127 /** Returns the value for the given storage key, or
128 dflt if the key is not found in the storage. */
129 get: (k,dflt)=>$storageHolder.hasOwnProperty(
130 storageKeyPrefix+k
131 ) ? $storage.getItem(storageKeyPrefix+k) : dflt,
132 /** Returns true if the given key has a value of "true". If the
133 key is not found, it returns true if the boolean value of dflt
134 is "true". (Remember that JS persistent storage values are all
135 strings.) */
136 getBool: function(k,dflt){
137 return 'true'===this.get(k,''+(!!dflt));
138 },
139 /** Returns the JSON.parse()'d value of the given
140 storage key's value, or dflt is the key is not
141 found or JSON.parse() fails. */
142 getJSON: function f(k,dflt){
143 try {
144 const x = this.get(k,f);
145 return x===f ? dflt : JSON.parse(x);
146 }
147 catch(e){return dflt}
148 },
149 /** Returns true if the storage contains the given key,
150 else false. */
151 contains: (k)=>$storageHolder.hasOwnProperty(storageKeyPrefix+k),
152 /** Removes the given key from the storage. Returns this. */
153 remove: function(k){
154 $storage.removeItem(storageKeyPrefix+k);
155 return this;
156 },
157 /** Clears ALL keys from the storage. Returns this. */
158 clear: function(){
159 this.keys().forEach((k)=>$storage.removeItem(/*w/o prefix*/k));
160 return this;
161 },
162 /** Returns an array of all keys currently in the storage. */
163 keys: ()=>Object.keys($storageHolder).filter((v)=>(v||'').startsWith(storageKeyPrefix)),
164 /** Returns true if this storage is transient (only available
165 until the page is reloaded), indicating that fileStorage
166 and sessionStorage are unavailable. */
167 isTransient: ()=>$storageHolder!==$storage,
168 /** Returns a symbolic name for the current storage mechanism. */
169 storageImplName: function(){
170 if($storage===window.localStorage) return 'localStorage';
171 else if($storage===window.sessionStorage) return 'sessionStorage';
172 else return 'transient';
173 },
174
175 /**
176 Returns a brief help text string for the currently-selected
177 storage type.
178 */
179 storageHelpDescription: function(){
180 return {
181 localStorage: "Browser-local persistent storage with an "+
182 "unspecified long-term lifetime (survives closing the browser, "+
183 "but maybe not a browser upgrade).",
184 sessionStorage: "Storage local to this browser tab, "+
185 "lost if this tab is closed.",
186 "transient": "Transient storage local to this invocation of this page."
187 }[this.storageImplName()];
188 }
189 };
190 return NS.storage;
191 })({})/*storage API setup*/;
192
193
194 /** Name of the stored copy of SqliteFiddle.config. */
195 const configStorageKey = 'sqlite3-fiddle-config';
196
197 /**
198 The SqliteFiddle object is intended to be the primary
199 app-level object for the main-thread side of the sqlite
200 fiddle application. It uses a worker thread to load the
201 sqlite WASM module and communicate with it.
202 */
203 const SF/*local convenience alias*/
204 = window.SqliteFiddle/*canonical name*/ = {
205 /* Config options. */
206 config: {
207 /* If true, SqliteFiddle.echo() will auto-scroll the
208 output widget to the bottom when it receives output,
209 else it won't. */
210 autoScrollOutput: true,
211 /* If true, the output area will be cleared before each
212 command is run, else it will not. */
213 autoClearOutput: false,
214 /* If true, SqliteFiddle.echo() will echo its output to
215 the console, in addition to its normal output widget.
216 That slows it down but is useful for testing. */
217 echoToConsole: false,
218 /* If true, display input/output areas side-by-side. */
219 sideBySide: true,
220 /* If true, swap positions of the input/output areas. */
221 swapInOut: false
222 },
223 /**
224 Emits the given text, followed by a line break, to the
225 output widget. If given more than one argument, they are
226 join()'d together with a space between each. As a special
227 case, if passed a single array, that array is used in place
228 of the arguments array (this is to facilitate receiving
229 lists of arguments via worker events).
230 */
231 echo: function f(text) {
232 /* Maintenance reminder: we currently require/expect a textarea
233 output element. It might be nice to extend this to behave
234 differently if the output element is a non-textarea element,
235 in which case it would need to append the given text as a TEXT
236 node and add a line break. */
237 if(!f._){
238 f._ = document.getElementById('output');
239 f._.value = ''; // clear browser cache
240 }
241 if(arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
242 else if(1===arguments.length && Array.isArray(text)) text = text.join(' ');
243 // These replacements are necessary if you render to raw HTML
244 //text = text.replace(/&/g, "&");
245 //text = text.replace(//g, ">");
247 //text = text.replace('\n', '
', 'g');
248 if(null===text){/*special case: clear output*/
249 f._.value = '';
250 return;
251 }else if(this.echo._clearPending){
252 delete this.echo._clearPending;
253 f._.value = '';
254 }
255 if(this.config.echoToConsole) console.log(text);
256 if(this.jqTerm) this.jqTerm.echo(text);
257 f._.value += text + "\n";
258 if(this.config.autoScrollOutput){
259 f._.scrollTop = f._.scrollHeight;
260 }
261 },
262 _msgMap: {},
263 /** Adds a worker message handler for messages of the given
264 type. */
265 addMsgHandler: function f(type,callback){
266 if(Array.isArray(type)){
267 type.forEach((t)=>this.addMsgHandler(t, callback));
268 return this;
269 }
270 (this._msgMap.hasOwnProperty(type)
271 ? this._msgMap[type]
272 : (this._msgMap[type] = [])).push(callback);
273 return this;
274 },
275 /** Given a worker message, runs all handlers for msg.type. */
276 runMsgHandlers: function(msg){
277 const list = (this._msgMap.hasOwnProperty(msg.type)
278 ? this._msgMap[msg.type] : false);
279 if(!list){
280 console.warn("No handlers found for message type:",msg);
281 return false;
282 }
283 //console.debug("runMsgHandlers",msg);
284 list.forEach((f)=>f(msg));
285 return true;
286 },
287 /** Removes all message handlers for the given message type. */
288 clearMsgHandlers: function(type){
289 delete this._msgMap[type];
290 return this;
291 },
292 /* Posts a message in the form {type, data} to the db worker. Returns this. */
293 wMsg: function(type,data,transferables){
294 this.worker.postMessage({type, data}, transferables || []);
295 return this;
296 },
297 /**
298 Prompts for confirmation and, if accepted, deletes
299 all content and tables in the (transient) database.
300 */
301 resetDb: function(){
302 if(window.confirm("Really destroy all content and tables "
303 +"in the (transient) db?")){
304 this.wMsg('db-reset');
305 }
306 return this;
307 },
308 /** Stores this object's config in the browser's storage. */
309 storeConfig: function(){
310 storage.setJSON(configStorageKey,this.config);
311 }
312 };
313
314 if(1){ /* Restore SF.config */
315 const storedConfig = storage.getJSON(configStorageKey);
316 if(storedConfig){
317 /* Copy all properties to SF.config which are currently in
318 storedConfig. We don't bother copying any other
319 properties: those have been removed from the app in the
320 meantime. */
321 Object.keys(SF.config).forEach(function(k){
322 if(storedConfig.hasOwnProperty(k)){
323 SF.config[k] = storedConfig[k];
324 }
325 });
326 }
327 }
328
329 SF.worker = new Worker('fiddle-worker.js'+self.location.search);
330 SF.worker.onmessage = (ev)=>SF.runMsgHandlers(ev.data);
331 SF.addMsgHandler(['stdout', 'stderr'], (ev)=>SF.echo(ev.data));
332 SF.addMsgHandler('sqlite-version', (ev)=>{
333 const v = ev.data;
334 const a = E('#sqlite-version-link');
335 const li = v.srcId.split(' ')/*DATE TIME HASH*/;
336 a.setAttribute('href',
337 //'https://sqlite.org/src/timeline/?c='+li[2].substr(0,20)
338 'https://sqlite.org/src/info/'+li[2].substr(0,20)
339 );
340 a.setAttribute('target', '_blank');
341 a.innerText = [
342 v.lib,
343 v.srcId.substr(0,34)
344 ].join(' ');
345 SF.echo("SQLite version",a.innerText);
346 });
347 SF.addMsgHandler('wasm-info', (ev)=>{
348 const v = ev.data;
349 SF.e.wasmInfo.innerText = 'WASM: '+(
350 4===v.pointerSize ? 32 : 64
351 )+'-bit'
352 +' heap: '+Number(v.heapSize)
353 // Heap size is not changing even when loading a huge db?
354 ;
355 SF.jqTerm?.set_prompt?.(v.prompt);
356 });
357
358 /* querySelectorAll() proxy */
359 const EAll = function(/*[element=document,] cssSelector*/){
360 return (arguments.length>1 ? arguments[0] : document)
361 .querySelectorAll(arguments[arguments.length-1]);
362 };
363 /* querySelector() proxy */
364 const E = function(/*[element=document,] cssSelector*/){
365 return (arguments.length>1 ? arguments[0] : document)
366 .querySelector(arguments[arguments.length-1]);
367 };
368
369 /** Handles status updates from the Emscripten Module object. */
370 SF.addMsgHandler('module', function f(ev){
371 ev = ev.data;
372 if('status'!==ev.type){
373 console.warn("Unexpected module-type message:",ev);
374 return;
375 }
376 if(!f.ui){
377 f.ui = {
378 status: E('#module-status'),
379 progress: E('#module-progress'),
380 spinner: E('#module-spinner')
381 };
382 }
383 const msg = ev.data;
384 if(f.ui.progres){
385 progress.value = msg.step;
386 progress.max = msg.step + 1/*we don't know how many steps to expect*/;
387 }
388 if(1==msg.step){
389 f.ui.progress.classList.remove('hidden');
390 f.ui.spinner.classList.remove('hidden');
391 }
392 if(msg.text){
393 f.ui.status.classList.remove('hidden');
394 f.ui.status.innerText = msg.text;
395 }else{
396 if(f.ui.progress){
397 f.ui.progress.remove();
398 f.ui.spinner.remove();
399 delete f.ui.progress;
400 delete f.ui.spinner;
401 }
402 f.ui.status.classList.add('hidden');
403 /* The module can post messages about fatal problems,
404 e.g. an exit() being triggered or assertion failure,
405 after the last "load" message has arrived, so
406 leave f.ui.status and message listener intact. */
407 }
408 });
409
410 /**
411 The 'fiddle-ready' event is fired (with no payload) when the
412 wasm module has finished loading. Interestingly, that happens
413 _before_ the final module:status event */
414 SF.addMsgHandler('fiddle-ready', function(){
415 SF.clearMsgHandlers('fiddle-ready');
416 self.onSFLoaded();
417 });
418
419 SF.e ={
420 about: E('#view-about'),
421 split: E('#view-split'),
422 wasmInfo: E('#opt-wasm-info'),
423 terminal: E('#view-terminal'),
424 hideInTerminal: EAll('.hide-in-terminal'
425 /* Elements to hide when in terminal mode */)
426 };
427 SF.eViews = EAll('.app-view');
428 SF.setMainView = function(eMain){
429 if( SF.e.main === eMain ) return;
430 SF.eViews.forEach((e)=>{
431 if( e===eMain ) e.classList.remove('hidden');
432 else e.classList.add('hidden');
433 });
434 SF.e.hideInTerminal.forEach(e=>{
435 if( eMain === SF.e.terminal ) e.classList.add('hidden');
436 else e.classList.remove('hidden');
437 });
438 SF.e.main = eMain;
439 SF.ForceResizeKludge();
440 };
441
442 /** Toggle the "About" view on and off. */
443 SF.toggleAbout = function(){
444 if( SF.e.about.classList.contains('hidden') ){
445 SF.e.about.$returnTo = SF.e.main;
446 SF.setMainView( SF.e.about );
447 }else{
448 const e = SF.e.about.$returnTo;
449 delete SF.e.about.$returnTo;
450 SF.setMainView( e );
451 }
452 };
453
454 /**
455 Given a DOM element, this routine measures its "effective
456 height", which is the bounding top/bottom range of this element
457 and all of its children, recursively. For some DOM structure
458 cases, a parent may have a reported height of 0 even though
459 children have non-0 sizes.
460
461 Returns 0 if !e or if the element really has no height.
462 */
463 const effectiveHeight = function f(e){
464 if(!e) return 0;
465 if(!f.measure){
466 f.measure = function callee(e, depth){
467 if(!e) return;
468 const m = e.getBoundingClientRect();
469 if(0===depth){
470 callee.top = m.top;
471 callee.bottom = m.bottom;
472 }else{
473 callee.top = m.top ? Math.min(callee.top, m.top) : callee.top;
474 callee.bottom = Math.max(callee.bottom, m.bottom);
475 }
476 Array.prototype.forEach.call(e.children,(e)=>callee(e,depth+1));
477 if(0===depth){
478 //console.debug("measure() height:",e.className, callee.top, callee.bottom, (callee.bottom - callee.top));
479 f.extra += callee.bottom - callee.top;
480 }
481 return f.extra;
482 };
483 }
484 f.extra = 0;
485 f.measure(e,0);
486 return f.extra;
487 };
488
489 /**
490 Returns a function, that, as long as it continues to be invoked,
491 will not be triggered. The function will be called after it stops
492 being called for N milliseconds. If `immediate` is passed, call
493 the callback immediately and hinder future invocations until at
494 least the given time has passed.
495
496 If passed only 1 argument, or passed a falsy 2nd argument,
497 the default wait time set in this function's $defaultDelay
498 property is used.
499
500 Source: underscore.js, by way of https://davidwalsh.name/javascript-debounce-function
501 */
502 const debounce = function f(func, wait, immediate) {
503 var timeout;
504 if(!wait) wait = f.$defaultDelay;
505 return function() {
506 const context = this, args = Array.prototype.slice.call(arguments);
507 const later = function() {
508 timeout = undefined;
509 if(!immediate) func.apply(context, args);
510 };
511 const callNow = immediate && !timeout;
512 clearTimeout(timeout);
513 timeout = setTimeout(later, wait);
514 if(callNow) func.apply(context, args);
515 };
516 };
517 debounce.$defaultDelay = 500 /*arbitrary*/;
518
519 SF.ForceResizeKludge = (function(){
520 /* Workaround for Safari mayhem regarding use of vh CSS
521 units.... We cannot use vh units to set the main view
522 size because Safari chokes on that, so we calculate
523 that height here. Larger than ~95% is too big for
524 Firefox on Android, causing the input area to move
525 off-screen. */
526 const eVisibles = EAll('.app-view');
527 const elemsToCount = [
528 /* Elements which we need to always count in the
529 visible body size. */
530 E('body > header'),
531 E('body > footer'),
532 E('body > fieldset.options')
533 ];
534 const resized = function f(){
535 if(f.$disabled) return;
536 const wh = window.innerHeight;
537 var ht;
538 var extra = 0;
539 elemsToCount.forEach((e)=>e ? extra += effectiveHeight(e) : false);
540 ht = wh - extra;
541 eVisibles.forEach(function(e){
542 e.style.height =
543 e.style.maxHeight = [
544 "calc(", (ht>=100 ? ht : 100), "px",
545 " - 2em"/*fudge value*/,")"
546 /* ^^^^ hypothetically not needed, but both
547 Chrome/FF on Linux will force scrollbars on the
548 body if this value is too small. */
549 ].join('');
550 });
551 };
552 resized.$disabled = true/*gets deleted when setup is finished*/;
553 window.addEventListener('resize', debounce(resized, 250), false);
554 return resized;
555 })();
556
557 /**
558 Performs all app initialization which must wait until after the
559 worker module is loaded. This function removes itself when it's
560 called.
561 */
562 self.onSFLoaded = function(){
563 delete this.onSFLoaded;
564
565 // Unhide all elements which start out hidden
566 EAll('.initially-hidden').forEach((e)=>e.classList.remove('initially-hidden'));
567 SF.e.main = EAll('.app-view:not(.hidden)')[0]
568 /** The main view widget. Initially the first non-hidden
569 .app-view element. */;
570 if( (new URL(self.location.href).searchParams).has('about') ){
571 SF.toggleAbout() /* for use while editing the About page */;
572 }
573 E('#btn-reset').addEventListener('click',()=>SF.resetDb());
574 EAll('#btn-about, #btn-about-close').forEach((e)=>{
575 e.addEventListener('click',()=>SF.toggleAbout())
576 });
577 const taInput = E('#input');
578 const btnClearIn = E('#btn-clear');
579 const selectExamples = E('#select-examples');
580 btnClearIn.addEventListener('click',function(){
581 taInput.value = '';
582 selectExamples.selectedIndex = 0;
583 },false);
584 // Ctrl-enter and shift-enter both run the current SQL.
585 taInput.addEventListener('keydown',function(ev){
586 if((ev.ctrlKey || ev.shiftKey) && 13 === ev.keyCode){
587 ev.preventDefault();
588 ev.stopPropagation();
589 btnShellExec.click();
590 }
591 }, false);
592 const taOutput = E('#output');
593 const btnClearOut = E('#btn-clear-output');
594 btnClearOut.addEventListener('click',function(){
595 taOutput.value = '';
596 if(SF.jqTerm) SF.jqTerm.clear();
597 },false);
598 const btnShellExec = E('#btn-shell-exec');
599 btnShellExec.addEventListener('click',function(ev){
600 let sql;
601 ev.preventDefault();
602 if(taInput.selectionStart e.addEventListener('click', cmdClick, false)
694 );
695
696 btnInterrupt.addEventListener('click',function(){
697 SF.wMsg('interrupt');
698 });
699
700 /** Initiate a download of the db. */
701 const btnExport = E('#btn-export');
702 const eLoadDb = E('#load-db');
703 const btnLoadDb = E('#btn-load-db');
704 btnLoadDb.addEventListener('click', ()=>eLoadDb.click());
705 /**
706 Enables (if passed true) or disables all UI elements which
707 "might," if timed "just right," interfere with an
708 in-progress db import/export/exec operation.
709 */
710 const enableMutatingElements = function f(enable){
711 if(!f._elems){
712 f._elems = [
713 /* UI elements to disable while import/export are
714 running. Normally the export is fast enough
715 that this won't matter, but we really don't
716 want to be reading (from outside of sqlite) the
717 db when the user taps btnShellExec. */
718 btnShellExec, btnExport, eLoadDb
719 ];
720 }
721 f._elems.forEach( enable
722 ? (e)=>e.removeAttribute('disabled')
723 : (e)=>e.setAttribute('disabled','disabled') );
724 };
725 btnExport.addEventListener('click',function(){
726 enableMutatingElements(false);
727 SF.wMsg('db-export');
728 });
729 SF.addMsgHandler('db-export', function(ev){
730 enableMutatingElements(true);
731 ev = ev.data;
732 if(ev.error){
733 SF.echo("Export failed:",ev.error);
734 return;
735 }
736 const blob = new Blob([ev.buffer],
737 {type:"application/x-sqlite3"});
738 const a = document.createElement('a');
739 document.body.appendChild(a);
740 a.href = window.URL.createObjectURL(blob);
741 a.download = ev.filename;
742 a.addEventListener('click',function(){
743 setTimeout(function(){
744 SF.echo("Exported (possibly auto-downloaded):",ev.filename);
745 window.URL.revokeObjectURL(a.href);
746 a.remove();
747 },500);
748 });
749 a.click();
750 });
751 /**
752 Handle load/import of an external db file.
753 */
754 eLoadDb.addEventListener('change',function(){
755 const f = this.files[0];
756 const r = new FileReader();
757 const status = {loaded: 0, total: 0};
758 enableMutatingElements(false);
759 r.addEventListener('loadstart', function(){
760 SF.echo("Loading",f.name,"...");
761 });
762 r.addEventListener('progress', function(ev){
763 SF.echo("Loading progress:",ev.loaded,"of",ev.total,"bytes.");
764 });
765 const that = this;
766 r.addEventListener('load', function(){
767 enableMutatingElements(true);
768 SF.echo("Loaded",f.name+". Opening db...");
769 SF.wMsg('open',{
770 filename: f.name,
771 buffer: this.result
772 }, [this.result]);
773 });
774 r.addEventListener('error',function(){
775 enableMutatingElements(true);
776 SF.echo("Loading",f.name,"failed for unknown reasons.");
777 });
778 r.addEventListener('abort',function(){
779 enableMutatingElements(true);
780 SF.echo("Cancelled loading of",f.name+".");
781 });
782 r.readAsArrayBuffer(f);
783 });
784
785 EAll('fieldset.collapsible').forEach(function(fs){
786 const btnToggle = E(fs,'legend > .fieldset-toggle'),
787 content = EAll(fs,':scope > div');
788 btnToggle.addEventListener('click', function(){
789 fs.classList.toggle('collapsed');
790 content.forEach((d)=>d.classList.toggle('hidden'));
791 }, false);
792 });
793
794 /** Set up a selection list of examples */
795 (function(){
796 const xElem = E('#select-examples');
797 const examples = [
798 {name: "Help", sql: [
799 "-- ================================================\n",
800 "-- Use ctrl-enter or shift-enter to execute sqlite3\n",
801 "-- shell commands and SQL.\n",
802 "-- If a subset of the text is currently selected,\n",
803 "-- only that part is executed.\n",
804 "-- ================================================\n",
805 ".help\n"
806 ]},
807 //{name: "Timer on", sql: ".timer on"},
808 // ^^^ re-enable if emscripten re-enables getrusage()
809 {name: "Box Mode", sql: ".mode box"},
810 {name: "Setup table T", sql:[
811 ".nullvalue NULL\n",
812 "CREATE TABLE t(a,b);\n",
813 "INSERT INTO t(a,b) VALUES('abc',123),('def',456),(NULL,789),('ghi',012);\n",
814 "SELECT * FROM t;\n"
815 ]},
816 {name: "sqlite_schema", sql: "select * from sqlite_schema"},
817 {name: "Mandelbrot", sql:[
818 "WITH RECURSIVE",
819 " xaxis(x) AS (VALUES(-2.0) UNION ALL SELECT x+0.05 FROM xaxis WHERE x<1.2),\n",
820 " yaxis(y) AS (VALUES(-1.0) UNION ALL SELECT y+0.1 FROM yaxis WHERE y<1.0),\n",
821 " m(iter, cx, cy, x, y) AS (\n",
822 " SELECT 0, x, y, 0.0, 0.0 FROM xaxis, yaxis\n",
823 " UNION ALL\n",
824 " SELECT iter+1, cx, cy, x*x-y*y + cx, 2.0*x*y + cy FROM m \n",
825 " WHERE (x*x + y*y) < 4.0 AND iter<28\n",
826 " ),\n",
827 " m2(iter, cx, cy) AS (\n",
828 " SELECT max(iter), cx, cy FROM m GROUP BY cx, cy\n",
829 " ),\n",
830 " a(t) AS (\n",
831 " SELECT group_concat( substr(' .+*#', 1+min(iter/7,4), 1), '') \n",
832 " FROM m2 GROUP BY cy\n",
833 " )\n",
834 "SELECT group_concat(rtrim(t),x'0a') as Mandelbrot FROM a;\n",
835 ]},
836 {name: "JSON pretty-print",
837 sql: "select json_pretty(json_object('ex',json('[52,3.14159]')))"
838 },
839 {name: "JSON pretty-print (with tabs)",
840 sql: "select json_pretty(json_object('ex',json('[52,3.14159]')),char(0x09))"
841 }
842 ];
843 const newOpt = function(lbl,val){
844 const o = document.createElement('option');
845 if(Array.isArray(val)) val = val.join('');
846 o.value = val;
847 if(!val) o.setAttribute('disabled',true);
848 o.appendChild(document.createTextNode(lbl));
849 xElem.appendChild(o);
850 };
851 newOpt("Examples (replaces input!)");
852 examples.forEach((o)=>newOpt(o.name, o.sql));
853 //xElem.setAttribute('disabled',true);
854 xElem.selectedIndex = 0;
855 xElem.addEventListener('change', function(){
856 taInput.value = '-- ' +
857 this.selectedOptions[0].innerText +
858 '\n' + this.value;
859 SF.dbExec(this.value);
860 });
861 })()/* example queries */;
862
863 //SF.echo(null/*clear any output generated by the init process*/);
864 if(window.jQuery && window.jQuery.terminal && SF.e.terminal){
865 /* Set up the terminal-style view... */
866 const jqeTerm = window.jQuery(SF.e.terminal).empty();
867 SF.jqTerm = jqeTerm.terminal(SF.dbExec.bind(SF),{
868 prompt: 'sqlite> ',
869 greetings: false /* the docs incorrectly call this 'greeting' */
870 });
871 /* Disable all special handling of the input:
872 https://sqlite.org/forum/forumpost/`c6665017c0dbba1f`
873 https://github.com/jcubic/jquery.terminal/issues/1044 */
874 const no_formatting = (str)=>window.jQuery.terminal.escape_formatting(str);
875 no_formatting.__meta__ = true;
876 window.jQuery.terminal.new_formatter(no_formatting);
877 EAll('.unhide-if-terminal-available').forEach(e=>{
878 e.classList.remove('hidden');
879 });
880 EAll('.remove-if-terminal-available').forEach(e=>{
881 e.parentElement.removeChild(e);
882 });
883 /* Set up a button to toggle the views... */
884 const ePlaceholder = E('#terminal-button-placeholder');
885 ePlaceholder.classList.add('labeled-input');
886 ePlaceholder.classList.remove('hidden');
887 const btnToggleView = document.createElement('button');
888 btnToggleView.innerText = "Toggle view";
889 ePlaceholder.appendChild( btnToggleView );
890 btnToggleView.addEventListener('click',function f(){
891 const terminalOn = document.body.classList.toggle('terminal-mode');
892 SF.setMainView( terminalOn ? SF.e.terminal : SF.e.split );
893 }, false);
894 btnToggleView.click()/*default to terminal view*/;
895 }
896 const urlParams = new URL(self.location.href).searchParams;
897 SF.dbExec(urlParams.get('sql') || null);
898 delete SF.ForceResizeKludge.$disabled;
899 SF.ForceResizeKludge();
900 globalThis.fiddle = SF;
901 }/*onSFLoaded()*/;
902 })();