-
Notifications
You must be signed in to change notification settings - Fork 26
/
Multtable.js
563 lines (472 loc) · 20.8 KB
/
Multtable.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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// @flow
import GEUtils from './js/GEUtils.js';
import * as Library from './js/Library.js';
import Log from './js/Log.js';
import Menu from './js/Menu.js';
import {MulttableView, createFullMulttableView} from './js/MulttableView.js';
import {LISTENER_READY_MESSAGE, STATE_LOADED_MESSAGE} from './js/SheetModel.js';
import Template from './js/Template.js';
import XMLGroup from './js/XMLGroup.js';
import * as SSD from './js/SubsetHighlightController.js';
import * as VC from './visualizerFramework/visualizer.js';
export {broadcastChange} from './visualizerFramework/visualizer.js';
// $FlowFixMe -- external module imports described in flow-typed directory
import {THREE} from './lib/externals.js';
export {load};
/*::
import type {MulttableJSON} from './js/MulttableView.js';
import type {MSG_external, MSG_editor} from './js/SheetModel.js';
declare type rowXcol = {row: number, col: number};
*/
/* Module variables */
let Group /*: XMLGroup */; // group about which information will be displayed
let Multtable_View /*: MulttableView */;
const HELP_PAGE = 'help/rf-um-mt-options/index.html';
const myDomain = new URL(window.location.href).origin;
/* Register static event managers (called after document is assembled) */
function registerCallbacks() {
// window-wide default actions
window.onresize = resizeBody;
$('#bodyDouble')[0].addEventListener('click', GEUtils.cleanWindow);
window.addEventListener('contextmenu', (mouseEvent /*: MouseEvent */) => {
GEUtils.cleanWindow();
mouseEvent.preventDefault();
});
$('#rainbow')[0].addEventListener('click', () => chooseColoration('rainbow'));
$('#grayscale')[0].addEventListener('click', () => chooseColoration('grayscale'));
$('#none')[0].addEventListener('click', () => chooseColoration('none'));
$('#color-order-top-row-fixed')[0].addEventListener('click', () => chooseColorReordering('topRowFixed'));
$('#color-order-element-colors-fixed')[0].addEventListener('click', () => chooseColorReordering('elementColorsFixed'));
// Large graphic events
LargeGraphic.init();
// Control panel events
if (GEUtils.isTouchDevice()) {
$('#controls')[0].addEventListener('touchstart', (event /*: Event */) => event.stopPropagation())
$('#controls')[0].addEventListener('touchmove', (event /*: Event */) => event.stopPropagation())
$('#controls')[0].addEventListener('touchend', (event /*: Event */) => event.stopPropagation())
} else { // must be mouse device
$('#controls')[0].addEventListener('mousedown', (event /*: Event */) => event.stopPropagation())
$('#controls')[0].addEventListener('mousemove', (event /*: Event */) => event.stopPropagation())
$('#controls')[0].addEventListener('mouseup', (event /*: Event */) => event.stopPropagation())
}
$('#subset-button')[0].addEventListener('click', () => VC.showPanel('#subset-control') );
$('#table-button')[0].addEventListener('click', () => VC.showPanel('#table-control') );
$('#organization-select')[0].addEventListener('change', organizationChangeHandler);
$('#separation-slider')[0].addEventListener('input', separation);
}
// Load group from invocation URL and complete setup
async function load() {
Group = await Library.loadFromURL()
const highlighters = [
{handler: highlightByBackground, label: 'Background'},
{handler: highlightByBorder, label: 'Border'},
{handler: highlightByCorner, label: 'Corner'}
];
await SSD.load($('#subset-control'), highlighters, clearHighlights, Group)
// Create header from group name
$('#heading').html(`Multiplication Table for ${Group.name}`)
// Draw Multtable in graphic
Multtable_View = createFullMulttableView({container: $('#graphic')});
Multtable_View.group = Group;
// Create list of subgroups for organize-by-subgroup menu:
const choices = Group.subgroups.slice(0, -1).map((subgroup, subgroupIndex) => {
const choice = (subgroupIndex === 0) ?
eval(Template.HTML('organization-choice-none-template')) :
eval(Template.HTML('organization-choice-template'))
return choice.trim()
})
GEUtils.setupFauxSelect($('#organization-select')[0], choices, 0)
organizeBySubgroup(0);
// Register event handlers
registerCallbacks();
// Is this an editor started by a Sheet? If so, set up communication with Sheet
if (window.location.href.includes('SheetEditor=true')) {
setupEditorCallback();
}
// Load icon strip in upper right-hand corner
VC.load(Group, HELP_PAGE);
}
function setupEditorCallback () {
// this only happens once, right after initialization
window.addEventListener('message', receiveInitialSetup, false);
// let any GE window that spawned this know that we're ready to receive signals
window.postMessage( LISTENER_READY_MESSAGE, myDomain );
// or if any external program is using GE as a service, let it know we're ready, too
window.parent.postMessage( LISTENER_READY_MESSAGE, '*' );
}
function receiveInitialSetup (event /*: MessageEvent */) {
if (event.data == undefined)
return;
const event_data /*: MSG_external<MulttableJSON> */ = (event.data /*: any */);
if (event_data.source == 'external') {
const json_data = event_data.json;
if (json_data.separation != undefined)
$('#separation-slider').val(json_data.separation * 100);
if (json_data.coloration != undefined)
$('#' + json_data.coloration.toString()).prop('checked', true);
if (json_data.organizingSubgroup != undefined)
organizeBySubgroup(json_data.organizingSubgroup);
Multtable_View.fromJSON(json_data);
VC.enableChangeBroadcast(() => Multtable_View.toJSON());
window.postMessage( STATE_LOADED_MESSAGE, myDomain )
} else if ( event_data.source == 'editor'
|| ((event.data /*: any */) /*: string */) == LISTENER_READY_MESSAGE
|| ((event.data /*: any */) /*: string */) == STATE_LOADED_MESSAGE)
{
// we're just receiving our own messages -- ignore them
} else {
Log.warn('unknown message of origin $[event.orgin} received in Multtable.js:');
Log.warn(event.data);
}
}
/* Organize subgroups by data-subgroup-index value of #organization-choice child */
function organizationChangeHandler(changeEvent /*: Event */) {
const organizationChoice = $(changeEvent.target).children()[0]
if (organizationChoice != null) {
const subgroupIndexChoice = $(organizationChoice).attr('data-subgroup-index')
if (subgroupIndexChoice != null) {
organizeBySubgroup(parseInt(subgroupIndexChoice))
}
}
}
/* Display multtable grouped by group.subgroups[subgroupIndex]
* (Note that the group itself is Group.subgroups[Group.subgroups.length - 1] */
function organizeBySubgroup (index /*: integer */) {
Multtable_View.organizeBySubgroup(index == 0 ? Group.subgroups.length - 1 : index);
}
/* Set separation between cosets in multtable display, and re-draw graphic */
function separation() {
Multtable_View.separation = parseInt($('#separation-slider').val())/100;
}
/* Set coloration option in multtable, and re-draw graphic */
function chooseColoration(coloration /*: 'rainbow' | 'grayscale' | 'none' */) {
Multtable_View.coloration = coloration;
}
/* Set color order option in multtable, and re-draw graphic */
function chooseColorReordering (colorReordering /*: 'topRowFixed' | 'elementColorsFixed' */) {
Multtable_View.colorReordering = colorReordering;
}
// Resize the body, including the graphic
function resizeBody() {
$('#bodyDouble').height(window.innerHeight);
$('#bodyDouble').width(window.innerWidth);
Multtable_View.resize();
}
/* Highlighting routines */
function highlightByBackground(elements /*: Array<Array<groupElement>> */) {
Multtable_View.highlightByBackground(elements);
}
function highlightByBorder(elements /*: Array<Array<groupElement>> */) {
Multtable_View.highlightByBorder(elements);
}
function highlightByCorner(elements /*: Array<Array<groupElement>> */) {
Multtable_View.highlightByCorner(elements);
}
function clearHighlights() {
Multtable_View.clearHighlights();
}
/*
* Large graphic mouse events
* display/clear label -- click / tap
* zoom in/out -- wheel / two-finger pinch-spread
* move graph -- drag-and-drop / two-finger drag
* recenter, reset zoom -- right click / two-finger tap
* move row/column -- Shift drag-and-drop / one-finger drag
*/
class LargeGraphic {
/*::
static lastEvent: ?Event;
*/
static init() {
LargeGraphic.lastEvent = null;
const graphic = $('#graphic')[0];
if (window.ontouchstart === undefined) { // determine whether device supports touch events
['click', 'wheel', 'contextmenu', 'mousedown', 'mousemove', 'mouseup']
.forEach( (eventType) => graphic.addEventListener(eventType, LargeGraphic.mouseHandler) );
} else {
['touchstart', 'touchmove', 'touchend']
.forEach( (eventType) => graphic.addEventListener(eventType, LargeGraphic.touchHandler) );
}
}
// Event handler for mouse-only platform
static mouseHandler(mouseEvent /*: MouseEvent */) {
// skip modified events, except for mouseXXX with shiftKey down
if ( mouseEvent.ctrlKey || mouseEvent.altKey || mouseEvent.metaKey
|| (mouseEvent.shiftKey && !mouseEvent.type.startsWith('mouse')) ) {
return;
};
const lastEvent /*: MouseEvent */ = (LargeGraphic.lastEvent /*: any */);
// create artificial event type like 'shift-mousedown' to branch on
const syntheticType = (mouseEvent.shiftKey ? 'shift-' : '') + mouseEvent.type;
switch (syntheticType) {
case 'click':
if (LargeGraphic.lastEvent == null) {
LargeGraphic.displayNewLabel(mouseEvent);
} else {
GEUtils.cleanWindow();
}
LargeGraphic.lastEvent = null;
mouseEvent.stopPropagation();
break;
case 'contextmenu':
LargeGraphic.zoom2fit();
LargeGraphic.lastEvent = null;
mouseEvent.preventDefault();
break;
case 'wheel':
GEUtils.cleanWindow();
const deltaY = ((mouseEvent /*: any */) /*: WheelEvent */).deltaY;
(deltaY < 0) ? Multtable_View.zoomIn(deltaY) : Multtable_View.zoomOut(deltaY);
break;
case 'mousedown':
LargeGraphic.lastEvent = mouseEvent;
break;
case 'shift-mousedown':
if (LargeGraphic.dragStart(mouseEvent)) {
LargeGraphic.lastEvent = mouseEvent;
} else {
LargeGraphic.lastEvent = null;
}
break;
case 'mousemove':
if (lastEvent != undefined && !lastEvent.shiftKey) {
LargeGraphic.mouseMove(lastEvent, mouseEvent);
LargeGraphic.lastEvent = mouseEvent;
} else {
LargeGraphic.lastEvent = null;
}
mouseEvent.preventDefault();
break;
case 'shift-mousemove':
if (lastEvent != undefined && lastEvent.shiftKey) {
LargeGraphic.dragOver(mouseEvent);
LargeGraphic.lastEvent = mouseEvent;
} else {
LargeGraphic.lastEvent = null;
}
mouseEvent.preventDefault();
break;
case 'mouseup':
if (lastEvent != undefined && !lastEvent.shiftKey && lastEvent.type == 'mousemove') {
LargeGraphic.mouseMove(lastEvent, mouseEvent); // leave last event there so ensuing 'click' event won't display tooltip
LargeGraphic.lastEvent = mouseEvent;
} else {
LargeGraphic.lastEvent = null;
}
mouseEvent.stopPropagation();
mouseEvent.preventDefault();
break;
case 'shift-mouseup':
if (lastEvent != undefined && lastEvent.shiftKey && lastEvent.type == 'mousemove') {
LargeGraphic.dragEnd(mouseEvent);
}
LargeGraphic.lastEvent = null;
mouseEvent.stopPropagation();
mouseEvent.preventDefault();
break;
default:
Log.warn('LargeGraphic.mouseHandler unknown event %s', syntheticType);
}
}
// Event handler for platforms that support touch events
static touchHandler(touchEvent /*: TouchEvent */) {
// skip modified events
if (touchEvent.shiftKey || touchEvent.ctrlKey || touchEvent.altKey || touchEvent.metaKey) {
return;
};
const touches = LargeGraphic.touches(touchEvent);
const touchCount = touches.length;
// only accept one- and two-finger touches
if (!(touchCount == 1 || touchCount == 2)) {
return;
}
const lastEvent /*: TouchEvent */ = (LargeGraphic.lastEvent /*: any */);
// start over -- somehow switched from one-touch to two-touch dnd in midstream
if (lastEvent != null && touchEvent.type != 'touchstart' && LargeGraphic.touches(lastEvent).length != touchCount) {
return;
}
const syntheticType = touchEvent.type + ((touchCount == 2) ? '_2' : '');
switch (syntheticType) {
case 'touchstart':
case 'touchstart_2':
LargeGraphic.lastEvent = touchEvent;
break;
case 'touchmove':
if (lastEvent != undefined) {
if (lastEvent.type == 'touchstart' && touchEvent.timeStamp - lastEvent.timeStamp < 350) {
// too soon to tell if this is a click or a drag -- don't do anything, wait for next event
} else {
if (lastEvent.type == 'touchstart') {
LargeGraphic.dragStart(touches[0]);
} else {
LargeGraphic.dragOver(touches[0]);
}
LargeGraphic.lastEvent = touchEvent;
}
}
touchEvent.preventDefault();
break;
case 'touchmove_2':
if (lastEvent != undefined) {
LargeGraphic.touchZoomAndMove(lastEvent, touchEvent);
LargeGraphic.lastEvent = touchEvent;
touchEvent.preventDefault();
}
break;
case 'touchend':
if (lastEvent != undefined) {
if (lastEvent.type == 'touchstart' && touchEvent.timeStamp - lastEvent.timeStamp < 350) {
if (LargeGraphic.displayNewLabel(touches[0])) {
touchEvent.preventDefault(); // prevent this from turning into a click event and clearing all labels
}
} else {
LargeGraphic.dragEnd(touches[0]);
}
}
LargeGraphic.lastEvent = null;
break;
case 'touchend_2':
if (lastEvent != undefined) {
if (lastEvent.type == 'touchstart' && touchEvent.timeStamp - lastEvent.timeStamp < 350) {
LargeGraphic.zoom2fit();
} else {
LargeGraphic.touchZoomAndMove(lastEvent, touchEvent);
}
}
LargeGraphic.lastEvent = null;
touchEvent.stopPropagation();
touchEvent.preventDefault();
break;
default:
Log.warn('LargeGraphic.touchHandler unknown event %s', syntheticType);
}
}
static loc2rowXcol(event /*: eventLocation */) /*: ?rowXcol */ {
const bounding_rectangle = $('#graphic')[0].getBoundingClientRect();
const canvasX = event.clientX - bounding_rectangle.left;
const canvasY = event.clientY - bounding_rectangle.top;
return Multtable_View.xy2rowXcol(canvasX, canvasY);
}
static displayNewLabel(loc /*: eventLocation */) /*: ?HTMLElement */ {
const rowXcol = LargeGraphic.loc2rowXcol(loc);
const hasLabel = rowXcol && $(`#node-label[row='${rowXcol.row}'][col='${rowXcol.col}']`).length != 0;
GEUtils.cleanWindow();
if (rowXcol == undefined || hasLabel) {
return null;
} else {
const element = Group.mult(Multtable_View.elements[rowXcol.row], Multtable_View.elements[rowXcol.col]);
const $label = $(eval(Template.HTML('node-label-template')))
.appendTo('#graphic');
Menu.setMenuLocation($label, loc);
return $label[0];
}
}
static touches(touchEvent /*: TouchEvent */) /*: Array<Touch> */ {
if (touchEvent.type == 'touchend') {
const result = Array.from(touchEvent.changedTouches);
result.push(...Array.from(touchEvent.touches));
return result;
} else {
return Array.from(touchEvent.touches);
}
}
static centroidAndDiameter(touchArray /*: Array<Touch> */) /*: [eventLocation, float] */ {
const centroid = {clientX: (touchArray[0].clientX + touchArray[1].clientX)/2,
clientY: (touchArray[0].clientY + touchArray[1].clientY)/2 },
dx = touchArray[0].clientX - touchArray[1].clientX,
dy = touchArray[0].clientY - touchArray[1].clientY,
diameter = Math.sqrt(dx*dx + dy*dy);
return [centroid, diameter];
}
static touchZoomAndMove(start /*: TouchEvent */, end /*: TouchEvent */) {
GEUtils.cleanWindow();
const [startCentroid, startDiameter] = LargeGraphic.centroidAndDiameter(LargeGraphic.touches(start)),
[endCentroid, endDiameter] = LargeGraphic.centroidAndDiameter(LargeGraphic.touches(end)),
zoomFactor = endDiameter / startDiameter;
Multtable_View
.zoom(endDiameter / startDiameter)
.move(endCentroid.clientX - startCentroid.clientX, endCentroid.clientY - startCentroid.clientY);
}
static mouseMove(start /*: MouseEvent */, end /*: MouseEvent */) {
GEUtils.cleanWindow();
Multtable_View.move(end.clientX - start.clientX, end.clientY - start.clientY);
}
static zoom2fit() {
GEUtils.cleanWindow();
Multtable_View.resetZoom();
}
static dragStart(loc /*: eventLocation */) /*: ?HTMLElement */ {
const rowXcol = LargeGraphic.loc2rowXcol(loc); // row, column of event location
if (rowXcol == undefined) {
return null;
}
GEUtils.cleanWindow();
const canvas = Multtable_View.canvas;
// find width of a single cell, and width of the entire table
// make these the width and height of the img, bounded by canvas size
const cellSize = Multtable_View.transform.elements[0]; // [0] is the scale in the transform matrix
const tableSize = Multtable_View.table_size * cellSize;
let width, height, swapping, start;
if (rowXcol.row == 0 && rowXcol.col != 0) { // dragging column?
[swapping, start, width, height] = ['col', rowXcol.col, cellSize, tableSize];
} else if (rowXcol.col == 0 && rowXcol.row != 0) { // dragging row?
[swapping, start, width, height] = ['row', rowXcol.row, tableSize, cellSize];
} else {
return null;
}
// upper left corner of clicked cell in canvas-relative coordinates
const position = new THREE.Vector3(rowXcol.col, rowXcol.row, 1).applyMatrix3(Multtable_View.transform);
const style =
'position: absolute; ' +
`width: ${width}; height: ${height}; ` +
'object-fit: none; ' +
`object-position: -${position.x.toFixed(0)}px -${position.y.toFixed(0)}px; ` +
'opacity: 0.75; ' +
'';
const $image = $(eval(Template.HTML('drag-image-template')))
.appendTo('#graphic');
LargeGraphic.dragOver(loc);
return $image[0];
}
static dragOver(loc /*: eventLocation */) {
const rowXcol = LargeGraphic.loc2rowXcol(loc);
// must be on first row / column to display drag image
const swapping = $('#drag-image').attr('swapping');
if ( rowXcol != undefined
&& ( (swapping == 'row' && rowXcol.col == 0 && rowXcol.row != 0)
|| (swapping == 'col' && rowXcol.row == 0 && rowXcol.col != 0) ) ) {
$('#drag-image').show()
.css('top', `${loc.clientY}`)
.css('left', `${loc.clientX}`);
} else {
$('#drag-image').hide();
}
}
static dragEnd(loc /*: eventLocation */) {
const cleanup = () => ($('#drag-image').remove(), undefined);
/* don't swap if
* there's no drag image
* loc isn't over the table
* loc isn't in the 1st row / column
* loc is in the original row / column (so there's no swap to be done)
*/
const $dragImage = $('#drag-image');
if ($dragImage.length == 0)
return cleanup();
const rowXcol = LargeGraphic.loc2rowXcol(loc);
if (rowXcol == undefined)
return cleanup();
const swapping = $dragImage.attr('swapping');
const start = parseInt($dragImage.attr('start'));
$dragImage.remove();
if ( (swapping == 'row' && (rowXcol.col != 0 || rowXcol.row == 0 || rowXcol.row == start))
|| (swapping == 'col' && (rowXcol.row != 0 || rowXcol.col == 0 || rowXcol.col == start)) )
return cleanup();
if (swapping == 'row') {
Multtable_View.swap(start, rowXcol.row);
} else {
Multtable_View.swap(start, rowXcol.col);
}
return cleanup();
}
}