-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
498 lines (416 loc) · 18.8 KB
/
index.js
File metadata and controls
498 lines (416 loc) · 18.8 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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
'use strict';
var grid, tabBar, tutorial;
window.onload = getSmart.bind(null, {
data: 'data/nasdaq-100-20181015.json',
state: 'data/state.json',
scrollbars: 'data/scrollbars.css;txt', // ;txt forces get as text rather than style element
localizer: 'data/localizers.js;snippets', // ;snippets forces get as text snippets array rather excuted code
editor: 'data/cell-editors.js;snippets',
toc: 'data/table-of-contents.js'
}, function(files) {
const NEW = '(New)';
const saveFuncs = {
editor: saveCellEditor,
localizer: saveLocalizer
};
const applyButtonSelector = 'input[type=button][value=Apply]';
// Append version numbers to <h1> header
document.querySelector('body > h1:first-child > span').setAttribute('title', 'Hypergrid v' + fin.Hypergrid.prototype.version + ', Tutorial v18 (11/1/2018)');
fin.enhance(document);
tabBar = new CurvyTabs(document.getElementById('editors'));
tabBar.paint();
grid = new fin.Hypergrid();
initLocalsButtons();
var tutorialTabBarContainer = document.getElementById('tutorial'),
tutorialPagerContainer = document.getElementById('page-panel'),
tutorialTabBar = new CurvyTabs(tutorialTabBarContainer),
toc = [], // built by walk below
pagerOptions = { path: 'pages/', toc: toc };
// load following *after* files loaded and tab bars instantiated so <span class="tab"> can be enlivened
tabBar.getTab('Help').querySelector('iframe').src = "Help.html";
tutorialTabBar.getTab('Help').querySelector('iframe').src = "pages/Help.html";
tutorialTabBar.getTab('Jump Start').querySelector('iframe').src = "pages/Jump%20Start.html";
// flatten the hierarchical files.toc into pagerOptions.toc
walk(files.toc);
function walk(list) {
list.forEach(function (item) {
if (Array.isArray(item)) {
walk(item);
} else {
pagerOptions.toc.push(item);
}
});
}
// If there is a page number cookie value, use it!
var match = location.search.match(/[?&]p=([^?&]+)/) || document.cookie.match(/\bp=([^?&]+)/);
if (match) {
pagerOptions.startPage = decodeURIComponent(match[1]);
}
tutorial = new CurvyTabsPager(tutorialPagerContainer, tutorialTabBar, pagerOptions);
tutorial.goFirstEl.style.display = tutorial.goLastEl.style.display = 'none';
tutorial.tabBar.onclick = function(e) {
var isTutorialTab = e.detail.content.getAttribute('name') === 'Tutorial';
document.getElementById('scroll-warning').style.display = isTutorialTab ? null : 'none';
};
// listen for page events to highlight the current page's line in the ToC
document.addEventListener('curvy-tabs-pager-paged', function(e) {
var pageIndex = e.detail.pager.num - 1;
var tocLineEls = tutorial.tabBar.container.querySelector('[name="ToC"] > iframe').contentDocument.querySelectorAll('li');
tocLineEls.forEach(function(el, index) {
el.classList.toggle('current-page', index === pageIndex);
});
});
callApi('data'); // inits both 'data' and 'state' editors
callApi('scrollbars'); // injects stylesheet
initObjectEditor('localizer'); // adds onclick handler
initObjectEditor('editor'); // adds onclick handler
applyButtonEl('Data').onclick = callApi.bind(null, 'data', 'Data set.');
applyButtonEl('State').onclick = callApi.bind(null, 'state', 'State set.');
applyButtonEl('Scrollbars').onclick = callApi.bind(null, 'scrollbars', 'Stylesheet injected.');
function applyButtonEl(tabName) {
return document.querySelector('div[name="' + tabName + '"] > ' + applyButtonSelector);
}
document.body.style.visibility = 'visible';
//// WIRE UP EVENT HANDLERS ////
document.getElementById('reset-all').onclick = function() {
if (confirm('Clear localStorage and reload?\n\nThis will reset all tabs to their default values, removing all edits, including new custom localizers and custom cell editors.')) {
localStorage.clear();
location.reload();
}
};
grid.addEventListener('fin-after-cell-edit', function(e) {
document.getElementById('data').value = stringifyAndUnquoteKeys(grid.behavior.getData());
});
var dragger, divider = document.querySelector('.divider');
divider.addEventListener('mousedown', function(e) {
var div = document.querySelector('#hypergrid > div:first-child');
div.classList.add('resizing');
dragger = {
delta: e.clientY - divider.getBoundingClientRect().top,
gridHeight: grid.div.getBoundingClientRect().height,
tabHeight: tabBar.container.getBoundingClientRect().height,
div: div
};
e.stopPropagation(); // no other element needs to handle
});
document.addEventListener('mousemove', function(e) {
if (dragger) {
var newDividerTop = e.clientY - dragger.delta,
oldDividerTop = divider.getBoundingClientRect().top,
topDelta = newDividerTop - oldDividerTop,
newGridHeight = dragger.gridHeight + topDelta,
newTabHeight = dragger.tabHeight - topDelta;
if (newGridHeight >= 65 && newTabHeight >= 130) {
divider.style.borderTopStyle = divider.style.borderTopColor = null; // revert to :active style
divider.style.top = newDividerTop + 'px';
grid.div.style.height = (dragger.gridHeight = newGridHeight) + 'px';
tabBar.container.style.height = (dragger.tabHeight = newTabHeight) + 'px';
} else {
// force :hover style when out of range even though dragging (i.e., :active)
divider.style.borderTopStyle = 'double';
divider.style.borderTopColor = '#444';
}
e.stopPropagation(); // no other element needs to handle
e.preventDefault(); // no other drag effects, please
if (e.buttons ^ 1) {
e.target.dispatchEvent(new CustomEvent('mouseup', e));
}
}
});
document.addEventListener('mouseup', function(e) {
if (dragger) {
dragger.div.classList.remove('resizing');
dragger = undefined;
}
});
// Handle window resizing (CSS calc() only performed at initial load for some reason)
window.addEventListener('resize', function() {
var width = window.innerWidth * .50,
height = window.innerHeight,
divY = document.querySelector('.divider').getBoundingClientRect().top;
tabBar.container.style.width = width - 16 + 'px';
tabBar.container.style.height = height - (divY + 32) + 'px';
tutorial.tabBar.container.style.width = width - 12 + 'px';
tutorial.tabBar.container.style.height = height - 58 + 'px';
var tutorialWindow = tutorial.tabBar.getTab('Tutorial').querySelector('iframe').contentWindow;
if (typeof tutorialWindow.resize === 'function') {
tutorialWindow.resize();
}
});
function callApi(type, confirmation, e) {
var textEl = document.getElementById(type); // tab editor's textarea element
var resetEl = document.getElementById('reset-' + type);
textEl.oninput = function() {
resetEl.classList.toggle('disabled', textEl.value === stringifyAndUnquoteKeys(files[type]));
};
if (textEl.value) {
localStorage.setItem(type, textEl.value);
} else if (!(textEl.value = localStorage.getItem(type))) {
textEl.value = stringifyAndUnquoteKeys(files[type]);
localStorage.setItem(type, textEl.value);
}
// We're using eval here instead of JSON.parse because we want to allow unquoted keys.
switch (type) {
case 'data':
grid.setData(eval(textEl.value), {schema: []});
callApi('state'); // reapply state after resetting schema (also inits state editor on first time called)
break;
case 'state':
// Note: L-value must be inside eval because R-value beginning with '{' is eval'd as BEGIN block.
var Lvalue;
grid.setState(eval('Lvalue =' + textEl.value));
break;
case 'scrollbars':
injectCSS('custom', textEl.value);
break;
}
if (confirmation) {
feedback(textEl.parentElement, confirmation);
}
textEl.oninput();
resetEl.onclick = resetTextEditor;
}
function resetTextEditor() {
var type = this.id.replace(/^reset-/, '');
if (confirm('Reset the ' + capitalize(type) + ' tab editor to its default?\n\nCAUTION: This is not an undo. It restores the editor content to the app\'s original built-in default value!')) {
document.getElementById(type).value = '';
localStorage.removeItem(type);
callApi(type);
}
}
function resetObject() {
var type = this.id.replace(/^reset-/, '');
var name = document.getElementById(type + '-dropdown').value;
if (!isDisabled(this) && confirm('Reset the "' + name + '" ' + type + ' to its default?')) {
var script = getDefaultScript(type, name);
if (name !== NEW) {
localStorage.setItem(type + '_' + name, script);
}
document.getElementById(type + '-script').value = script;
enableResetAndDeleteIcons(type, name);
}
}
function deleteObject() {
var type = this.id.replace(/^delete-/, '');
var dropdown = document.getElementById(type + '-dropdown');
var name = dropdown.value;
if (!isDisabled(this) && confirm('Delete the "' + name + '" ' + type + '?')) {
localStorage.removeItem(type + '_' + name);
dropdown.options.remove(dropdown.selectedIndex);
dropdown.selectedIndex = 0; // "(New)"
dropdown.onchange();
}
}
function isDisabled(el) {d
return el.classList.contains('disabled');
}
function capitalize(str) {
return str[0].toUpperCase() + str.substr(1);
}
function initLocalsButton(type, locals) {
var el = document.getElementById(type + '-dropdown').parentElement.querySelector('.locals');
locals = locals.sort();
el.title = locals.join('\n');
el.onclick = function() {
alert('Local variables: ' + locals.join(', '));
};
}
function initLocalsButtons() {
initLocalsButton('editor', ['module', 'exports', 'CellEditor'].concat(Object.keys(grid.cellEditors.items)));
initLocalsButton('localizer', ['module', 'exports']);
}
function initObjectEditor(type) {
var dropdownEl = document.getElementById(type + '-dropdown'),
resetEl = document.getElementById('reset-' + type),
deleteEl = document.getElementById('delete-' + type),
scriptEl = document.getElementById(type + '-script'),
addButtonEl = dropdownEl.parentElement.querySelector(applyButtonSelector),
prefix = type + '_',
save = saveFuncs[type],
newScript;
// STEP 1: Save default scripts to local storage not previously saved
files[type].map(extractName).sort().forEach(function(name) {
var script = getDefaultScript(type, name);
if (name === NEW) {
dropdownEl.add(new Option(name));
newScript = scriptEl.value = script;
} else if (!localStorage.getItem(prefix + name)) {
localStorage.setItem(prefix + name, script);
}
});
// STEP 2: Load scripts from local storage, re-saving each which adds it to drop-down
for (var i = 0; i < localStorage.length; ++i) {
var key = localStorage.key(i);
if (key.substr(0, prefix.length) === prefix) {
save(localStorage.getItem(key), dropdownEl);
}
}
// STEP 3: Reset drop-down to first item: "(New)"
dropdownEl.selectedIndex = 0;
enableResetAndDeleteIcons(type, NEW);
// STEP 4: Assign handlers
resetEl.onclick = resetObject;
deleteEl.onclick = deleteObject;
var name = NEW;
dropdownEl.onchange = function() {
var newName = this.value;
var savedScript = localStorage.getItem(prefix + name) || getDefaultScript(type, name);
var editedScript = document.getElementById(type + '-script').value;
if (!savedScript || savedScript === editedScript || confirm('Discard unsaved changes?')) {
name = newName;
if (name === NEW) {
scriptEl.value = newScript;
enableResetAndDeleteIcons(type);
} else {
scriptEl.value = localStorage.getItem(prefix + name);
enableResetAndDeleteIcons(type, name);
}
} else if (savedScript) {
this.value = name;
}
};
scriptEl.oninput = function() {
enableResetAndDeleteIcons(type, dropdownEl.value);
};
addButtonEl.onclick = function() {
save(scriptEl.value, dropdownEl);
name = dropdownEl.value;
grid.repaint();
};
}
function enableResetAndDeleteIcons(type, name) {
var resetEl = document.getElementById('reset-' + type);
var deleteEl = document.getElementById('delete-' + type);
if (name) {
var defaultScript = getDefaultScript(type, name);
var editedScript = document.getElementById(type + '-script').value;
var alteredFromDefault = defaultScript && defaultScript !== editedScript;
resetEl.classList.toggle('disabled', !alteredFromDefault);
deleteEl.classList.toggle('disabled', !!defaultScript);
} else {
resetEl.classList.add('disabled');
deleteEl.classList.add('disabled');
}
}
function getDefaultScript(type, name) {
return files[type].find(isScriptByName.bind(null, name));
}
function isScriptByName(name, script) {
return extractName(script) === name;
}
function extractName(script) {
var match = script.match(/\.extend\('([^']+)'|\.extend\("([^"]+)"|\bname:\s*'([^']+)'|\bname:\s*"([^"]+)"/);
return match[1] || match[2] || match[3] || match[4];
}
function stringifyAndUnquoteKeys(obj) {
return typeof obj === 'object'
? JSON.stringify(obj, undefined, 2)
.replace(/( +)"([a-zA-Z$_]+)"(: )/g, '$1$2$3') // un-quote keys
: obj;
}
function saveCellEditor(script, select) {
var cellEditors = grid.cellEditors;
var editorNames = Object.keys(cellEditors.items);
var editors = editorNames.map(function(name) {
return cellEditors.items[name];
});
var exports = {}, module = { exports: exports };
var formalArgs = [null, 'module', 'exports', 'CellEditor'] // null is for bind's thisArg
.concat(editorNames) // additional params
.concat(script); // function body
var actualArgs = [module, exports, cellEditors.BaseClass]
.concat(editors);
try {
var closure = new (Function.prototype.bind.apply(Function, formalArgs)); // calls Function constructor using .apply
closure.apply(null, actualArgs);
var Editor = module.exports;
var name = Editor.prototype.$$CLASS_NAME;
if (!(Editor.prototype instanceof cellEditors.BaseClass)) {
throw 'Cannot save cell editor "' + name + '" because it is not a subclass of CellEditor (aka grid.cellEditors.BaseClass).';
}
if (!name || name === NEW) {
throw 'Cannot save cell editor. A name other than "(New)" is required.';
}
} catch (err) {
console.error(err);
alert(err + '\n\nAvailable locals: ' + formalArgs.slice(1, formalArgs.length - 1).join(', ') +
'\n\nNOTE: Cell editors that extend directly from CellEditor must define a `template` property.');
return;
}
cellEditors.add(Editor);
localStorage.setItem('editor_' + name, script);
addOptionInAlphaOrder(select, name);
enableResetAndDeleteIcons('editor', name);
if (select) {
feedback(select.parentElement);
}
initLocalsButtons();
}
function saveLocalizer(script, select) {
var module = {};
try {
var closure = new Function('module', script);
closure(module);
var localizer = module.exports;
var name = localizer.name;
if (!name || name === NEW) {
throw 'Cannot save localizer. A `name` property with a value other than "(New)" is required.';
}
grid.localization.add(localizer);
} catch (err) {
console.error(err);
alert(err + '\n\nAvailable locals:\nmodule');
return;
}
localStorage.setItem('localizer_' + name, script);
addOptionInAlphaOrder(select, name);
enableResetAndDeleteIcons('localizer', name);
if (select) {
feedback(select.parentElement);
}
}
function addOptionInAlphaOrder(el, text, value) {
if (!el) {
return;
}
var optionEls = el.options;
var index = optionEls.findIndex(function(optionEl) {
return optionEl.textContent === text;
});
if (index >= 0) {
el.selectedIndex = index;
return; // already in dropdown
}
var firstOptionGreaterThan = optionEls.find(function(optionEl) {
return optionEl.textContent > text;
});
el.value = name;
if (el.selectedIndex === -1) {
el.add(new Option(text, value), firstOptionGreaterThan);
el.value = value || text;
}
}
function feedback(content, confirmation) {
var el = content.querySelector('span.feedback');
if (!confirmation) {
confirmation = 'Saved';
}
el.innerText = confirmation;
el.style.display = 'inline';
setTimeout(function() {
el.style.display = 'none';
}, 750 + 50 * confirmation.length);
}
function injectCSS(name, css) {
var prefix = 'injected-stylesheet-finbar-';
var id = prefix + name;
var el = document.getElementById(id);
if (!el) {
el = document.createElement('style');
el.setAttribute('id', id);
}
el.innerHTML = css;
var baseEl = document.getElementById(prefix + 'base');
baseEl.parentElement.insertBefore(el, baseEl.nextElementSibling);
}
});