More layering (#6541)

* layer unlayered code; fix layering

* readd os

* fix definition of recommended extensions

* protect against tests
This commit is contained in:
Anthony Dresser
2019-07-31 22:20:39 -07:00
committed by GitHub
parent 161c182a56
commit 9bfe8813b1
38 changed files with 77 additions and 67 deletions

View File

@@ -0,0 +1,33 @@
<!--
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
-->
<div class="fullsize vertBox editdata-component">
<div id="results" *ngIf="renderedDataSets.length > 0" class="results vertBox scrollable"
(onScroll)="onScroll($event)" [class.hidden]="!resultActive">
<div class="boxRow content horzBox slickgrid editable" *ngFor="let dataSet of renderedDataSets; let i = index"
[style.max-height]="dataSet.maxHeight" [style.min-height]="dataSet.minHeight">
<slick-grid #slickgrid id="slickgrid_{{i}}" [columnDefinitions]="dataSet.columnDefinitions"
[ngClass]="i === activeGrid ? 'active' : ''"
[dataRows]="dataSet.dataRows"
enableAsyncPostRender="true"
showDataTypeIcon="false"
showHeader="true"
[resized]="dataSet.resized"
[plugins]="plugins[i]"
(onActiveCellChanged)="onActiveCellChanged($event)"
(onCellChange)="onCellEditEnd($event)"
(onContextMenu)="openContextMenu($event, dataSet.batchId, dataSet.resultId, i)"
(onRendered)="onGridRendered($event)"
[isCellEditValid]="onIsCellEditValid"
[overrideCellFn]="overrideCellFn"
[onBeforeAppendCell]="onBeforeAppendCell"
[enableEditing]="true"
class="boxCol content vertBox slickgrid">
</slick-grid>
</div>
</div>
</div>

View File

@@ -0,0 +1,736 @@
/*---------------------------------------------------------------------------------------------
* 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/editData';
import { ElementRef, ChangeDetectorRef, OnInit, OnDestroy, Component, Inject, forwardRef, EventEmitter } from '@angular/core';
import { VirtualizedCollection } from 'angular2-slickgrid';
import { IGridDataSet } from 'sql/workbench/parts/grid/common/interfaces';
import * as Services from 'sql/base/browser/ui/table/formatters';
import { IEditDataComponentParams, IBootstrapParams } from 'sql/platform/bootstrap/common/bootstrapParams';
import { GridParentComponent } from 'sql/workbench/parts/editData/browser/gridParentComponent';
import { EditDataGridActionProvider } from 'sql/workbench/parts/editData/browser/editDataGridActions';
import { IQueryEditorService } from 'sql/workbench/services/queryEditor/common/queryEditorService';
import { RowNumberColumn } from 'sql/base/browser/ui/table/plugins/rowNumberColumn.plugin';
import { AutoColumnSize } from 'sql/base/browser/ui/table/plugins/autoSizeColumns.plugin';
import { AdditionalKeyBindings } from 'sql/base/browser/ui/table/plugins/additionalKeyBindings.plugin';
import { escape } from 'sql/base/common/strings';
import { INotificationService } from 'vs/platform/notification/common/notification';
import Severity from 'vs/base/common/severity';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { KeyCode } from 'vs/base/common/keyCodes';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { EditUpdateCellResult } from 'azdata';
import { ILogService } from 'vs/platform/log/common/log';
import { deepClone } from 'vs/base/common/objects';
export const EDITDATA_SELECTOR: string = 'editdata-component';
@Component({
selector: EDITDATA_SELECTOR,
host: { '(window:keydown)': 'keyEvent($event)', '(window:gridnav)': 'keyEvent($event)' },
templateUrl: decodeURI(require.toUrl('./editData.component.html'))
})
export class EditDataComponent extends GridParentComponent implements OnInit, OnDestroy {
// The time(in milliseconds) we wait before refreshing the grid.
// We use clearTimeout and setTimeout pair to avoid unnecessary refreshes.
private refreshGridTimeoutInMs = 200;
// The timeout handle for the refresh grid task
private refreshGridTimeoutHandle: NodeJS.Timer;
// Optimized for the edit top 200 rows scenario, only need to retrieve the data once
// to make the scroll experience smoother
private windowSize = 200;
// FIELDS
// All datasets
private dataSet: IGridDataSet;
private firstRender = true;
private totalElapsedTimeSpan: number;
private complete = false;
// Current selected cell state
private currentCell: { row: number, column: number, isEditable: boolean, isDirty: boolean };
private currentEditCellValue: string;
private newRowVisible: boolean;
private removingNewRow: boolean;
private rowIdMappings: { [gridRowId: number]: number } = {};
private dirtyCells: number[] = [];
protected plugins = new Array<Array<Slick.Plugin<any>>>();
// Edit Data functions
public onActiveCellChanged: (event: Slick.OnActiveCellChangedEventArgs<any>) => void;
public onCellEditEnd: (event: Slick.OnCellChangeEventArgs<any>) => void;
public onIsCellEditValid: (row: number, column: number, newValue: any) => boolean;
public onIsColumnEditable: (column: number) => boolean;
public overrideCellFn: (rowNumber, columnId, value?, data?) => string;
public loadDataFunction: (offset: number, count: number) => Promise<{}[]>;
public onBeforeAppendCell: (row: number, column: number) => string;
public onGridRendered: (event: Slick.OnRenderedEventArgs<any>) => void;
private savedViewState: {
gridSelections: Slick.Range[];
scrollTop;
scrollLeft;
};
constructor(
@Inject(forwardRef(() => ElementRef)) el: ElementRef,
@Inject(forwardRef(() => ChangeDetectorRef)) cd: ChangeDetectorRef,
@Inject(IBootstrapParams) params: IEditDataComponentParams,
@Inject(IInstantiationService) private instantiationService: IInstantiationService,
@Inject(INotificationService) private notificationService: INotificationService,
@Inject(IContextMenuService) contextMenuService: IContextMenuService,
@Inject(IKeybindingService) keybindingService: IKeybindingService,
@Inject(IContextKeyService) contextKeyService: IContextKeyService,
@Inject(IConfigurationService) configurationService: IConfigurationService,
@Inject(IClipboardService) clipboardService: IClipboardService,
@Inject(IQueryEditorService) queryEditorService: IQueryEditorService,
@Inject(ILogService) logService: ILogService
) {
super(el, cd, contextMenuService, keybindingService, contextKeyService, configurationService, clipboardService, queryEditorService, logService);
this._el.nativeElement.className = 'slickgridContainer';
this.dataService = params.dataService;
this.actionProvider = this.instantiationService.createInstance(EditDataGridActionProvider, this.dataService, this.onGridSelectAll(), this.onDeleteRow(), this.onRevertRow());
params.onRestoreViewState(() => this.restoreViewState());
params.onSaveViewState(() => this.saveViewState());
}
/**
* Called by Angular when the object is initialized
*/
ngOnInit(): void {
const self = this;
this.baseInit();
// Add the subscription to the list of things to be disposed on destroy, or else on a new component init
// may get the "destroyed" object still getting called back.
this.subscribeWithDispose(this.dataService.queryEventObserver, (event) => {
switch (event.type) {
case 'start':
self.handleStart(self, event);
break;
case 'complete':
self.handleComplete(self, event);
break;
case 'message':
self.handleMessage(self, event);
break;
case 'resultSet':
self.handleResultSet(self, event);
break;
case 'editSessionReady':
self.handleEditSessionReady(self, event);
break;
default:
this.logService.error('Unexpected query event type "' + event.type + '" sent');
break;
}
self._cd.detectChanges();
});
this.dataService.onAngularLoaded();
}
protected initShortcuts(shortcuts: { [name: string]: Function }): void {
// TODO add any Edit Data-specific shortcuts here
}
public ngOnDestroy(): void {
this.baseDestroy();
}
handleStart(self: EditDataComponent, event: any): void {
self.dataSet = undefined;
self.placeHolderDataSets = [];
self.renderedDataSets = self.placeHolderDataSets;
this._cd.detectChanges();
self.totalElapsedTimeSpan = undefined;
self.complete = false;
// Hooking up edit functions
this.onIsCellEditValid = (row, column, value): boolean => {
// TODO can only run sync code
return true;
};
this.onActiveCellChanged = this.onCellSelect;
this.onCellEditEnd = (event: Slick.OnCellChangeEventArgs<any>): void => {
if (self.currentEditCellValue !== event.item[event.cell]) {
self.currentCell.isDirty = true;
}
// Store the value that was set
self.currentEditCellValue = event.item[event.cell];
};
this.overrideCellFn = (rowNumber, columnId, value?, data?): string => {
let returnVal = '';
// replace the line breaks with space since the edit text control cannot
// render line breaks and strips them, updating the value.
if (Services.DBCellValue.isDBCellValue(value)) {
returnVal = this.spacefyLinebreaks(value.displayValue);
} else if (typeof value === 'string') {
returnVal = this.spacefyLinebreaks(value);
}
return returnVal;
};
// This is the event slickgrid will raise in order to get the additional cell CSS classes for the cell
// Due to performance advantage we are using this event instead of the onViewportChanged event.
this.onBeforeAppendCell = (row: number, column: number): string => {
let cellClass = undefined;
if (this.isRowDirty(row) && column === 0) {
cellClass = ' dirtyRowHeader ';
} else if (this.isCellDirty(row, column)) {
cellClass = ' dirtyCell ';
}
return cellClass;
};
this.onGridRendered = (args: Slick.OnRenderedEventArgs<any>): void => {
// After rendering move the focus back to the previous active cell
if (this.currentCell.column !== undefined && this.currentCell.row !== undefined
&& this.isCellOnScreen(this.currentCell.row, this.currentCell.column)) {
this.focusCell(this.currentCell.row, this.currentCell.column, false);
}
};
// Setup a function for generating a promise to lookup result subsets
this.loadDataFunction = (offset: number, count: number): Promise<{}[]> => {
return new Promise<{}[]>((resolve, reject) => {
self.dataService.getEditRows(offset, count).subscribe(result => {
let gridData = result.subset.map(r => {
let dataWithSchema = {};
// skip the first column since its a number column
for (let i = 1; i < this.dataSet.columnDefinitions.length; i++) {
dataWithSchema[this.dataSet.columnDefinitions[i].field] = {
displayValue: r.cells[i - 1].displayValue,
ariaLabel: escape(r.cells[i - 1].displayValue),
isNull: r.cells[i - 1].isNull
};
}
return dataWithSchema;
});
// should add null row?
if (offset + count > this.dataSet.totalRows - 1) {
gridData.push(this.dataSet.columnDefinitions.reduce((p, c) => {
p[c.field] = 'NULL';
return p;
}, {}));
}
resolve(gridData);
});
});
};
}
onDeleteRow(): (index: number) => void {
const self = this;
return (index: number): void => {
// If the user is deleting a new row that hasn't been committed yet then use the revert code
if (self.newRowVisible && index === self.dataSet.dataRows.getLength() - 2) {
self.revertCurrentRow();
}
else if (self.isNullRow(index)) {
// Don't try to delete NULL (new) row since it doesn't actually exist and will throw an error
// TODO #478 : We should really just stop the context menu from showing up for this row, but that's a bit more involved
// so until then at least make it not display an error
return;
}
else {
self.dataService.deleteRow(index)
.then(() => self.dataService.commitEdit())
.then(() => self.removeRow(index));
}
};
}
onRevertRow(): () => void {
const self = this;
return (): void => {
self.revertCurrentRow();
};
}
onCellSelect(event: Slick.OnActiveCellChangedEventArgs<any>): void {
let self = this;
let row = event.row;
let column = event.cell;
// Skip processing if the newly selected cell is undefined or we don't have column
// definition for the column (ie, the selection was reset)
if (row === undefined || column === undefined) {
return;
}
// Skip processing if the cell hasn't moved (eg, we reset focus to the previous cell after a failed update)
if (this.currentCell.row === row && this.currentCell.column === column && this.currentCell.isDirty === false) {
return;
}
let cellSelectTasks: Promise<void> = this.submitCurrentCellChange(
(result: EditUpdateCellResult) => {
// Cell update was successful, update the flags
self.setCellDirtyState(self.currentCell.row, self.currentCell.column, result.cell.isDirty);
self.setRowDirtyState(self.currentCell.row, result.isRowDirty);
return Promise.resolve();
},
(error) => {
// Cell update failed, jump back to the last cell we were on
self.focusCell(self.currentCell.row, self.currentCell.column, true);
return Promise.reject(null);
});
if (this.currentCell.row !== row) {
// We're changing row, commit the changes
cellSelectTasks = cellSelectTasks.then(() => {
return self.dataService.commitEdit().then(result => {
// Committing was successful, clean the grid
self.setGridClean();
self.rowIdMappings = {};
self.newRowVisible = false;
return Promise.resolve();
}, error => {
// Committing failed, jump back to the last selected cell
self.focusCell(self.currentCell.row, self.currentCell.column);
return Promise.reject(null);
});
});
}
// At the end of a successful cell select, update the currently selected cell
cellSelectTasks = cellSelectTasks.then(() => {
self.setCurrentCell(row, column);
});
// Cap off any failed promises, since they'll be handled
cellSelectTasks.catch(() => { });
}
handleComplete(self: EditDataComponent, event: any): void {
self.totalElapsedTimeSpan = event.data;
self.complete = true;
}
handleEditSessionReady(self, event): void {
// TODO: update when edit session is ready
}
handleMessage(self: EditDataComponent, event: any): void {
if (event.data && event.data.isError) {
self.notificationService.notify({
severity: Severity.Error,
message: event.data.message
});
}
}
handleResultSet(self: EditDataComponent, event: any): void {
// Clone the data before altering it to avoid impacting other subscribers
let resultSet = Object.assign({}, event.data);
if (!resultSet.complete) {
return;
}
// Add an extra 'new row'
resultSet.rowCount++;
// Precalculate the max height and min height
let maxHeight = this.getMaxHeight(resultSet.rowCount);
let minHeight = this.getMinHeight(resultSet.rowCount);
let rowNumberColumn = new RowNumberColumn({ numberOfRows: resultSet.rowCount });
// Store the result set from the event
let dataSet: IGridDataSet = {
resized: undefined,
batchId: resultSet.batchId,
resultId: resultSet.id,
totalRows: resultSet.rowCount,
maxHeight: maxHeight,
minHeight: minHeight,
dataRows: new VirtualizedCollection(
self.windowSize,
resultSet.rowCount,
this.loadDataFunction,
index => { return {}; }
),
columnDefinitions: [rowNumberColumn.getColumnDefinition()].concat(resultSet.columnInfo.map((c, i) => {
let columnIndex = (i + 1).toString();
return {
id: columnIndex,
name: escape(c.columnName),
field: columnIndex,
formatter: Services.textFormatter,
isEditable: c.isUpdatable
};
}))
};
self.plugins.push([rowNumberColumn, new AutoColumnSize({ maxWidth: this.configurationService.getValue<number>('resultsGrid.maxColumnWidth') }), new AdditionalKeyBindings()]);
self.dataSet = dataSet;
// Create a dataSet to render without rows to reduce DOM size
let undefinedDataSet = deepClone(dataSet);
undefinedDataSet.columnDefinitions = dataSet.columnDefinitions;
undefinedDataSet.dataRows = undefined;
undefinedDataSet.resized = new EventEmitter();
self.placeHolderDataSets.push(undefinedDataSet);
self.refreshGrid();
// Setup the state of the selected cell
this.resetCurrentCell();
this.currentEditCellValue = undefined;
this.removingNewRow = false;
this.newRowVisible = false;
this.dirtyCells = [];
}
/**
* Handles rendering the results to the DOM that are currently being shown
* and destroying any results that have moved out of view
* @param scrollTop The scrolltop value, if not called by the scroll event should be 0
*/
onScroll(scrollTop): void {
this.refreshGrid();
}
/**
* Replace the line breaks with space.
*/
private spacefyLinebreaks(inputStr: string): string {
return inputStr.replace(/(\r\n|\n|\r)/g, ' ');
}
private refreshGrid(): Thenable<void> {
return new Promise<void>((resolve, reject) => {
const self = this;
clearTimeout(self.refreshGridTimeoutHandle);
this.refreshGridTimeoutHandle = setTimeout(() => {
for (let i = 0; i < self.placeHolderDataSets.length; i++) {
self.placeHolderDataSets[i].dataRows = self.dataSet.dataRows;
self.placeHolderDataSets[i].resized.emit();
}
self._cd.detectChanges();
if (self.firstRender) {
let setActive = function () {
if (self.firstRender && self.slickgrids.toArray().length > 0) {
self.slickgrids.toArray()[0].setActive();
self.firstRender = false;
}
};
setTimeout(() => {
setActive();
});
}
resolve();
}, self.refreshGridTimeoutInMs);
});
}
protected tryHandleKeyEvent(e: StandardKeyboardEvent): boolean {
let handled: boolean = false;
// If the esc key was pressed while in a create session
let currentNewRowIndex = this.dataSet.totalRows - 2;
if (e.keyCode === KeyCode.Escape) {
this.revertCurrentRow();
handled = true;
}
return handled;
}
// Private Helper Functions ////////////////////////////////////////////////////////////////////////////
private async revertCurrentRow(): Promise<void> {
let currentNewRowIndex = this.dataSet.totalRows - 2;
if (this.newRowVisible && this.currentCell.row === currentNewRowIndex) {
// revert our last new row
this.removingNewRow = true;
this.dataService.revertRow(this.rowIdMappings[currentNewRowIndex])
.then(() => {
return this.removeRow(currentNewRowIndex);
}).then(() => {
this.newRowVisible = false;
this.resetCurrentCell();
});
} else {
try {
// Perform a revert row operation
if (this.currentCell && this.currentCell.row !== undefined) {
await this.dataService.revertRow(this.currentCell.row);
}
} finally {
// The operation may fail if there were no changes sent to the service to revert,
// so clear any existing client-side edit and refresh on-screen data
// do not refresh the whole dataset as it will move the focus away to the first row.
//
this.currentEditCellValue = undefined;
this.dirtyCells = [];
let row = this.currentCell.row;
this.resetCurrentCell();
if (row !== undefined) {
this.dataSet.dataRows.resetWindowsAroundIndex(row);
}
}
}
}
private submitCurrentCellChange(resultHandler, errorHandler): Promise<void> {
let self = this;
let updateCellPromise: Promise<void> = Promise.resolve();
let refreshGrid = false;
if (this.currentCell && this.currentCell.isEditable && this.currentEditCellValue !== undefined && !this.removingNewRow) {
if (this.isNullRow(this.currentCell.row)) {
refreshGrid = true;
// We've entered the "new row", so we need to add a row and jump to it
updateCellPromise = updateCellPromise.then(() => {
return self.addRow(this.currentCell.row);
});
}
// We're exiting a read/write cell after having changed the value, update the cell value in the service
updateCellPromise = updateCellPromise.then(() => {
// Use the mapped row ID if we're on that row
let sessionRowId = self.rowIdMappings[self.currentCell.row] !== undefined
? self.rowIdMappings[self.currentCell.row]
: self.currentCell.row;
return self.dataService.updateCell(sessionRowId, self.currentCell.column - 1, self.currentEditCellValue);
}).then(
result => {
self.currentEditCellValue = undefined;
let refreshPromise: Thenable<void> = Promise.resolve();
if (refreshGrid) {
refreshPromise = self.refreshGrid();
}
return refreshPromise.then(() => {
return resultHandler(result);
});
},
error => {
return errorHandler(error);
}
);
}
return updateCellPromise;
}
// Checks if input row is our NULL new row
private isNullRow(row: number): boolean {
// Null row is always at index (totalRows - 1)
return (row === this.dataSet.totalRows - 1);
}
// Adds CSS classes to slickgrid cells to indicate a dirty state
private setCellDirtyState(row: number, column: number, dirtyState: boolean): void {
let slick: any = this.slickgrids.toArray()[0];
let grid = slick._grid;
if (dirtyState) {
// Change cell color
jQuery(grid.getCellNode(row, column)).addClass('dirtyCell').removeClass('selected');
if (this.dirtyCells.indexOf(column) === -1) {
this.dirtyCells.push(column);
}
} else {
jQuery(grid.getCellNode(row, column)).removeClass('dirtyCell');
if (this.dirtyCells.indexOf(column) !== -1) {
this.dirtyCells.splice(this.dirtyCells.indexOf(column), 1);
}
}
}
// Adds CSS classes to slickgrid rows to indicate a dirty state
private setRowDirtyState(row: number, dirtyState: boolean): void {
let slick: any = this.slickgrids.toArray()[0];
let grid = slick._grid;
if (dirtyState) {
// Change row header color
jQuery(grid.getCellNode(row, 0)).addClass('dirtyRowHeader');
} else {
jQuery(grid.getCellNode(row, 0)).removeClass('dirtyRowHeader');
}
}
// Sets CSS to clean the entire grid of dirty state cells and rows
private setGridClean(): void {
// Remove dirty classes from the entire table
let allRows = jQuery(jQuery('.grid-canvas').children());
let allCells = jQuery(allRows.children());
allCells.removeClass('dirtyCell').removeClass('dirtyRowHeader');
this.dirtyCells = [];
}
// Adds an extra row to the end of slickgrid (just for rendering purposes)
// Then sets the focused call afterwards
private addRow(row: number): Thenable<void> {
let self = this;
// Add a new row to the edit session in the tools service
return this.dataService.createRow()
.then(result => {
// Map the new row ID to the row ID we have
self.rowIdMappings[row] = result.newRowId;
self.newRowVisible = true;
// Add a new "new row" to the end of the results
// Adding an extra row for 'new row' functionality
self.dataSet.totalRows++;
self.dataSet.maxHeight = self.getMaxHeight(self.dataSet.totalRows);
self.dataSet.minHeight = self.getMinHeight(self.dataSet.totalRows);
self.dataSet.dataRows = new VirtualizedCollection(
self.windowSize,
self.dataSet.totalRows,
self.loadDataFunction,
index => { return {}; }
);
});
}
// removes a row from the end of slickgrid (just for rendering purposes)
// Then sets the focused call afterwards
private removeRow(row: number): Thenable<void> {
// Removing the new row
this.dataSet.totalRows--;
this.dataSet.dataRows = new VirtualizedCollection(
this.windowSize,
this.dataSet.totalRows,
this.loadDataFunction,
index => { return {}; }
);
// refresh results view
return this.refreshGrid().then(() => {
// Set focus to the row index column of the removed row if the current selection is in the removed row
if (this.currentCell.row === row && !this.removingNewRow) {
this.focusCell(row, 1);
}
this.removingNewRow = false;
});
}
private focusCell(row: number, column: number, forceEdit: boolean = true): void {
let slick: any = this.slickgrids.toArray()[0];
let grid = slick._grid;
grid.gotoCell(row, column, forceEdit);
}
private getMaxHeight(rowCount: number): any {
return rowCount < this._defaultNumShowingRows
? ((rowCount + 1) * this._rowHeight) + 10
: 'inherit';
}
private getMinHeight(rowCount: number): any {
return rowCount > this._defaultNumShowingRows
? (this._defaultNumShowingRows + 1) * this._rowHeight + 10
: this.getMaxHeight(rowCount);
}
private saveViewState(): void {
let grid = this.slickgrids.toArray()[0];
let self = this;
if (grid) {
let gridSelections = grid.getSelectedRanges();
let gridObject = grid as any;
let viewport = (gridObject._grid.getCanvasNode() as HTMLElement).parentElement;
this.savedViewState = {
gridSelections,
scrollTop: viewport.scrollTop,
scrollLeft: viewport.scrollLeft
};
// Save the cell that is currently being edited.
// Note: This is only updating the data in tools service, not saving the change to database.
// This is added to fix the data inconsistency: the updated value is displayed but won't be saved to the database
// when committing the changes for the row.
if (this.currentCell.row !== undefined && this.currentCell.column !== undefined && this.currentCell.isEditable) {
gridObject._grid.getEditorLock().commitCurrentEdit();
this.submitCurrentCellChange((result: EditUpdateCellResult) => {
self.setCellDirtyState(self.currentCell.row, self.currentCell.column, result.cell.isDirty);
}, (error: any) => {
self.notificationService.error(error);
});
}
}
}
private restoreViewState(): void {
if (this.savedViewState) {
this.slickgrids.toArray()[0].selection = this.savedViewState.gridSelections;
let viewport = ((this.slickgrids.toArray()[0] as any)._grid.getCanvasNode() as HTMLElement).parentElement;
viewport.scrollLeft = this.savedViewState.scrollLeft;
viewport.scrollTop = this.savedViewState.scrollTop;
this.savedViewState = undefined;
// This block of code is responsible for restoring the dirty state indicators if slickgrid decides not to re-render the dirty row
// Other scenarios will be taken care of by getAdditionalCssClassesForCell method when slickgrid needs to re-render the rows.
if (this.currentCell.row !== undefined) {
if (this.isRowDirty(this.currentCell.row)) {
this.setRowDirtyState(this.currentCell.row, true);
this.dirtyCells.forEach(cell => {
this.setCellDirtyState(this.currentCell.row, cell, true);
});
}
}
}
}
private isRowDirty(row: number): boolean {
return this.currentCell.row === row && this.dirtyCells.length > 0;
}
private isCellDirty(row: number, column: number): boolean {
return this.currentCell.row === row && this.dirtyCells.indexOf(column) !== -1;
}
private isCellOnScreen(row: number, column: number): boolean {
let slick: any = this.slickgrids.toArray()[0];
let grid = slick._grid;
let viewport = grid.getViewport();
let cellBox = grid.getCellNodeBox(row, column);
return viewport && cellBox
&& viewport.leftPx <= cellBox.left && viewport.rightPx >= cellBox.right
&& viewport.top <= row && viewport.bottom >= row;
}
private resetCurrentCell() {
this.currentCell = {
row: undefined,
column: undefined,
isEditable: false,
isDirty: false
};
}
private setCurrentCell(row: number, column: number) {
// Only update if we're actually changing cells
if (this.currentCell && (row !== this.currentCell.row || column !== this.currentCell.column)) {
this.currentCell = {
row: row,
column: column,
isEditable: this.dataSet.columnDefinitions[column]
? this.dataSet.columnDefinitions[column].isEditable
: false,
isDirty: false
};
}
}
}

