move code from parts to contrib (#8319)

This commit is contained in:
Anthony Dresser
2019-11-14 12:23:11 -08:00
committed by GitHub
parent 6438967202
commit 7a2c30e159
619 changed files with 848 additions and 848 deletions

View File

@@ -0,0 +1,196 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IInsight } from 'sql/workbench/contrib/charts/browser/interfaces';
import { Graph } from 'sql/workbench/contrib/charts/browser/graphInsight';
import { IClipboardService } from 'sql/platform/clipboard/common/clipboardService';
import { localize } from 'vs/nls';
import { Action } from 'vs/base/common/actions';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { URI } from 'vs/base/common/uri';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { QueryInput } from 'sql/workbench/contrib/query/common/queryInput';
import { IInsightsConfig } from 'sql/platform/dashboard/browser/insightRegistry';
import { IInsightOptions } from 'sql/workbench/contrib/charts/common/interfaces';
import { IFileService } from 'vs/platform/files/common/files';
import { IFileDialogService, FileFilter } from 'vs/platform/dialogs/common/dialogs';
import { VSBuffer } from 'vs/base/common/buffer';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { assign } from 'vs/base/common/objects';
export interface IChartActionContext {
options: IInsightOptions;
insight: IInsight;
}
export class CreateInsightAction extends Action {
public static ID = 'chartview.createInsight';
public static LABEL = localize('createInsightLabel', "Create Insight");
public static ICON = 'createInsight';
constructor(
@IEditorService private editorService: IEditorService,
@INotificationService private notificationService: INotificationService,
@IUntitledEditorService private untitledEditorService: IUntitledEditorService
) {
super(CreateInsightAction.ID, CreateInsightAction.LABEL, CreateInsightAction.ICON);
}
public run(context: IChartActionContext): Promise<boolean> {
let uriString: string = this.getActiveUriString();
if (!uriString) {
this.showError(localize('createInsightNoEditor', "Cannot create insight as the active editor is not a SQL Editor"));
return Promise.resolve(false);
}
let uri: URI = URI.parse(uriString);
let queryFile: string = uri.fsPath;
let query: string = undefined;
let type = {};
let options = assign({}, context.options);
delete options.type;
type[context.options.type] = options;
// create JSON
let config: IInsightsConfig = {
type,
query,
queryFile
};
let widgetConfig = {
name: localize('myWidgetName', "My-Widget"),
gridItemConfig: {
sizex: 2,
sizey: 1
},
widget: {
'insights-widget': config
}
};
let input = this.untitledEditorService.createOrGet(undefined, 'json', JSON.stringify(widgetConfig));
return this.editorService.openEditor(input, { pinned: true })
.then(
() => true,
error => {
this.notificationService.notify({
severity: Severity.Error,
message: error
});
return false;
}
);
}
private getActiveUriString(): string {
let editor = this.editorService.activeEditor;
if (editor instanceof QueryInput) {
return editor.uri;
}
return undefined;
}
private showError(errorMsg: string) {
this.notificationService.notify({
severity: Severity.Error,
message: errorMsg
});
}
}
export class CopyAction extends Action {
public static ID = 'chartview.copy';
public static LABEL = localize('copyChartLabel', "Copy as image");
public static ICON = 'copyImage';
constructor(
@IClipboardService private clipboardService: IClipboardService,
@INotificationService private notificationService: INotificationService
) {
super(CopyAction.ID, CopyAction.LABEL, CopyAction.ICON);
}
public run(context: IChartActionContext): Promise<boolean> {
if (context.insight instanceof Graph) {
let data = context.insight.getCanvasData();
if (!data) {
this.showError(localize('chartNotFound', "Could not find chart to save"));
return Promise.resolve(false);
}
this.clipboardService.writeImageDataUrl(data);
return Promise.resolve(true);
}
return Promise.resolve(false);
}
private showError(errorMsg: string) {
this.notificationService.notify({
severity: Severity.Error,
message: errorMsg
});
}
}
export class SaveImageAction extends Action {
public static ID = 'chartview.saveImage';
public static LABEL = localize('saveImageLabel', "Save as image");
public static ICON = 'saveAsImage';
constructor(
@INotificationService private readonly notificationService: INotificationService,
@IFileService private readonly fileService: IFileService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IOpenerService private readonly openerService: IOpenerService
) {
super(SaveImageAction.ID, SaveImageAction.LABEL, SaveImageAction.ICON);
}
public async run(context: IChartActionContext): Promise<boolean> {
if (context.insight instanceof Graph) {
let fileFilters = new Array<FileFilter>({ extensions: ['png'], name: localize('resultsSerializer.saveAsFileExtensionPNGTitle', "PNG") });
const filePath = await this.fileDialogService.pickFileToSave({ filters: fileFilters });
const data = (<Graph>context.insight).getCanvasData();
if (!data) {
this.notificationService.error(localize('chartNotFound', "Could not find chart to save"));
return false;
}
if (filePath) {
let buffer = this.decodeBase64Image(data);
try {
await this.fileService.writeFile(filePath, buffer);
} catch (err) {
if (err) {
this.notificationService.error(err.message);
} else {
this.openerService.open(filePath, { openExternal: true });
this.notificationService.notify({
severity: Severity.Error,
message: localize('chartSaved', "Saved Chart to path: {0}", filePath.toString())
});
}
}
}
return true;
}
return Promise.resolve(false);
}
private decodeBase64Image(data: string): VSBuffer {
const marker = ';base64,';
const raw = atob(data.substring(data.indexOf(marker) + marker.length));
const n = raw.length;
const a = new Uint8Array(new ArrayBuffer(n));
for (let i = 0; i < n; i++) {
a[i] = raw.charCodeAt(i);
}
return VSBuffer.wrap(a);
}
}

