/
visual.ts
858 lines (736 loc) · 40.3 KB
/
visual.ts
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
/*
* Power BI Population Pyramid Visualization
*
* Copyright (c) Tanzo Creative
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ''Software''), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
module powerbi.extensibility.visual {
'use strict';
import IVisual = powerbi.extensibility.visual.IVisual;
import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
import IInteractivityService = powerbi.extensibility.utils.interactivity.IInteractivityService;
import createInteractivityService = powerbi.extensibility.utils.interactivity.createInteractivityService;
import appendClearCatcher = powerbi.extensibility.utils.interactivity.appendClearCatcher;
import ISelectableDataPoint = powerbi.extensibility.utils.interactivity.SelectableDataPoint;
import ISelectionID = powerbi.extensibility.ISelectionId;
import IVisualSelectionId = powerbi.visuals.ISelectionId;
import ISemanticFilter = powerbi.data.ISemanticFilter;
import svgUtils = powerbi.extensibility.utils.svg;
/**
* Collection of datapoints that constitutes the totality of data loaded into the model.
*
* @interface
* @property {PopChartDataPoint[]} dataPoints - Set of data points the visual will render.
*/
class ChartViewModel {
public dataPoints: DataPoint[] = [];
public isHighlighted: boolean = false;
private savedSelection: { [key: string]: boolean } = {};
public saveSelection(): void {
for (const dataPoint of this.dataPoints) {
this.savedSelection[dataPoint.selectionId.getKey()] = dataPoint.selected;
}
}
public restoreSelection(): void {
for (const dataPoint of this.dataPoints) {
dataPoint.selected = this.savedSelection[dataPoint.selectionId.getKey()] || false;
}
}
public getKeys(): string[] {
return this.dataPoints.map(function (d: DataPoint): string { return d.selectionId.getKey(); });
}
}
export interface IDataPoint extends ISelectableDataPoint {
age: string;
gender: string;
value: number;
reference: number;
highlightValue: number;
highlightReference: number;
highlighted: boolean;
// Inherited from ISelectableDataPoint (Remember to check as may change)
// selected: boolean;
// identity: ISelectionId | ExtensibilityISelectionId;
// specificIdentity?: ISelectionId | ExtensibilityISelectionId;
}
/**
* Interface for describing each dataPoint loaded into the visual.
*
* @interface
* @property {string} age - Age range for the category
* @property {number} female - Count of females in category
* @property {number} male - Count of males in categoy
*/
export class DataPoint implements IDataPoint {
public age: string;
public gender: string;
public value: number;
public reference: number;
public highlightValue: number;
public highlightReference: number;
public identity: ISelectionId;
public specificIdentity?: ISelectionId;
public highlighted: boolean;
public selected: boolean;
constructor(params: IDataPoint) {
this.age = params.age;
this.gender = params.gender;
this.value = params.value;
this.reference = params.reference;
this.highlightValue = params.highlightValue;
this.highlightReference = params.highlightReference;
this.identity = params.identity;
this.specificIdentity = params.specificIdentity;
this.highlighted = params.highlighted;
this.selected = params.selected;
}
// Use a property to expose the methods on ISelectionId devined in powerbi.visuals.
get selectionId(): IVisualSelectionId {
return this.identity as IVisualSelectionId;
}
public static convert(element: SVGElement): IDataPoint {
return {
age: element['age'],
gender: element['gender'],
value: element['values'],
reference: element['reference'],
highlightValue: element['highlightValue'],
highlightReference: element['highlightReference'],
identity: element['identity'],
specificIdentity: element['specificIdentity'],
highlighted: element['highlighted'],
selected: element['selected']
};
}
}
/**
* Interface to define clickable-axis labels
* This data is bound to the label and passed to the event handler
* @export
* @interface ILabelData
*/
export interface ILabelData {
name: string;
text: string;
filter: string;
location: string;
anchor: string;
}
/**
* Class implementing the IVisual interface - the basis for custom visuals within Power BI
* The class must implement:
* +constructor - called when the visual is created
* +visualTransform - a method to load data from the interface into the visual
* +parseSettings - a method to load the settings from the interface and persist them in the settings object
* +enumerateObjectInstances - called when the settings panel is redrawn. Allows selection of controls and loading of settings for display.
* +update - called each time the visual needs to be redrawn
* @export
* @class Visual
* @implements {IVisual}
*/
export class Visual implements IVisual {
private host: IVisualHost;
private target: HTMLElement;
private svg: d3.Selection<SVGElement>;
private chart: d3.Selection<SVGElement>;
private settings: VisualSettings = new VisualSettings();
private viewModel: ChartViewModel = new ChartViewModel();
private selectionTools: VisualSelectionTools; //Accessible in static functions
private locale: string;
private wasHighlighted: boolean;
private wasSelected: boolean;
/**
* Creates an instance of Visual. Power BI passes parameters descriing the environment to the visual which may
* be persisted in the class
* @param {VisualConstructorOptions} options - parameters passed to the visual when instantiated.
* @memberof Visual
*/
constructor(options: VisualConstructorOptions) {
this.target = options.element;
this.host = options.host;
this.locale = options.host.locale;
this.svg = d3.select(this.target).append('svg');
// Create selection tools to manage data selections in the visual
this.selectionTools = new VisualSelectionTools(this.host);
this.selectionTools.interactivityService = createInteractivityService(options.host);
this.selectionTools.selectionManager = this.host.createSelectionManager();
this.selectionTools.settings = this.settings.dataPoint;
this.selectionTools.clearCatcher = appendClearCatcher(this.svg) as d3.Selection<SVGElement>;
this.selectionTools.allowInteractions = this.host.allowInteractions;
}
/**
* Method called by Power BI when the visual needs to be updated
*
* @param {VisualUpdateOptions} options - details of data and settings passed from Power BI interface to visual
* @memberof Visual
*/
public update(options: VisualUpdateOptions): void {
// Refresh settings from the interface
this.settings = this.parseSettings(options && options.dataViews && options.dataViews[0]);
// console.log('Published Filter:', (this.settings.dataPoint.filter));
// Refresh data from the interface/tables
this.refreshData(this.viewModel, options);
this.updateState();
// Draw the visual
this.popPyramidChart(options.viewport.width, options.viewport.height, this.viewModel.dataPoints);
if (this.selectionTools.allowInteractions) {
// Select all clickable data points (class are added when drawing the visual and then used to select event targets)
const selectionToolsParams: ISelectionToolsParams = {
visualDataPoints: this.chart.selectAll('.dataPoint'),
categories: this.chart.selectAll('.categories'),
axisLabel: this.chart.selectAll('.axisLabel')
};
// Bind event handlers to the event targets.
this.selectionTools.interactivityService.bind(this.viewModel.dataPoints, this.selectionTools, selectionToolsParams);
}
}
/**
* Helper function for identifying state transitions which require synchronising states across visuals
*
* @memberof Visual
*/
public updateState(): void {
// Check status of highlights and selections to drive the state model
const isHighlighted: boolean = this.viewModel.isHighlighted;
const isSelected: boolean = this.selectionTools.interactivityService.hasSelection();
// Need to clear selection & filters when we click on another object which filters the selection.
if (this.wasSelected && isHighlighted) {
this.selectionTools.clearSelection();
}
this.wasHighlighted = isHighlighted;
this.wasSelected = isSelected;
}
/**
* This function gets called for each of the settings objects defined in the capabilities.json files and allows you to select which of the
* objects and properties you want to expose to the users in the property pane.
*
* @param {EnumerateVisualObjectInstancesOptions} options list of objects to be displayed
* @returns {(VisualObjectInstance[] | VisualObjectInstanceEnumerationObject)} object returned to Power BI with setting values
* @memberof Visual
*/
public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstance[] | VisualObjectInstanceEnumerationObject {
const objectName: string = options.objectName;
const objectEnumeration: VisualObjectInstance[] = [];
// For each control object provie a link between the uer interface and the settings property
switch (objectName) {
case 'textFormat':
objectEnumeration.push({
objectName: objectName,
properties: {
fontSize: this.settings.dataPoint.axisFontSize
},
selector: null
});
case 'axisControl':
objectEnumeration.push({
objectName: objectName,
properties: {
percent: this.settings.dataPoint.axisPercent,
leftFilter: this.settings.dataPoint.leftFilter,
leftLabel: this.settings.dataPoint.leftLabel,
leftBarColor: { solid: { color: this.settings.dataPoint.leftBarColor } },
rightFilter: this.settings.dataPoint.rightFilter,
rightLabel: this.settings.dataPoint.rightLabel,
rightBarColor: { solid: { color: this.settings.dataPoint.rightBarColor } }
},
selector: null
});
case 'referenceBar':
objectEnumeration.push({
objectName: objectName,
properties: {
show: this.settings.dataPoint.showReferenceBars,
refBarWidth: this.settings.dataPoint.refBarWidth,
refBarColor: { solid: { color: this.settings.dataPoint.refBarColor } }
},
selector: null
});
default:
}
return objectEnumeration;
}
/**
*
* parseSettings is called when the visual is updated
*
* For each control added on the interface:
* + Define the control in the capabilities.json file - this signals to the interface what is to be displayed
* + Added a property to the settings.ts (dataPointSettings class) to store the user interface state
* + Add an object to in enumerateObjectInstance to link the user interface to the settings variable
* + Add an assignment to parse the setting from the returned DataView object.
*
* @private
* @static
* @param {DataView} dataView - current status of the settings interface (only non-default values included)
* @returns {VisualSettings} - returns the persisted settings object.
* @memberof Visual
*/
private parseSettings(dataView: DataView): VisualSettings {
const visualSettings: VisualSettings = <VisualSettings>VisualSettings.parse(dataView);
// Updat manually added settings
const root: DataViewObjects = dataView.metadata.objects;
const setting: DataPointSettings = visualSettings.dataPoint;
if ('textFormat' in root) {
const axisControl: DataViewObject = root['textFormat'];
setting.axisFontSize = ('fontSize' in axisControl) ? <number>axisControl['fontSize'] : setting.axisFontSize;
}
if ('axisControl' in root) {
const axisControl: DataViewObject = root['axisControl'];
setting.axisPercent = ('percent' in axisControl) ? <boolean>axisControl['percent'] : setting.axisPercent;
setting.leftFilter = ('leftFilter' in axisControl) ? <string>axisControl['leftFilter'] : setting.leftFilter;
setting.leftLabel = ('leftLabel' in axisControl) ? <string>axisControl['leftLabel'] : setting.leftLabel;
setting.leftBarColor = ('leftBarColor' in axisControl) ? <string>axisControl['leftBarColor']['solid']['color'] : setting.leftBarColor;
setting.rightFilter = ('rightFilter' in axisControl) ? <string>axisControl['rightFilter'] : setting.rightFilter;
setting.rightLabel = ('rightLabel' in axisControl) ? <string>axisControl['rightLabel'] : setting.rightLabel;
setting.rightBarColor = ('rightBarColor' in axisControl) ? <string>axisControl['rightBarColor']['solid']['color'] : setting.rightBarColor;
}
if ('referenceBar' in root) {
const referenceBar: DataViewObject = root['referenceBar'];
setting.showReferenceBars = ('show' in referenceBar) ? <boolean>referenceBar['show'] : setting.showReferenceBars;
setting.refBarWidth = ('refBarWidth' in referenceBar) ? <number>referenceBar['refBarWidth'] : setting.refBarWidth;
setting.refBarColor = ('refBarColor' in referenceBar) ? <string>referenceBar['refBarColor']['solid']['color'] : setting.refBarColor;
}
if ('general' in root) {
const general: DataViewObject = root['general'];
setting.selection = ('selection' in general) ? <string>general['selection'] : setting.selection;
setting.filter = ('filter' in general) ? <ISemanticFilter>general['filter'] : setting.filter;
}
return visualSettings;
}
/**
* Method called by update to load data from Power BI into the visual
*
* @private
* @param {ChartViewModel} chartViewModel Pointer to data used in the model
* @param {VisualUpdateOptions} data Pointer to data from the host
* @memberof Visual
*/
private refreshData(chartViewModel: ChartViewModel, data: VisualUpdateOptions): void {
// Create new chartViewModel instance (note initialisation of variables in class)
// const chartViewModel: ChartViewModel = new ChartViewModel();
// Reset list of DataPoints, whilst retaining saved selectoin
chartViewModel.saveSelection();
chartViewModel.dataPoints = [];
// Initialise the list of fields in the interface - enum must match field names in capabilities.json
enum interfaceFields { 'values', 'reference' }
const fieldIndices: { [key: number]: number } = {};
// Identify which field names are present and map the data column index to them.
// Note the mapping of measures to values will vary depending upon how the user has populated interface fields
// It CANNOT be assumed that a measure will be at the same index position with each update.
const node: DataViewValueColumns = data.dataViews[0].categorical.values;
for (let i: number = 0; i < node.length; i++) {
for (const field in interfaceFields) {
if (field in node[i].source.roles) {
fieldIndices[interfaceFields[field]] = i;
}
}
}
// Category columns are more easily mapped as the visual will not update until they are both populated.
const ageRange: DataViewCategoryColumn = data.dataViews[0].categorical.categories[0];
const gender: DataViewCategoryColumn = data.dataViews[0].categorical.categories[1];
const valueColumn: DataViewValueColumn = data.dataViews[0].categorical.values[fieldIndices[interfaceFields.values]];
const refColumn: DataViewValueColumn = data.dataViews[0].categorical.values[fieldIndices[interfaceFields.reference]];
// TODO: Can we move this to the filtering section? Reset, Add.
// Initialise the selection tool to point to the correct tables/columns for filtering data.
this.selectionTools.visFilterColumnTargets = {
ageRange: {
table: ageRange.source.queryName.substr(0, ageRange.source.queryName.indexOf('.')),
column: ageRange.source.displayName
},
gender: {
table: gender.source.queryName.substr(0, gender.source.queryName.indexOf('.')),
column: gender.source.displayName
}
};
this.selectionTools.visFilterMeasureTargets = {
values: {
table: valueColumn.source.queryName.substr(0, valueColumn.source.queryName.indexOf('.')),
measure: valueColumn.source.queryName
},
reference: {
table: refColumn.source.queryName.substr(0, refColumn.source.queryName.indexOf('.')),
measure: refColumn.source.queryName
}
};
// Create function to read data values, and highlights, from columns into view model.
const getValues: (name: number, i: number) => number = function (name: number, i: number): number {
return (fieldIndices[name] != null && ('values' in node[fieldIndices[name]])) ?
<number>node[fieldIndices[name]].values[i] : null;
};
const getHighlights: (name: number, i: number) => number = function (name: number, i: number): number {
return (fieldIndices[name] != null && ('highlights' in node[fieldIndices[name]])) ?
<number>node[fieldIndices[name]].highlights[i] : null;
};
chartViewModel.isHighlighted = false;
// For each record load the data...
for (let i: number = 0; i < data.dataViews[0].categorical.categories[0].values.length; i++) {
// ..Create selectionID....
const selectionId: ISelectionId = this.host.createSelectionIdBuilder()
.withCategory(ageRange, i)
.withCategory(gender, i)
.createSelectionId();
// console.log('Selectors:', (selectionId as IVisualSelectionId).getSelectorsByColumn());
// Identify if highlighted...
const isHighlighted: boolean = (getHighlights(interfaceFields.values, i) == null ? false : true) ||
(getHighlights(interfaceFields.reference, i) == null ? false : true);
// ...if at least one record is hilghlighted then set entire chart to highlighted
if (isHighlighted) {
chartViewModel.isHighlighted = true;
}
// Create a new DataPoint in the chartView model
chartViewModel.dataPoints.push(new DataPoint({
age: <string>ageRange.values[i],
gender: <string>gender.values[i],
value: getValues(interfaceFields.values, i) || 0,
reference: getValues(interfaceFields.reference, i) || 0,
highlightValue: getHighlights(interfaceFields.values, i) || 0,
highlightReference: getHighlights(interfaceFields.reference, i) || 0,
identity: selectionId,
specificIdentity: selectionId,
highlighted: isHighlighted,
selected: false
}));
}
// Restore previously stored points selection...when a filter is applied it updates the visual
// Therefore, if this visual is driving the selection we need to restore the selected points.
//if (chartViewModel.isHighlighted) {
// this.selectionTools.clearSelection();
//} else
if (this.selectionTools.interactivityService.hasSelection()) {
chartViewModel.restoreSelection();
}
}
/**
* Method to draw the population pyramid
*
* @private
* @param {number} windowWidth Width of the visual window
* @param {number} windowHeight Height of the visual window
* @param {DataPoint[]} data List of datapoints to be displayed
* @memberof Visual
*/
private popPyramidChart(windowWidth: number, windowHeight: number, data: DataPoint[]): void {
//#region INITIALISE VISUAL
const settings: DataPointSettings = this.settings.dataPoint;
const numberTicks: number = Math.floor(windowWidth / 100 * 8 / this.settings.dataPoint.axisFontSize);
const yInnerTick: number = 4;
const yOuterTick: number = 0;
const xInnerTick: number = 4;
const xOuterTick: number = 1;
const chartFontSize: string = settings.axisFontSize.toString().concat('pt');
// Calculate width of category labels
const ageLabelWidth: number[] = [];
for (const j of data) {
ageLabelWidth.push(this.textSize(j.age, chartFontSize).width);
}
// Calculate the maximum width of the largest category label.
const maxLabelWidth: number = d3.max(ageLabelWidth, function (d: number): number { return d; });
const charSize: { width: number, height: number } = this.textSize('W', chartFontSize);
// Define the canvas size
const margin: { top: number, right: number, bottom: number, left: number, middle: number, axisLabel: number }
= { top: 0, right: charSize.width * 2, bottom: 10, left: charSize.width * 2, middle: maxLabelWidth / 2 + 6, axisLabel: charSize.height + 20 };
const width: number = windowWidth - margin.left - margin.right;
const height: number = windowHeight - margin.top - margin.bottom - margin.axisLabel;
// Setup central axes (left, right y axes).
const regionWidth: number = (width / 2) - margin.middle;
const leftInnerMargin: number = regionWidth + margin.left;
const rightInnerMargin: number = width - regionWidth + margin.left;
//#endregion
//#region CREATE SVG
this.svg
.attr('width', windowWidth)
.attr('height', windowHeight);
if (this.chart != null && !this.chart.empty()) {
this.svg.selectAll('#chart').remove();
}
this.chart = this.svg.append('g');
this.chart
.attr('id', 'chart')
.attr('width', width)
.attr('height', height);
//#endregion
//#region CREATE LEFT AND RIGHT DATA
const dataLeft: DataPoint[] = data.filter(function (d: DataPoint): boolean { return (d.gender === settings.leftFilter); });
const dataRight: DataPoint[] = data.filter(function (d: DataPoint): boolean { return (d.gender === settings.rightFilter); });
//#endregion
//#region GET THE TOTAL POPULATION SIZE AND CREATE A FUNCTION FOR RETURNING THE PERCENTAGE TODO: Move to method with persisted maxValues (Why??).
// Sum left and right data (don't use original data as it may contain values that are not filtered-in to the two lists)
const totalValues: number = d3.sum(dataLeft, function (d: DataPoint): number { return d.value; }) + d3.sum(dataRight, function (d: DataPoint): number { return d.value; });
const totalReference: number = d3.sum(dataLeft, function (d: DataPoint): number { return d.reference; }) + d3.sum(dataRight, function (d: DataPoint): number { return d.reference; });
// Function to calculate percentage, or return original value; also return zero if there is no valid data
const scaled: (n: number, total: number) => number = function (n: number, total: number): number {
return ((!isNaN(n) && (total > 0)) ? ((settings.axisPercent) ? (n / total) : n) : 0);
};
// find the maximum data value on either side
// since this will be shared by both of the x-axes
const maxValue: number = Math.max(
(dataLeft.length > 0) ? d3.max(dataLeft, function (d: DataPoint): number { return scaled(d.value, totalValues); }) : 0,
(dataRight.length > 0) ? d3.max(dataRight, function (d: DataPoint): number { return scaled(d.value, totalValues); }) : 0,
(settings.showReferenceBars && (dataLeft.length > 0)) ? d3.max(dataLeft, function (d: DataPoint): number { return scaled(d.reference, totalReference); }) : 0,
(settings.showReferenceBars && (dataRight.length > 0)) ? d3.max(dataRight, function (d: DataPoint): number { return scaled(d.reference, totalReference); }) : 0);
//#endregion
//#region CREATE AXES
// the xScale goes from 0 to the width of a region
// it will be reversed for the left x-axis
const yScale: d3.scale.Ordinal<string, number> = d3.scale.ordinal()
.domain(data.map(function (d: DataPoint): string { return d.age; }))
.rangeRoundBands([height, 0], 0.1);
// SET UP AXES
const yAxisLeft: d3.svg.Axis = d3.svg.axis()
.scale(yScale)
.orient('right')
.tickSize(yInnerTick, yOuterTick)
.tickPadding(margin.middle - 4);
const yAxisRight: d3.svg.Axis = d3.svg.axis()
.scale(yScale)
.orient('left')
.tickSize(yInnerTick, yOuterTick)
.tickFormat('');
const tickFormat: (n: number) => string = d3.format((settings.axisPercent) ? '.1%' : '0,f0');
const xScale: d3.scale.Linear<number, number> = d3.scale.linear()
.domain([0, maxValue])
.range([0, regionWidth])
.nice();
const xAxisRight: d3.svg.Axis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.tickSize(xInnerTick, xOuterTick)
.tickFormat(tickFormat)
.ticks(numberTicks);
const xAxisLeft: d3.svg.Axis = d3.svg.axis()
.scale(xScale.copy().range([leftInnerMargin, margin.left]))
.orient('bottom')
.tickSize(xInnerTick, xOuterTick)
.tickFormat(tickFormat)
.ticks(numberTicks);
// REVERSE THE X-AXIS SCALE ON THE LEFT SIDE BY REVERSING THE RANGE
// MAKE GROUPS FOR EACH SIDE OF CHART
// scale(-1,1) is used to reverse the left side so the bars grow left instead of right
const leftBarGroup: d3.Selection<SVGElement> = this.chart.append('g')
.attr('transform', svgUtils.translate(leftInnerMargin, 0) + ' scale(-1,1)');
const rightBarGroup: d3.Selection<SVGElement> = this.chart.append('g')
.attr('transform', svgUtils.translate(rightInnerMargin, 0));
// DRAW AXES
this.chart.append('g')
.attr('class', 'axis y left')
.attr('transform', svgUtils.translate(leftInnerMargin, 0))
.call(yAxisLeft)
.selectAll('text')
.attr('class', 'categories') // Class to enable selection of category labels for interactivity.
.style('text-anchor', 'middle')
.style('font-size', chartFontSize);
this.chart.append('g')
.attr('class', 'axis y right')
.attr('transform', svgUtils.translate(rightInnerMargin, 0))
.call(yAxisRight)
.style('font-size', chartFontSize);
this.chart.append('g')
.attr('class', 'axis x left')
.attr('transform', svgUtils.translate(0, height))
.call(xAxisLeft)
.style('font-size', chartFontSize);
this.chart.append('g')
.attr('class', 'axis x right')
.attr('transform', svgUtils.translate(rightInnerMargin, height))
.call(xAxisRight)
.style('font-size', chartFontSize);
//#endregion
//#region AXIS LABELS
// The event model doesn't work with plain text labels, the axis has to be data driven for selections to work when clicking the axis labels.
const labelData: ILabelData[] = [
{
name: 'leftLabel',
text: settings.leftLabel,
filter: this.settings.dataPoint.leftFilter,
location: svgUtils.translate(margin.left, height + margin.axisLabel),
anchor: 'left'
},
{
name: 'rightLabel',
text: settings.rightLabel,
filter: this.settings.dataPoint.rightFilter,
location: svgUtils.translate(windowWidth - margin.right, height + margin.axisLabel),
anchor: 'end'
}
];
this.chart.append('g')
.attr('class', 'labels')
.selectAll('.axisLabel')
.data(labelData)
.enter().append('text')
.attr('class', 'axisLabel')
.attr('transform', function (d: ILabelData): string { return d.location; })
.style('text-anchor', function (d: ILabelData): string { return d.anchor; })
.text(function (d: ILabelData): string { return d.text; })
.style('font-size', chartFontSize);
//#endregion
//#region DRAW BARS
this.drawBar({
bar: leftBarGroup,
data: dataLeft,
className: '.bar.left',
xScale: xScale,
yScale: yScale,
color: settings.leftBarColor,
totalOfValues: totalValues,
isRefBar: false
});
this.drawBar({
bar: rightBarGroup,
data: dataRight,
className: '.bar.right',
xScale: xScale,
yScale: yScale,
color: settings.rightBarColor,
totalOfValues: totalValues,
isRefBar: false
});
if (settings.showReferenceBars) {
this.drawBar({
bar: leftBarGroup,
data: dataLeft,
className: '.refBar.left',
xScale: xScale,
yScale: yScale,
color: settings.refBarColor,
totalOfValues: totalReference,
isRefBar: true
});
this.drawBar({
bar: rightBarGroup,
data: dataRight,
className: '.refBar.right',
xScale: xScale,
yScale: yScale,
color: settings.refBarColor,
totalOfValues: totalReference,
isRefBar: true
});
}
//#endregion
}
//#region DRAW BAR - Method to draw bars
/**
* Method to draw the bars on either side of the population pyramid
* Draws both value and reference bars, as well as managing highlighting
* Changes to the visual as a result of selection is handled in selectionTools.
* Note parameters are passed as an opbject so that each parameter may be more easily
* identified when the method is called (reducing errors).
* @private
* @param bar: d3.Selection<SVGElement> - DOM element to which bars will be attached
* @param data: DataPoint[] - Data driving the chart
* @param className: string - Name of the class for the elements to be attached
* @param xScale: d3.scale.Linear<number, number> - Horizontal chart scale
* @param yScale: d3.scale.Ordinal<string, number> - Vertical chart scale
* @param color: string - Fill and stroke color for the bars
* @param totalOfValues: number - Total of bar values (use for scaling percent display)
* @param isRefBar: boolean - true if this is a reference bar, false if value bar.
*
* @memberof Visual
*/
private drawBar(params: {
bar: d3.Selection<SVGElement>,
data: DataPoint[],
className: string,
xScale: d3.scale.Linear<number, number>,
yScale: d3.scale.Ordinal<string, number>,
color: string,
totalOfValues: number,
isRefBar: boolean
}): void {
const settings: DataPointSettings = this.settings.dataPoint;
const isHighlighted: boolean = this.viewModel.isHighlighted;
const isSelected: boolean = this.selectionTools.interactivityService.hasSelection();
const scaled: (n: number, total: number) => number = function (n: number, total: number): number {
return ((!isNaN(n) && (total > 0)) ? ((settings.axisPercent) ? (n / total) : n) : 0);
};
const valueWidth: (d: DataPoint) => number = function (d: DataPoint): number { return params.xScale(scaled(params.isRefBar ? d.reference : d.value, params.totalOfValues)); };
// Assumption that total of highlight values will never exceed total of values.
const highlightWidth: (d: DataPoint) => number = function (d: DataPoint): number { return params.xScale(scaled(params.isRefBar ? d.highlightReference : d.highlightValue, params.totalOfValues)); };
const fillOpacity: (d: DataPoint) => number = function (d: DataPoint): number {
if (params.isRefBar) { return settings.transparent; }
if (isHighlighted) { return settings.opaque; }
if (isSelected) {
if (d.selected) {
return settings.solid;
} else {
return settings.opaque;
}
}
return settings.solid;
};
// Draw non-highlighted value and reference bars, if highlighted drop opacity of value bars.
params.bar.selectAll(params.className)
.data(params.data)
.enter().append('rect')
.attr('class', params.isRefBar ? 'notSelectable' : 'dataPoint')
.attr('x', 0)
.attr('y', function (d: DataPoint): number { return params.yScale(d.age) + ((params.isRefBar) ? settings.refBarWidth : 0); })
.attr('width', valueWidth)
.attr('height', params.yScale.rangeBand() - (params.isRefBar ? settings.refBarWidth : 0) * 2)
.style('fill', params.color)
.style('fill-opacity', fillOpacity)
.style('stroke', params.color)
.style('stroke-width', ((params.isRefBar ? settings.refBarWidth : 0) * 2).toString());
// If we have highlighting enabled then draw a opacity of value bars will be reduced, and we need to draw a solid bar of the correct width for highlighted values.
// TODO: Consider making refBar highlight sensitive.
if (isHighlighted && !params.isRefBar) {
params.bar.selectAll(params.className)
.data(params.data)
.enter().append('rect')
.attr('class', 'notSelectable')
.attr('x', 0)
.attr('y', function (d: DataPoint): number { return params.yScale(d.age) + ((params.isRefBar) ? settings.refBarWidth : 0); })
.attr('width', highlightWidth)
.attr('height', params.yScale.rangeBand() - ((params.isRefBar) ? settings.refBarWidth : 0) * 2)
.style('fill', params.color)
.style('fill-opacity', settings.solid)
.style('stroke', params.color)
.style('stroke-width', (((params.isRefBar) ? settings.refBarWidth : 0) * 2).toString());
}
}
//#endregion
// TODO: Power BI has tools for determining text size, etc...
/**
* Method to return the size of a text node (Written for SVG1.1, with SVG2 could use SVGGraphicsElement more elegantly)
* TODO: Include Font/Type within the definition.
*
* @private
* @param {string} text Text from which the screen width and height is required
* @param {string} chartFontSize Font size of the text
* @returns {{ width: number, height: number }} Width and Height of the bounding text box.
* @memberof Visual
*/
private textSize(text: string, chartFontSize: string): { width: number, height: number } {
const docElement: HTMLDivElement = this.target.appendChild(document.createElement('div')) as HTMLDivElement;
const svgDoc: SVGSVGElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
docElement.appendChild(svgDoc);
const textElement: SVGTextElement = document.createElementNS('http://www.w3.org/2000/svg', 'text');
textElement.setAttributeNS(null, 'font-size', chartFontSize);
textElement.textContent = text;
svgDoc.appendChild(textElement);
const size: { width: number, height: number } = textElement.getBBox();
this.target.removeChild(docElement);
return { width: size.width, height: size.height };
}
}
}