View File

@@ -0,0 +1,57 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ApplicationRef, ComponentFactoryResolver, NgModule, Inject, forwardRef, Type } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { SlickGrid } from 'angular2-slickgrid';
import { EditDataComponent } from 'sql/workbench/parts/editData/browser/editData.component';
import { providerIterator } from 'sql/platform/bootstrap/browser/bootstrapService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IBootstrapParams, ISelector } from 'sql/platform/bootstrap/common/bootstrapParams';
export const EditDataModule = (params: IBootstrapParams, selector: string, instantiationService: IInstantiationService): Type<any> => {
@NgModule({
imports: [
CommonModule,
BrowserModule
],
declarations: [
EditDataComponent,
SlickGrid
],
entryComponents: [
EditDataComponent
],
providers: [
{ provide: IBootstrapParams, useValue: params },
{ provide: ISelector, useValue: selector },
...providerIterator(instantiationService)
]
})
class ModuleClass {
constructor(
@Inject(forwardRef(() => ComponentFactoryResolver)) private _resolver: ComponentFactoryResolver,
@Inject(ISelector) private selector: string
) {
}
ngDoBootstrap(appRef: ApplicationRef) {
const factory = this._resolver.resolveComponentFactory(EditDataComponent);
(<any>factory).factory.selector = this.selector;
appRef.bootstrap(factory);
}
}
return ModuleClass;
};