View File

@@ -0,0 +1,220 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions, IInsightRegistry } from 'sql/platform/dashboard/browser/insightRegistry';
import { IInsightOptions, DataDirection, DataType, LegendPosition, ChartType, InsightType } from 'sql/workbench/contrib/charts/common/interfaces';
import { values } from 'vs/base/common/collections';
const insightRegistry = Registry.as<IInsightRegistry>(Extensions.InsightContribution);
export enum ControlType {
combo,
numberInput,
input,
checkbox,
dateInput
}
export interface IChartOption {
label: string;
type: ControlType;
configEntry: string;
default: any;
options?: any[];
displayableOptions?: string[];
if?: (options: IInsightOptions) => boolean;
}
export interface IChartOptions {
general: Array<IChartOption>;
[x: string]: Array<IChartOption>;
}
const dataDirectionOption: IChartOption = {
label: localize('dataDirectionLabel', "Data Direction"),
type: ControlType.combo,
displayableOptions: [localize('verticalLabel', "Vertical"), localize('horizontalLabel', "Horizontal")],
options: [DataDirection.Vertical, DataDirection.Horizontal],
configEntry: 'dataDirection',
default: DataDirection.Horizontal
};
const columnsAsLabelsInput: IChartOption = {
label: localize('columnsAsLabelsLabel', "Use column names as labels"),
type: ControlType.checkbox,
configEntry: 'columnsAsLabels',
default: true,
if: (options: IInsightOptions) => {
return options.dataDirection === DataDirection.Vertical && options.dataType !== DataType.Point;
}
};
const labelFirstColumnInput: IChartOption = {
label: localize('labelFirstColumnLabel', "Use first column as row label"),
type: ControlType.checkbox,
configEntry: 'labelFirstColumn',
default: false,
if: (options: IInsightOptions) => {
return options.dataDirection === DataDirection.Horizontal && options.dataType !== DataType.Point;
}
};
const legendInput: IChartOption = {
label: localize('legendLabel', "Legend Position"),
type: ControlType.combo,
options: values(LegendPosition),
configEntry: 'legendPosition',
default: LegendPosition.Top
};
const yAxisLabelInput: IChartOption = {
label: localize('yAxisLabel', "Y Axis Label"),
type: ControlType.input,
configEntry: 'yAxisLabel',
default: undefined
};
const yAxisMinInput: IChartOption = {
label: localize('yAxisMinVal', "Y Axis Minimum Value"),
type: ControlType.numberInput,
configEntry: 'yAxisMin',
default: undefined
};
const yAxisMaxInput: IChartOption = {
label: localize('yAxisMaxVal', "Y Axis Maximum Value"),
type: ControlType.numberInput,
configEntry: 'yAxisMax',
default: undefined
};
const xAxisLabelInput: IChartOption = {
label: localize('xAxisLabel', "X Axis Label"),
type: ControlType.input,
configEntry: 'xAxisLabel',
default: undefined
};
const xAxisMinInput: IChartOption = {
label: localize('xAxisMinVal', "X Axis Minimum Value"),
type: ControlType.numberInput,
configEntry: 'xAxisMin',
default: undefined
};
const xAxisMaxInput: IChartOption = {
label: localize('xAxisMaxVal', "X Axis Maximum Value"),
type: ControlType.numberInput,
configEntry: 'xAxisMax',
default: undefined
};
const xAxisMinDateInput: IChartOption = {
label: localize('xAxisMinDate', "X Axis Minimum Date"),
type: ControlType.dateInput,
configEntry: 'xAxisMin',
default: undefined
};
const xAxisMaxDateInput: IChartOption = {
label: localize('xAxisMaxDate', "X Axis Maximum Date"),
type: ControlType.dateInput,
configEntry: 'xAxisMax',
default: undefined
};
const dataTypeInput: IChartOption = {
label: localize('dataTypeLabel', "Data Type"),
type: ControlType.combo,
options: [DataType.Number, DataType.Point],
displayableOptions: [localize('numberLabel', "Number"), localize('pointLabel', "Point")],
configEntry: 'dataType',
default: DataType.Number
};
export const ChartOptions: IChartOptions = {
general: [
{
label: localize('chartTypeLabel', "Chart Type"),
type: ControlType.combo,
options: insightRegistry.getAllIds(),
configEntry: 'type',
default: ChartType.Bar
}
],
[ChartType.Line]: [
dataTypeInput,
columnsAsLabelsInput,
labelFirstColumnInput,
yAxisLabelInput,
xAxisLabelInput,
legendInput
],
[ChartType.Scatter]: [
legendInput,
yAxisLabelInput,
xAxisLabelInput
],
[ChartType.TimeSeries]: [
legendInput,
yAxisLabelInput,
yAxisMinInput,
yAxisMaxInput,
xAxisLabelInput,
xAxisMinDateInput,
xAxisMaxDateInput,
],
[ChartType.Bar]: [
dataDirectionOption,
columnsAsLabelsInput,
labelFirstColumnInput,
legendInput,
yAxisLabelInput,
yAxisMinInput,
yAxisMaxInput,
xAxisLabelInput
],
[ChartType.HorizontalBar]: [
dataDirectionOption,
columnsAsLabelsInput,
labelFirstColumnInput,
legendInput,
xAxisLabelInput,
xAxisMinInput,
xAxisMaxInput,
yAxisLabelInput
],
[ChartType.Pie]: [
dataDirectionOption,
columnsAsLabelsInput,
labelFirstColumnInput,
legendInput
],
[ChartType.Doughnut]: [
dataDirectionOption,
columnsAsLabelsInput,
labelFirstColumnInput,
legendInput
],
[InsightType.Table]: [],
[InsightType.Count]: [],
[InsightType.Image]: [
{
configEntry: 'encoding',
label: localize('encodingOption', "Encoding"),
type: ControlType.input,
default: 'hex'
},
{
configEntry: 'imageFormat',
label: localize('imageFormatOption', "Image Format"),
type: ControlType.input,
default: 'jpeg'
}
]
};

