This repository has been archived by the owner on Jul 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
hax-body.html
1521 lines (1509 loc) · 63.5 KB
/
hax-body.html
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
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../paper-menu/paper-menu.html">
<link rel="import" href="../paper-item/paper-item.html">
<link rel="import" href="../grid-plate/grid-plate.html">
<link rel="import" href="../iron-a11y-keys/iron-a11y-keys.html">
<link rel="import" href="hax-text-context.html">
<link rel="import" href="hax-ce-context.html">
<link rel="import" href="hax-plate-context.html">
<link rel="import" href="hax-input-mixer.html">
<!--
`hax-body`
A LRN element that will change the world.
@demo demo/index.html
@microcopy - the mental model for this element
- body is effectively a body of content that can be manipulated in the browser. This is for other HAX elements ultimately to interface with and reside in. It is the controller of input and output for all of HAX as it exists in a document. body is not the <body> tag but we need a similar mental model container for all our other elements.
- text-context - the context menu that shows up when an item is active so it can have text based operations performed to it.
- plate/grid plate - a plate or grid plate is a container that we can operate on in HAX. it can also have layout / "global" type of body operations performed on it such as delete, duplicate and higher level format styling.
-->
<dom-module id="hax-body">
<template strip-whitespace>
<style>
:host {
display: block;
min-height: 32px;
min-width: 32px;
/*font-family: sans-serif;*/
}
:host #bodycontainer ::slotted(.hax-context-menu) {
padding: 0;
margin: 0;
position: absolute;
visibility: hidden;
opacity: 0;
transition: all .3s ease;
z-index: 100;
float: left;
display: block;
}
:host #bodycontainer ::slotted(#haxinputmixer) {
z-index: 10000000;
}
:host #bodycontainer ::slotted(.hax-context-visible) {
visibility: visible;
opacity: 1;
}
:host[edit-mode] #bodycontainer ::slotted(*[data-editable]) {
outline: none;
transition:
.6s width ease-in-out,
.6s height ease-in-out,
.6s margin ease-in-out;
}
:host[edit-mode] #bodycontainer ::slotted(p):empty {
background: #f8f8f8;
}
:host[edit-mode] #bodycontainer ::slotted(*[data-editable]):hover {
outline: 1px dotted #d3d3d3;
outline-offset: 2px;
}
:host[edit-mode] #bodycontainer ::slotted(* [data-editable]):hover {
outline: 1px dotted #d3d3d3;
outline-offset: 2px;
}
:host[edit-mode] #bodycontainer ::slotted(*[data-editable])::before {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 32px;
transition: .6s all ease;
}
:host[edit-mode] #bodycontainer ::slotted(*[data-editable]):hover::before {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 32px;
transition: .6s all ease;
}
:host[edit-mode] #bodycontainer ::slotted(*.hax-active[data-editable]) {
cursor: text !important;
outline: 1px dashed #c3c3c3 !important;
outline-offset: 4px;
}
:host[edit-mode] #bodycontainer ::slotted(*[data-editable] .hax-active) {
cursor: text !important;
outline: 1px dashed #c3c3c3 !important;
outline-offset: 4px;
}
:host[edit-mode] #bodycontainer ::slotted(*.hax-active[data-editable])::before {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 32px;
transition: .6s all ease;
}
:host[edit-mode] #bodycontainer ::slotted(code.hax-active[data-editable]) {
display: block;
}
:host[edit-mode] #bodycontainer ::slotted(hr[data-editable]) {
height:4px;
background-color: #EEEEEE;
padding-top: 8px;
padding-bottom: 8px;
}
/** Fix to support safari as it defaults to none */
:host[edit-mode] #bodycontainer ::slotted(*[data-editable]) {
-webkit-user-select: text;
cursor:pointer;
}
:host[edit-mode] #bodycontainer ::slotted(*[data-editable]::-moz-selection),
:host[edit-mode] #bodycontainer ::slotted(*[data-editable] *::-moz-selection) {
background-color: var(--hax-body-highlight, --paper-yellow-300);
color: black;
}
:host[edit-mode] #bodycontainer ::slotted(*[data-editable]::selection),
:host[edit-mode] #bodycontainer ::slotted(*[data-editable] *::selection) {
background-color: var(--hax-body-highlight, --paper-yellow-300);
color: black;
}
#bodycontainer {
-webkit-user-select: text;
user-select: text;
}
#contextcontainer {
display: none;
}
:host[edit-mode][hax-ray-mode] #bodycontainer ::slotted(*[data-editable]) {
outline: 1px dashed #d3d3d3;
outline-offset: 4px;
}
:host[edit-mode][hax-ray-mode] #bodycontainer ::slotted(*[data-editable])::before {
content: attr(data-hax-ray) " " attr(resource) " " attr(typeof) " " attr(property) " " attr(content);
font-size: 10px;
font-style: italic;
left: unset;
right: unset;
top: unset;
background-color: #d3d3d3;
color: #000000;
bottom: unset;
width: auto;
padding: 8px;
margin: 0;
z-index: 1;
margin: -16px 0 0 0;
float: left;
line-height: 2;
}
</style>
<div id="bodycontainer" class="ignore-activation">
<slot id="body"></slot>
</div>
<div id="contextcontainer">
<hax-text-context id="textcontextmenu" class="hax-context-menu ignore-activation"></hax-text-context>
<hax-ce-context id="cecontextmenu" class="hax-context-menu ignore-activation"></hax-ce-context>
<hax-plate-context id="platecontextmenu" class="hax-context-menu ignore-activation"></hax-plate-context>
<hax-input-mixer id="haxinputmixer" class="hax-context-menu ignore-activation"></hax-input-mixer>
</div>
<iron-a11y-keys target="[[activeContainerNode]]" keys="esc" on-keys-pressed="_escKeyPressed" stop-keyboard-event-propagation></iron-a11y-keys>
<iron-a11y-keys target="[[activeContainerNode]]" keys="del backspace" on-keys-pressed="_delKeyPressed"></iron-a11y-keys>
<iron-a11y-keys target="[[activeContainerNode]]" keys="shift+tab" on-keys-pressed="_tabBackKeyPressed" stop-keyboard-event-propagation></iron-a11y-keys>
<iron-a11y-keys target="[[activeContainerNode]]" keys="tab" on-keys-pressed="_tabKeyPressed" stop-keyboard-event-propagation></iron-a11y-keys>
<iron-a11y-keys target="[[activeContainerNode]]" keys="up" on-keys-pressed="_upKeyPressed" stop-keyboard-event-propagation></iron-a11y-keys>
<iron-a11y-keys target="[[activeContainerNode]]" keys="down" on-keys-pressed="_downKeyPressed" stop-keyboard-event-propagation></iron-a11y-keys>
</template>
<script>
Polymer({
is: 'hax-body',
listeners: {
'focusin': '_focusIn',
'mousedown': '_focusIn',
'hax-context-item-selected': '_haxContextOperation',
'hax-input-mixer-update': '_haxInputMixerOperation',
'place-holder-replace': 'replacePlaceholder',
},
behaviors: [
simpleColorsBehaviors,
],
properties: {
/**
* State of if we are editing or not.
*/
editMode: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: '_editModeChanged',
},
/**
* Access to the global properties object.
*/
globalPreferences: {
type: Object,
value: {},
observer: '_globalPreferencesUpdated',
},
/**
* Bust out the HAX Ray mode
*/
haxRayMode: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/**
* A reference to the active node in the slot.
*/
activeNode: {
type: Object,
value: null,
notify: true,
observer: '_activeNodeChanged',
},
/**
* A reference to the active node in the slot.
*/
activeContainerNode: {
type: Object,
value: null,
notify: true,
observer: '_activeContainerNodeChanged',
},
},
/**
* Ready state to tee everything up.
*/
ready: function() {
this.polyfillSafe = Polymer.HaxStore.instance.computePolyfillSafe();
// mutation observer that ensures state of hax applied correctly
this._observer = Polymer.dom(this).observeNodes(function(info) {
// MAKE SURE WE KNOW WHAT JUST GOT ADDED HERE
Polymer.dom.flush();
// if we've got new nodes, we have to react to that
if (info.addedNodes.length > 0) {
info.addedNodes.map((node) => {
if (this._haxElementTest(node)) {
if (this._HTMLPrimativeTest(node)) {
node.contentEditable = this.editMode;
}
// this does the real targetting
node.setAttribute('data-editable', this.editMode);
node.setAttribute('data-hax-ray', node.tagName);
this.fire('hax-body-tag-added', {node: node});
}
});
}
// if we dropped nodes via the UI (delete event basically)
if (info.removedNodes.length > 0) {
// handle removing items... not sure we need to do anything here
info.removedNodes.map((node) => {
if (this._haxElementTest(node) && !node.classList.contains('hax-active')) {
this.fire('hax-body-tag-removed', {node: node});
}
});
}
});
},
/**
* Attached to the DOM; now we can fire event to the store that
* we exist and are the thing being edited.
*/
attached: function() {
this.__tabTrap = false;
this.fire('hax-register-body', this);
document.body.addEventListener('hax-store-property-updated', this._haxStorePropertyUpdated.bind(this));
document.body.addEventListener("selectstart", this._selectionChange.bind(this));
document.body.addEventListener("mouseup", this._selectionMouseUp.bind(this));
window.addEventListener("scroll", this._keepContextVisible.bind(this));
},
/**
* Detached life cycle
*/
detached: function () {
document.body.removeEventListener('hax-store-property-updated', this._haxStorePropertyUpdated.bind(this));
document.body.removeEventListener("selectstart", this._selectionChange.bind(this));
document.body.removeEventListener("mouseup", this._selectionMouseUp.bind(this));
window.removeEventListener("scroll", this._keepContextVisible.bind(this));
},
/**
* Keep the context menu visible if needed
*/
_keepContextVisible: function (e) {
// see if the text context menu is visible
let el = false;
if (this.$.textcontextmenu.classList.contains('hax-context-visible')) {
el = this.$.textcontextmenu;
}
else if (this.$.cecontextmenu.classList.contains('hax-context-visible')) {
el = this.$.cecontextmenu;
}
// if we see it, ensure we don't have the pin
if (el) {
if (this.elementInViewport(el)) {
el.classList.remove('hax-context-pin-bottom');
el.classList.remove('hax-context-pin-top');
}
else {
if (this.__OffBottom) {
el.classList.add('hax-context-pin-top');
}
else {
el.classList.add('hax-context-pin-bottom');
}
}
}
},
/**
* Check if part of the passed element is int he viewport
*/
elementInViewport: function(el) {
let top = el.offsetTop - 32 - Polymer.HaxStore.instance.haxPanel.$.drawer.offsetHeight;
let left = el.offsetLeft;
let width = el.offsetWidth;
let height = el.offsetHeight;
while (el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
this.__OffBottom = (top < (window.pageYOffset + window.innerHeight));
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
},
/**
* Selection changed
*/
_selectionChange: function (e) {
window.__startedSelection = true;
},
_selectionMouseUp: function (e) {
if (window.__startedSelection && this.editMode) {
try {
let selection = window.getSelection();
let range = selection.getRangeAt(0);
let newRange = range.cloneRange();
window.__startedSelection = false;
if (newRange.startContainer.parentNode.parentNode.parentElement.tagName === 'HAX-BODY' ||
newRange.startContainer.parentNode.parentElement.tagName === 'HAX-BODY') {
Polymer.HaxStore.write('activePlaceHolder', newRange, this);
}
} catch (err) {
}
}
},
/**
* Replace place holder after an event has called for it in the element itself
*/
replacePlaceholder: function(e) {
// generate a paragraph of text here on click
if (e.detail === 'text') {
// make sure text just escalates to a paragraph tag
let p = document.createElement('p');
this.haxReplaceNode(this.activeNode, p, Polymer.dom(this.activeNode).parentNode);
// allow swap out to happen
setTimeout( () => {
// set active to this p tag
Polymer.HaxStore.write('activeNode', p, this);
// focus on it
p.focus();
}, 100);
}
else {
this.replaceElementWorkflow();
}
},
/**
* Whole workflow of replacing something in place contextually.
* This can fire for things like events needing this workflow to
* invoke whether it's a "convert" event or a "replace placeholder" event
*/
replaceElementWorkflow: function() {
let element = Polymer.HaxStore.nodeToHaxElement(this.activeNode, null);
let type = '*';
let skipPropMatch = false;
// special support for place holder which defines exactly
// what the user wants this replaced with
if (element.tag === 'place-holder' && typeof element.properties['type'] !== typeof undefined) {
type = element.properties['type'];
skipPropMatch = true;
}
var props = {};
// see if we have a gizmo as it's not a requirement to registration
// as well as having handlers since mapping is not required either
if (typeof Polymer.HaxStore.instance.elementList[element.tag] !== typeof undefined && Polymer.HaxStore.instance.elementList[element.tag].gizmo !== false && typeof Polymer.HaxStore.instance.elementList[element.tag].gizmo.handles !== typeof undefined && Polymer.HaxStore.instance.elementList[element.tag].gizmo.handles.length > 0) {
// get the haxProperties for this item
let gizmo = Polymer.HaxStore.instance.elementList[element.tag].gizmo;
// walk through each handler
for (var i = 0; i < gizmo.handles.length; i++) {
// walk the properties defined as they would be to the
// left side of the ledger and tell us which property to
// mesh with. This effectively rehydrates / inverts that
// relationship where we have an element and want to say
// "oh ya, but what could have handled this" so that we
// can use that translation to offer up convertion to a
// new element. This is insane.
for (var prop in gizmo.handles[i]) {
// type is a reserved handler but any other property
// which we actually have in our element let's go for it
if (prop !== 'type' && typeof element.properties[gizmo.handles[i][prop]] !== typeof undefined) {
// The cake is a lie... oh wait... no it's not.
// This will completely bend your mind when it comes to
// what HTML is, how it should operate and what universe
// we can now contort as a result. This effectively allows
// reverse engineering any element on the page into any
// other compatible element based on the properties in
// each element claiming to be compatible.
props[prop] = element.properties[gizmo.handles[i][prop]];
}
}
}
}
let haxElements = Polymer.HaxStore.guessGizmo(type, props, skipPropMatch);
// see if we got anything
if (haxElements.length > 0) {
// hand off to hax-app-picker to deal with the rest of this
let tag = this.activeNode.tagName.toLowerCase();
let humanName = tag.replace('-', ' ');
if (typeof Polymer.HaxStore.instance.elementList[tag] !== typeof undefined && Polymer.HaxStore.instance.elementList[tag].gizmo !== false) {
humanName = Polymer.HaxStore.instance.elementList[tag].gizmo.title;
}
Polymer.HaxStore.instance.haxAppPicker.presentOptions(haxElements, '__convert', `Transform ${humanName} to..`, 'gizmo');
}
else {
Polymer.HaxStore.toast('Sorry, this can not be transformed!', 5000);
}
},
/**
* Global prefs updated, let's visualize stuff from hax-ray
*/
_globalPreferencesUpdated: function(newValue, oldValue) {
if (typeof newValue !== typeof undefined && newValue != null) {
this.haxRayMode = newValue.haxRayMode;
}
},
/**
* Store updated, sync.
*/
_haxStorePropertyUpdated: function(e) {
if (e.detail && typeof e.detail.value !== typeof undefined && e.detail.property) {
if (typeof e.detail.value === 'object') {
this.set(e.detail.property, null);
}
this.set(e.detail.property, e.detail.value);
}
},
/**
* Clear area.
*/
haxClearBody: function(confirm = true) {
let status = true;
// only confirm if asked so we can support wipes without it
if (confirm) {
status = prompt('Are you sure you want to delete all content?');
}
// ensure they said yes
if (status) {
Polymer.HaxStore.wipeSlot(this);
}
},
/**
* Insert new tag + content into the local DOM as a node.
*/
haxInsert: function(tag, content, properties = {}) {
var tags = Polymer.HaxStore.instance.validTagList;
// verify this tag is a valid one
if (tags.includes(tag)) {
// create a new element fragment w/ content in it
// if this is a custom-element it won't expand though
var frag = document.createElement(tag);
frag.innerHTML = content;
// clone the fragment which will force an escalation to full node
var newNode = frag.cloneNode(true);
// support for properties if they exist
for (var property in properties) {
let attributeName = Polymer.HaxStore.camelToDash(property);
if (properties.hasOwnProperty(property)) {
// special supporting for boolean because html is weird :p
if (properties[property] === true) {
newNode.setAttribute(attributeName, properties[property]);
}
else if (properties[property] === false) {
newNode.removeAttribute(attributeName);
}
else if (properties[property] != null && properties[property].constructor === Array && !newNode.properties[property].readOnly) {
newNode.set(attributeName, properties[property]);
}
else if (properties[property] != null && properties[property].constructor === Object && !newNode.properties[property].readOnly) {
newNode.set(attributeName, properties[property]);
}
else {
newNode.setAttribute(attributeName, properties[property]);
}
}
}
// special support for a drag and drop into a place-holder tag
// as this is a more aggressive operation then the others
if (Polymer.HaxStore.instance.activePlaceHolder !== null && typeof Polymer.HaxStore.instance.activePlaceHolder.style !== typeof undefined) {
// replicate styles so that it doesn't jar the UI
newNode.style.width = Polymer.HaxStore.instance.activePlaceHolder.style.width;
newNode.style.float = Polymer.HaxStore.instance.activePlaceHolder.style.float;
newNode.style.margin = Polymer.HaxStore.instance.activePlaceHolder.style.margin;
newNode.style.display = Polymer.HaxStore.instance.activePlaceHolder.style.display;
this.haxReplaceNode(Polymer.HaxStore.instance.activePlaceHolder, newNode, Polymer.dom(Polymer.HaxStore.instance.activePlaceHolder).parentNode);
Polymer.HaxStore.instance.activePlaceHolder = null;
}
// insert at active insert point if we have one
else if (this.activeContainerNode !== null) {
// allow for inserting things into things but not grid plate
if (newNode.tagName !== 'GRID-PLATE' && this.activeContainerNode.tagName === 'GRID-PLATE' && this.activeContainerNode !== this.activeNode) {
newNode.setAttribute('slot', this.activeNode.getAttribute('slot'));
Polymer.dom(this.activeContainerNode).insertBefore(newNode, this.activeNode);
}
else {
Polymer.dom(this).insertBefore(newNode, this.activeContainerNode.nextElementSibling);
}
}
else {
// send this into the root, which should filter it back down into the slot
Polymer.dom(this).appendChild(newNode);
}
this.$.textcontextmenu.highlightOps = false;
// wait so that the DOM can have the node to then attach to
setTimeout( () => {
Polymer.HaxStore.write('activeContainerNode', newNode, this);
Polymer.HaxStore.write('activeNode', newNode, this);
// attempt to focus on the new node, may not always work
newNode.focus();
// scroll to it
if (typeof newNode.scrollIntoViewIfNeeded === 'function') {
newNode.scrollIntoViewIfNeeded(true);
}
else {
newNode.scrollIntoView({behavior: "smooth", inline: "center"});
}
}, 100);
return true;
}
return false;
},
/**
* Return the current hax content area as text that could be
* inserted into something.
*/
haxToContent: function() {
// remove from the body area so we can generate a legit html structure
this.hideContextMenus();
var __active = this.activeNode;
// null this to drop hax based classes
Polymer.HaxStore.write('activeNode', null, this);
Polymer.HaxStore.write('activeContainerNode', null, this);
let children = Polymer.dom(this.$.body).getDistributedNodes();
if (this.globalPreferences.haxDeveloperMode) {
console.log(children);
}
var content = '';
for (var i = 0, len = children.length; i < len; i++) {
// see if this is a valid element or not, providing
// some mild front-end sanitization
if (this._haxElementTest(children[i])) {
children[i].removeAttribute('data-editable');
children[i].removeAttribute('data-hax-ray');
children[i].contentEditable = false;
content += Polymer.HaxStore.haxNodeToContent(children[i]);
if (children[i].tagName.toLowerCase() === 'grid-plate') {
this._applyContentEditable(this.editMode, children[i]);
}
}
// keep comments with a special case since they need wrapped
else if (children[i].nodeType === 8) {
content += '<!-- ' + children[i].textContent + ' -->';
}
// keep everything NOT an element at this point, this helps
// preserve whitespace because we're crazy about accuracy
else if (children[i].nodeType !== 1 && typeof children[i].textContent !== typeof undefined && children[i].textContent !== 'undefined') {
content += children[i].textContent;
}
}
// remove the contenteditable attribute
content = content.replace(/\scontenteditable=\"false\"/g, '');
// remove the data-editable attribute
content = content.replace(/\sdata-editable=\"true\"/g, '');
content = content.replace(/\sdata-editable=\"false\"/g, '');
content = content.replace(/\sdata-editable=\""/g, '');
// remove other attributes that can linger in slots
content = content.replace(/\sdata-editable/g, '');
content = content.replace(/\scontenteditable/g, '');
content = content.replace(/\sdraggable/g, '');
content = content.replace(/\sdata-draggable/g, '');
// clean up stray hax-ray leftovers
content = content.replace(/\sdata-hax-ray=\".*?\"/g, '');
// remove HAX specific classes / scoping classes
let parentTag = this.parentNode.tagName.toLowerCase();
let string = 'style-scope ' + parentTag + ' x-scope';
let re = new RegExp(string, "g");
content = content.replace(re, '');
// remove without the deeeper scope as well for primitives
string = 'style-scope ' + parentTag;
re = new RegExp(string, "g");
content = content.replace(re, '');
// remove the last common one unpacked
string = 'x-scope ' + parentTag + '-0';
re = new RegExp(string, "g");
content = content.replace(re, '');
// now all tags we have defined as valid
let tags = Polymer.HaxStore.instance.validTagList;
tags.push('hax-preview');
for (var i in tags) {
string = 'style-scope ' + tags[i];
re = new RegExp(string, "g");
content = content.replace(re, '');
string = 'x-scope ' + tags[i] + '-0 ';
re = new RegExp(string, "g");
content = content.replace(re, '');
string = 'x-scope ' + tags[i] + '-0';
re = new RegExp(string, "g");
content = content.replace(re, '');
}
// remove empty class structures
content = content.replace(/\sclass=\"\"/g, '');
content = content.replace(/\sclass=\"\s\"/g, '');
// re-apply contenteditable if needed
this._applyContentEditable(this.editMode);
// set active again
Polymer.HaxStore.write('activeNode', __active, this);
Polymer.HaxStore.write('activeContainerNode', __active, this);
// oh one last thing. escape all script/style tags
content = Polymer.HaxStore.encapScript(content);
if (this.globalPreferences.haxDeveloperMode) {
console.log(content);
}
return content;
},
/**
* Duplicate node into the local DOM below the current item if we can.
*/
haxDuplicateNode: function(node, parent = this) {
// move the context menu before duplicating!!!!
this.hideContextMenus();
var nodeClone = Polymer.dom(node).cloneNode(true);
if (nodeClone.tagName.toLowerCase() === 'webview' && Polymer.HaxStore.instance._isSandboxed && typeof nodeClone.guestinstance !== typeof undefined) {
delete nodeClone.guestinstance;
}
// shouldn't be possible but might as well check
if (node !== null) {
Polymer.dom(parent).insertBefore(nodeClone, Polymer.dom(node).nextSibling);
}
else {
Polymer.dom(parent).appendChild(nodeClone);
}
setTimeout( () => {
// test for a grid plate clone
if (parent === this) {
Polymer.HaxStore.write('activeContainerNode', nodeClone, this);
}
Polymer.HaxStore.write('activeNode', nodeClone, this);
}, 100);
return true;
},
/**
* Hide all context menus.
*/
hideContextMenus: function() {
// primary context menus
this._hideContextMenu(this.$.textcontextmenu);
this._hideContextMenu(this.$.cecontextmenu);
// secondary menus and clean up areas
this._hideContextMenu(this.$.platecontextmenu);
this._hideContextMenu(this.$.haxinputmixer);
// force context menu state to closed
this.$.textcontextmenu.highlightOps = false;
},
/**
* Reposition context menus to match an element.
*/
positionContextMenus: function(node, container) {
let tag = node.tagName.toLowerCase();
if (Polymer.HaxStore.instance._isSandboxed && tag === 'webview') {
tag = 'iframe';
}
let props = Polymer.HaxStore.instance.elementList[tag];
// get width from window size and do very minor responsive inline support
let w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
let offsetmenu = -39;
let offsetplate = -31;
// if we go below 800 break point, change menu positioning
if ( w < 800) {
offsetmenu = 0;
offsetplate = 0;
}
// try and work against anything NOT a P tag
if (typeof props !== typeof undefined && node.tagName !== 'P') {
this.__activeContextType = this.$.cecontextmenu;
props.element = node;
this.__activeContextType.setHaxProperties(props);
}
else {
// @todo test if this is a custom element, then if it is
// try and guess what the properties are based on what's
// currently been set. it's by no means perfect but it'll
// be a really good start
this.__activeContextType = this.$.textcontextmenu;
}
this._positionContextMenu(this.__activeContextType, container, offsetmenu, -37);
this._positionContextMenu(this.$.platecontextmenu, container, offsetplate, 0, false);
// special case for node not matching container
if (!this._HTMLPrimativeTest(node) && node !== container) {
container.contentEditable = false;
}
else if (this._HTMLPrimativeTest(container)) {
container.contentEditable = true;
}
},
/**
* Move grid plate around
*/
haxMoveGridPlate: function(direction, node, container) {
// menu is actually in the element for render purposes
this.hideContextMenus();
// support moving things multiple directions
switch (direction) {
case 'first':
// ensure we can go up, first being a mode of up
if (container.previousElementSibling !== null) {
Polymer.dom(this).insertBefore(container, Polymer.dom(this).firstChild);
}
break;
case 'up':
// ensure we can go up
if (container.previousElementSibling !== null) {
Polymer.dom(this).insertBefore(container, container.previousElementSibling);
}
break;
case 'down':
if (container.nextElementSibling !== null) {
Polymer.dom(this).insertBefore(container.nextElementSibling, container);
}
break;
case 'last':
if (container.nextElementSibling !== null) {
Polymer.dom(this).appendChild(container);
}
break;
// @todo support other directions for when inside of an element
}
this.positionContextMenus(node, container);
setTimeout( () => {
if (typeof container.scrollIntoViewIfNeeded === 'function') {
container.scrollIntoViewIfNeeded(true);
}
else {
container.scrollIntoView({behavior: "smooth", inline: "center"});
}
}, 250);
return true;
},
/**
* Convert an element from one tag to another.
*/
haxReplaceNode: function (node, replacement, parent = this) {
// ensure we're not in the document tree for the replaced node
this.hideContextMenus();
// Switch, try loop in case we screwed up elsewhere
try {
// test for slots to match
if (node.getAttribute('slot') != null) {
replacement.setAttribute('slot', node.getAttribute('slot'));
}
Polymer.dom(parent).replaceChild(replacement, node);
}
catch(e) {
console.log(e);
}
return replacement;
},
/**
* Convert an element from one tag to another.
*/
haxChangeTagName: function (node, tagName, newNode) {
// ensure we're not in the document tree for the replaced node
this.hideContextMenus();
// Create a replacement tag of the desired type
var replacement = document.createElement(tagName);
// Grab all of the original's attributes, and pass them to the replacement
for(var i = 0, l = node.attributes.length; i < l; ++i){
var nodeName = node.attributes.item(i).nodeName;
var value = node.attributes.item(i).value;
replacement.setAttribute(nodeName, value);
}
// Persist contents
replacement.innerHTML = node.innerHTML;
// Switch!
Polymer.dom(this).replaceChild(replacement, node);
return replacement;
},
/**
* Delete the node passed in
*/
haxDeleteNode: function(node, parent = this) {
// move the context menu before deleting!!!!
this.hideContextMenus();
// shift active to a viable replacement
if (this.activeContainerNode != null && this.activeContainerNode.previousElementSibling !== null) {
this.activeContainerNode.previousElementSibling.focus();
// cursor at the END of the element assuming not empty
if (this.activeContainerNode != null && Polymer.HaxStore.instance.isTextElement(this.activeContainerNode) && Polymer.dom(this.activeContainerNode).textContent !== '') {
try {
var range = document.createRange();
var sel = window.getSelection();
range.setStart(this.activeContainerNode, 1);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
this.activeContainerNode.focus();
}
catch(e) {
console.log(e);
}
}
}
else if (this.activeContainerNode != null && this.activeContainerNode.nextElementSibling !== null) {
this.activeContainerNode.nextElementSibling.focus();
}
else {
Polymer.HaxStore.write('activeContainerNode', null, this);
Polymer.HaxStore.write('activeNode', null, this);
}
// @todo figure out why this is complaining
try {
return Polymer.dom(parent).removeChild(node);
}
catch(e) {
console.log(e);
}
},
/**
* Bulk import HTML with option to clear what is currently
* in the slot of this tag. This also validates tags
* that are being inserted for security based on the
* internal whitelist.
*/
importContent: function(html, clear = true) {
// kill the slot of the active body, all of it
if (clear) {
Polymer.HaxStore.wipeSlot(this, '*');
}
// pause quickly to ensure wipe goes through successfully
setTimeout( () => {
html = Polymer.HaxStore.encapScript(html);
const validTags = Polymer.HaxStore.instance.validTagList;
let fragment = document.createElement('div');
fragment.insertAdjacentHTML( 'beforeend', html );
while (fragment.firstChild !== null) {
if (typeof fragment.firstChild.tagName !== typeof undefined && validTags.includes(fragment.firstChild.tagName.toLowerCase())) {
// ensure import doesn't import non-sandbox safe things!
if (Polymer.HaxStore.instance._isSandboxed && fragment.firstChild.tagName.toLowerCase() === 'iframe') {
// Create a replacement tag of the desired type
var replacement = document.createElement('webview');
// Grab all of the original's attributes, and pass them to the replacement
for(var j = 0, l = fragment.firstChild.attributes.length; j < l; ++j){
var nodeName = fragment.firstChild.attributes.item(j).nodeName;
var value = fragment.firstChild.attributes.item(j).value;
if (nodeName === 'height' || nodeName === 'width') {
replacement.style[nodeName] == value;
}
replacement.setAttribute(nodeName, value);
}
Polymer.dom(this).appendChild(replacement);
}
else {
Polymer.dom(this).appendChild(fragment.firstChild);
}
}
else {
// this tag didn't pass the test, get rid of it
fragment.removeChild(fragment.firstChild);
}
}
}, 200);
},
/**
* Respond to hax operations.
*/
_haxContextOperation: function(e) {
let detail = e.detail;
var haxElement;
// support a simple insert event to bubble up or everything else
switch(detail.eventName) {
// text based operations for primatives
case 'p':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
case 'code':
case 'blockquote':
// trigger the default selected value in context menu to match
this.$.textcontextmenu.selectedValue = detail.eventName;
Polymer.HaxStore.write('activeContainerNode', this.haxChangeTagName(this.activeContainerNode, detail.eventName), this);
break;
case 'text-align-left':
this.activeNode.style.textAlign = null;
this.positionContextMenus(this.activeNode, this.activeContainerNode);
break;
case 'text-align-right':
this.activeNode.style.textAlign = 'right';
this.positionContextMenus(this.activeNode, this.activeContainerNode);
break;
// grid plate based operations
// allow for transforming this haxElement into another one
case 'grid-plate-convert':
this.replaceElementWorkflow();
break;
// duplicate the active item or container
case 'grid-plate-duplicate':
if (this.activeNode === this.activeContainerNode) {
this.haxDuplicateNode(this.activeNode);
}
else {
this.haxDuplicateNode(this.activeNode, this.activeContainerNode);
}
break;
case 'grid-plate-delete':
let options = [
{
'icon': 'thumb-up',
'color': 'green',
'title': 'Yes',
},
{
'icon': 'thumb-down',
'color': 'red',
'title': 'No',
}
];
let tag = this.activeNode.tagName.toLowerCase();
let humanName = tag.replace('-', ' ');
if (typeof Polymer.HaxStore.instance.elementList[tag] !== typeof undefined && Polymer.HaxStore.instance.elementList[tag].gizmo !== false) {
humanName = Polymer.HaxStore.instance.elementList[tag].gizmo.title;
}
Polymer.HaxStore.instance.haxAppPicker.presentOptions(options, '', `Remove this \`${humanName}\`?`, 'delete');
break;
case 'grid-plate-first':
this.haxMoveGridPlate('first', this.activeNode, this.activeContainerNode);
break;
case 'grid-plate-up':
this.haxMoveGridPlate('up', this.activeNode, this.activeContainerNode);
break;
case 'hax-manager-open':
Polymer.HaxStore.write('activeHaxElement', {}, this);
Polymer.HaxStore.instance.haxManager.resetManager(parseInt(detail.value));
Polymer.HaxStore.instance.haxManager.toggleDialog();
break;
case 'grid-plate-down':
this.haxMoveGridPlate('down', this.activeNode, this.activeContainerNode);
break;
case 'grid-plate-last':
this.haxMoveGridPlate('last', this.activeNode, this.activeContainerNode);
break;
case 'close-menu':
// this is the equivalent of hiding menus and resetting the board
Polymer.HaxStore.write('activeContainerNode', null, this);
Polymer.HaxStore.write('activeNode', null, this);
break;
case 'hax-edit-property':
let haxInputMixer = this.$.haxinputmixer;
haxInputMixer.label = detail.target.label;
haxInputMixer.options = detail.target.options;
haxInputMixer.icon = detail.target.icon;
haxInputMixer.description = detail.target.description;
haxInputMixer.required = detail.target.required;
haxInputMixer.validation = detail.target.validation;
haxInputMixer.validationType = detail.target.validationType;
haxInputMixer.inputMethod = detail.target.inputMethod;
haxInputMixer.value = '';
// see if response should bind to the slot or property
if (typeof detail.target.propertyToBind !== typeof undefined && detail.target.propertyToBind != null && detail.target.propertyToBind != false) {
haxInputMixer.propertyToBind = detail.target.propertyToBind;