View File

@@ -0,0 +1,68 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IGridInfo } from 'sql/workbench/parts/grid/common/interfaces';
import { DataService } from 'sql/workbench/parts/grid/common/dataService';
import { GridActionProvider } from 'sql/workbench/parts/editData/common/gridActions';
import { localize } from 'vs/nls';
import { IAction, Action } from 'vs/base/common/actions';
export class EditDataGridActionProvider extends GridActionProvider {
constructor(
dataService: DataService,
selectAllCallback: (index: number) => void,
private _deleteRowCallback: (index: number) => void,
private _revertRowCallback: () => void
) {
super(dataService, selectAllCallback);
}
/**
* Return actions given a click on an edit data grid
*/
public getGridActions(): IAction[] {
let actions: IAction[] = [];
actions.push(new DeleteRowAction(DeleteRowAction.ID, DeleteRowAction.LABEL, this._deleteRowCallback));
actions.push(new RevertRowAction(RevertRowAction.ID, RevertRowAction.LABEL, this._revertRowCallback));
return actions;
}
}
export class DeleteRowAction extends Action {
public static ID = 'grid.deleteRow';
public static LABEL = localize('deleteRow', "Delete Row");
constructor(
id: string,
label: string,
private callback: (index: number) => void
) {
super(id, label);
}
public run(gridInfo: IGridInfo): Promise<boolean> {
this.callback(gridInfo.rowIndex);
return Promise.resolve(true);
}
}
export class RevertRowAction extends Action {
public static ID = 'grid.revertRow';
public static LABEL = localize('revertRow', "Revert Current Row");
constructor(
id: string,
label: string,
private callback: () => void
) {
super(id, label);
}
public run(gridInfo: IGridInfo): Promise<boolean> {
this.callback();
return Promise.resolve(true);
}
}