View File

@@ -0,0 +1,37 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IPanelTab } from 'sql/base/browser/ui/panel/panel';
import { ChartView } from './chartView';
import QueryRunner from 'sql/platform/query/common/queryRunner';
import { localize } from 'vs/nls';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
export class ChartTab implements IPanelTab {
public readonly title = localize('chartTabTitle', "Chart");
public readonly identifier = 'ChartTab';
public readonly view: ChartView;
constructor(@IInstantiationService instantiationService: IInstantiationService) {
this.view = instantiationService.createInstance(ChartView);
}
public set queryRunner(runner: QueryRunner) {
this.view.queryRunner = runner;
}
public chart(dataId: { batchId: number, resultId: number }): void {
this.view.chart(dataId);
}
public dispose() {
this.view.dispose();
}
public clear() {
this.view.clear();
}
}

View File

@@ -0,0 +1,399 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/chartView';
import { IPanelView } from 'sql/base/browser/ui/panel/panel';
import { Insight } from './insight';
import QueryRunner from 'sql/platform/query/common/queryRunner';
import { ChartOptions, IChartOption, ControlType } from './chartOptions';
import { Extensions, IInsightRegistry } from 'sql/platform/dashboard/browser/insightRegistry';
import { IInsightData } from './interfaces';
import { Registry } from 'vs/platform/registry/common/platform';
import * as DOM from 'vs/base/browser/dom';
import { SelectBox } from 'sql/base/browser/ui/selectBox/selectBox';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle';
import { attachSelectBoxStyler, attachInputBoxStyler } from 'vs/platform/theme/common/styler';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { isUndefinedOrNull } from 'vs/base/common/types';
import { CreateInsightAction, CopyAction, SaveImageAction, IChartActionContext } from 'sql/workbench/contrib/charts/browser/actions';
import { Taskbar } from 'sql/base/browser/ui/taskbar/taskbar';
import { Checkbox } from 'sql/base/browser/ui/checkbox/checkbox';
import { ChartState, IInsightOptions, ChartType } from 'sql/workbench/contrib/charts/common/interfaces';
import * as nls from 'vs/nls';
import { find } from 'vs/base/common/arrays';
const insightRegistry = Registry.as<IInsightRegistry>(Extensions.InsightContribution);
//Map used to store names and alternative names for chart types.
//This is mainly used for comparison when options are parsed into the constructor.
const altNameHash: { [oldName: string]: string } = {
'horizontalBar': nls.localize('horizontalBarAltName', "Horizontal Bar"),
'bar': nls.localize('barAltName', "Bar"),
'line': nls.localize('lineAltName', "Line"),
'pie': nls.localize('pieAltName', "Pie"),
'scatter': nls.localize('scatterAltName', "Scatter"),
'timeSeries': nls.localize('timeSeriesAltName', "Time Series"),
'image': nls.localize('imageAltName', "Image"),
'count': nls.localize('countAltName', "Count"),
'table': nls.localize('tableAltName', "Table"),
'doughnut': nls.localize('doughnutAltName', "Doughnut")
};
export class ChartView extends Disposable implements IPanelView {
private insight: Insight;
private _queryRunner: QueryRunner;
private _data: IInsightData;
private _currentData: { batchId: number, resultId: number };
private taskbar: Taskbar;
private _createInsightAction: CreateInsightAction;
private _copyAction: CopyAction;
private _saveAction: SaveImageAction;
private _state: ChartState;
private options: IInsightOptions = {
type: ChartType.Bar
};
/** parent container */
private container: HTMLElement;
/** container for the options controls */
private optionsControl: HTMLElement;
/** container for type specific controls */
private typeControls: HTMLElement;
/** container for the insight */
private insightContainer: HTMLElement;
/** container for the action bar */
private taskbarContainer: HTMLElement;
/** container for the charting (includes insight and options) */
private chartingContainer: HTMLElement;
private optionDisposables: IDisposable[] = [];
private optionMap: { [x: string]: { element: HTMLElement; set: (val) => void } } = {};
constructor(
@IContextViewService private _contextViewService: IContextViewService,
@IThemeService private _themeService: IThemeService,
@IInstantiationService private _instantiationService: IInstantiationService,
) {
super();
this.taskbarContainer = DOM.$('div.taskbar-container');
this.taskbar = new Taskbar(this.taskbarContainer);
this.optionsControl = DOM.$('div.options-container');
const generalControls = DOM.$('div.general-controls');
this.optionsControl.appendChild(generalControls);
this.typeControls = DOM.$('div.type-controls');
this.optionsControl.appendChild(this.typeControls);
this._createInsightAction = this._instantiationService.createInstance(CreateInsightAction);
this._copyAction = this._instantiationService.createInstance(CopyAction);
this._saveAction = this._instantiationService.createInstance(SaveImageAction);
this.taskbar.setContent([{ action: this._createInsightAction }]);
const self = this;
this.options = new Proxy(this.options, {
get: function (target, key) {
return target[key];
},
set: function (target, key, value) {
let change = false;
if (target[key] !== value) {
change = true;
}
target[key] = value;
// mirror the change in our state
if (self.state) {
self.state.options[key] = value;
}
if (change) {
self.taskbar.context = <IChartActionContext>{ options: self.options, insight: self.insight ? self.insight.insight : undefined };
if (key === 'type') {
self.buildOptions();
} else {
self.verifyOptions();
}
}
return true;
}
}) as IInsightOptions;
ChartOptions.general[0].options = insightRegistry.getAllIds();
ChartOptions.general.map(o => {
this.createOption(o, generalControls);
});
this.buildOptions();
}
public clear() {
}
/**
* Function used to generate list of alternative names for use with SelectBox
* @param option - the original option names.
*/
private changeToAltNames(option: string[]): string[] {
return option.map(o => altNameHash[o] || o);
}
public dispose() {
dispose(this.optionDisposables);
super.dispose();
}
render(container: HTMLElement): void {
if (!this.container) {
this.container = DOM.$('div.chart-parent-container');
this.insightContainer = DOM.$('div.insight-container');
this.chartingContainer = DOM.$('div.charting-container');
this.container.appendChild(this.taskbarContainer);
this.container.appendChild(this.chartingContainer);
this.chartingContainer.appendChild(this.insightContainer);
this.chartingContainer.appendChild(this.optionsControl);
this.insight = new Insight(this.insightContainer, this.options, this._instantiationService);
}
container.appendChild(this.container);
if (this._data) {
this.insight.data = this._data;
} else {
this.queryRunner = this._queryRunner;
}
this.verifyOptions();
}
public chart(dataId: { batchId: number, resultId: number }) {
this.state.dataId = dataId;
this._currentData = dataId;
this.shouldGraph();
}
layout(dimension: DOM.Dimension): void {
if (this.insight) {
this.insight.layout(new DOM.Dimension(DOM.getContentWidth(this.insightContainer), DOM.getContentHeight(this.insightContainer)));
}
}
focus(): void {
}
public set queryRunner(runner: QueryRunner) {
this._queryRunner = runner;
this.shouldGraph();
}
private shouldGraph() {
// Check if we have the necessary information
if (this._currentData && this._queryRunner) {
// check if we are being asked to graph something that is available
let batch = this._queryRunner.batchSets[this._currentData.batchId];
if (batch) {
let summary = batch.resultSetSummaries[this._currentData.resultId];
if (summary) {
this._queryRunner.getQueryRows(0, summary.rowCount, 0, 0).then(d => {
this._data = {
columns: summary.columnInfo.map(c => c.columnName),
rows: d.resultSubset.rows.map(r => r.map(c => c.displayValue))
};
if (this.insight) {
this.insight.data = this._data;
}
});
}
}
// if we have the necessary information but the information isn't available yet,
// we should be smart and retrying when the information might be available
}
}
private buildOptions() {
// The first element in the disposables list is for the chart type: the master dropdown that controls other option controls.
// whiling rebuilding the options we should not dispose it, otherwise it would react to the theme change event
if (this.optionDisposables.length > 1) { // this logic needs to be rewritten
dispose(this.optionDisposables.slice(1));
this.optionDisposables.splice(1);
}
this.optionMap = {
'type': this.optionMap['type']
};
DOM.clearNode(this.typeControls);
this.updateActionbar();
ChartOptions[this.options.type].map(o => {
this.createOption(o, this.typeControls);
});
if (this.insight) {
this.insight.options = this.options;
}
this.verifyOptions();
}
private verifyOptions() {
this.updateActionbar();
for (let key in this.optionMap) {
if (this.optionMap.hasOwnProperty(key)) {
let option = find(ChartOptions[this.options.type], e => e.configEntry === key);
if (option && option.if) {
if (option.if(this.options)) {
DOM.show(this.optionMap[key].element);
} else {
DOM.hide(this.optionMap[key].element);
}
}
}
}
}
private updateActionbar() {
if (this.insight && this.insight.isCopyable) {
this.taskbar.context = { insight: this.insight.insight, options: this.options };
this.taskbar.setContent([
{ action: this._createInsightAction },
{ action: this._copyAction },
{ action: this._saveAction }
]);
} else {
this.taskbar.setContent([{ action: this._createInsightAction }]);
}
}
private createOption(option: IChartOption, container: HTMLElement) {
let label = DOM.$('div');
label.innerText = option.label;
let optionContainer = DOM.$('div.option-container');
optionContainer.appendChild(label);
let setFunc: (val) => void;
let value = this.state ? this.state.options[option.configEntry] || option.default : option.default;
switch (option.type) {
case ControlType.checkbox:
let checkbox = new Checkbox(optionContainer, {
label: '',
ariaLabel: option.label,
checked: value,
onChange: () => {
if (this.options[option.configEntry] !== checkbox.checked) {
this.options[option.configEntry] = checkbox.checked;
if (this.insight) {
this.insight.options = this.options;
}
}
}
});
setFunc = (val: boolean) => {
checkbox.checked = val;
};
break;
case ControlType.combo:
//pass options into changeAltNames in order for SelectBox to show user-friendly names.
let dropdown = new SelectBox(option.displayableOptions || this.changeToAltNames(option.options), undefined, this._contextViewService);
dropdown.select(option.options.indexOf(value));
dropdown.render(optionContainer);
dropdown.onDidSelect(e => {
if (this.options[option.configEntry] !== option.options[e.index]) {
this.options[option.configEntry] = option.options[e.index];
if (this.insight) {
this.insight.options = this.options;
}
}
});
setFunc = (val: string) => {
if (!isUndefinedOrNull(val)) {
dropdown.select(option.options.indexOf(val));
}
};
this.optionDisposables.push(attachSelectBoxStyler(dropdown, this._themeService));
break;
case ControlType.input:
let input = new InputBox(optionContainer, this._contextViewService);
input.value = value || '';
input.onDidChange(e => {
if (this.options[option.configEntry] !== e) {
this.options[option.configEntry] = e;
if (this.insight) {
this.insight.options = this.options;
}
}
});
setFunc = (val: string) => {
if (!isUndefinedOrNull(val)) {
input.value = val;
}
};
this.optionDisposables.push(attachInputBoxStyler(input, this._themeService));
break;
case ControlType.numberInput:
let numberInput = new InputBox(optionContainer, this._contextViewService, { type: 'number' });
numberInput.value = value || '';
numberInput.onDidChange(e => {
if (this.options[option.configEntry] !== Number(e)) {
this.options[option.configEntry] = Number(e);
if (this.insight) {
this.insight.options = this.options;
}
}
});
setFunc = (val: string) => {
if (!isUndefinedOrNull(val)) {
numberInput.value = val;
}
};
this.optionDisposables.push(attachInputBoxStyler(numberInput, this._themeService));
break;
case ControlType.dateInput:
let dateInput = new InputBox(optionContainer, this._contextViewService, { type: 'datetime-local' });
dateInput.value = value || '';
dateInput.onDidChange(e => {
if (this.options[option.configEntry] !== e) {
this.options[option.configEntry] = e;
if (this.insight) {
this.insight.options = this.options;
}
}
});
setFunc = (val: string) => {
if (!isUndefinedOrNull(val)) {
dateInput.value = val;
}
};
this.optionDisposables.push(attachInputBoxStyler(dateInput, this._themeService));
break;
}
this.optionMap[option.configEntry] = { element: optionContainer, set: setFunc };
container.appendChild(optionContainer);
this.options[option.configEntry] = value;
}
public set state(val: ChartState) {
this._state = val;
if (this.state.options) {
for (let key in this.state.options) {
if (this.state.options.hasOwnProperty(key) && this.optionMap[key]) {
this.options[key] = this.state.options[key];
this.optionMap[key].set(this.state.options[key]);
}
}
}
if (this.state.dataId) {
this.chart(this.state.dataId);
}
}
public get state(): ChartState {
return this._state;
}
}

