-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathvisualizerBase.ts
633 lines (566 loc) · 19 KB
/
visualizerBase.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
import { Question, QuestionCommentModel, settings } from "survey-core";
import { IDataInfo, DataProvider } from "./dataProvider";
import { VisualizerFactory } from "./visualizerFactory";
import { DocumentHelper } from "./utils";
import { localization } from "./localizationManager";
import { Event } from "survey-core";
var styles = require("./visualizerBase.scss");
/**
* A base object for all visualizers. Use it to implement a custom visualizer.
*
* Constructor parameters:
*
* - `question`: [`Question`](https://surveyjs.io/form-library/documentation/api-reference/question)\
* A survey question to visualize.
* - `data`: `Array<any>`\
* Survey results.
* - `options`\
* An object with the following properties:
* - `seriesValues`: `Array<String>`\
* Series values used to group data.
* - `seriesLabels`: `Array<String>`\
* Series labels to display. If this property is not set, `seriesValues` are used as labels.
* - `survey`: [`SurveyModel`](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model)\
* Pass a `SurveyModel` instance if you want to use locales from the survey JSON schema.
* - `dataProvider`: `DataProvider`\
* A data provider for this visualizer.
* - `type`: `String`\
* *(Optional)* The visualizer's type.
*
* [View Demo](https://surveyjs.io/dashboard/examples/how-to-plot-survey-data-in-custom-bar-chart/ (linkStyle))
*/
export class VisualizerBase implements IDataInfo {
private _showToolbar = true;
private _footerVisualizer: VisualizerBase = undefined;
private _dataProvider: DataProvider = undefined;
public labelTruncateLength: number = 27;
protected renderResult: HTMLElement = undefined;
protected toolbarContainer: HTMLElement = undefined;
protected headerContainer: HTMLElement = undefined;
protected contentContainer: HTMLElement = undefined;
protected footerContainer: HTMLElement = undefined;
protected _supportSelection: boolean = false;
// public static otherCommentQuestionType = "comment"; // TODO: make it configureable - allow choose what kind of question/visualizer will be used for comments/others
public static otherCommentCollapsed = true;
/**
* An event that is raised after the visualizer's content is rendered.
*
* Parameters:
*
* - `sender`: `VisualizerBase`\
* A `VisualizerBase` instance that raised the event.
*
* - `options.htmlElement`: `HTMLElement`\
* A page element with the visualizer's content.
* @see render
* @see refresh
**/
public onAfterRender: Event<
(sender: VisualizerBase, options: any) => any,
VisualizerBase,
any
> = new Event<(sender: VisualizerBase, options: any) => any, VisualizerBase, any>();
protected afterRender(contentContainer: HTMLElement) {
this.onAfterRender.fire(this, { htmlElement: contentContainer });
}
/**
* An event that is raised after a new locale is set.
*
* Parameters:
*
* - `sender`: `VisualizerBase`\
* A `VisualizerBase` instance that raised the event.
*
* - `options.locale`: `String`\
* The indentifier of a new locale (for example, "en").
* @see locale
*/
public onLocaleChanged = new Event<
(sender: VisualizerBase, options: { locale: string }) => any,
VisualizerBase,
any
>();
protected toolbarItemCreators: { [name: string]: (toolbar?: HTMLDivElement) => HTMLElement } = {};
constructor(
public question: Question,
data: Array<{ [index: string]: any }>,
public options: { [index: string]: any } = {},
private _type?: string
) {
this._dataProvider = options.dataProvider || new DataProvider(data);
this._dataProvider.onDataChanged.add(() => this.onDataChanged());
if (typeof options.labelTruncateLength !== "undefined") {
this.labelTruncateLength = options.labelTruncateLength;
}
}
protected get questionOptions() {
return this.options[this.question.name];
}
protected onDataChanged() {
this.refresh();
}
/**
* Returns the identifier of a visualized question.
*/
get name(): string | Array<string> {
return this.question.valueName || this.question.name;
}
/**
* Indicates whether the visualizer displays a header. This property is `true` when a visualized question has a correct answer.
* @see hasFooter
*/
get hasHeader(): boolean {
if (!this.options || !this.options.showCorrectAnswers) {
return false;
}
return !!this.question && !!this.question.correctAnswer;
}
/**
* Indicates whether the visualizer displays a footer. This property is `true` when a visualized question has a comment.
* @see hasHeader
*/
get hasFooter(): boolean {
return (
!!this.question && (this.question.hasComment || this.question.hasOther)
);
}
protected createVisualizer<T = VisualizerBase>(question: Question): T {
let options = Object.assign({}, this.options);
if (options.dataProvider === undefined) {
options.dataProvider = this.dataProvider;
}
return VisualizerFactory.createVisualizer(question, this.data, options) as T;
}
/**
* Allows you to access the footer visualizer. Returns `undefined` if the footer is absent.
* @see hasFooter
*/
get footerVisualizer() {
if (!this.hasFooter) {
return undefined;
}
if (!this._footerVisualizer) {
const question = new QuestionCommentModel(
this.question.name + (settings || {}).commentPrefix
);
question.title = this.processText(this.question.title);
this._footerVisualizer = this.createVisualizer(question);
this._footerVisualizer.onUpdate = () => this.invokeOnUpdate();
}
return this._footerVisualizer;
}
/**
* Indicates whether users can select series points to cross-filter charts. To allow or disallow selection, set the `allowSelection` property of the `options` object in the constructor.
*/
public get supportSelection(): boolean {
return (
(this.options.allowSelection === undefined ||
this.options.allowSelection) &&
this._supportSelection
);
}
getSeriesValues(): Array<string> {
return this.options.seriesValues || [];
}
getSeriesLabels(): Array<string> {
return this.options.seriesLabels || this.getSeriesValues();
}
getValues(): Array<any> {
throw new Error("Method not implemented.");
}
getLabels(): Array<string> {
return this.getValues();
}
/**
* Registers a function used to create a toolbar item for this visualizer.
*
* The following code shows how to add a custom button and drop-down menu to the toolbar:
*
* ```js
* import { VisualizationPanel, DocumentHelper } from "survey-analytics";
*
* const vizPanel = new VisualizationPanel( ... );
*
* // Add a custom button to the toolbar
* visPanel.visualizers[0].registerToolbarItem("my-toolbar-button", () => {
* return DocumentHelper.createButton(
* // A button click event handler
* () => {
* alert("Custom toolbar button is clicked");
* },
* // Button caption
* "Button"
* );
* });
*
* // Add a custom drop-down menu to the toolbar
* vizPanel.visualizers[0].registerToolbarItem("my-toolbar-dropdown", () => {
* return DocumentHelper.createSelector(
* // Menu items
* [
* { value: 1, text: "One" },
* { value: 2, text: "Two" },
* { value: 3, text: "Three" }
* ],
* // A function that specifies initial selection
* (option) => false,
* // An event handler that is executed when selection is changed
* (e) => {
* alert(e.target.value);
* }
* );
* });
* ```
* @param name A custom name for the toolbar item.
* @param creator A function that accepts the toolbar and should return an `HTMLElement` with the toolbar item.
*/
public registerToolbarItem(
name: string,
creator: (toolbar?: HTMLDivElement) => HTMLElement
) {
this.toolbarItemCreators[name] = creator;
}
/**
* Returns the visualizer's type.
*/
public get type() {
return this._type || "visualizer";
}
/**
* Returns an array of survey results used to calculate values for visualization. If a user applies a filter, the array is also filtered.
*
* To get an array of calculated and visualized values, call the [`getData()`](https://surveyjs.io/dashboard/documentation/api-reference/visualizerbase#getData) method.
*/
protected get data() {
return this.dataProvider.filteredData;
}
protected get dataProvider(): DataProvider {
return this._dataProvider;
}
/**
* Updates visualized data.
* @param data A data array with survey results to be visualized.
*/
updateData(data: Array<{ [index: string]: any }>) {
if (!this.options.dataProvider) {
this.dataProvider.data = data;
}
if (this.hasFooter) {
this.footerVisualizer.updateData(data);
}
}
onUpdate: () => void;
invokeOnUpdate() {
this.onUpdate && this.onUpdate();
}
/**
* Deletes the visualizer and all its elements from the DOM.
* @see clear
*/
destroy() {
if (!!this.renderResult) {
this.clear();
this.toolbarContainer = undefined;
this.headerContainer = undefined;
this.contentContainer = undefined;
this.footerContainer = undefined;
this.renderResult.innerHTML = "";
this.renderResult = undefined;
}
if (!!this._footerVisualizer) {
this._footerVisualizer.destroy();
this._footerVisualizer.onUpdate = undefined;
this._footerVisualizer = undefined;
}
}
/**
* Empties the toolbar, header, footer, and content containers.
*
* If you want to empty and delete the visualizer and all its elements from the DOM, call the [`destroy()`](https://surveyjs.io/dashboard/documentation/api-reference/visualizerbase#destroy) method instead.
*/
public clear() {
if (!!this.toolbarContainer) {
this.destroyToolbar(this.toolbarContainer);
}
if (!!this.headerContainer) {
this.destroyHeader(this.headerContainer);
}
if (!!this.contentContainer) {
this.destroyContent(this.contentContainer);
}
if (!!this.footerContainer) {
this.destroyFooter(this.footerContainer);
}
}
protected createToolbarItems(toolbar: HTMLDivElement) {
Object.keys(this.toolbarItemCreators || {}).forEach((toolbarItemName) => {
let toolbarItem = this.toolbarItemCreators[toolbarItemName](toolbar);
if (!!toolbarItem) {
toolbar.appendChild(toolbarItem);
}
});
}
protected getCorrectAnswerText(): string {
return !!this.question ? this.question.correctAnswer : "";
}
protected destroyToolbar(container: HTMLElement) {
container.innerHTML = "";
}
protected renderToolbar(container: HTMLElement) {
if (this.showToolbar) {
const toolbar = <HTMLDivElement>(
DocumentHelper.createElement("div", "sa-toolbar")
);
this.createToolbarItems(toolbar);
container.appendChild(toolbar);
}
}
protected destroyHeader(container: HTMLElement) {
if (!!this.options && typeof this.options.destroyHeader === "function") {
this.options.destroyHeader(container, this);
} else {
container.innerHTML = "";
}
}
protected destroyContent(container: HTMLElement) {
if (!!this.options && typeof this.options.destroyContent === "function") {
this.options.destroyContent(container, this);
} else {
container.innerHTML = "";
}
}
protected renderHeader(container: HTMLElement) {
if (!!this.options && typeof this.options.renderHeader === "function") {
this.options.renderHeader(container, this);
} else {
const correctAnswerElement = DocumentHelper.createElement(
"div",
"sa-visualizer__correct-answer"
);
correctAnswerElement.innerText = localization.getString("correctAnswer") + this.getCorrectAnswerText();
container.appendChild(correctAnswerElement);
}
}
protected renderContent(container: HTMLElement) {
if (!!this.options && typeof this.options.renderContent === "function") {
this.options.renderContent(container, this);
} else {
container.innerText = localization.getString("noVisualizerForQuestion");
}
this.afterRender(container);
}
protected destroyFooter(container: HTMLElement) {
container.innerHTML = "";
}
protected renderFooter(container: HTMLElement) {
container.innerHTML = "";
if (this.hasFooter) {
const footerTitleElement = DocumentHelper.createElement(
"h4",
"sa-visualizer__footer-title",
{ innerText: localization.getString("otherCommentTitle") }
);
container.appendChild(footerTitleElement);
const footerContentElement = DocumentHelper.createElement(
"div",
"sa-visualizer__footer-content"
);
footerContentElement.style.display = VisualizerBase.otherCommentCollapsed
? "none"
: "block";
const visibilityButton = DocumentHelper.createButton(() => {
if (footerContentElement.style.display === "none") {
footerContentElement.style.display = "block";
visibilityButton.innerText = localization.getString("hideButton");
} else {
footerContentElement.style.display = "none";
visibilityButton.innerText = localization.getString(
VisualizerBase.otherCommentCollapsed ? "showButton" : "hideButton"
);
}
this.footerVisualizer.invokeOnUpdate();
}, localization.getString("showButton") /*, "sa-toolbar__button--right"*/);
container.appendChild(visibilityButton);
container.appendChild(footerContentElement);
this.footerVisualizer.render(footerContentElement);
}
}
/**
* Renders the visualizer in a specified container.
* @param targetElement An `HTMLElement` or an `id` of a page element in which you want to render the visualizer.
*/
render(targetElement: HTMLElement | string) {
if (typeof targetElement === "string") {
targetElement = document.getElementById(targetElement);
}
this.renderResult = targetElement;
this.toolbarContainer = DocumentHelper.createElement(
"div",
"sa-visualizer__toolbar"
);
targetElement.appendChild(this.toolbarContainer);
this.renderToolbar(this.toolbarContainer);
if (this.hasHeader) {
this.headerContainer = DocumentHelper.createElement(
"div",
"sa-visualizer__header"
);
targetElement.appendChild(this.headerContainer);
this.renderHeader(this.headerContainer);
}
this.contentContainer = DocumentHelper.createElement(
"div",
"sa-visualizer__content"
);
targetElement.appendChild(this.contentContainer);
this.renderContent(this.contentContainer);
this.footerContainer = DocumentHelper.createElement(
"div",
"sa-visualizer__footer"
);
targetElement.appendChild(this.footerContainer);
this.renderFooter(this.footerContainer);
}
/**
* Re-renders the visualizer and its content.
*/
public refresh() {
if (!!this.headerContainer) {
setTimeout(() => {
this.destroyHeader(this.headerContainer);
this.renderHeader(this.headerContainer);
this.invokeOnUpdate();
});
}
if (!!this.contentContainer) {
setTimeout(() => {
this.destroyContent(this.contentContainer);
this.renderContent(this.contentContainer);
this.invokeOnUpdate();
});
}
if (!!this.footerContainer) {
setTimeout(() => {
this.destroyFooter(this.footerContainer);
this.renderFooter(this.footerContainer);
this.invokeOnUpdate();
});
}
}
protected processText(text: string): string {
if (this.options.stripHtmlFromTitles !== false) {
let originalText = text || "";
let processedText = originalText.replace(/(<([^>]+)>)/gi, "");
return processedText;
}
return text;
}
getRandomColor() {
const colors = this.getColors();
return colors[Math.floor(Math.random() * colors.length)];
}
private _backgroundColor = "#f7f7f7";
get backgroundColor() { return this.getBackgroundColorCore(); }
set backgroundColor(value) { this.setBackgroundColorCore(value); }
protected getBackgroundColorCore() {
return this._backgroundColor;
}
protected setBackgroundColorCore(color: string) {
this._backgroundColor = color;
if (this.footerVisualizer) this.footerVisualizer.backgroundColor = color;
}
static customColors: string[] = [];
private static colors = [
"#86e1fb",
"#3999fb",
"#ff6771",
"#1eb496",
"#ffc152",
"#aba1ff",
"#7d8da5",
"#4ec46c",
"#cf37a6",
"#4e6198",
];
getColors(count = 10) {
const colors =
Array.isArray(VisualizerBase.customColors) &&
VisualizerBase.customColors.length > 0
? VisualizerBase.customColors
: VisualizerBase.colors;
let manyColors: any = [];
for (let index = 0; index < count; index++) {
manyColors = manyColors.concat(colors);
}
return manyColors;
}
/**
* Gets or sets the visibility of the visualizer's toolbar.
*
* Default value: `true`
*/
get showToolbar() {
return this._showToolbar;
}
set showToolbar(newValue: boolean) {
if (newValue != this._showToolbar) {
this._showToolbar = newValue;
if (!!this.toolbarContainer) {
this.destroyToolbar(this.toolbarContainer);
this.renderToolbar(this.toolbarContainer);
}
}
}
/**
* Returns an array of calculated and visualized values. If a user applies a filter, the array is also filtered.
*
* To get an array of source survey results, use the [`data`](https://surveyjs.io/dashboard/documentation/api-reference/visualizerbase#data) property.
*/
getData(): any {
return this.dataProvider.getData(this);
}
/**
* Returns an object with properties that describe a current visualizer state. The properties are different for each individual visualizer.
*
* > This method is overriden in descendant classes.
* @see setState
*/
public getState(): any {
return {};
}
/**
* Sets the visualizer's state.
*
* > This method is overriden in descendant classes.
* @see getState
*/
public setState(state: any): void {
}
/**
* Gets or sets the current locale.
*
* If you want to inherit the locale from a visualized survey, assign a `SurveyModel` instance to the `survey` property of the `options` object in the constructor.
*
* If the survey is [translated into more than one language](https://surveyjs.io/form-library/examples/survey-localization/), the toolbar displays a language selection drop-down menu.
* @see onLocaleChanged
*/
public get locale() {
var survey = this.options.survey;
if (!!survey) {
return survey.locale;
}
return localization.currentLocale;
}
public set locale(newLocale: string) {
this.setLocale(newLocale);
this.onLocaleChanged.fire(this, { locale: newLocale });
this.refresh();
}
protected setLocale(newLocale: string) {
localization.currentLocale = newLocale;
var survey = this.options.survey;
if (!!survey && survey.locale !== newLocale) {
survey.locale = newLocale;
}
}
}