View File

@@ -18,8 +18,8 @@ import { IQueryModelService } from 'sql/platform/query/common/queryModel';
import { bootstrapAngular } from 'sql/platform/bootstrap/browser/bootstrapService';
import { BareResultsGridInfo } from 'sql/workbench/parts/query/browser/queryResultsEditor';
import { IEditDataComponentParams } from 'sql/platform/bootstrap/common/bootstrapParams';
import { EditDataModule } from 'sql/workbench/parts/grid/views/editData/editData.module';
import { EDITDATA_SELECTOR } from 'sql/workbench/parts/grid/views/editData/editData.component';
import { EditDataModule } from 'sql/workbench/parts/editData/browser/editData.module';
import { EDITDATA_SELECTOR } from 'sql/workbench/parts/editData/browser/editData.component';
import { EditDataResultsInput } from 'sql/workbench/parts/editData/common/editDataResultsInput';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IStorageService } from 'vs/platform/storage/common/storage';

View File

@@ -0,0 +1,92 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as GridContentEvents from 'sql/workbench/parts/grid/common/gridContentEvents';
import { IQueryModelService } from 'sql/platform/query/common/queryModel';
import { QueryEditor } from 'sql/workbench/parts/query/browser/queryEditor';
import { EditDataEditor } from 'sql/workbench/parts/editData/browser/editDataEditor';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
function runActionOnActiveResultsEditor(accessor: ServicesAccessor, eventName: string): void {
let editorService = accessor.get(IEditorService);
const candidates = [editorService.activeControl, ...editorService.visibleControls].filter(e => {
if (e) {
let id = e.getId();
if (id === QueryEditor.ID || id === EditDataEditor.ID) {
// This is a query or edit data editor
return true;
}
}
return false;
});
if (candidates.length > 0) {
let queryModelService: IQueryModelService = accessor.get(IQueryModelService);
let uri = (<any>candidates[0].input).uri;
queryModelService.sendGridContentEvent(uri, eventName);
}
}
export const copySelection = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.CopySelection);
};
export const copyMessagesSelection = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.CopyMessagesSelection);
};
export const copyWithHeaders = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.CopyWithHeaders);
};
export const toggleMessagePane = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.ToggleMessagePane);
};
export const toggleResultsPane = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.ToggleResultPane);
};
export const goToNextQueryOutputTab = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.GoToNextQueryOutputTab);
};
export const saveAsCsv = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.SaveAsCsv);
};
export const saveAsJson = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.SaveAsJSON);
};
export const saveAsExcel = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.SaveAsExcel);
};
export const saveAsXml = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.SaveAsXML);
};
export const selectAll = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.SelectAll);
};
export const selectAllMessages = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.SelectAllMessages);
};
export const viewAsChart = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.ViewAsChart);
};
export const viewAsVisualizer = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.ViewAsVisualizer);
};
export const goToNextGrid = (accessor: ServicesAccessor) => {
runActionOnActiveResultsEditor(accessor, GridContentEvents.GoToNextGrid);
};