View File

@@ -0,0 +1,45 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/countInsight';
import { IInsight, IInsightData } from './interfaces';
import { $, clearNode } from 'vs/base/browser/dom';
import { InsightType } from 'sql/workbench/contrib/charts/common/interfaces';
export class CountInsight implements IInsight {
public options;
public static readonly types = [InsightType.Count];
public readonly types = CountInsight.types;
private countImage: HTMLElement;
constructor(container: HTMLElement, options: any) {
this.countImage = $('div');
container.appendChild(this.countImage);
}
public layout() { }
set data(data: IInsightData) {
clearNode(this.countImage);
for (let i = 0; i < data.columns.length; i++) {
let container = $('div.count-label-container');
let label = $('span.label-container');
label.innerText = data.columns[i];
let value = $('span.value-container');
value.innerText = data.rows[0][i];
container.appendChild(label);
container.appendChild(value);
this.countImage.appendChild(container);
}
}
dispose() {
}
}

View File

@@ -0,0 +1,441 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as chartjs from 'chart.js';
import { mixin } from 'sql/base/common/objects';
import { localize } from 'vs/nls';
import * as colors from 'vs/platform/theme/common/colorRegistry';
import { editorLineNumbers } from 'vs/editor/common/view/editorColorRegistry';
import { IThemeService, ITheme } from 'vs/platform/theme/common/themeService';
import { IInsight, IInsightData, IPointDataSet, customMixin } from './interfaces';
import { IInsightOptions, DataDirection, ChartType, LegendPosition, DataType } from 'sql/workbench/contrib/charts/common/interfaces';
import { values } from 'vs/base/common/collections';
import { find } from 'vs/base/common/arrays';
const noneLineGraphs = [ChartType.Doughnut, ChartType.Pie];
const timeSeriesScales: chartjs.ChartOptions = {
scales: {
xAxes: [{
type: 'time',
display: true,
ticks: {
autoSkip: false,
maxRotation: 45,
minRotation: 45
}
}],
yAxes: [{
display: true,
}]
}
};
const defaultOptions: IInsightOptions = {
type: ChartType.Bar,
dataDirection: DataDirection.Horizontal
};
export class Graph implements IInsight {
private _options: IInsightOptions;
private canvas: HTMLCanvasElement;
private chartjs: chartjs;
private _data: IInsightData;
private originalType: ChartType;
public static readonly types = [ChartType.Bar, ChartType.Doughnut, ChartType.HorizontalBar, ChartType.Line, ChartType.Pie, ChartType.Scatter, ChartType.TimeSeries];
public readonly types = Graph.types;
private _theme: ITheme;
constructor(
container: HTMLElement, options: IInsightOptions = defaultOptions,
@IThemeService themeService: IThemeService
) {
this._theme = themeService.getTheme();
themeService.onThemeChange(e => {
this._theme = e;
this.data = this._data;
});
this.options = mixin(options, defaultOptions, false);
let canvasContainer = document.createElement('div');
canvasContainer.style.width = '100%';
canvasContainer.style.height = '100%';
this.canvas = document.createElement('canvas');
canvasContainer.appendChild(this.canvas);
container.appendChild(canvasContainer);
}
public dispose() {
}
public layout() {
}
public getCanvasData(): string {
return this.chartjs.toBase64Image();
}
public set data(data: IInsightData) {
if (!data) {
return;
}
this._data = data;
let labels: Array<string>;
let chartData: Array<Chart.ChartDataSets>;
if (this.options.dataDirection === DataDirection.Horizontal) {
if (this.options.labelFirstColumn) {
labels = data.columns.slice(1);
} else {
labels = data.columns;
}
} else {
labels = data.rows.map(row => row[0]);
}
if (this.originalType === ChartType.TimeSeries) {
let dataSetMap: { [label: string]: IPointDataSet } = {};
this._data.rows.map(row => {
if (row && row.length >= 3) {
let legend = row[0];
if (!dataSetMap[legend]) {
dataSetMap[legend] = { label: legend, data: [], fill: false };
}
dataSetMap[legend].data.push({ x: row[1], y: Number(row[2]) });
}
});
chartData = values(dataSetMap);
} else {
if (this.options.dataDirection === DataDirection.Horizontal) {
if (this.options.labelFirstColumn) {
chartData = data.rows.map((row) => {
return {
data: row.map(item => Number(item)).slice(1),
label: row[0]
};
});
} else {
chartData = data.rows.map((row, i) => {
return {
data: row.map(item => Number(item)),
label: localize('series', "Series {0}", i)
};
});
}
} else {
if (this.options.columnsAsLabels) {
chartData = data.rows[0].slice(1).map((row, i) => {
return {
data: data.rows.map(row => Number(row[i + 1])),
label: data.columns[i + 1]
};
});
} else {
chartData = data.rows[0].slice(1).map((row, i) => {
return {
data: data.rows.map(row => Number(row[i + 1])),
label: localize('series', "Series {0}", i + 1)
};
});
}
}
}
chartData = chartData.map((c, i) => {
return mixin(c, getColors(this.options.type, i, c.data.length), false);
});
if (this.chartjs) {
this.chartjs.data.datasets = chartData;
this.chartjs.config.type = this.options.type;
// we don't want to include lables for timeSeries
this.chartjs.data.labels = this.originalType === 'timeSeries' ? [] : labels;
this.chartjs.config.options = this.transformOptions(this.options);
this.chartjs.update(0);
} else {
this.chartjs = new chartjs.Chart(this.canvas.getContext('2d'), {
data: {
// we don't want to include lables for timeSeries
labels: this.originalType === 'timeSeries' ? [] : labels,
datasets: chartData
},
type: this.options.type,
options: this.transformOptions(this.options)
});
}
}
private transformOptions(options: IInsightOptions): Chart.ChartOptions {
let retval: Chart.ChartOptions = {};
retval.maintainAspectRatio = false;
let foregroundColor = this._theme.getColor(colors.editorForeground);
let foreground = foregroundColor ? foregroundColor.toString() : null;
let gridLinesColor = this._theme.getColor(editorLineNumbers);
let gridLines = gridLinesColor ? gridLinesColor.toString() : null;
let backgroundColor = this._theme.getColor(colors.editorBackground);
let background = backgroundColor ? backgroundColor.toString() : null;
if (options) {
retval.scales = {};
// we only want to include axis if it is a axis based graph type
if (!find(noneLineGraphs, x => x === options.type as ChartType)) {
retval.scales.xAxes = [{
scaleLabel: {
fontColor: foreground,
labelString: options.xAxisLabel,
display: options.xAxisLabel ? true : false
},
ticks: {
fontColor: foreground
},
gridLines: {
color: gridLines
}
}];
if (options.xAxisMax) {
retval.scales = mixin(retval.scales, { xAxes: [{ ticks: { max: options.xAxisMax } }] }, true, customMixin);
}
if (options.xAxisMin) {
retval.scales = mixin(retval.scales, { xAxes: [{ ticks: { min: options.xAxisMin } }] }, true, customMixin);
}
retval.scales.yAxes = [{
scaleLabel: {
fontColor: foreground,
labelString: options.yAxisLabel,
display: options.yAxisLabel ? true : false
},
ticks: {
fontColor: foreground
},
gridLines: {
color: gridLines
}
}];
if (options.yAxisMax) {
retval.scales = mixin(retval.scales, { yAxes: [{ ticks: { max: options.yAxisMax } }] }, true, customMixin);
}
if (options.yAxisMin) {
retval.scales = mixin(retval.scales, { yAxes: [{ ticks: { min: options.yAxisMin } }] }, true, customMixin);
}
if (this.originalType === ChartType.TimeSeries) {
retval = mixin(retval, timeSeriesScales, true, customMixin);
if (options.xAxisMax) {
retval = mixin(retval, {
scales: {
xAxes: [{
time: {
max: options.xAxisMax
}
}],
}
}, true, customMixin);
}
if (options.xAxisMin) {
retval = mixin(retval, {
scales: {
xAxes: [{
time: {
min: options.xAxisMin
}
}],
}
}, true, customMixin);
}
}
}
retval.legend = <Chart.ChartLegendOptions>{
position: options.legendPosition as Chart.PositionType,
display: options.legendPosition !== LegendPosition.None,
labels: {
fontColor: foreground
}
};
}
// these are custom options that will throw compile errors
(<any>retval).viewArea = {
backgroundColor: background
};
return retval;
}
public set options(options: IInsightOptions) {
this._options = options;
this.originalType = options.type as ChartType;
if (this.options.type === ChartType.TimeSeries) {
this.options.type = ChartType.Line;
this.options.dataType = DataType.Point;
this.options.dataDirection = DataDirection.Horizontal;
}
this.data = this._data;
}
public get options(): IInsightOptions {
return this._options;
}
}
/**
* The Following code is pulled from ng2-charting in order to keep the same
* color functionality
*/
const defaultColors: Array<Color> = [
[255, 99, 132],
[54, 162, 235],
[255, 206, 86],
[231, 233, 237],
[75, 192, 192],
[151, 187, 205],
[220, 220, 220],
[247, 70, 74],
[70, 191, 189],
[253, 180, 92],
[148, 159, 177],
[77, 83, 96]
];
type Color = [number, number, number];
interface ILineColor {
backgroundColor: string;
borderColor: string;
pointBackgroundColor: string;
pointBorderColor: string;
pointHoverBackgroundColor: string;
pointHoverBorderColor: string;
}
interface IBarColor {
backgroundColor: string;
borderColor: string;
hoverBackgroundColor: string;
hoverBorderColor: string;
}
interface IPieColors {
backgroundColor: Array<string>;
borderColor: Array<string>;
pointBackgroundColor: Array<string>;
pointBorderColor: Array<string>;
pointHoverBackgroundColor: Array<string>;
pointHoverBorderColor: Array<string>;
}
interface IPolarAreaColors {
backgroundColor: Array<string>;
borderColor: Array<string>;
hoverBackgroundColor: Array<string>;
hoverBorderColor: Array<string>;
}
function rgba(colour: Color, alpha: number): string {
return 'rgba(' + colour.concat(alpha).join(',') + ')';
}
function getRandomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomColor(): Color {
return [getRandomInt(0, 255), getRandomInt(0, 255), getRandomInt(0, 255)];
}
/**
* Generate colors for line|bar charts
*/
function generateColor(index: number): Color {
return defaultColors[index] || getRandomColor();
}
/**
* Generate colors for pie|doughnut charts
*/
function generateColors(count: number): Array<Color> {
const colorsArr = new Array(count);
for (let i = 0; i < count; i++) {
colorsArr[i] = defaultColors[i] || getRandomColor();
}
return colorsArr;
}
function formatLineColor(colors: Color): ILineColor {
return {
backgroundColor: rgba(colors, 0.4),
borderColor: rgba(colors, 1),
pointBackgroundColor: rgba(colors, 1),
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: rgba(colors, 0.8)
};
}
function formatBarColor(colors: Color): IBarColor {
return {
backgroundColor: rgba(colors, 0.6),
borderColor: rgba(colors, 1),
hoverBackgroundColor: rgba(colors, 0.8),
hoverBorderColor: rgba(colors, 1)
};
}
function formatPieColors(colors: Array<Color>): IPieColors {
return {
backgroundColor: colors.map(color => rgba(color, 0.6)),
borderColor: colors.map(() => '#fff'),
pointBackgroundColor: colors.map(color => rgba(color, 1)),
pointBorderColor: colors.map(() => '#fff'),
pointHoverBackgroundColor: colors.map(color => rgba(color, 1)),
pointHoverBorderColor: colors.map(color => rgba(color, 1))
};
}
function formatPolarAreaColors(colors: Array<Color>): IPolarAreaColors {
return {
backgroundColor: colors.map(color => rgba(color, 0.6)),
borderColor: colors.map(color => rgba(color, 1)),
hoverBackgroundColor: colors.map(color => rgba(color, 0.8)),
hoverBorderColor: colors.map(color => rgba(color, 1))
};
}
/**
* Generate colors by chart type
*/
function getColors(chartType: string, index: number, count: number): Color | ILineColor | IBarColor | IPieColors | IPolarAreaColors {
if (chartType === 'pie' || chartType === 'doughnut') {
return formatPieColors(generateColors(count));
}
if (chartType === 'polarArea') {
return formatPolarAreaColors(generateColors(count));
}
if (chartType === 'line' || chartType === 'radar') {
return formatLineColor(generateColor(index));
}
if (chartType === 'bar' || chartType === 'horizontalBar') {
return formatBarColor(generateColor(index));
}
return generateColor(index);
}

