-
Notifications
You must be signed in to change notification settings - Fork 482
/
designMode.js
1282 lines (1132 loc) · 41 KB
/
designMode.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global Applab, dashboard */
import $ from 'jquery';
import 'jquery-ui'; // for $.fn.resizable();
import React from 'react';
import ReactDOM from 'react-dom';
import DesignWorkspace from './DesignWorkspace';
import * as assetPrefix from '../assetManagement/assetPrefix';
import elementLibrary from './designElements/library';
import * as elementUtils from './designElements/elementUtils';
import {singleton as studioApp} from '../StudioApp';
import {KeyCodes} from '../constants';
import * as applabConstants from './constants';
import sanitizeHtml from './sanitizeHtml';
import * as utils from '../utils';
import * as gridUtils from './gridUtils';
import logToCloud from '../logToCloud';
import * as actions from './actions';
import * as screens from './redux/screens';
var designMode = {};
export default designMode;
var ICON_PREFIX = applabConstants.ICON_PREFIX;
var ICON_PREFIX_REGEX = applabConstants.ICON_PREFIX_REGEX;
var currentlyEditedElement = null;
var clipboardElement = null;
var ApplabInterfaceMode = applabConstants.ApplabInterfaceMode;
var ANIMATION_LENGTH_MS = applabConstants.ANIMATION_LENGTH_MS;
/**
* Subscribe to state changes on the store.
* @param {!Store} store
*/
designMode.setupReduxSubscribers = function (store) {
var state;
store.subscribe(function () {
var lastState = state;
state = store.getState();
if (!lastState ||
state.screens.currentScreenId !== lastState.screens.currentScreenId) {
renderScreens(state.screens.currentScreenId);
}
});
};
/**
* If in design mode and program is not running, display Properties
* pane for editing the clicked element.
* @param event
*/
designMode.onDesignModeVizClick = function (event) {
if (!Applab.isInDesignMode() ||
$('#resetButton').is(':visible')) {
return;
}
event.preventDefault();
var element = event.target;
if (element.id === 'designModeViz') {
element = designMode.activeScreen();
}
if ($(element).is('.ui-resizable')) {
element = getInnerElement(element);
} else if ($(element).is('.ui-resizable-handle')) {
element = getInnerElement(element.parentNode);
} else if ($(element).attr('class') === undefined && $(element.parentNode).is('.textArea')) {
// User may have clicked one of the divs of a multiline text area - in this case, the element is just a plain
// div with no class, and we want to use the full text area element.
element = getInnerElement(element.parentNode.parentNode);
}
// Give the div focus so that we can listen for keyboard events.
$("#designModeViz").focus();
designMode.editElementProperties(element);
};
/**
* @returns {HTMLElement} The currently visible screen element.
*/
designMode.activeScreen = function () {
return elementUtils.getScreens().filter(function () {
return this.style.display !== 'none';
}).first()[0];
};
/**
* Create a new element of the specified type within the play space.
* @param {ElementType} elementType Type of element to create
* @param {number} left Position from left.
* @param {number} top Position from top.
* @returns {HTMLElement} The generated element
*/
designMode.createElement = function (elementType, left, top) {
var element = elementLibrary.createElement(elementType, left, top);
designMode.attachElement(element);
return element;
};
designMode.attachElement = function (element) {
var parent;
var isScreen = $(element).hasClass('screen');
if (isScreen) {
parent = document.getElementById('designModeViz');
} else {
parent = designMode.activeScreen();
}
parent.appendChild(element);
if (!isScreen) {
makeDraggable($(element));
}
designMode.editElementProperties(element);
};
designMode.editElementProperties = function (element) {
var designPropertiesElement = document.getElementById('design-properties');
if (!designPropertiesElement) {
// design-properties won't exist when !user.isAdmin
return;
}
highlightElement(element);
currentlyEditedElement = element;
designMode.renderDesignWorkspace(element);
};
/**
* Loads the current element or current screen into the property tab.
* Also makes sure we re-render design mode to update properties such as isDimmed.
*/
designMode.resetPropertyTab = function () {
var element = currentlyEditedElement || designMode.activeScreen();
designMode.editElementProperties(element);
Applab.render();
};
/**
* Enable (or disable) dragging of new elements from the element tray
* @param allowEditing {boolean}
*/
designMode.resetElementTray = function (allowEditing) {
$('#design-toolbox .new-design-element').each(function () {
$(this).draggable(allowEditing ? 'enable' : 'disable');
});
};
/**
* Given an input value produce a valid css value that is
* either in pixels or empty.
*/
function appendPx(input) {
// Don't append if we already have a px
if (/px/.test(input)) {
return input;
}
return input ? input + 'px' : '';
}
/**
* While in design mode, elements get wrapped in a ui-draggable container.
* @returns {true} If element is currently wrapped
*/
function isDraggableContainer(element) {
return $(element).hasClass('ui-draggable');
}
/**
* Handle a change from our properties table.
* @param element {Element}
* @param name {string}
* @param value {string}
*/
designMode.onPropertyChange = function (element, name, value) {
designMode.updateProperty(element, name, value);
designMode.editElementProperties(element);
};
/**
* After handling properties generically, give elementLibrary a chance
* to do any element specific changes.
* @param element
* @param name
* @param value
*/
designMode.updateProperty = function (element, name, value) {
var handled = true;
switch (name) {
case 'id':
value = value.trim();
elementUtils.setId(element, value);
if (elementLibrary.getElementType(element) ===
elementLibrary.ElementType.SCREEN) {
// rerender design toggle, which has a dropdown of screen ids
designMode.changeScreen(value);
}
break;
case 'left':
var newLeft = appendPx(value);
element.style.left = newLeft;
if (isDraggableContainer(element.parentNode)) {
element.parentNode.style.left = newLeft;
}
break;
case 'top':
var newTop = appendPx(value);
element.style.top = newTop;
if (isDraggableContainer(element.parentNode)) {
element.parentNode.style.top = newTop;
}
break;
case 'width':
element.setAttribute('width', appendPx(value));
break;
case 'height':
element.setAttribute('height', appendPx(value));
break;
case 'style-width':
var newWidth = appendPx(value);
element.style.width = newWidth;
if (isDraggableContainer(element.parentNode)) {
element.parentNode.style.width = newWidth;
}
break;
case 'style-height':
var newHeight = appendPx(value);
element.style.height = newHeight;
if (isDraggableContainer(element.parentNode)) {
element.parentNode.style.height = newHeight;
}
break;
case 'text':
element.innerHTML = utils.escapeText(value);
break;
case 'textColor':
element.style.color = value;
break;
case 'backgroundColor':
element.style.backgroundColor = value;
break;
case 'fontSize':
element.style.fontSize = appendPx(value);
break;
case 'textAlign':
element.style.textAlign = value;
break;
case 'icon-color':
element.setAttribute('data-icon-color', value);
break;
case 'image':
var originalValue = element.getAttribute('data-canonical-image-url');
element.setAttribute('data-canonical-image-url', value);
var fitImage = function () {
// Fit the image into the button
element.style.backgroundSize = 'contain';
element.style.backgroundPosition = '50% 50%';
element.style.backgroundRepeat = 'no-repeat';
// Re-render properties
if (currentlyEditedElement === element) {
designMode.editElementProperties(element);
}
};
if (ICON_PREFIX_REGEX.test(value)) {
element.style.backgroundImage = 'url(' + assetPrefix.renderIconToString(value, element) + ')';
fitImage();
break;
}
var backgroundImage = new Image();
backgroundImage.src = assetPrefix.fixPath(value);
element.style.backgroundImage = 'url(' + backgroundImage.src + ')';
// do not resize if only the asset path has changed (e.g. on remix).
if (value !== originalValue) {
backgroundImage.onload = fitImage;
}
break;
case 'screen-image': {
element.setAttribute('data-canonical-image-url', value);
// We stretch the image to fit the element
var width = parseInt(element.style.width, 10);
var height = parseInt(element.style.height, 10);
element.style.backgroundSize = width + 'px ' + height + 'px';
let url;
if (ICON_PREFIX_REGEX.test(value)) {
url = assetPrefix.renderIconToString(value, element);
} else {
const screenImage = new Image();
screenImage.src = assetPrefix.fixPath(value);
url = screenImage.src;
}
element.style.backgroundImage = 'url(' + url + ')';
break;
}
case 'picture':
originalValue = element.getAttribute('data-canonical-image-url');
element.setAttribute('data-canonical-image-url', value);
if (ICON_PREFIX_REGEX.test(value)) {
element.src = assetPrefix.renderIconToString(value, element);
break;
}
element.src = assetPrefix.fixPath(value);
// do not resize if only the asset path has changed (e.g. on remix).
if (value !== originalValue) {
var resizeElement = function (width, height) {
element.style.width = width + 'px';
element.style.height = height + 'px';
if (isDraggableContainer(element.parentNode)) {
element.parentNode.style.width = width + 'px';
element.parentNode.style.height = height + 'px';
}
// Re-render properties
if (currentlyEditedElement === element) {
designMode.editElementProperties(element);
}
};
if (value === '') {
element.src = '/blockly/media/1x1.gif';
resizeElement(100, 100);
} else {
element.onload = function () {
// naturalWidth/Height aren't populated until image has loaded.
var left = parseFloat(element.style.left);
var top = parseFloat(element.style.top);
var dimensions = boundedResize(left, top, element.naturalWidth, element.naturalHeight, true);
resizeElement(dimensions.width, dimensions.height);
// only perform onload once
element.onload = null;
};
}
}
break;
case 'hidden':
// Add a class that shows as 30% opacity in design mode, and invisible
// in code mode.
$(element).toggleClass('design-mode-hidden', value === true);
break;
case 'checked':
// element.checked represents the current state, the attribute represents
// the serialized state
element.checked = value;
if (value) {
var groupName = element.getAttribute('name');
if (groupName) {
// Remove checked attribute from all other radio buttons in group
var buttons = document.getElementsByName(groupName);
Array.prototype.forEach.call(buttons, function (item) {
if (item.type === 'radio') {
item.removeAttribute('checked');
}
});
}
element.setAttribute('checked', 'checked');
} else {
element.removeAttribute('checked');
}
break;
case 'options':
// value should be an array of options in this case
for (var i = 0; i < value.length; i++) {
var optionElement = element.children[i];
if (!optionElement) {
optionElement = document.createElement('option');
element.appendChild(optionElement);
}
optionElement.textContent = value[i];
}
// remove any extra options
while (element.children[i]) {
element.removeChild(element.children[i]);
}
break;
case 'groupId':
element.setAttribute('name', value);
break;
case 'placeholder':
element.setAttribute('placeholder', value);
break;
case 'rows':
element.setAttribute('rows', value);
break;
case 'cols':
element.setAttribute('rows', value);
break;
case 'readonly':
element.setAttribute('contenteditable', !value);
break;
case 'is-default':
if (value === true) {
// Make this one default
$('#designModeViz').prepend(element);
//Resort elements in the dropdown list
var options = $('#screenSelector option');
var newScreenText = applabConstants.NEW_SCREEN;
var defaultScreenId = elementUtils.getId(element);
options.sort(function (a, b) {
if (a.text === defaultScreenId) {
return -1;
} else if (b.text === defaultScreenId) {
return 1;
} else if (a.text === newScreenText) {
return 1;
} else if (b.text === newScreenText) {
return -1;
} else {
return a.text.localeCompare(b.text);
}
});
$('#screenSelector').html(options);
$('#screenSelector')[0].selectedIndex = 0;
}
break;
default:
// Mark as unhandled, but give typeSpecificPropertyChange a chance to
// handle it
handled = false;
}
if (elementLibrary.typeSpecificPropertyChange(element, name, value)) {
handled = true;
}
if (!handled) {
throw "unknown property name " + name;
}
};
/**
* Reads property 'name' of html element 'element'.
* @param {Element} element The html element to read the property from. The element could
* have been created in design mode or code mode.
* @param {string} name The internal name of the property to read. This is not always
* the name of an html attribute or css style. Valid names are different for each
* element as defined in PROP_INFO in setPropertyDropdown.js.
* @returns {*}
*/
designMode.readProperty = function (element, name) {
switch (name) {
case 'left':
// Ignore 'px' suffix
return parseFloat(element.style.left);
case 'top':
return parseFloat(element.style.top);
case 'width':
return parseFloat(element.getAttribute('width'));
case 'height':
return parseFloat(element.getAttribute('height'));
case 'style-width':
return parseFloat(element.style.width);
case 'style-height':
return parseFloat(element.style.height);
case 'text':
return utils.escapeText(element.innerHTML);
case 'textColor':
return element.style.color;
case 'backgroundColor':
return element.style.backgroundColor;
case 'fontSize':
return parseFloat(element.style.fontSize);
case 'textAlign':
return element.style.textAlign;
case 'image':
return element.getAttribute('data-canonical-image-url');
case 'screen-image':
return element.getAttribute('data-canonical-image-url');
case 'picture':
return element.getAttribute('data-canonical-image-url');
case 'hidden':
return $(element).hasClass('design-mode-hidden');
case 'checked':
// element.checked represents the current state, the attribute represents
// the serialized state
return !!element.checked;
case 'options':
return $(element).children().map((i, child) => child.text).get();
case 'groupId':
return element.getAttribute('name');
case 'placeholder':
return element.getAttribute('placeholder');
case 'readonly':
return element.getAttribute('contenteditable') !== 'true';
default:
// The property was not found in the list of properties which apply to all elements.
// Check to see if the element-specific handler knows how to read the property,
// which will raise an error if the property or handler is not found.
return elementLibrary.typeSpecificPropertyRead(element, name);
}
};
designMode.onDuplicate = function (element, event) {
var isScreen = $(element).hasClass('screen');
if (isScreen) {
// Not duplicating screens for now
return;
}
var duplicateElement = element.cloneNode(true);
var dupLeft = parseInt(element.style.left, 10) + 10;
var dupTop = parseInt(element.style.top, 10) + 10;
var dupWidth = parseInt(element.style.width, 10);
var dupHeight = parseInt(element.style.height, 10);
// Ensure the position of the duplicate element is within the bounds of the container
var position = enforceContainment(dupLeft, dupTop, dupWidth, dupHeight);
// Change the ID and location of the duplicate element
duplicateElement.style.left = appendPx(position.left);
duplicateElement.style.top = appendPx(position.top);
var elementType = elementLibrary.getElementType(element);
elementUtils.setId(duplicateElement, elementLibrary.getUnusedElementId(elementType.toLowerCase()));
// Attach the duplicate element and then focus on it
designMode.attachElement(duplicateElement);
duplicateElement.focus();
designMode.editElementProperties(duplicateElement);
return duplicateElement;
};
designMode.onDeletePropertiesButton = function (element, event) {
deleteElement(element);
};
function deleteElement(element) {
var isScreen = $(element).hasClass('screen');
if ($(element.parentNode).is('.ui-resizable')) {
element = element.parentNode;
}
$(element).remove();
if (isScreen) {
designMode.loadDefaultScreen();
} else {
designMode.editElementProperties(
elementUtils.getPrefixedElementById(
studioApp.reduxStore.getState().screens.currentScreenId));
}
}
designMode.onDepthChange = function (element, depthDirection) {
// move to outer resizable div
var outerElement = element.parentNode;
var parent = outerElement.parentNode;
var index = Array.prototype.indexOf.call(parent.children, outerElement);
if (depthDirection === 'forward' && index + 2 >= parent.children.length) {
// We're either the last or second to last element
depthDirection = 'toFront';
}
var removed;
// TODO (brent) - use an enum?
switch (depthDirection) {
case 'forward':
var twoAhead = outerElement.nextSibling.nextSibling;
removed = parent.removeChild(outerElement);
parent.insertBefore(removed, twoAhead);
break;
case 'toFront':
removed = parent.removeChild(outerElement);
parent.appendChild(removed);
break;
case 'backward':
var previous = outerElement.previousSibling;
if (!previous) {
return;
}
removed = parent.removeChild(outerElement);
parent.insertBefore(removed, previous);
break;
case 'toBack':
if (parent.children.length === 1) {
return;
}
removed = parent.removeChild(outerElement);
parent.insertBefore(removed, parent.children[0]);
break;
default:
throw new Error('unknown depthDirection: ' + depthDirection);
}
element.focus();
designMode.editElementProperties(element);
};
designMode.onInsertEvent = function (code) {
Applab.appendToEditor(code);
studioApp.reduxStore.dispatch(actions.changeInterfaceMode(ApplabInterfaceMode.CODE));
Applab.scrollToEnd();
};
/**/
designMode.serializeToLevelHtml = function () {
var designModeViz = $('#designModeViz');
// Children are screens. Want to operate on grandchildren
var madeUndraggable = makeUndraggable(designModeViz.children().children());
// Make a copy so that we don't affect designModeViz contents as we
// remove prefixes from the element ids.
var designModeVizClone = designModeViz.clone();
designModeVizClone.children().each(function () {
elementUtils.removeIdPrefix(this);
});
designModeVizClone.children().children().each(function () {
elementUtils.removeIdPrefix(this);
});
// Remove the "data:img/png..." URI from icon images
designModeVizClone.find('[data-canonical-image-url^="' + ICON_PREFIX + '"]').each(function () {
this.removeAttribute('src');
this.style.backgroundImage = '';
});
var serialization = designModeVizClone[0] ? designModeVizClone[0].outerHTML : '';
if (madeUndraggable) {
makeDraggable(designModeViz.children().children());
}
Applab.levelHtml = serialization;
return serialization;
};
function getUnsafeHtmlReporter(sanitizationTarget) {
return function (removed, unsafe, safe) {
var msg = "The following lines of HTML were modified or removed:\n" + removed +
"\noriginal html:\n" + unsafe + "\nmodified html:\n" + safe + "\ntarget: " + sanitizationTarget;
console.log(msg);
logToCloud.addPageAction(logToCloud.PageAction.SanitizedLevelHtml, {
removedHtml: removed,
unsafeHtml: unsafe,
safeHtml: safe,
sanitizationTarget: sanitizationTarget
});
};
}
/**
* Parses/modifies a single screen's html representation as loaded from levelHTML.
*
* @param screenEl {Element|string} element encapsulating the dom for a single screen
* within a level's html. Can be a string of html as well. Note: If this is an element,
* then this function will have side effects.
* @param allowDragging {boolean} Whether to make elements resizable and draggable.
* @param prefix {string} Optional prefix to attach to element ids of children and
* grandchildren after parsing. Defaults to ''.
*
* @returns returns the modified version of the element passed in for screenEl.
*/
designMode.parseScreenFromLevelHtml = function (screenEl, allowDragging, prefix) {
var screen = $(screenEl);
elementUtils.addIdPrefix(screen[0], prefix);
screen.children().each(function () {
elementUtils.addIdPrefix(this, prefix);
});
if (allowDragging) {
// screen are screens. make grandchildren draggable
makeDraggable(screen.children());
}
elementLibrary.onDeserialize(screen[0], designMode.updateProperty.bind(this));
screen.children().each(function () {
var element = $(this).hasClass('ui-draggable') ? this.firstChild : this;
elementLibrary.onDeserialize(element, designMode.updateProperty.bind(element));
});
return screen[0];
};
/**
* Replace the contents of rootEl with the children of the DOM node obtained by
* parsing Applab.levelHtml (the root node in the levelHtml is ignored).
* @param rootEl {Element} Element whose children should be replaced.
* @param allowDragging {boolean} Whether to make elements resizable and draggable.
* @param prefix {string} Optional prefix to attach to element ids of children and
* grandchildren after parsing. Defaults to ''.
*/
designMode.parseFromLevelHtml = function (rootEl, allowDragging, prefix) {
if (!rootEl) {
return;
}
while (rootEl.firstChild) {
rootEl.removeChild(rootEl.firstChild);
}
if (!Applab.levelHtml) {
return;
}
var reportUnsafeHtml = getUnsafeHtmlReporter(rootEl.id);
var levelDom = $.parseHTML(sanitizeHtml(Applab.levelHtml, reportUnsafeHtml, true));
var children = $(levelDom).children();
children.each(function () { designMode.parseScreenFromLevelHtml(this, allowDragging, prefix); });
children.appendTo(rootEl);
};
/**
* When we make elements resizable, we wrap them in an outer div. Given an outer
* div, this returns the inner element
*/
function getInnerElement(outerElement) {
// currently assume inner element is first child.
return outerElement.children[0];
}
/**
* Returns a new width/height bounded to the visualization area.
* @param {number} left
* @param {number} top
* @param {number} width Requested width.
* @param {number} height Requested height.
* @param {boolean} preserveAspectRatio Constrain the width/height to the
* initial aspect ratio.
* @return {{width: number, height: number}}
*/
function boundedResize(left, top, width, height, preserveAspectRatio) {
var container = $('#designModeViz');
var maxWidth = container.outerWidth() - left;
var maxHeight = container.outerHeight() - top;
var newWidth = Math.min(width, maxWidth);
newWidth = Math.max(newWidth, 20);
var newHeight = Math.min(height, maxHeight);
newHeight = Math.max(newHeight, 20);
if (preserveAspectRatio) {
var ratio = Math.min(newWidth / width, newHeight / height);
newWidth = width * ratio;
newHeight = height * ratio;
}
return {width: newWidth, height: newHeight};
}
/**
*
* @param {jQuery} jqueryElements jQuery object containing DOM elements to make
* draggable.
*/
function makeDraggable(jqueryElements) {
// For a non-div to be draggable & resizable it needs to be wrapped in a div.
jqueryElements.each(function () {
var elm = $(this);
var wrapper = elm.wrap('<div>').parent().resizable({
create: function () {
// resizable sets z-index to 90, which we don't want
$(this).children().css('z-index', '');
},
start: function () {
highlightElement(elm[0]);
},
resize: function (event, ui) {
// Wishing for a vector maths library...
// Customize motion according to current visualization scale.
var scale = getVisualizationScale();
var deltaWidth = ui.size.width - ui.originalSize.width;
var deltaHeight = ui.size.height - ui.originalSize.height;
var newWidth = ui.originalSize.width + (deltaWidth / scale);
var newHeight = ui.originalSize.height + (deltaHeight / scale);
// Get positions that snap to the grid
newWidth = gridUtils.snapToGridSize(newWidth);
newHeight = gridUtils.snapToGridSize(newHeight);
// Get positions that are bounded within app space
var dimensions = boundedResize(ui.position.left, ui.position.top, newWidth, newHeight, false);
// Update the position of wrapper (.ui-resizable) div
ui.element.outerWidth(dimensions.width);
ui.element.outerHeight(dimensions.height);
// Set original element properties to update values in Property tab
if (elm.is("canvas")) {
// for canvas we need to set width/height attributes directly as these
// control canvas size rather than style.width/style.height
elm.attr('width', dimensions.width + "px");
elm.attr('height', dimensions.height + "px");
}
// set style.width/style.height regardless, as this is used to size our
// background image
elm.outerWidth(dimensions.width);
elm.outerHeight(dimensions.height);
// Re-render design work space for this element
designMode.renderDesignWorkspace(elm[0]);
}
}).draggable({
cancel: false, // allow buttons and inputs to be dragged
start: function () {
highlightElement(elm[0]);
// Turn off clipping in app space so we can drag the element
// out of it
setAppSpaceClipping(false);
},
drag: function (event, ui) {
// draggables are not compatible with CSS transform-scale,
// so adjust the position in various ways here.
// Scale position to express it relative to app-space (instead of screen-space)
var scale = getVisualizationScale();
var newLeft = ui.position.left / scale;
var newTop = ui.position.top / scale;
// Get positions that snap to the grid
newLeft = gridUtils.snapToGridSize(newLeft);
newTop = gridUtils.snapToGridSize(newTop);
// Update the position of wrapper (.ui-draggable) div to snap to grid
ui.position.left = newLeft;
ui.position.top = newTop;
// Set original element properties to update values in Property tab
elm.css({
left: newLeft,
top: newTop,
});
// Dim the element if it's dragged out of bounds
if (!isMouseEventInBounds(event)) {
elm.addClass("toDelete");
} else {
elm.removeClass("toDelete");
}
// Re-render design work space for this element
designMode.renderDesignWorkspace(elm[0]);
},
stop: function (event, ui) {
// Note: It looks like the ui.position values don't change between
// the last drag event and the stop event. Since we already performed
// the scale transformation on ui.position values in the drag handler,
// there's no need to transform ui.position coordinates again here.
// Check the drop location to determine whether we delete this element
if (!isMouseEventInBounds(event)) {
// It's dropped out of bounds, animate and delete
ui.helper.hide( "drop", { direction: "down" }, ANIMATION_LENGTH_MS, function () {
deleteElement(elm[0]);
});
} else {
// Render design work space for this element
designMode.renderDesignWorkspace(elm[0]);
}
// Turn clipping back on so it's not possible for elements
// to bleed out of app space
setAppSpaceClipping(true);
},
}).css({
position: 'absolute',
lineHeight: '0px'
});
wrapper.css({
top: elm.css('top'),
left: elm.css('left'),
});
// Chrome/Safari both have issues where they don't properly render the
// wrapper if the inner element is a div. This is a hack that causes a
// rerender to happen in chrome
var currHeight = wrapper.parent().height();
wrapper.parent().height(currHeight + 1);
wrapper.parent().height(currHeight);
// And a hack for Safari
if (this.tagName === 'DIV') {
setTimeout(function () {
wrapper.hide().show(0);
}, 0);
}
elm.css('position', 'static');
});
}
/**
* Provide coordinates for the element that are enforced within the container space.
*/
function enforceContainment(left, top, width, height) {
var container = $('#designModeViz');
var maxLeft = container.outerWidth() - width;
var maxTop = container.outerHeight() - height;
var newLeft = Math.min(left, maxLeft);
newLeft = Math.max(newLeft, 0);
var newTop = Math.min(top, maxTop);
newTop = Math.max(newTop, 0);
return {'left': newLeft, 'top': newTop};
}
/**
* Tests whether the coordinates of the mouse event are inside designModeViz,
* taking into account any scaling transforms that may be applied to designModeViz.
* @param {jQuery.Event} mouseEvent
* @returns {boolean}
*/
function isMouseEventInBounds(mouseEvent) {
const container = $('#designModeViz');
return gridUtils.isMouseEventInBounds(mouseEvent, container);
}
/**
* Sets app space clipping behavior. App space is clipped if clip == true.
* @param {boolean} clip
*/
function setAppSpaceClipping(clip) {
var container = $('#designModeViz');
if (clip) {
// Delay the clipping until we're done the delete/pushback animation
container.delay(ANIMATION_LENGTH_MS).addClass('clip-content', ANIMATION_LENGTH_MS);
} else {
container.removeClass('clip-content');
}
}
/**
* Calculate the current visualization scale factor, as screenWidth / domWidth.
* @returns {number}
*/
function getVisualizationScale() {
var div = document.getElementById('designModeViz');
return div.getBoundingClientRect().width / div.offsetWidth;
}
/**
* Inverse of `makeDraggable`.
* @param {jQuery} jqueryElements jQuery object containing DOM elements to make
* undraggable.
* @returns {boolean} True if we made something undraggable
*/
function makeUndraggable(jqueryElements) {
var foundOne = false;
jqueryElements.each(function () {
var wrapper = $(this);
var elm = $(getInnerElement(this));
// Don't unwrap elements that aren't wrapped with a draggable div.
if (!wrapper.hasClass('ui-draggable')) {
return;
}
foundOne = true;
wrapper.resizable('destroy').draggable('destroy');
elm.css('position', 'absolute');
elm.unwrap();
});
return foundOne;
}
/**
* Highlights an element with a dashed border, removes border from all other elements
* Must only be called on an element wrapped in a draggable div
*/
function highlightElement(element) {
removeElementHighlights();
if ($(element).is('#designModeViz img[src!=""], #designModeViz label')) {
$(element).parent().css({
outlineStyle: 'dashed',
outlineWidth: '1px',
});
}
}
/**
* Remove dashed borders from all elements
*/