View File

@@ -0,0 +1,521 @@
/*---------------------------------------------------------------------------------------------
* 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/flexbox';
import 'vs/css!./media/styles';
import { Subscription, Subject } from 'rxjs/Rx';
import { ElementRef, QueryList, ChangeDetectorRef, ViewChildren } from '@angular/core';
import { SlickGrid } from 'angular2-slickgrid';
import * as Constants from 'sql/workbench/parts/query/common/constants';
import * as LocalizedConstants from 'sql/workbench/parts/query/common/localizedConstants';
import { IGridInfo, IGridDataSet, SaveFormat } from 'sql/workbench/parts/grid/common/interfaces';
import * as Utils from 'sql/platform/connection/common/utils';
import { DataService } from 'sql/workbench/parts/grid/common/dataService';
import * as actions from 'sql/workbench/parts/editData/common/gridActions';
import * as GridContentEvents from 'sql/workbench/parts/grid/common/gridContentEvents';
import { ResultsVisibleContext, ResultsGridFocussedContext, ResultsMessagesFocussedContext, QueryEditorVisibleContext } from 'sql/workbench/parts/query/common/queryContext';
import { IQueryEditorService } from 'sql/workbench/services/queryEditor/common/queryEditorService';
import { CellSelectionModel } from 'sql/base/browser/ui/table/plugins/cellSelectionModel.plugin';
import { IAction } from 'vs/base/common/actions';
import { ResolvedKeybinding } from 'vs/base/common/keyCodes';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { ILogService } from 'vs/platform/log/common/log';
import { subscriptionToDisposable } from 'sql/base/browser/lifecycle';
export abstract class GridParentComponent {
// CONSTANTS
// tslint:disable:no-unused-variable
protected get selectionModel() { return new CellSelectionModel(); }
protected _rowHeight = 29;
protected _defaultNumShowingRows = 8;
protected Constants = Constants;
protected LocalizedConstants = LocalizedConstants;
protected Utils = Utils;
// tslint:disable-next-line:no-unused-variable
protected startString = new Date().toLocaleTimeString();
protected shortcutfunc: { [name: string]: Function };
// tslint:enable
// FIELDS
// Service for interaction with the IQueryModel
protected dataService: DataService;
protected actionProvider: actions.GridActionProvider;
protected toDispose: IDisposable[];
// Context keys to set when keybindings are available
private resultsVisibleContextKey: IContextKey<boolean>;
private gridFocussedContextKey: IContextKey<boolean>;
private messagesFocussedContextKey: IContextKey<boolean>;
private queryEditorVisible: IContextKey<boolean>;
// All datasets
// Place holder data sets to buffer between data sets and rendered data sets
protected placeHolderDataSets: IGridDataSet[] = [];
// Datasets currently being rendered on the DOM
protected renderedDataSets: IGridDataSet[] = this.placeHolderDataSets;
protected resultActive = true;
protected _messageActive = true;
protected activeGrid = 0;
@ViewChildren('slickgrid') slickgrids: QueryList<SlickGrid>;
set messageActive(input: boolean) {
this._messageActive = input;
if (this.resultActive) {
this.resizeGrids();
}
this._cd.detectChanges();
}
get messageActive(): boolean {
return this._messageActive;
}
constructor(
protected _el: ElementRef,
protected _cd: ChangeDetectorRef,
protected contextMenuService: IContextMenuService,
protected keybindingService: IKeybindingService,
protected contextKeyService: IContextKeyService,
protected configurationService: IConfigurationService,
protected clipboardService: IClipboardService,
protected queryEditorService: IQueryEditorService,
protected logService: ILogService
) {
this.toDispose = [];
}
protected baseInit(): void {
const self = this;
this.initShortcutsBase();
if (this.configurationService) {
let sqlConfig = this.configurationService.getValue('sql');
if (sqlConfig) {
this._messageActive = sqlConfig['messagesDefaultOpen'];
}
}
this.subscribeWithDispose(this.dataService.gridContentObserver, (type) => {
switch (type) {
case GridContentEvents.RefreshContents:
self.refreshResultsets();
break;
case GridContentEvents.ResizeContents:
self.resizeGrids();
break;
case GridContentEvents.CopySelection:
self.copySelection();
break;
case GridContentEvents.CopyWithHeaders:
self.copyWithHeaders();
break;
case GridContentEvents.CopyMessagesSelection:
self.copyMessagesSelection();
break;
case GridContentEvents.ToggleResultPane:
self.toggleResultPane();
break;
case GridContentEvents.ToggleMessagePane:
self.toggleMessagePane();
break;
case GridContentEvents.SelectAll:
self.onSelectAllForActiveGrid();
break;
case GridContentEvents.SelectAllMessages:
self.selectAllMessages();
break;
case GridContentEvents.SaveAsCsv:
self.sendSaveRequest(SaveFormat.CSV);
break;
case GridContentEvents.SaveAsJSON:
self.sendSaveRequest(SaveFormat.JSON);
break;
case GridContentEvents.SaveAsExcel:
self.sendSaveRequest(SaveFormat.EXCEL);
break;
case GridContentEvents.SaveAsXML:
self.sendSaveRequest(SaveFormat.XML);
break;
case GridContentEvents.GoToNextQueryOutputTab:
self.goToNextQueryOutputTab();
break;
case GridContentEvents.ViewAsChart:
self.showChartForGrid(self.activeGrid);
break;
case GridContentEvents.ViewAsVisualizer:
self.showVisualizerForGrid(self.activeGrid);
break;
case GridContentEvents.GoToNextGrid:
self.goToNextGrid();
break;
default:
this.logService.error('Unexpected grid content event type "' + type + '" sent');
break;
}
});
this.bindKeys(this.contextKeyService);
}
/*
* Add the subscription to the list of things to be disposed on destroy, or else on a new component init
* may get the "destroyed" object still getting called back.
*/
protected subscribeWithDispose<T>(subject: Subject<T>, event: (value: any) => void): void {
let sub: Subscription = subject.subscribe(event);
this.toDispose.push(subscriptionToDisposable(sub));
}
private bindKeys(contextKeyService: IContextKeyService): void {
if (contextKeyService) {
this.queryEditorVisible = QueryEditorVisibleContext.bindTo(contextKeyService);
this.queryEditorVisible.set(true);
let gridContextKeyService = this.contextKeyService.createScoped(this._el.nativeElement);
this.toDispose.push(gridContextKeyService);
this.resultsVisibleContextKey = ResultsVisibleContext.bindTo(gridContextKeyService);
this.resultsVisibleContextKey.set(true);
this.gridFocussedContextKey = ResultsGridFocussedContext.bindTo(gridContextKeyService);
this.messagesFocussedContextKey = ResultsMessagesFocussedContext.bindTo(gridContextKeyService);
}
}
protected baseDestroy(): void {
this.toDispose = dispose(this.toDispose);
}
protected toggleResultPane(): void {
this.resultActive = !this.resultActive;
if (this.resultActive) {
this.resizeGrids();
}
this._cd.detectChanges();
}
protected toggleMessagePane(): void {
this.messageActive = !this.messageActive;
}
protected onGridFocus() {
this.gridFocussedContextKey.set(true);
}
protected onGridFocusout() {
this.gridFocussedContextKey.set(false);
}
protected onMessagesFocus() {
this.messagesFocussedContextKey.set(true);
}
protected onMessagesFocusout() {
this.messagesFocussedContextKey.set(false);
}
protected getSelection(index?: number): Slick.Range[] {
let selection = this.slickgrids.toArray()[index || this.activeGrid].getSelectedRanges();
if (selection) {
selection = selection.map(c => { return <Slick.Range>{ fromCell: c.fromCell - 1, toCell: c.toCell - 1, toRow: c.toRow, fromRow: c.fromRow }; });
return selection;
} else {
return undefined;
}
}
private copySelection(): void {
let messageText = this.getMessageText();
if (messageText.length > 0) {
this.clipboardService.writeText(messageText);
} else {
let activeGrid = this.activeGrid;
this.dataService.copyResults(this.getSelection(activeGrid), this.renderedDataSets[activeGrid].batchId, this.renderedDataSets[activeGrid].resultId);
}
}
private copyWithHeaders(): void {
let activeGrid = this.activeGrid;
this.dataService.copyResults(this.getSelection(activeGrid), this.renderedDataSets[activeGrid].batchId,
this.renderedDataSets[activeGrid].resultId, true);
}
private copyMessagesSelection(): void {
let messageText = this.getMessageText();
if (messageText.length === 0) {
// Since we know we're specifically copying messages, do a select all if nothing is selected
this.selectAllMessages();
messageText = this.getMessageText();
}
if (messageText.length > 0) {
this.clipboardService.writeText(messageText);
}
}
private getMessageText(): string {
if (document.activeElement === this.getMessagesElement()) {
if (window.getSelection()) {
return window.getSelection().toString();
}
}
return '';
}
protected goToNextQueryOutputTab(): void {
}
protected showChartForGrid(index: number) {
}
protected showVisualizerForGrid(index: number) {
}
protected goToNextGrid() {
if (this.renderedDataSets.length > 0) {
let next = this.activeGrid + 1;
if (next >= this.renderedDataSets.length) {
next = 0;
}
this.navigateToGrid(next);
}
}
protected navigateToGrid(index: number) {
}
private initShortcutsBase(): void {
let shortcuts = {
'ToggleResultPane': () => {
this.toggleResultPane();
},
'ToggleMessagePane': () => {
this.toggleMessagePane();
},
'CopySelection': () => {
this.copySelection();
},
'CopyWithHeaders': () => {
this.copyWithHeaders();
},
'SelectAll': () => {
this.onSelectAllForActiveGrid();
},
'SaveAsCSV': () => {
this.sendSaveRequest(SaveFormat.CSV);
},
'SaveAsJSON': () => {
this.sendSaveRequest(SaveFormat.JSON);
},
'SaveAsExcel': () => {
this.sendSaveRequest(SaveFormat.EXCEL);
},
'SaveAsXML': () => {
this.sendSaveRequest(SaveFormat.XML);
},
'GoToNextQueryOutputTab': () => {
this.goToNextQueryOutputTab();
}
};
this.initShortcuts(shortcuts);
this.shortcutfunc = shortcuts;
}
protected abstract initShortcuts(shortcuts: { [name: string]: Function }): void;
/**
* Send save result set request to service
*/
handleContextClick(event: { type: string, batchId: number, resultId: number, index: number, selection: Slick.Range[] }): void {
switch (event.type) {
case 'savecsv':
this.dataService.sendSaveRequest({ batchIndex: event.batchId, resultSetNumber: event.resultId, format: SaveFormat.CSV, selection: event.selection });
break;
case 'savejson':
this.dataService.sendSaveRequest({ batchIndex: event.batchId, resultSetNumber: event.resultId, format: SaveFormat.JSON, selection: event.selection });
break;
case 'saveexcel':
this.dataService.sendSaveRequest({ batchIndex: event.batchId, resultSetNumber: event.resultId, format: SaveFormat.EXCEL, selection: event.selection });
break;
case 'savexml':
this.dataService.sendSaveRequest({ batchIndex: event.batchId, resultSetNumber: event.resultId, format: SaveFormat.XML, selection: event.selection });
break;
case 'selectall':
this.activeGrid = event.index;
this.onSelectAllForActiveGrid();
break;
case 'copySelection':
this.dataService.copyResults(event.selection, event.batchId, event.resultId);
break;
case 'copyWithHeaders':
this.dataService.copyResults(event.selection, event.batchId, event.resultId, true);
break;
default:
break;
}
}
private sendSaveRequest(format: SaveFormat) {
let activeGrid = this.activeGrid;
let batchId = this.renderedDataSets[activeGrid].batchId;
let resultId = this.renderedDataSets[activeGrid].resultId;
this.dataService.sendSaveRequest({ batchIndex: batchId, resultSetNumber: resultId, format: format, selection: this.getSelection(activeGrid) });
}
protected _keybindingFor(action: IAction): ResolvedKeybinding {
let [kb] = this.keybindingService.lookupKeybindings(action.id);
return kb;
}
openContextMenu(event, batchId, resultId, index): void {
let slick: any = this.slickgrids.toArray()[index];
let grid = slick._grid;
let selection = this.getSelection(index);
if (selection && selection.length === 0) {
let cell = (grid as Slick.Grid<any>).getCellFromEvent(event);
selection = [new Slick.Range(cell.row, cell.cell - 1)];
}
let rowIndex = grid.getCellFromEvent(event).row;
let actionContext: IGridInfo = {
batchIndex: batchId,
resultSetNumber: resultId,
selection: selection,
gridIndex: index,
rowIndex: rowIndex
};
let anchor = { x: event.pageX + 1, y: event.pageY };
this.contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => this.actionProvider.getGridActions(),
getKeyBinding: (action) => this._keybindingFor(action),
getActionsContext: () => (actionContext)
});
}
/**
* Returns a function that selects all elements of a grid. This needs to
* return a function in order to capture the scope for this component
*
* @memberOf QueryComponent
*/
protected onGridSelectAll(): (gridIndex: number) => void {
let self = this;
return (gridIndex: number) => {
self.activeGrid = gridIndex;
let grid = self.slickgrids.toArray()[self.activeGrid];
grid.setActive();
grid.selection = true;
};
}
private onSelectAllForActiveGrid(): void {
if (this.activeGrid >= 0 && this.slickgrids.length > this.activeGrid) {
this.slickgrids.toArray()[this.activeGrid].selection = true;
}
}
/**
* Makes a resultset take up the full result height if this is not already true
* Otherwise rerenders the result sets from default
*/
magnify(index: number): void {
const self = this;
if (this.renderedDataSets.length > 1) {
this.renderedDataSets = [this.placeHolderDataSets[index]];
} else {
this.renderedDataSets = this.placeHolderDataSets;
this.onScroll(0);
}
setTimeout(() => {
self.resizeGrids();
self.slickgrids.toArray()[0].setActive();
self._cd.detectChanges();
});
}
abstract onScroll(scrollTop): void;
protected getResultsElement(): any {
return this._el.nativeElement.querySelector('#results');
}
protected getMessagesElement(): any {
return this._el.nativeElement.querySelector('#messages');
}
/**
* Force angular to re-render the results grids. Calling this upon unhide (upon focus) fixes UI
* glitches that occur when a QueryRestulsEditor is hidden then unhidden while it is running a query.
*/
refreshResultsets(): void {
let tempRenderedDataSets = this.renderedDataSets;
this.renderedDataSets = [];
this._cd.detectChanges();
this.renderedDataSets = tempRenderedDataSets;
this._cd.detectChanges();
}
getSelectedRangeUnderMessages(): Selection {
if (document.activeElement === this.getMessagesElement()) {
return window.getSelection();
} else {
return undefined;
}
}
selectAllMessages(): void {
let msgEl = this._el.nativeElement.querySelector('#messages');
this.selectElementContents(msgEl);
}
selectElementContents(el: HTMLElement): void {
let range = document.createRange();
range.selectNodeContents(el);
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
keyEvent(e: KeyboardEvent): void {
if (this.tryHandleKeyEvent(new StandardKeyboardEvent(e))) {
e.preventDefault();
e.stopPropagation();
}
// Else assume that keybinding service handles routing this to a command
}
/**
* Called by keyEvent method to give child classes a chance to
* handle key events.
*
* @memberOf GridParentComponent
*/
protected abstract tryHandleKeyEvent(e: StandardKeyboardEvent): boolean;
resizeGrids(): void {
const self = this;
setTimeout(() => {
for (let grid of self.renderedDataSets) {
grid.resized.emit();
}
});
}
// Private Helper Functions ////////////////////////////////////////////////////////////////////////////
}