View File

@@ -0,0 +1,79 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IInsight, IInsightData } from './interfaces';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { $ } from 'vs/base/browser/dom';
import { mixin } from 'vs/base/common/objects';
import { IInsightOptions, InsightType } from 'sql/workbench/contrib/charts/common/interfaces';
import * as nls from 'vs/nls';
import { startsWith } from 'vs/base/common/strings';
export interface IConfig extends IInsightOptions {
encoding?: string;
imageFormat?: string;
}
const defaultConfig: IConfig = {
type: InsightType.Image,
encoding: 'hex',
imageFormat: 'jpeg'
};
export class ImageInsight implements IInsight {
public static readonly types = [InsightType.Image];
public readonly types = ImageInsight.types;
private _options: IConfig;
private imageEle: HTMLImageElement;
constructor(container: HTMLElement, options: IConfig, @INotificationService private _notificationService: INotificationService) {
this._options = mixin(options, defaultConfig, false);
this.imageEle = $('img');
container.appendChild(this.imageEle);
}
public layout() {
}
public dispose() {
}
set options(config: IConfig) {
this._options = mixin(config, defaultConfig, false);
}
get options(): IConfig {
return this._options;
}
set data(data: IInsightData) {
const that = this;
if (data.rows && data.rows.length > 0 && data.rows[0].length > 0) {
let img = data.rows[0][0];
if (this._options.encoding === 'hex') {
img = ImageInsight._hexToBase64(img);
}
this.imageEle.onerror = function () {
this.src = require.toUrl(`./media/images/invalidImage.png`);
that._notificationService.error(nls.localize('invalidImage', "Table does not contain a valid image"));
};
this.imageEle.src = `data:image/${this._options.imageFormat};base64,${img}`;
}
}
private static _hexToBase64(hexVal: string) {
if (startsWith(hexVal, '0x')) {
hexVal = hexVal.slice(2);
}
// should be able to be replaced with new Buffer(hexVal, 'hex').toString('base64')
return btoa(String.fromCharCode.apply(null, hexVal.replace(/\r|\n/g, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ').map(v => Number(v))));
}
}

View File

@@ -0,0 +1,103 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Graph } from './graphInsight';
import { ImageInsight } from './imageInsight';
import { TableInsight } from './tableInsight';
import { IInsight, IInsightCtor, IInsightData } from './interfaces';
import { CountInsight } from './countInsight';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { Dimension, clearNode } from 'vs/base/browser/dom';
import { deepClone } from 'vs/base/common/objects';
import { IInsightOptions, ChartType, DataDirection, InsightType } from 'sql/workbench/contrib/charts/common/interfaces';
import { find } from 'vs/base/common/arrays';
const defaultOptions: IInsightOptions = {
type: ChartType.Bar,
dataDirection: DataDirection.Horizontal
};
export class Insight {
private _insight: IInsight;
public get insight(): IInsight {
return this._insight;
}
private _options: IInsightOptions;
private _data: IInsightData;
private dim: Dimension;
constructor(
private container: HTMLElement, options: IInsightOptions = defaultOptions,
@IInstantiationService private _instantiationService: IInstantiationService
) {
this.options = options;
this.buildInsight();
}
public layout(dim: Dimension) {
this.dim = dim;
this.insight.layout(dim);
}
public set options(val: IInsightOptions) {
this._options = deepClone(val);
if (this.insight) {
// check to see if we need to change the insight type
if (!find(this.insight.types, x => x === this.options.type)) {
this.buildInsight();
} else {
this.insight.options = this.options;
}
}
}
public get options(): IInsightOptions {
return this._options;
}
public set data(val: IInsightData) {
this._data = val;
if (this.insight) {
this.insight.data = val;
}
}
private buildInsight() {
if (this.insight) {
this.insight.dispose();
}
clearNode(this.container);
let ctor = this.findctor(this.options.type);
if (ctor) {
this._insight = this._instantiationService.createInstance(ctor, this.container, this.options);
this.insight.layout(this.dim);
if (this._data) {
this.insight.data = this._data;
}
}
}
public get isCopyable(): boolean {
return !!find(Graph.types, x => x === this.options.type as ChartType);
}
private findctor(type: ChartType | InsightType): IInsightCtor {
if (find(Graph.types, x => x === type as ChartType)) {
return Graph;
} else if (find(ImageInsight.types, x => x === type as InsightType)) {
return ImageInsight;
} else if (find(TableInsight.types, x => x === type as InsightType)) {
return TableInsight;
} else if (find(CountInsight.types, x => x === type as InsightType)) {
return CountInsight;
}
return undefined;
}
}

View File

@@ -0,0 +1,51 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Dimension } from 'vs/base/browser/dom';
import { mixin } from 'sql/base/common/objects';
import * as types from 'vs/base/common/types';
import { IInsightOptions, InsightType, ChartType } from 'sql/workbench/contrib/charts/common/interfaces';
export interface IPointDataSet {
data: Array<{ x: number | string, y: number }>;
label?: string;
fill: boolean;
backgroundColor?: string;
}
export function customMixin(destination: any, source: any, overwrite?: boolean): any {
if (types.isObject(source)) {
mixin(destination, source, overwrite, customMixin);
} else if (types.isArray(source)) {
for (let i = 0; i < source.length; i++) {
if (destination[i]) {
mixin(destination[i], source[i], overwrite, customMixin);
} else {
destination[i] = source[i];
}
}
} else {
destination = source;
}
return destination;
}
export interface IInsightData {
columns: Array<string>;
rows: Array<Array<string>>;
}
export interface IInsight {
options: IInsightOptions;
data: IInsightData;
readonly types: Array<InsightType | ChartType>;
layout(dim: Dimension);
dispose();
}
export interface IInsightCtor {
new(container: HTMLElement, options: IInsightOptions, ...services: { _serviceBrand: undefined; }[]): IInsight;
readonly types: Array<InsightType | ChartType>;
}

View File

@@ -0,0 +1,30 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.chart-parent-container {
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
}
.actionbar-container {
width: 100%;
flex: 0 0 auto;
}
.charting-container {
display: flex;
flex: 1 1 auto;
}
.insight-container {
flex: 1 1 0;
}
.options-container {
width: 250px;
padding-right: 10px;
}

View File

@@ -0,0 +1,12 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.count-label-container {
margin-left: 5px;
}
.label-container {
font-size: 20px
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

@@ -0,0 +1,72 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IInsight, IInsightData } from './interfaces';
import { TableDataView } from 'sql/base/browser/ui/table/tableDataView';
import { Table } from 'sql/base/browser/ui/table/table';
import { attachTableStyler } from 'sql/platform/theme/common/styler';
import { CellSelectionModel } from 'sql/base/browser/ui/table/plugins/cellSelectionModel.plugin';
import { $, Dimension } from 'vs/base/browser/dom';
import { Disposable } from 'vs/base/common/lifecycle';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { InsightType } from 'sql/workbench/contrib/charts/common/interfaces';
export class TableInsight extends Disposable implements IInsight {
public static readonly types = [InsightType.Table];
public readonly types = TableInsight.types;
private table: Table<any>;
private dataView: TableDataView<any>;
private columns: Slick.Column<any>[];
constructor(container: HTMLElement, options: any,
@IThemeService themeService: IThemeService
) {
super();
let tableContainer = $('div');
tableContainer.style.width = '100%';
tableContainer.style.height = '100%';
container.appendChild(tableContainer);
this.dataView = new TableDataView();
this.table = new Table(tableContainer, { dataProvider: this.dataView }, { showRowNumber: true });
this.table.setSelectionModel(new CellSelectionModel());
this._register(attachTableStyler(this.table, themeService));
}
set data(data: IInsightData) {
this.dataView.clear();
this.dataView.push(transformData(data.rows, data.columns));
this.columns = transformColumns(data.columns);
this.table.columns = this.columns;
}
layout(dim: Dimension) {
this.table.layout(dim);
}
public options;
}
function transformData(rows: string[][], columns: string[]): { [key: string]: string }[] {
return rows.map(row => {
let object: { [key: string]: string } = {};
row.forEach((val, index) => {
object[columns[index]] = val;
});
return object;
});
}
function transformColumns(columns: string[]): Slick.Column<any>[] {
return columns.map(col => {
return <Slick.Column<any>>{
name: col,
id: col,
field: col
};
});
}