-
Notifications
You must be signed in to change notification settings - Fork 64
/
index.js
1916 lines (1550 loc) · 70.3 KB
/
index.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
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// ----------------------------------------------------------------------------
// On ready event, bootstrap the embed containers and embed the report
$(document).ready(async function () {
// Bootstrap the embed-container for report embedding
powerbi.bootstrap(reportContainer, {
"type": "report"
});
// Bootstrap the visual display container for visual authoring
powerbi.bootstrap(visualDisplayArea, {
"type": "report"
});
// Hide the authoring area and display the edit screen
visualAuthoringArea.hide();
// Load quick visual creator report properties into session
await loadQuickVisualCreatorReportConfigIntoSession();
// Embed the report by calling Endpoint
await embedBaseReport();
// Embed the report for visual-authoring
await embedVisualAuthoringReport();
// Initialize the custom dropdowns
initializeDropdowns();
// Select the contents of the visual title when it is focused
visualTitleText.focus(function () { $(this).select(); });
// Focus the close button when modal opens
visualCreatorModal.on("shown.bs.modal", function () {
closeModalButton.focus();
});
// Pressing Tab should move focus to Close button
createVisualButton.on("keydown", function (event) {
// Tab
if (!event.shiftKey && (event.keyCode === KEYCODE_TAB || event.key === Keys.TAB)) {
closeModalButton.focus();
event.preventDefault();
}
});
// If Create button is enabled, moves focus to it
closeModalButton.on("keydown", function (event) {
// Shift + Tab
if (event.shiftKey && (event.keyCode === KEYCODE_TAB || event.key === Keys.TAB)) {
if (!createVisualButton.is(":disabled")) {
createVisualButton.focus();
event.preventDefault();
}
else {
event.preventDefault();
}
}
});
// When the close button is clicked
closeModalButton.click(function () {
// Empty the custom visual title variable
customVisualTitle = "";
// Empty the state for the edited visual
selectedVisual.visual = null;
// Close the modal
visualCreatorModal.modal("hide");
// Reset visual generator
resetVisualGenerator();
// Clean up the modal
resetModal();
});
// On click of 'Create', append the visual to the base report
createVisualButton.click(async function () {
// Hide the modal
visualCreatorModal.modal("hide");
// Append the visual to the base report
appendVisualToReport();
// Empty the state for the edited visual
selectedVisual.visual = null;
// Clean up the modal
resetModal();
});
titleToggle.change(function () {
if (this.checked) {
// Reset the visual title if no custom title is set
if (!customVisualTitle) {
visualCreatorShowcaseState.newVisual.resetProperty(propertyToSelector("titleText"));
}
customTitleWrapper.removeClass(TOGGLE_WRAPPERS_DISABLED);
visualTitleText.prop("disabled", false);
hideDisabledEraserAndAligns();
}
else {
customTitleWrapper.addClass(TOGGLE_WRAPPERS_DISABLED);
visualTitleText.prop("disabled", true);
showDisabledEraserAndAligns();
}
});
// Close all the open select dropdowns if clicked inside the modal
visualCreatorModal.click(function () {
const selectItems = $(".select-items");
selectItems.each(function () {
$(this).addClass(HIDE);
})
});
// Focus on the alignment blocks using keyboard
alignmentBlocks.on("keydown", function (event) {
if ((event.keyCode === KEYCODE_ENTER || event.key === Keys.ENTER || event.keyCode === KEYCODE_SPACE || event.key === Keys.SPACE)) {
// Split the alignment from the id and call the function
const alignmentId = this.id.split("-")[1];
onAlignClicked(alignmentId);
}
})
// Focus on the eraser tool blocks using keyboard
enabledEraseTool.on("keydown", function (event) {
if ((event.keyCode === KEYCODE_ENTER || event.key === Keys.ENTER || event.keyCode === KEYCODE_SPACE || event.key === Keys.SPACE)) {
onEraseToolClicked();
}
});
// Attach the rearrangeInCustomLayout() to the resize event
$(window).on("resize", rearrangeInCustomLayout);
});
// Add event listener on document for keyboard
$(document).keydown(function (event) {
// Close the modal on Escape key
if (event.keyCode === KEYCODE_ESCAPE || event.key === Keys.ESCAPE) {
// Hide the modal
visualCreatorModal.modal("hide");
// Reset visual generator
resetVisualGenerator();
// Clean up the modal
resetModal();
}
});
function hideDisabledEraserAndAligns() {
enabledEraseTool.prop("disabled", false);
alignmentBlocks.prop("disabled", false);
disabledEraseTool.hide();
enabledEraseTool.show();
enabledAligns.show();
disabledAligns.hide();
}
// Show the disabled items on modal close
function showDisabledEraserAndAligns() {
disabledEraseTool.prop("disabled", true);
alignmentBlocks.prop("disabled", true);
disabledEraseTool.show();
enabledEraseTool.hide();
disabledAligns.show();
enabledAligns.hide();
}
// Reset the modal and perform clean-up activities
function resetModal() {
// Hide all the select-box when the modal is closed
$(".select-items").addClass(HIDE);
// Show the Edit icon container and hide the authoring container
editArea.show();
visualAuthoringArea.hide();
resetVisualCreatorOptions();
}
function resetVisualCreatorOptions() {
// Disable the create button
createVisualButton.prop("disabled", true);
// Uncheck the visual properties checkboxes
visualPropertiesCheckboxes.prop("checked", false);
// Disable the visual properties checkboxes
visualPropertiesCheckboxes.prop("disabled", true);
// Disable the visual title textbox
visualTitleText.prop("disabled", true);
// Enable all the toggle wrappers
toggleWrappers.removeClass(TOGGLE_WRAPPERS_DISABLED);
togglePropertiesSliders.addClass(DISABLED_SLIDERS);
// Remove disabled class from custom title wrapper
customTitleWrapper.removeClass(TOGGLE_WRAPPERS_DISABLED);
}
// Set accessibility insights for the report
function setAccessibilityInsights() {
baseReportState.report.setComponentTitle("Playground showcase quick visual creator");
baseReportState.report.setComponentTabIndex(0);
}
function setAccessibilityInsightsForAuthoringReport() {
visualCreatorShowcaseState.report.setComponentTitle("Visual authoring report");
}
// Embed the report and retrieve all report visuals
async function embedBaseReport() {
// Embed configuration used to describe the what and how to embed
// This object is used when calling powerbi.embed
// This also includes settings and options such as filters
// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details
let config = {
type: "report",
tokenType: models.TokenType.Embed,
accessToken: reportConfig.accessToken,
embedUrl: reportConfig.embedUrl,
id: reportConfig.reportId,
// Use the view permissions
permissions: models.Permissions.View,
settings: {
panes: {
filters: {
visible: false
},
pageNavigation: {
visible: false
}
},
extensions: [
{
command: {
name: "changeVisual",
title: "Change visual",
extend: {
visualOptionsMenu: {
title: "Change visual",
menuLocation: models.MenuLocation.Top,
}
}
}
}
]
},
theme: { themeJson: theme }
};
// Embed Power BI report when Access token and Embed URL are available
baseReportState.report = powerbi.load(reportContainer, config);
// For accessibility insights
setAccessibilityInsights();
// Clear any other loaded handler events
baseReportState.report.off("loaded");
// Triggers when a report schema is successfully loaded
baseReportState.report.on("loaded", async function () {
const pages = await baseReportState.report.getPages();
// Get the visuals from the first page
pages[0].setActive();
baseReportState.page = pages[0];
// Get the visuals of the active page
baseReportState.visuals = await baseReportState.page.getVisuals();
// Rearrange the visuals in 3x3 custom layout
await rearrangeInCustomLayout();
// Implement phase embedding to first load the report, arrange the visuals and call the render
baseReportState.report.render();
// Implement Phase-embedding
// Hide the loader
overlay.hide();
$(".content").children().show();
});
// Clear any other rendered handler events
baseReportState.report.off("rendered");
// Triggers when a report is successfully embedded in UI
baseReportState.report.on("rendered", function () {
// Update available visual types on UI
updateAvailableVisualTypes();
// Enable choosing visual type
generatorType.removeClass(DISABLED);
generatorType.removeClass(TYPES_DISABLED);
console.log("Report render successfully");
});
// Listen the commandTriggered event
baseReportState.report.on("commandTriggered", function (event) {
// Open the modal and set the fields, properties and title for the visual
openModalAndFillState(event.detail);
});
baseReportState.report.on("buttonClicked", function () {
// Show the modal to create the visual
openModalAndFillState();
});
// Clear any other error handler events
baseReportState.report.off("error");
// Handle embed errors
baseReportState.report.on("error", function (event) {
console.error(event.detail);
});
}
async function embedVisualAuthoringReport() {
let config = {
type: "report",
tokenType: models.TokenType.Embed,
accessToken: reportConfig.accessToken,
embedUrl: reportConfig.embedUrl,
id: reportConfig.reportId,
// Use the view permissions
permissions: models.Permissions.View,
settings: {
panes: {
filters: {
visible: false
},
pageNavigation: {
visible: false
}
},
background: models.BackgroundType.Transparent
}
};
// Embed Power BI report when Access token and Embed URL are available
visualCreatorShowcaseState.report = powerbi.embed(visualDisplayArea, config);
// For accessibility insights
setAccessibilityInsightsForAuthoringReport();
// Clear any other loaded handler events
visualCreatorShowcaseState.report.off("loaded");
// Triggers when a report schema is successfully loaded
visualCreatorShowcaseState.report.on("loaded", async function () {
// Set the tabindex to -1 to remove the authoring iFrame from keyboard navigation
authoringiFrame = $(visualDisplayArea).find("iframe");
authoringiFrame.prop("tabindex", -1);
const pages = await visualCreatorShowcaseState.report.getPages();
// pages[1] is an empty page, on which the visual would be created
pages[1].setActive().catch(error => console.log(error));
visualCreatorShowcaseState.page = pages[1];
});
// Clear any other rendered handler events
visualCreatorShowcaseState.report.off("rendered");
// Triggers when a report is successfully embedded in UI
visualCreatorShowcaseState.report.on("rendered", function () {
visualCreatorShowcaseState.report.off("rendered");
console.log("Visual authoring report render successfully");
// Protection against cross-origin failure
try {
if (window.parent.playground && window.parent.playground.logShowcaseDoneRendering) {
window.parent.playground.logShowcaseDoneRendering('QuickCreate');
}
} catch { }
});
// Clear any other error handler events
visualCreatorShowcaseState.report.off("error");
// Handle embed errors
visualCreatorShowcaseState.report.on("error", function (event) {
console.error(event.detail);
});
}
// Render all visuals with 3x3 custom layout
async function rearrangeInCustomLayout() {
// render only if report and visuals initialized
if (!baseReportState.report || !baseReportState.visuals) {
return;
}
// Get report-container width and height
let reportContainer = $(".report-container");
let reportWidth = reportContainer.width();
let reportHeight = 0;
let visuals = baseReportState.visuals;
// Calculating the combined width of the all visuals in a row
let visualsTotalWidth = reportWidth - (VISUAL_CREATOR_SHOWCASE.MARGIN * (VISUAL_CREATOR_SHOWCASE.COLUMNS + 1));
// Calculate the width of a single visual, according to the number of columns
// For one and three columns visuals width will be a third of visuals total width
let visualWidth = visualsTotalWidth / VISUAL_CREATOR_SHOWCASE.COLUMNS;
// Building visualsLayout object
// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Custom-Layout
let visualsLayout = {};
// Visuals starting point
let x = VISUAL_CREATOR_SHOWCASE.MARGIN;
let y = VISUAL_CREATOR_SHOWCASE.MARGIN;
// Calculate visualHeight with margins
let visualHeight = visualWidth * VISUAL_CREATOR_SHOWCASE.VISUAL_ASPECT_RATIO;
// Calculate the number of rows
let rows = 0;
// Do not count the overlapping visuals in generating the rows and final report height
rows = Math.ceil((visuals.length - 2) / VISUAL_CREATOR_SHOWCASE.COLUMNS);
reportHeight = Math.max(reportHeight, (rows * visualHeight) + (rows + 1) * VISUAL_CREATOR_SHOWCASE.MARGIN);
visuals.forEach((visual) => {
// Hide the main and overlapping visuals, if new visual is being created
if (visualCreationInProgress) {
// Hide the visual
if (visual.name === MAIN_VISUAL_GUID || visual.name === imageVisual.name || visual.name === actionButtonVisual.name) {
visualsLayout[visual.name] = {
displayState: {
mode: models.VisualContainerDisplayMode.Hidden
}
}
return;
}
}
if (visual.name === MAIN_VISUAL_GUID) {
// Store the position of the mainVisual
mainVisualState = {
x: x,
y: y,
width: visualWidth,
height: visualHeight,
displayState: {
// Change the selected visuals display mode to visible
mode: models.VisualContainerDisplayMode.Visible
}
}
}
// If the visual is image, which is to be overlapped in the main visual, position it accordingly
if (visual.name === imageVisual.name && mainVisualState.x) {
visualsLayout[imageVisual.name] = {
x: mainVisualState.x + mainVisualState.width * imageVisual.ratio.xPositionRatioWithMainVisual - 6,
y: mainVisualState.y + mainVisualState.height * imageVisual.ratio.yPositionRatioWithMainVisual,
// Set minimum width and height for image visual in smaller screens
width: Math.max(mainVisualState.width * imageVisual.ratio.widthRatioWithMainVisual - 4.5, 36),
height: Math.max(mainVisualState.height * imageVisual.ratio.heightRatioWithMainVisual - 4.5, 36),
displayState: {
// Change the selected visuals display mode to visible
mode: models.VisualContainerDisplayMode.Visible
}
};
imageVisual.yPos = visualsLayout[imageVisual.name].y;
imageVisual.height = visualsLayout[imageVisual.name].height;
}
// If the visual to be placed is the action button, which is to be overlapped in the main visual, position it accordingly
else if (visual.name === actionButtonVisual.name && mainVisualState.x) {
visualsLayout[actionButtonVisual.name] = {
// To center align the action-button
x: mainVisualState.x + (mainVisualState.width - actionButtonVisual.width) / 2,
y: imageVisual.height + imageVisual.yPos + DISTANCE,
// Set the width constant for the button because of non-scalable button value
width: actionButtonVisual.width,
// Set the height constant for the button because of non-scalable button value
height: actionButtonVisual.height,
displayState: {
// Change the selected visuals display mode to visible
mode: models.VisualContainerDisplayMode.Visible
}
};
}
// For remaining visuals, position them and update the x and y coordinates
else {
if (visual.name === MAIN_VISUAL_GUID) {
visualWidth += 4.5;
visualHeight += 4.5;
}
visualsLayout[visual.name] = {
x: x,
y: y,
width: visualWidth,
height: visualHeight,
displayState: {
// Change the selected visuals display mode to visible
mode: models.VisualContainerDisplayMode.Visible
}
};
// Calculating (x,y) position for the next visual
x += visualWidth + VISUAL_CREATOR_SHOWCASE.MARGIN;
// Reset x
if (x + visualWidth > reportWidth) {
x = VISUAL_CREATOR_SHOWCASE.MARGIN;
y += visualHeight + VISUAL_CREATOR_SHOWCASE.MARGIN;
}
}
});
// Building visualsLayout object
// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Custom-Layout
// Building pagesLayout object
let pagesLayout = {};
pagesLayout[baseReportState.page.name] = {
defaultLayout: {
displayState: {
// Default display mode for visuals is hidden
mode: models.VisualContainerDisplayMode.Hidden
}
},
visualsLayout: visualsLayout
};
// Building settings object
let settings = {
// Change page background to transparent
background: models.BackgroundType.Transparent,
layoutType: models.LayoutType.Custom,
customLayout: {
pageSize: {
type: models.PageSizeType.Custom,
width: reportWidth,
height: reportHeight
},
displayOption: models.DisplayOption.FitToWidth,
pagesLayout: pagesLayout
},
// Hide default commands from the context menu for the visuals on the base report
commands: [
{
exportData: {
displayOption: models.CommandDisplayOption.Hidden,
},
drill: {
displayOption: models.CommandDisplayOption.Hidden,
},
spotlight: {
displayOption: models.CommandDisplayOption.Hidden,
},
sort: {
displayOption: models.CommandDisplayOption.Hidden,
},
seeData: {
displayOption: models.CommandDisplayOption.Hidden,
}
}
],
};
// If reportWidth or reportHeight is changed, change display option to actual size to add scroll bar
if (reportWidth !== reportContainer.width() || reportHeight !== reportContainer.height()) {
// Reset the height of the report-container to avoid the scroll-bar
resetContainerHeight(reportHeight + VISUAL_CREATOR_SHOWCASE.MARGIN);
settings.customLayout.displayOption = models.DisplayOption.FitToWidth;
}
// Call updateSettings with the new settings object
await baseReportState.report.updateSettings(settings);
}
// Reset the report-container based on the visuals inside it
function resetContainerHeight(newHeight) {
const reportContainer = $(".report-container");
reportContainer.height(newHeight);
}
// Initialize the visual-types dropdown and attach a click-listener to the dropdown
function initializeDropdowns() {
// Look for any elements with the class "styled-select"
const styledSelects = document.getElementsByClassName("styled-select");
const length = styledSelects.length;
for (let i = 0; i < length; i++) {
const selectedElement = styledSelects[i].getElementsByTagName("select")[0];
// For each element, create a new div that will act as the selected item
const dropdownElement = document.createElement("div");
dropdownElement.setAttribute("class", "select-selected");
dropdownElement.setAttribute("id", "selected-value-" + i);
dropdownElement.setAttribute("tabindex", 0);
dropdownElement.innerHTML = selectedElement.options[selectedElement.selectedIndex].innerHTML;
styledSelects[i].appendChild(dropdownElement);
// For each element, create a new div that will contain the option list
const dropdownItem = document.createElement("div");
dropdownItem.setAttribute("class", "select-items select-hide");
dropdownItem.setAttribute("role", "listbox");
// Create 3 options of data-field for selected visual-type
const selectedElementLength = selectedElement.length;
for (let j = 0; j < selectedElementLength; j++) {
// For each option in the original select element,
// create a new div that will act as an option item
const optionItem = document.createElement("div");
optionItem.setAttribute("role", "option");
optionItem.setAttribute("tabindex", 0);
// Create first default option for visual selection dropdown
if (i === 0 && j === 0) {
optionItem.innerHTML = VISUAL_TYPE_HEADER;
}
else {
optionItem.innerHTML = selectedElement.options[j].innerHTML;
}
// Add new click event listener
optionItem.addEventListener("click", function () {
// When an item is clicked, update the original select box, and the selected item
updateAuthoringVisual(this);
});
// Add new keydown event listener
optionItem.addEventListener("keydown", function (event) {
// Handle all the keyboard events
handleKeyEventsForDropdownItems(event, this);
});
dropdownItem.appendChild(optionItem);
}
styledSelects[i].appendChild(dropdownItem);
// Add new click event listener for the select box
dropdownElement.addEventListener("click", function (event) {
// When the select box is clicked, close any other select boxes,
// and open/close the current select box
event.stopPropagation();
closeAllSelect(this);
this.nextSibling.classList.toggle(HIDE);
});
// Open the dropdowns using Enter OR Space press
dropdownElement.addEventListener("keydown", function (event) {
// When the Enter OR Space is pressed on the button, close any other select boxes,
// and open/close the current select box
handleKeyEventsForDropdowns(event, this);
});
}
}
// Handle key events for dropdown elements
function handleKeyEventsForDropdowns(event, dropdownElement) {
if (event.keyCode === KEYCODE_ENTER || event.key === Keys.ENTER || event.keyCode === KEYCODE_SPACE || event.key === Keys.SPACE) {
if (dropdownElement.id === TYPE_DROPDOWN_ID || !generatorFields.hasClass(FIELDS_DISABLED)) {
event.stopPropagation();
closeAllSelect(dropdownElement);
dropdownElement.nextSibling.classList.toggle(HIDE);
// Focus on the first option when dropdown opens
if (!dropdownElement.nextSibling.classList.contains(HIDE)) {
dropdownElement.nextSibling.firstChild.focus();
}
}
}
// If dropdown is open, the focus should not move using Keyboard to other dropdowns
if ((event.keyCode === KEYCODE_TAB || event.key === Keys.TAB)) {
// If data-fields dropdowns is disabled, then move the focus to Close button
if (dropdownElement.id === TYPE_DROPDOWN_ID && dropdownElement.nextElementSibling.classList.contains(HIDE) && generatorFields.hasClass(FIELDS_DISABLED)) {
closeModalButton.focus();
event.preventDefault();
}
// Shift + Tab
if (event.shiftKey) {
if (!dropdownElement.nextSibling.classList.contains(HIDE)) {
dropdownElement.focus();
event.preventDefault();
}
}
// Tab
else {
if (dropdownElement.id === "selected-value-3" && createVisualButton.is(":disabled")) {
closeModalButton.focus();
event.preventDefault();
}
}
}
}
// All the key-events for the dropdown items
function handleKeyEventsForDropdownItems(event, optionItem) {
// Focus trap for the dropdowns
if (event.keyCode === KEYCODE_TAB || event.key === Keys.TAB) {
// Shift + Tab
if (event.shiftKey) {
if (document.activeElement.innerHTML === optionItem.parentNode.firstChild.innerHTML) {
optionItem.parentElement.previousSibling.focus();
event.preventDefault();
}
}
// Tab
else {
// To handle the case of hidden dropdown items
// If the focus is on the second last item of the dropdown with the last item as hidden and Tab is pressed, Move focus to the top
let flag = false;
let flag2 = false;
const sibilings = optionItem.parentElement.children;
const length = sibilings.length;
if (sibilings[length - 1].style.display === "none") {
flag = true;
}
// If the focus is on the first item of the dropdown and last two items are hidden, Move focus to the top
for (let i = 0; i < length; i++) {
if (i < 2) {
if (sibilings[i].style.display === "none" && sibilings[i + 1].style.display === "none") {
flag2 = true;
}
else {
flag2 = false;
}
}
}
if (document.activeElement.innerHTML === (flag2 ? (optionItem.parentNode.firstChild.innerHTML) : (flag) ? optionItem.parentNode.lastChild.previousSibling.innerHTML : optionItem.parentNode.lastChild.innerHTML)) {
optionItem.parentElement.previousSibling.focus();
event.preventDefault();
}
// Reset
flag = false;
flag2 = false;
}
}
// Using the keyboard, update the original select box, and the selected item by pressing Space OR Enter
if ((event.keyCode === KEYCODE_ENTER || event.key === Keys.ENTER || event.keyCode === KEYCODE_SPACE || event.key === Keys.SPACE)) {
updateAuthoringVisual(optionItem);
}
}
// Update the visual based on the selections in the dropdowns
async function updateAuthoringVisual(element) {
let selects, previousSibling;
selects = element.parentNode.parentNode.getElementsByTagName("select")[0];
const selectsLength = selects.length;
previousSibling = element.parentNode.previousSibling;
for (let i = 0; i < selectsLength; i++) {
if (selects.options[i].innerHTML === element.innerHTML) {
selects.selectedIndex = i;
previousSibling.innerHTML = element.innerHTML;
let childElements = element.parentNode.getElementsByClassName(SAME_AS_SELECTED);
let childElementsLength = childElements.length;
for (let k = 0; k < childElementsLength; k++) {
childElements[k].removeAttribute("class");
}
// Do not add the class if default option is selected for the data-fields
if (getFirstWord(element.innerHTML) !== "select") {
element.setAttribute("class", SAME_AS_SELECTED);
}
break;
}
}
// Focus on the div when the dropdown is closed
document.getElementById(element.parentElement.previousSibling.id).focus();
previousSibling.click();
// Change the visual type or update the data role field, according to the dropdown id
if (selects.id === "visual-type") {
await changeVisualType(previousSibling.innerHTML);
// If default option is selected, show the edit area and hide the authoring container
if (previousSibling.innerHTML === VISUAL_TYPE_HEADER) {
editArea.show();
visualAuthoringArea.hide();
}
else {
editArea.hide();
visualAuthoringArea.show();
}
}
else {
await updateDataRoleField(selects.parentNode.parentNode.children[0].id, previousSibling.innerHTML);
}
}
// Close all select boxes in the document, except the current select box
function closeAllSelect(element) {
const arrNo = [];
const selected = $(".select-selected");
const selectItems = $(".select-items");
for (let i = 0; i < selected.length; i++) {
if (element === selected[i]) {
arrNo.push(i);
}
}
for (let i = 0; i < selectItems.length; i++) {
if (arrNo.indexOf(i)) {
selectItems[i].classList.add(HIDE);
}
}
}
// Get the visual data from it's display name (e.x. Area Chart)
function getVisualFromDisplayName(visualTypeDisplayName) {
return visualTypeToDataRoles.filter((function (e) { return e.displayName === visualTypeDisplayName }))[0];
}
// Get the visual data from it's name (e.x. areaChart)
function getVisualFromName(name) {
return visualTypeToDataRoles.filter((function (e) { return e.name === name }))[0];
}
// Change the visual type
async function changeVisualType(visualTypeDisplayName) {
// If default option is selected, delete the already created visual and reset the showcase state and modal options
if (visualTypeDisplayName === VISUAL_TYPE_HEADER) {
resetVisualGenerator();
visualCreatorShowcaseState.newVisual = null;
resetModal();
return;
}
// Get the visual-type and data-roles from it's display name
const visual = getVisualFromDisplayName(visualTypeDisplayName);
const visualType = visual.name;
const dataRoles = visual.dataRoles;
// Do not change OR reset the modal when the same option is selected while changing the visual
if (visualCreatorShowcaseState.visualType === visualType) {
return;
}
// Remove all data-fields from the state if visual is being edited
if (selectedVisual.visual) {
resetGeneratorDataRoles();
}
// Retrieve the visual's capabilities
const capabilities = await baseReportState.report.getVisualCapabilities(visualType);
// Validate data roles existence on the given visual type
if (!validateDataRoles(capabilities, dataRoles)) {
resetVisualGenerator();
handleInvalidDataRoles();
return;
}
// Enable the data fields section
generatorFields.removeClass(DISABLED);
generatorFields.removeClass(FIELDS_DISABLED);
// Disable the properties section
generatorProperties.addClass(DISABLED);
// Disable the toggle sliders
togglePropertiesSliders.addClass(DISABLED_SLIDERS);
// Reset all the properties
resetGeneratorProperties();
// Disable the Create button
createVisualButton.prop("disabled", true);
// Reset the data fields count
visualCreatorShowcaseState.dataFieldsCount = 0;
// If the visual doesn't exist, create new visual, otherwise, delete the old visual and create new visual
if (!visualCreatorShowcaseState.newVisual) {
await visualCreatorShowcaseState.page.createVisual(visualType, getVisualLayout());
updateVisualType(visualType, dataRoles);
}
else if (visualType !== visualCreatorShowcaseState.visualType) {
await visualCreatorShowcaseState.page.deleteVisual(visualCreatorShowcaseState.newVisual.name);
await visualCreatorShowcaseState.page.createVisual(visualType, getVisualLayout());
updateVisualType(visualType, dataRoles);
}
}
// Update showcase after visual type change
function updateVisualType(visualTypeName, dataRoles) {
// Hide the visual headers for the visual inside the modal
visualCreatorShowcaseState.report.updateSettings(visualHeaderReportSetting);
updateCurrentVisualState(visualTypeName);
resetGeneratorDataRoles();
updateAvailableDataRoles(dataRoles);
// Update the dropdown options to hide the selected items
updateDropdownOptions();
// Uncheck all the properties checkbox
visualPropertiesCheckboxes.prop("checked", false);
// Enable all the properties checkbox
visualPropertiesCheckboxes.prop("disabled", true);
// Enable the visual title textbox
visualTitleText.prop("disabled", true);
// Disable the properties div
generatorProperties.addClass(PROPERTIES_DISABLED);
// Show the disabled items on visual type is changed
showDisabledEraserAndAligns();
// Focus on the visual type dropdown
$("#selected-value-0").focus();
}
// Update the visual state
async function updateCurrentVisualState(visualTypeName) {
const visuals = await visualCreatorShowcaseState.page.getVisuals();
// Update visual and visual type
visualCreatorShowcaseState.newVisual = visuals[0];
visualCreatorShowcaseState.visualType = visualTypeName;
// Enable the pie chart legend (disabled by default)
if (visualTypeName === "pieChart") {
visualCreatorShowcaseState.newVisual.setProperty(propertyToSelector("legend"), { schema: schemas.property, value: true });
}
// Format the title to be more accessible
visualCreatorShowcaseState.newVisual.setProperty(propertyToSelector("titleSize"), { schema: schemas.property, value: 25 });
visualCreatorShowcaseState.newVisual.setProperty(propertyToSelector("titleColor"), { schema: schemas.property, value: "#000" });
// Disable unavailable properties for specific visual types
toggleWrappers.removeClass(TOGGLE_WRAPPERS_DISABLED);
for (let i = 0; i < showcasePropertiesLength; i++) {
if (visualTypeProperties[visualTypeName].indexOf(showcaseProperties[i]) < 0) {
// Uncheck the unavailable properties for the created visual
$("#" + showcaseProperties[i] + "-toggle").prop("checked", false);
// Disable the pointer events for the properties
$("#" + showcaseProperties[i] + ".toggle-wrapper").addClass(TOGGLE_WRAPPERS_DISABLED);
}
}
}
// Update the labels for the dropdowns
function updateAvailableDataRoles(dataRoles) {