View File

@@ -0,0 +1,13 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.editdata-component * {
box-sizing: border-box;
}
#workbench\.editor\.editDataEditor .monaco-toolbar .monaco-select-box {
margin-top: 4px;
margin-bottom: 4px;
}

View File

@@ -0,0 +1,76 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.fullsize {
height: 100%;
width: 100%;
}
/* vertical box styles */
.vertBox {
display: flex;
flex-flow: column;
}
.vertBox .boxRow.header {
flex: 0 0 auto;
}
.vertBox .boxRow.content {
flex: 1 1 0;
}
.edgesPadding {
padding-left: 10px;
padding-right: 10px;
padding-top: 10px;
}
.messagesTopSpacing {
height: 5px;
}
.results {
flex: 100 1 0;
}
.scrollable {
overflow: auto;
}
.maxHeight {
max-height: fit-content;
}
.minHeight {
min-height: fit-content;
}
/* horizontal box style */
.horzBox {
display: flex;
flex-flow: row;
}
.horzBox .boxCol.content {
flex: 1 1 1%;
overflow: auto;
max-width: fit-content;
}
.hidden {
display: none !important;
}
/* testing
.vertBox {
border: 1px solid green;
}
.horzBox {
border: 1px solid red;
}
*/

View File

@@ -0,0 +1,109 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* slick grid */
.boxRow.content.horzBox.slickgrid {
margin-bottom: 2px;
}
.boxRow.content.horzBox.slickgrid:last-child {
margin-bottom: 0px;
}
.boxRow.content.padded {
padding: 15px
}
/* icon */
.gridIcon {
padding: 8px;
background-repeat: no-repeat;
background-position: 0px;
}
.gridIconContainer {
margin: 5px 5px;
}
/* messages */
.resultsMessageTable {
font-weight: inherit;
font-size: inherit;
table-layout: fixed;
border-collapse: collapse;
width: 100%;
user-select: initial;
-webkit-user-select: initial;
}
.wideResultsMessage {
width: 110px;
}
#messageTable td {
padding-right: 20px;
}
#messageTable tbody tr:last-child > td {
padding-bottom: 1em;
}
#messageTable {
-webkit-user-select: text;
user-select: text;
}
.resultsMessageValue {
white-space: pre-line;
}
/* headers */
.resultsMessageHeader {
height: auto;
overflow: hidden;
height: 22px;
padding-left: 20px;
line-height: 22px;
}
.resultsMessageHeader > span {
float: left;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
}
.resizableHandle {
font-size: 0.1px;
display: block;
float: right;
position: absolute;
cursor: row-resize;
top: 0;
height: 4px;
width: 100%;
z-index: 1;
}
#resizeHandle {
font-size: 0.1px;
position: absolute;
cursor: row-resize;
height: 4px;
width: 100%;
z-index: 2;
background-color: var(--color-resize-handle);
}
.header > span.shortCut {
float: right;
padding-right: 5px;
}
.queryLink {
cursor: pointer;
text-decoration: underline;
}

View File

@@ -0,0 +1,125 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IGridInfo, SaveFormat } from 'sql/workbench/parts/grid/common/interfaces';
import { DataService } from 'sql/workbench/parts/grid/common/dataService';
import { localize } from 'vs/nls';
import { IAction, Action } from 'vs/base/common/actions';
export const GRID_SAVECSV_ID = 'grid.saveAsCsv';
export const GRID_SAVEJSON_ID = 'grid.saveAsJson';
export const GRID_SAVEEXCEL_ID = 'grid.saveAsExcel';
export const GRID_SAVEXML_ID = 'grid.saveAsXml';
export const GRID_COPY_ID = 'grid.copySelection';
export const GRID_COPYWITHHEADERS_ID = 'grid.copyWithHeaders';
export const GRID_SELECTALL_ID = 'grid.selectAll';
export const MESSAGES_SELECTALL_ID = 'grid.messages.selectAll';
export const MESSAGES_COPY_ID = 'grid.messages.copy';
export const TOGGLERESULTS_ID = 'grid.toggleResultPane';
export const TOGGLEMESSAGES_ID = 'grid.toggleMessagePane';
export const GOTONEXTQUERYOUTPUTTAB_ID = 'query.goToNextQueryOutputTab';
export const GRID_VIEWASCHART_ID = 'grid.viewAsChart';
export const GRID_VIEWASVISUALIZER_ID = 'grid.viewAsVisualizer';
export const GRID_GOTONEXTGRID_ID = 'grid.goToNextGrid';
export class GridActionProvider {
constructor(
protected _dataService: DataService,
protected _selectAllCallback: (index: number) => void
) {
}
/**
* Return actions given a click on a grid
*/
public getGridActions(): IAction[] {
const actions: IAction[] = [];
actions.push(new SaveResultAction(SaveResultAction.SAVECSV_ID, SaveResultAction.SAVECSV_LABEL, SaveFormat.CSV, this._dataService));
actions.push(new SaveResultAction(SaveResultAction.SAVEJSON_ID, SaveResultAction.SAVEJSON_LABEL, SaveFormat.JSON, this._dataService));
actions.push(new SaveResultAction(SaveResultAction.SAVEEXCEL_ID, SaveResultAction.SAVEEXCEL_LABEL, SaveFormat.EXCEL, this._dataService));
actions.push(new SaveResultAction(SaveResultAction.SAVEXML_ID, SaveResultAction.SAVEXML_LABEL, SaveFormat.XML, this._dataService));
actions.push(new SelectAllGridAction(SelectAllGridAction.ID, SelectAllGridAction.LABEL, this._selectAllCallback));
actions.push(new CopyResultAction(CopyResultAction.COPY_ID, CopyResultAction.COPY_LABEL, false, this._dataService));
actions.push(new CopyResultAction(CopyResultAction.COPYWITHHEADERS_ID, CopyResultAction.COPYWITHHEADERS_LABEL, true, this._dataService));
return actions;
}
}
class SaveResultAction extends Action {
public static SAVECSV_ID = GRID_SAVECSV_ID;
public static SAVECSV_LABEL = localize('saveAsCsv', "Save As CSV");
public static SAVEJSON_ID = GRID_SAVEJSON_ID;
public static SAVEJSON_LABEL = localize('saveAsJson', "Save As JSON");
public static SAVEEXCEL_ID = GRID_SAVEEXCEL_ID;
public static SAVEEXCEL_LABEL = localize('saveAsExcel', "Save As Excel");
public static SAVEXML_ID = GRID_SAVEXML_ID;
public static SAVEXML_LABEL = localize('saveAsXml', "Save As XML");
constructor(
id: string,
label: string,
private format: SaveFormat,
private dataService: DataService
) {
super(id, label);
}
public run(gridInfo: IGridInfo): Promise<boolean> {
this.dataService.sendSaveRequest({
batchIndex: gridInfo.batchIndex,
resultSetNumber: gridInfo.resultSetNumber,
selection: gridInfo.selection,
format: this.format
});
return Promise.resolve(true);
}
}
class CopyResultAction extends Action {
public static COPY_ID = GRID_COPY_ID;
public static COPY_LABEL = localize('copySelection', "Copy");
public static COPYWITHHEADERS_ID = GRID_COPYWITHHEADERS_ID;
public static COPYWITHHEADERS_LABEL = localize('copyWithHeaders', "Copy With Headers");
constructor(
id: string,
label: string,
private copyHeader: boolean,
private dataService: DataService
) {
super(id, label);
}
public run(gridInfo: IGridInfo): Promise<boolean> {
this.dataService.copyResults(gridInfo.selection, gridInfo.batchIndex, gridInfo.resultSetNumber, this.copyHeader);
return Promise.resolve(true);
}
}
class SelectAllGridAction extends Action {
public static ID = GRID_SELECTALL_ID;
public static LABEL = localize('selectAll', "Select All");
constructor(
id: string,
label: string,
private selectAllCallback: (index: number) => void
) {
super(id, label);
}
public run(gridInfo: IGridInfo): Promise<boolean> {
this.selectAllCallback(gridInfo.gridIndex);
return Promise.resolve(true);
}
}