hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 5,
"code_window": [
"\t\t\t}, 1000);\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate _updateOutputs(splice: NotebookCellOutputsSplice) {\n",
"\t\tconst previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;\n",
"\n",
"\t\t// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _updateOutputs(splice: NotebookCellOutputsSplice, context: CellOutputUpdateContext = CellOutputUpdateContext.Other) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 545
} | {
"iconDefinitions": {
"_root_folder_dark": {
"iconPath": "./images/root-folder-dark.svg"
},
"_root_folder_open_dark": {
"iconPath": "./images/root-folder-open-dark.svg"
},
"_folder_dark": {
"iconPath": "./images/folder-dark.svg"
},
"_folder_open_dark": {
"iconPath": "./images/folder-open-dark.svg"
},
"_file_dark": {
"iconPath": "./images/document-dark.svg"
},
"_root_folder": {
"iconPath": "./images/root-folder-light.svg"
},
"_root_folder_open": {
"iconPath": "./images/root-folder-open-light.svg"
},
"_folder_light": {
"iconPath": "./images/folder-light.svg"
},
"_folder_open_light": {
"iconPath": "./images/folder-open-light.svg"
},
"_file_light": {
"iconPath": "./images/document-light.svg"
}
},
"folderExpanded": "_folder_open_dark",
"folder": "_folder_dark",
"file": "_file_dark",
"rootFolderExpanded": "_root_folder_open_dark",
"rootFolder": "_root_folder_dark",
"fileExtensions": {
// icons by file extension
},
"fileNames": {
// icons by file name
},
"languageIds": {
// icons by language id
},
"light": {
"folderExpanded": "_folder_open_light",
"folder": "_folder_light",
"rootFolderExpanded": "_root_folder_open",
"rootFolder": "_root_folder",
"file": "_file_light",
"fileExtensions": {
// icons by file extension
},
"fileNames": {
// icons by file name
},
"languageIds": {
// icons by language id
}
},
"highContrast": {
// overrides for high contrast
}
} | extensions/theme-defaults/fileicons/vs_minimal-icon-theme.json | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017611445218790323,
0.00017451413441449404,
0.00017300338367931545,
0.00017447593563701957,
0.0000011065575336033362
] |
{
"id": 5,
"code_window": [
"\t\t\t}, 1000);\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate _updateOutputs(splice: NotebookCellOutputsSplice) {\n",
"\t\tconst previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;\n",
"\n",
"\t\t// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _updateOutputs(splice: NotebookCellOutputsSplice, context: CellOutputUpdateContext = CellOutputUpdateContext.Other) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 545
} | function foo(): void {
var a = 1;
a = 1;
a = 1;
a = 1;
a = 1;
a = 1;
a = 1;
a = 1;
} | extensions/vscode-api-tests/testWorkspace/10linefile.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0001749320508679375,
0.00017478139488957822,
0.00017463073891121894,
0.00017478139488957822,
1.5065597835928202e-7
] |
{
"id": 6,
"code_window": [
"\t\t\tDOM.hide(this.templateData.outputContainer.domNode);\n",
"\t\t}\n",
"\n",
"\t\tthis.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));\n",
"\t\tthis._renderNow(splice);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._renderNow(splice, context);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 558
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event';
import { dispose } from 'vs/base/common/lifecycle';
import * as UUID from 'vs/base/common/uuid';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { PrefixSumComputer } from 'vs/editor/common/model/prefixSumComputer';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { CellEditState, CellFindMatch, CodeCellLayoutChangeEvent, CodeCellLayoutInfo, CellLayoutState, ICellOutputViewModel, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CellOutputViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/cellOutputViewModel';
import { ViewContext } from 'vs/workbench/contrib/notebook/browser/viewModel/viewContext';
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { CellKind, INotebookSearchOptions, NotebookCellOutputsSplice } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptionsChangeEvent } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { BaseCellViewModel } from './baseCellViewModel';
import { NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
export class CodeCellViewModel extends BaseCellViewModel implements ICellViewModel {
readonly cellKind = CellKind.Code;
protected readonly _onLayoutInfoRead = this._register(new Emitter<void>());
readonly onLayoutInfoRead = this._onLayoutInfoRead.event;
protected readonly _onDidChangeOutputs = this._register(new Emitter<NotebookCellOutputsSplice>());
readonly onDidChangeOutputs = this._onDidChangeOutputs.event;
private readonly _onDidRemoveOutputs = this._register(new Emitter<readonly ICellOutputViewModel[]>());
readonly onDidRemoveOutputs = this._onDidRemoveOutputs.event;
private _outputCollection: number[] = [];
private _outputsTop: PrefixSumComputer | null = null;
protected _pauseableEmitter = this._register(new PauseableEmitter<CodeCellLayoutChangeEvent>());
readonly onDidChangeLayout = this._pauseableEmitter.event;
private _editorHeight = 0;
set editorHeight(height: number) {
this._editorHeight = height;
this.layoutChange({ editorHeight: true }, 'CodeCellViewModel#editorHeight');
}
get editorHeight() {
throw new Error('editorHeight is write-only');
}
private _commentHeight = 0;
set commentHeight(height: number) {
if (this._commentHeight === height) {
return;
}
this._commentHeight = height;
this.layoutChange({ commentHeight: true }, 'CodeCellViewModel#commentHeight');
}
private _hoveringOutput: boolean = false;
public get outputIsHovered(): boolean {
return this._hoveringOutput;
}
public set outputIsHovered(v: boolean) {
this._hoveringOutput = v;
this._onDidChangeState.fire({ outputIsHoveredChanged: true });
}
private _focusOnOutput: boolean = false;
public get outputIsFocused(): boolean {
return this._focusOnOutput;
}
public set outputIsFocused(v: boolean) {
this._focusOnOutput = v;
this._onDidChangeState.fire({ outputIsFocusedChanged: true });
}
private _outputMinHeight: number = 0;
private get outputMinHeight() {
return this._outputMinHeight;
}
/**
* The minimum height of the output region. It's only set to non-zero temporarily when replacing an output with a new one.
* It's reset to 0 when the new output is rendered, or in one second.
*/
private set outputMinHeight(newMin: number) {
this._outputMinHeight = newMin;
}
private _layoutInfo: CodeCellLayoutInfo;
get layoutInfo() {
return this._layoutInfo;
}
private _outputViewModels: ICellOutputViewModel[];
get outputsViewModels() {
return this._outputViewModels;
}
constructor(
viewType: string,
model: NotebookCellTextModel,
initialNotebookLayoutInfo: NotebookLayoutInfo | null,
readonly viewContext: ViewContext,
@IConfigurationService configurationService: IConfigurationService,
@INotebookService private readonly _notebookService: INotebookService,
@ITextModelService modelService: ITextModelService,
@IUndoRedoService undoRedoService: IUndoRedoService,
@ICodeEditorService codeEditorService: ICodeEditorService
) {
super(viewType, model, UUID.generateUuid(), viewContext, configurationService, modelService, undoRedoService, codeEditorService);
this._outputViewModels = this.model.outputs.map(output => new CellOutputViewModel(this, output, this._notebookService));
this._register(this.model.onDidChangeOutputs((splice) => {
const removedOutputs: ICellOutputViewModel[] = [];
let outputLayoutChange = false;
for (let i = splice.start; i < splice.start + splice.deleteCount; i++) {
if (this._outputCollection[i] !== undefined && this._outputCollection[i] !== 0) {
outputLayoutChange = true;
}
}
this._outputCollection.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(() => 0));
removedOutputs.push(...this._outputViewModels.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(output => new CellOutputViewModel(this, output, this._notebookService))));
this._outputsTop = null;
this._onDidChangeOutputs.fire(splice);
this._onDidRemoveOutputs.fire(removedOutputs);
if (outputLayoutChange) {
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#model.onDidChangeOutputs');
}
dispose(removedOutputs);
}));
this._outputCollection = new Array(this.model.outputs.length);
this._layoutInfo = {
fontInfo: initialNotebookLayoutInfo?.fontInfo || null,
editorHeight: 0,
editorWidth: initialNotebookLayoutInfo
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(initialNotebookLayoutInfo.width)
: 0,
statusBarHeight: 0,
commentHeight: 0,
outputContainerOffset: 0,
outputTotalHeight: 0,
outputShowMoreContainerHeight: 0,
outputShowMoreContainerOffset: 0,
totalHeight: this.computeTotalHeight(17, 0, 0),
codeIndicatorHeight: 0,
outputIndicatorHeight: 0,
bottomToolbarOffset: 0,
layoutState: CellLayoutState.Uninitialized,
estimatedHasHorizontalScrolling: false
};
}
updateOptions(e: NotebookOptionsChangeEvent) {
if (e.cellStatusBarVisibility || e.insertToolbarPosition || e.cellToolbarLocation) {
this.layoutChange({});
}
}
pauseLayout() {
this._pauseableEmitter.pause();
}
resumeLayout() {
this._pauseableEmitter.resume();
}
layoutChange(state: CodeCellLayoutChangeEvent, source?: string) {
// recompute
this._ensureOutputsTop();
const notebookLayoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const bottomToolbarDimensions = this.viewContext.notebookOptions.computeBottomToolbarDimensions();
const outputShowMoreContainerHeight = state.outputShowMoreContainerHeight ? state.outputShowMoreContainerHeight : this._layoutInfo.outputShowMoreContainerHeight;
const outputTotalHeight = Math.max(this._outputMinHeight, this.isOutputCollapsed ? notebookLayoutConfiguration.collapsedIndicatorHeight : this._outputsTop!.getTotalSum());
const commentHeight = state.commentHeight ? this._commentHeight : this._layoutInfo.commentHeight;
const originalLayout = this.layoutInfo;
if (!this.isInputCollapsed) {
let newState: CellLayoutState;
let editorHeight: number;
let totalHeight: number;
let hasHorizontalScrolling = false;
if (!state.editorHeight && this._layoutInfo.layoutState === CellLayoutState.FromCache && !state.outputHeight) {
// No new editorHeight info - keep cached totalHeight and estimate editorHeight
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this._layoutInfo.totalHeight;
newState = CellLayoutState.FromCache;
} else if (state.editorHeight || this._layoutInfo.layoutState === CellLayoutState.Measured) {
// Editor has been measured
editorHeight = this._editorHeight;
totalHeight = this.computeTotalHeight(this._editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Measured;
hasHorizontalScrolling = this._layoutInfo.estimatedHasHorizontalScrolling;
} else {
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this.computeTotalHeight(editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Estimated;
}
const statusBarHeight = this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri);
const codeIndicatorHeight = editorHeight + statusBarHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.editorToolbarHeight
+ notebookLayoutConfiguration.cellTopMargin // CELL_TOP_MARGIN
+ editorHeight
+ statusBarHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight,
editorWidth,
statusBarHeight,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: newState,
estimatedHasHorizontalScrolling: hasHorizontalScrolling
};
} else {
const codeIndicatorHeight = notebookLayoutConfiguration.collapsedIndicatorHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.cellTopMargin + notebookLayoutConfiguration.collapsedIndicatorHeight;
const totalHeight =
notebookLayoutConfiguration.cellTopMargin
+ notebookLayoutConfiguration.collapsedIndicatorHeight
+ notebookLayoutConfiguration.cellBottomMargin //CELL_BOTTOM_MARGIN
+ bottomToolbarDimensions.bottomToolbarGap //BOTTOM_CELL_TOOLBAR_GAP
+ commentHeight
+ outputTotalHeight + outputShowMoreContainerHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight: this._layoutInfo.editorHeight,
editorWidth,
statusBarHeight: 0,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: this._layoutInfo.layoutState,
estimatedHasHorizontalScrolling: false
};
}
this._fireOnDidChangeLayout({
...state,
totalHeight: this.layoutInfo.totalHeight !== originalLayout.totalHeight,
source,
});
}
private _fireOnDidChangeLayout(state: CodeCellLayoutChangeEvent) {
this._pauseableEmitter.fire(state);
}
override restoreEditorViewState(editorViewStates: editorCommon.ICodeEditorViewState | null, totalHeight?: number) {
super.restoreEditorViewState(editorViewStates);
if (totalHeight !== undefined && this._layoutInfo.layoutState !== CellLayoutState.Measured) {
this._layoutInfo = {
fontInfo: this._layoutInfo.fontInfo,
editorHeight: this._layoutInfo.editorHeight,
editorWidth: this._layoutInfo.editorWidth,
statusBarHeight: this.layoutInfo.statusBarHeight,
commentHeight: this.layoutInfo.commentHeight,
outputContainerOffset: this._layoutInfo.outputContainerOffset,
outputTotalHeight: this._layoutInfo.outputTotalHeight,
outputShowMoreContainerHeight: this._layoutInfo.outputShowMoreContainerHeight,
outputShowMoreContainerOffset: this._layoutInfo.outputShowMoreContainerOffset,
totalHeight: totalHeight,
codeIndicatorHeight: this._layoutInfo.codeIndicatorHeight,
outputIndicatorHeight: this._layoutInfo.outputIndicatorHeight,
bottomToolbarOffset: this._layoutInfo.bottomToolbarOffset,
layoutState: CellLayoutState.FromCache,
estimatedHasHorizontalScrolling: this._layoutInfo.estimatedHasHorizontalScrolling
};
}
}
hasDynamicHeight() {
// CodeCellVM always measures itself and controls its cell's height
return false;
}
getDynamicHeight() {
this._onLayoutInfoRead.fire();
return this._layoutInfo.totalHeight;
}
getHeight(lineHeight: number) {
if (this._layoutInfo.layoutState === CellLayoutState.Uninitialized) {
const estimate = this.estimateEditorHeight(lineHeight);
return this.computeTotalHeight(estimate.editorHeight, 0, 0);
} else {
return this._layoutInfo.totalHeight;
}
}
private estimateEditorHeight(lineHeight: number | undefined = 20): { editorHeight: number; hasHorizontalScrolling: boolean } {
let hasHorizontalScrolling = false;
const cellEditorOptions = this.viewContext.getBaseCellEditorOptions(this.language);
if (this.layoutInfo.fontInfo && cellEditorOptions.value.wordWrap === 'off') {
for (let i = 0; i < this.lineCount; i++) {
const max = this.textBuffer.getLineLastNonWhitespaceColumn(i + 1);
const estimatedWidth = max * (this.layoutInfo.fontInfo.typicalHalfwidthCharacterWidth + this.layoutInfo.fontInfo.letterSpacing);
if (estimatedWidth > this.layoutInfo.editorWidth) {
hasHorizontalScrolling = true;
break;
}
}
}
const verticalScrollbarHeight = hasHorizontalScrolling ? 12 : 0; // take zoom level into account
const editorPadding = this.viewContext.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
const editorHeight = this.lineCount * lineHeight
+ editorPadding.top
+ editorPadding.bottom // EDITOR_BOTTOM_PADDING
+ verticalScrollbarHeight;
return {
editorHeight,
hasHorizontalScrolling
};
}
private computeTotalHeight(editorHeight: number, outputsTotalHeight: number, outputShowMoreContainerHeight: number): number {
const layoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const { bottomToolbarGap } = this.viewContext.notebookOptions.computeBottomToolbarDimensions(this.viewType);
return layoutConfiguration.editorToolbarHeight
+ layoutConfiguration.cellTopMargin
+ editorHeight
+ this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri)
+ this._commentHeight
+ outputsTotalHeight
+ outputShowMoreContainerHeight
+ bottomToolbarGap
+ layoutConfiguration.cellBottomMargin;
}
protected onDidChangeTextModelContent(): void {
if (this.getEditState() !== CellEditState.Editing) {
this.updateEditState(CellEditState.Editing, 'onDidChangeTextModelContent');
this._onDidChangeState.fire({ contentChanged: true });
}
}
onDeselect() {
this.updateEditState(CellEditState.Preview, 'onDeselect');
}
updateOutputShowMoreContainerHeight(height: number) {
this.layoutChange({ outputShowMoreContainerHeight: height }, 'CodeCellViewModel#updateOutputShowMoreContainerHeight');
}
updateOutputMinHeight(height: number) {
this.outputMinHeight = height;
}
unlockOutputHeight() {
this.outputMinHeight = 0;
this.layoutChange({ outputHeight: true });
}
updateOutputHeight(index: number, height: number, source?: string) {
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
this._ensureOutputsTop();
if (height < 28 && this._outputViewModels[index].hasMultiMimeType()) {
height = 28;
}
this._outputCollection[index] = height;
if (this._outputsTop!.setValue(index, height)) {
this.layoutChange({ outputHeight: true }, source);
}
}
getOutputOffsetInContainer(index: number) {
this._ensureOutputsTop();
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
return this._outputsTop!.getPrefixSum(index - 1);
}
getOutputOffset(index: number): number {
return this.layoutInfo.outputContainerOffset + this.getOutputOffsetInContainer(index);
}
spliceOutputHeights(start: number, deleteCnt: number, heights: number[]) {
this._ensureOutputsTop();
this._outputsTop!.removeValues(start, deleteCnt);
if (heights.length) {
const values = new Uint32Array(heights.length);
for (let i = 0; i < heights.length; i++) {
values[i] = heights[i];
}
this._outputsTop!.insertValues(start, values);
}
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#spliceOutputs');
}
private _ensureOutputsTop(): void {
if (!this._outputsTop) {
const values = new Uint32Array(this._outputCollection.length);
for (let i = 0; i < this._outputCollection.length; i++) {
values[i] = this._outputCollection[i];
}
this._outputsTop = new PrefixSumComputer(values);
}
}
private readonly _hasFindResult = this._register(new Emitter<boolean>());
public readonly hasFindResult: Event<boolean> = this._hasFindResult.event;
startFind(value: string, options: INotebookSearchOptions): CellFindMatch | null {
const matches = super.cellStartFind(value, options);
if (matches === null) {
return null;
}
return {
cell: this,
contentMatches: matches
};
}
override dispose() {
super.dispose();
this._outputCollection = [];
this._outputsTop = null;
dispose(this._outputViewModels);
}
}
| src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.007944312877953053,
0.0003949383972212672,
0.0001636187662370503,
0.00017102787387557328,
0.0011259234743192792
] |
{
"id": 6,
"code_window": [
"\t\t\tDOM.hide(this.templateData.outputContainer.domNode);\n",
"\t\t}\n",
"\n",
"\t\tthis.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));\n",
"\t\tthis._renderNow(splice);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._renderNow(splice, context);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 558
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { IDebugAdapter } from 'vs/workbench/contrib/debug/common/debug';
import { timeout } from 'vs/base/common/async';
import { localize } from 'vs/nls';
/**
* Abstract implementation of the low level API for a debug adapter.
* Missing is how this API communicates with the debug adapter.
*/
export abstract class AbstractDebugAdapter implements IDebugAdapter {
private sequence: number;
private pendingRequests = new Map<number, (e: DebugProtocol.Response) => void>();
private requestCallback: ((request: DebugProtocol.Request) => void) | undefined;
private eventCallback: ((request: DebugProtocol.Event) => void) | undefined;
private messageCallback: ((message: DebugProtocol.ProtocolMessage) => void) | undefined;
private queue: DebugProtocol.ProtocolMessage[] = [];
protected readonly _onError = new Emitter<Error>();
protected readonly _onExit = new Emitter<number | null>();
constructor() {
this.sequence = 1;
}
abstract startSession(): Promise<void>;
abstract stopSession(): Promise<void>;
abstract sendMessage(message: DebugProtocol.ProtocolMessage): void;
get onError(): Event<Error> {
return this._onError.event;
}
get onExit(): Event<number | null> {
return this._onExit.event;
}
onMessage(callback: (message: DebugProtocol.ProtocolMessage) => void): void {
if (this.messageCallback) {
this._onError.fire(new Error(`attempt to set more than one 'Message' callback`));
}
this.messageCallback = callback;
}
onEvent(callback: (event: DebugProtocol.Event) => void): void {
if (this.eventCallback) {
this._onError.fire(new Error(`attempt to set more than one 'Event' callback`));
}
this.eventCallback = callback;
}
onRequest(callback: (request: DebugProtocol.Request) => void): void {
if (this.requestCallback) {
this._onError.fire(new Error(`attempt to set more than one 'Request' callback`));
}
this.requestCallback = callback;
}
sendResponse(response: DebugProtocol.Response): void {
if (response.seq > 0) {
this._onError.fire(new Error(`attempt to send more than one response for command ${response.command}`));
} else {
this.internalSend('response', response);
}
}
sendRequest(command: string, args: any, clb: (result: DebugProtocol.Response) => void, timeout?: number): number {
const request: any = {
command: command
};
if (args && Object.keys(args).length > 0) {
request.arguments = args;
}
this.internalSend('request', request);
if (typeof timeout === 'number') {
const timer = setTimeout(() => {
clearTimeout(timer);
const clb = this.pendingRequests.get(request.seq);
if (clb) {
this.pendingRequests.delete(request.seq);
const err: DebugProtocol.Response = {
type: 'response',
seq: 0,
request_seq: request.seq,
success: false,
command,
message: localize('timeout', "Timeout after {0} ms for '{1}'", timeout, command)
};
clb(err);
}
}, timeout);
}
if (clb) {
// store callback for this request
this.pendingRequests.set(request.seq, clb);
}
return request.seq;
}
acceptMessage(message: DebugProtocol.ProtocolMessage): void {
if (this.messageCallback) {
this.messageCallback(message);
} else {
this.queue.push(message);
if (this.queue.length === 1) {
// first item = need to start processing loop
this.processQueue();
}
}
}
/**
* Returns whether we should insert a timeout between processing messageA
* and messageB. Artificially queueing protocol messages guarantees that any
* microtasks for previous message finish before next message is processed.
* This is essential ordering when using promises anywhere along the call path.
*
* For example, take the following, where `chooseAndSendGreeting` returns
* a person name and then emits a greeting event:
*
* ```
* let person: string;
* adapter.onGreeting(() => console.log('hello', person));
* person = await adapter.chooseAndSendGreeting();
* ```
*
* Because the event is dispatched synchronously, it may fire before person
* is assigned if they're processed in the same task. Inserting a task
* boundary avoids this issue.
*/
protected needsTaskBoundaryBetween(messageA: DebugProtocol.ProtocolMessage, messageB: DebugProtocol.ProtocolMessage) {
return messageA.type !== 'event' || messageB.type !== 'event';
}
/**
* Reads and dispatches items from the queue until it is empty.
*/
private async processQueue() {
let message: DebugProtocol.ProtocolMessage | undefined;
while (this.queue.length) {
if (!message || this.needsTaskBoundaryBetween(this.queue[0], message)) {
await timeout(0);
}
message = this.queue.shift();
if (!message) {
return; // may have been disposed of
}
switch (message.type) {
case 'event':
this.eventCallback?.(<DebugProtocol.Event>message);
break;
case 'request':
this.requestCallback?.(<DebugProtocol.Request>message);
break;
case 'response': {
const response = <DebugProtocol.Response>message;
const clb = this.pendingRequests.get(response.request_seq);
if (clb) {
this.pendingRequests.delete(response.request_seq);
clb(response);
}
break;
}
}
}
}
private internalSend(typ: 'request' | 'response' | 'event', message: DebugProtocol.ProtocolMessage): void {
message.type = typ;
message.seq = this.sequence++;
this.sendMessage(message);
}
protected async cancelPendingRequests(): Promise<void> {
if (this.pendingRequests.size === 0) {
return Promise.resolve();
}
const pending = new Map<number, (e: DebugProtocol.Response) => void>();
this.pendingRequests.forEach((value, key) => pending.set(key, value));
await timeout(500);
pending.forEach((callback, request_seq) => {
const err: DebugProtocol.Response = {
type: 'response',
seq: 0,
request_seq,
success: false,
command: 'canceled',
message: 'canceled'
};
callback(err);
this.pendingRequests.delete(request_seq);
});
}
getPendingRequestIds(): number[] {
return Array.from(this.pendingRequests.keys());
}
dispose(): void {
this.queue = [];
}
}
| src/vs/workbench/contrib/debug/common/abstractDebugAdapter.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00018019457638729364,
0.00017226298223249614,
0.0001657344400882721,
0.00017302468768320978,
0.000003365886868778034
] |
{
"id": 6,
"code_window": [
"\t\t\tDOM.hide(this.templateData.outputContainer.domNode);\n",
"\t\t}\n",
"\n",
"\t\tthis.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));\n",
"\t\tthis._renderNow(splice);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._renderNow(splice, context);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 558
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI, UriComponents } from 'vs/base/common/uri';
import { ILogService } from 'vs/platform/log/common/log';
import { ExtHostInteractiveShape, IMainContext } from 'vs/workbench/api/common/extHost.protocol';
import { ApiCommand, ApiCommandArgument, ApiCommandResult, ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
import { NotebookEditor } from 'vscode';
export class ExtHostInteractive implements ExtHostInteractiveShape {
constructor(
mainContext: IMainContext,
private _extHostNotebooks: ExtHostNotebookController,
private _textDocumentsAndEditors: ExtHostDocumentsAndEditors,
private _commands: ExtHostCommands,
_logService: ILogService
) {
const openApiCommand = new ApiCommand(
'interactive.open',
'_interactive.open',
'Open interactive window and return notebook editor and input URI',
[
new ApiCommandArgument('showOptions', 'Show Options', v => true, v => v),
new ApiCommandArgument('resource', 'Interactive resource Uri', v => true, v => v),
new ApiCommandArgument('controllerId', 'Notebook controller Id', v => true, v => v),
new ApiCommandArgument('title', 'Interactive editor title', v => true, v => v)
],
new ApiCommandResult<{ notebookUri: UriComponents; inputUri: UriComponents; notebookEditorId?: string }, { notebookUri: URI; inputUri: URI; notebookEditor?: NotebookEditor }>('Notebook and input URI', (v: { notebookUri: UriComponents; inputUri: UriComponents; notebookEditorId?: string }) => {
_logService.debug('[ExtHostInteractive] open iw with notebook editor id', v.notebookEditorId);
if (v.notebookEditorId !== undefined) {
const editor = this._extHostNotebooks.getEditorById(v.notebookEditorId);
_logService.debug('[ExtHostInteractive] notebook editor found', editor.id);
return { notebookUri: URI.revive(v.notebookUri), inputUri: URI.revive(v.inputUri), notebookEditor: editor.apiEditor };
}
_logService.debug('[ExtHostInteractive] notebook editor not found, uris for the interactive document', v.notebookUri, v.inputUri);
return { notebookUri: URI.revive(v.notebookUri), inputUri: URI.revive(v.inputUri) };
})
);
this._commands.registerApiCommand(openApiCommand);
}
$willAddInteractiveDocument(uri: UriComponents, eol: string, languageId: string, notebookUri: UriComponents) {
this._textDocumentsAndEditors.acceptDocumentsAndEditorsDelta({
addedDocuments: [{
EOL: eol,
lines: [''],
languageId: languageId,
uri: uri,
isDirty: false,
versionId: 1,
notebook: this._extHostNotebooks.getNotebookDocument(URI.revive(notebookUri))?.apiNotebook
}]
});
}
$willRemoveInteractiveDocument(uri: UriComponents, notebookUri: UriComponents) {
this._textDocumentsAndEditors.acceptDocumentsAndEditorsDelta({
removedDocuments: [uri]
});
}
}
| src/vs/workbench/api/common/extHostInteractive.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017631288210395724,
0.0001745128392940387,
0.00017118212417699397,
0.00017502665286883712,
0.0000017382304804414161
] |
{
"id": 6,
"code_window": [
"\t\t\tDOM.hide(this.templateData.outputContainer.domNode);\n",
"\t\t}\n",
"\n",
"\t\tthis.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));\n",
"\t\tthis._renderNow(splice);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._renderNow(splice, context);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 558
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { basename } from 'vs/base/common/resources';
import { URI, UriComponents } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ILocalizedString } from 'vs/platform/action/common/action';
import { Action2, IAction2Options, MenuId } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { ITextEditorOptions } from 'vs/platform/editor/common/editor';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IEditorIdentifier, IResourceMergeEditorInput } from 'vs/workbench/common/editor';
import { MergeEditorInput, MergeEditorInputData } from 'vs/workbench/contrib/mergeEditor/browser/mergeEditorInput';
import { IMergeEditorInputModel } from 'vs/workbench/contrib/mergeEditor/browser/mergeEditorInputModel';
import { MergeEditor } from 'vs/workbench/contrib/mergeEditor/browser/view/mergeEditor';
import { MergeEditorViewModel } from 'vs/workbench/contrib/mergeEditor/browser/view/viewModel';
import { ctxIsMergeEditor, ctxMergeEditorLayout, ctxMergeEditorShowBase, ctxMergeEditorShowBaseAtTop, ctxMergeEditorShowNonConflictingChanges, StorageCloseWithConflicts } from 'vs/workbench/contrib/mergeEditor/common/mergeEditor';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
abstract class MergeEditorAction extends Action2 {
constructor(desc: Readonly<IAction2Options>) {
super(desc);
}
run(accessor: ServicesAccessor): void {
const { activeEditorPane } = accessor.get(IEditorService);
if (activeEditorPane instanceof MergeEditor) {
const vm = activeEditorPane.viewModel.get();
if (!vm) {
return;
}
this.runWithViewModel(vm, accessor);
}
}
abstract runWithViewModel(viewModel: MergeEditorViewModel, accessor: ServicesAccessor): void;
}
interface MergeEditorAction2Args {
inputModel: IMergeEditorInputModel;
viewModel: MergeEditorViewModel;
input: MergeEditorInput;
editorIdentifier: IEditorIdentifier;
}
abstract class MergeEditorAction2 extends Action2 {
constructor(desc: Readonly<IAction2Options>) {
super(desc);
}
override run(accessor: ServicesAccessor, ...args: any[]): void {
const { activeEditorPane } = accessor.get(IEditorService);
if (activeEditorPane instanceof MergeEditor) {
const vm = activeEditorPane.viewModel.get();
if (!vm) {
return;
}
return this.runWithMergeEditor({
viewModel: vm,
inputModel: activeEditorPane.inputModel.get()!,
input: activeEditorPane.input as MergeEditorInput,
editorIdentifier: {
editor: activeEditorPane.input,
groupId: activeEditorPane.group.id,
}
}, accessor, ...args) as any;
}
}
abstract runWithMergeEditor(context: MergeEditorAction2Args, accessor: ServicesAccessor, ...args: any[]): unknown;
}
export class OpenMergeEditor extends Action2 {
constructor() {
super({
id: '_open.mergeEditor',
title: { value: localize('title', "Open Merge Editor"), original: 'Open Merge Editor' },
});
}
run(accessor: ServicesAccessor, ...args: unknown[]): void {
const validatedArgs = IRelaxedOpenArgs.validate(args[0]);
const input: IResourceMergeEditorInput = {
base: { resource: validatedArgs.base },
input1: { resource: validatedArgs.input1.uri, label: validatedArgs.input1.title, description: validatedArgs.input1.description, detail: validatedArgs.input1.detail },
input2: { resource: validatedArgs.input2.uri, label: validatedArgs.input2.title, description: validatedArgs.input2.description, detail: validatedArgs.input2.detail },
result: { resource: validatedArgs.output },
options: { preserveFocus: true }
};
accessor.get(IEditorService).openEditor(input);
}
}
namespace IRelaxedOpenArgs {
export function validate(obj: unknown): {
base: URI;
input1: MergeEditorInputData;
input2: MergeEditorInputData;
output: URI;
} {
if (!obj || typeof obj !== 'object') {
throw new TypeError('invalid argument');
}
const o = obj as IRelaxedOpenArgs;
const base = toUri(o.base);
const output = toUri(o.output);
const input1 = toInputData(o.input1);
const input2 = toInputData(o.input2);
return { base, input1, input2, output };
}
function toInputData(obj: unknown): MergeEditorInputData {
if (typeof obj === 'string') {
return new MergeEditorInputData(URI.parse(obj, true), undefined, undefined, undefined);
}
if (!obj || typeof obj !== 'object') {
throw new TypeError('invalid argument');
}
if (isUriComponents(obj)) {
return new MergeEditorInputData(URI.revive(obj), undefined, undefined, undefined);
}
const o = obj as IRelaxedInputData;
const title = o.title;
const uri = toUri(o.uri);
const detail = o.detail;
const description = o.description;
return new MergeEditorInputData(uri, title, detail, description);
}
function toUri(obj: unknown): URI {
if (typeof obj === 'string') {
return URI.parse(obj, true);
} else if (obj && typeof obj === 'object') {
return URI.revive(<UriComponents>obj);
}
throw new TypeError('invalid argument');
}
function isUriComponents(obj: unknown): obj is UriComponents {
if (!obj || typeof obj !== 'object') {
return false;
}
const o = obj as UriComponents;
return typeof o.scheme === 'string'
&& typeof o.authority === 'string'
&& typeof o.path === 'string'
&& typeof o.query === 'string'
&& typeof o.fragment === 'string';
}
}
type IRelaxedInputData = { uri: UriComponents; title?: string; detail?: string; description?: string };
type IRelaxedOpenArgs = {
base: UriComponents | string;
input1: IRelaxedInputData | string;
input2: IRelaxedInputData | string;
output: UriComponents | string;
};
export class SetMixedLayout extends Action2 {
constructor() {
super({
id: 'merge.mixedLayout',
title: {
value: localize('layout.mixed', 'Mixed Layout'),
original: 'Mixed Layout',
},
toggled: ctxMergeEditorLayout.isEqualTo('mixed'),
menu: [
{
id: MenuId.EditorTitle,
when: ctxIsMergeEditor,
group: '1_merge',
order: 9,
},
],
precondition: ctxIsMergeEditor,
});
}
run(accessor: ServicesAccessor): void {
const { activeEditorPane } = accessor.get(IEditorService);
if (activeEditorPane instanceof MergeEditor) {
activeEditorPane.setLayoutKind('mixed');
}
}
}
export class SetColumnLayout extends Action2 {
constructor() {
super({
id: 'merge.columnLayout',
title: { value: localize('layout.column', "Column Layout"), original: 'Column Layout' },
toggled: ctxMergeEditorLayout.isEqualTo('columns'),
menu: [{
id: MenuId.EditorTitle,
when: ctxIsMergeEditor,
group: '1_merge',
order: 10,
}],
precondition: ctxIsMergeEditor,
});
}
run(accessor: ServicesAccessor): void {
const { activeEditorPane } = accessor.get(IEditorService);
if (activeEditorPane instanceof MergeEditor) {
activeEditorPane.setLayoutKind('columns');
}
}
}
export class ShowNonConflictingChanges extends Action2 {
constructor() {
super({
id: 'merge.showNonConflictingChanges',
title: {
value: localize('showNonConflictingChanges', 'Show Non-Conflicting Changes'),
original: 'Show Non-Conflicting Changes',
},
toggled: ctxMergeEditorShowNonConflictingChanges.isEqualTo(true),
menu: [
{
id: MenuId.EditorTitle,
when: ctxIsMergeEditor,
group: '3_merge',
order: 9,
},
],
precondition: ctxIsMergeEditor,
});
}
run(accessor: ServicesAccessor): void {
const { activeEditorPane } = accessor.get(IEditorService);
if (activeEditorPane instanceof MergeEditor) {
activeEditorPane.toggleShowNonConflictingChanges();
}
}
}
export class ShowHideBase extends Action2 {
constructor() {
super({
id: 'merge.showBase',
title: {
value: localize('layout.showBase', 'Show Base'),
original: 'Show Base',
},
toggled: ctxMergeEditorShowBase.isEqualTo(true),
menu: [
{
id: MenuId.EditorTitle,
when: ContextKeyExpr.and(ctxIsMergeEditor, ctxMergeEditorLayout.isEqualTo('columns')),
group: '2_merge',
order: 9,
},
]
});
}
run(accessor: ServicesAccessor): void {
const { activeEditorPane } = accessor.get(IEditorService);
if (activeEditorPane instanceof MergeEditor) {
activeEditorPane.toggleBase();
}
}
}
export class ShowHideTopBase extends Action2 {
constructor() {
super({
id: 'merge.showBaseTop',
title: {
value: localize('layout.showBaseTop', 'Show Base Top'),
original: 'Show Base Top',
},
toggled: ContextKeyExpr.and(ctxMergeEditorShowBase, ctxMergeEditorShowBaseAtTop),
menu: [
{
id: MenuId.EditorTitle,
when: ContextKeyExpr.and(ctxIsMergeEditor, ctxMergeEditorLayout.isEqualTo('mixed')),
group: '2_merge',
order: 10,
},
],
});
}
run(accessor: ServicesAccessor): void {
const { activeEditorPane } = accessor.get(IEditorService);
if (activeEditorPane instanceof MergeEditor) {
activeEditorPane.toggleShowBaseTop();
}
}
}
export class ShowHideCenterBase extends Action2 {
constructor() {
super({
id: 'merge.showBaseCenter',
title: {
value: localize('layout.showBaseCenter', 'Show Base Center'),
original: 'Show Base Center',
},
toggled: ContextKeyExpr.and(ctxMergeEditorShowBase, ctxMergeEditorShowBaseAtTop.negate()),
menu: [
{
id: MenuId.EditorTitle,
when: ContextKeyExpr.and(ctxIsMergeEditor, ctxMergeEditorLayout.isEqualTo('mixed')),
group: '2_merge',
order: 11,
},
],
});
}
run(accessor: ServicesAccessor): void {
const { activeEditorPane } = accessor.get(IEditorService);
if (activeEditorPane instanceof MergeEditor) {
activeEditorPane.toggleShowBaseCenter();
}
}
}
const mergeEditorCategory: ILocalizedString = {
value: localize('mergeEditor', 'Merge Editor'),
original: 'Merge Editor',
};
export class OpenResultResource extends MergeEditorAction {
constructor() {
super({
id: 'merge.openResult',
icon: Codicon.goToFile,
title: {
value: localize('openfile', 'Open File'),
original: 'Open File',
},
category: mergeEditorCategory,
menu: [{
id: MenuId.EditorTitle,
when: ctxIsMergeEditor,
group: 'navigation',
order: 1,
}],
precondition: ctxIsMergeEditor,
});
}
override runWithViewModel(viewModel: MergeEditorViewModel, accessor: ServicesAccessor): void {
const editorService = accessor.get(IEditorService);
editorService.openEditor({ resource: viewModel.model.resultTextModel.uri });
}
}
export class GoToNextUnhandledConflict extends MergeEditorAction {
constructor() {
super({
id: 'merge.goToNextUnhandledConflict',
category: mergeEditorCategory,
title: {
value: localize('merge.goToNextUnhandledConflict', 'Go to Next Unhandled Conflict'),
original: 'Go to Next Unhandled Conflict',
},
icon: Codicon.arrowDown,
menu: [
{
id: MenuId.EditorTitle,
when: ctxIsMergeEditor,
group: 'navigation',
order: 3
},
],
f1: true,
precondition: ctxIsMergeEditor,
});
}
override runWithViewModel(viewModel: MergeEditorViewModel): void {
viewModel.model.telemetry.reportNavigationToNextConflict();
viewModel.goToNextModifiedBaseRange(r => !viewModel.model.isHandled(r).get());
}
}
export class GoToPreviousUnhandledConflict extends MergeEditorAction {
constructor() {
super({
id: 'merge.goToPreviousUnhandledConflict',
category: mergeEditorCategory,
title: {
value: localize(
'merge.goToPreviousUnhandledConflict',
'Go to Previous Unhandled Conflict'
),
original: 'Go to Previous Unhandled Conflict',
},
icon: Codicon.arrowUp,
menu: [
{
id: MenuId.EditorTitle,
when: ctxIsMergeEditor,
group: 'navigation',
order: 2
},
],
f1: true,
precondition: ctxIsMergeEditor,
});
}
override runWithViewModel(viewModel: MergeEditorViewModel): void {
viewModel.model.telemetry.reportNavigationToPreviousConflict();
viewModel.goToPreviousModifiedBaseRange(r => !viewModel.model.isHandled(r).get());
}
}
export class ToggleActiveConflictInput1 extends MergeEditorAction {
constructor() {
super({
id: 'merge.toggleActiveConflictInput1',
category: mergeEditorCategory,
title: {
value: localize(
'merge.toggleCurrentConflictFromLeft',
'Toggle Current Conflict from Left'
),
original: 'Toggle Current Conflict from Left',
},
f1: true,
precondition: ctxIsMergeEditor,
});
}
override runWithViewModel(viewModel: MergeEditorViewModel): void {
viewModel.toggleActiveConflict(1);
}
}
export class ToggleActiveConflictInput2 extends MergeEditorAction {
constructor() {
super({
id: 'merge.toggleActiveConflictInput2',
category: mergeEditorCategory,
title: {
value: localize(
'merge.toggleCurrentConflictFromRight',
'Toggle Current Conflict from Right'
),
original: 'Toggle Current Conflict from Right',
},
f1: true,
precondition: ctxIsMergeEditor,
});
}
override runWithViewModel(viewModel: MergeEditorViewModel): void {
viewModel.toggleActiveConflict(2);
}
}
export class CompareInput1WithBaseCommand extends MergeEditorAction {
constructor() {
super({
id: 'mergeEditor.compareInput1WithBase',
category: mergeEditorCategory,
title: {
value: localize(
'mergeEditor.compareInput1WithBase',
'Compare Input 1 With Base'
),
original: 'Compare Input 1 With Base',
},
shortTitle: localize('mergeEditor.compareWithBase', 'Compare With Base'),
f1: true,
precondition: ctxIsMergeEditor,
menu: { id: MenuId.MergeInput1Toolbar }
});
}
override runWithViewModel(viewModel: MergeEditorViewModel, accessor: ServicesAccessor): void {
const editorService = accessor.get(IEditorService);
mergeEditorCompare(viewModel, editorService, 1);
}
}
export class CompareInput2WithBaseCommand extends MergeEditorAction {
constructor() {
super({
id: 'mergeEditor.compareInput2WithBase',
category: mergeEditorCategory,
title: {
value: localize(
'mergeEditor.compareInput2WithBase',
'Compare Input 2 With Base'
),
original: 'Compare Input 2 With Base',
},
shortTitle: localize('mergeEditor.compareWithBase', 'Compare With Base'),
f1: true,
precondition: ctxIsMergeEditor,
menu: { id: MenuId.MergeInput2Toolbar }
});
}
override runWithViewModel(viewModel: MergeEditorViewModel, accessor: ServicesAccessor): void {
const editorService = accessor.get(IEditorService);
mergeEditorCompare(viewModel, editorService, 2);
}
}
async function mergeEditorCompare(viewModel: MergeEditorViewModel, editorService: IEditorService, inputNumber: 1 | 2) {
editorService.openEditor(editorService.activeEditor!, { pinned: true });
const model = viewModel.model;
const base = model.base;
const input = inputNumber === 1 ? viewModel.inputCodeEditorView1.editor : viewModel.inputCodeEditorView2.editor;
const lineNumber = input.getPosition()!.lineNumber;
await editorService.openEditor({
original: { resource: base.uri },
modified: { resource: input.getModel()!.uri },
options: {
selection: {
startLineNumber: lineNumber,
startColumn: 1,
},
revealIfOpened: true,
revealIfVisible: true,
} as ITextEditorOptions
});
}
export class OpenBaseFile extends MergeEditorAction {
constructor() {
super({
id: 'merge.openBaseEditor',
category: mergeEditorCategory,
title: {
value: localize('merge.openBaseEditor', 'Open Base File'),
original: 'Open Base File',
},
f1: true,
precondition: ctxIsMergeEditor,
});
}
override runWithViewModel(viewModel: MergeEditorViewModel, accessor: ServicesAccessor): void {
const openerService = accessor.get(IOpenerService);
openerService.open(viewModel.model.base.uri);
}
}
export class AcceptAllInput1 extends MergeEditorAction {
constructor() {
super({
id: 'merge.acceptAllInput1',
category: mergeEditorCategory,
title: {
value: localize(
'merge.acceptAllInput1',
'Accept All Changes from Left'
),
original: 'Accept All Changes from Left',
},
f1: true,
precondition: ctxIsMergeEditor,
menu: [
{ id: MenuId.MergeInput1Toolbar, }
]
});
}
override runWithViewModel(viewModel: MergeEditorViewModel): void {
viewModel.acceptAll(1);
}
}
export class AcceptAllInput2 extends MergeEditorAction {
constructor() {
super({
id: 'merge.acceptAllInput2',
category: mergeEditorCategory,
title: {
value: localize(
'merge.acceptAllInput2',
'Accept All Changes from Right'
),
original: 'Accept All Changes from Right',
},
f1: true,
precondition: ctxIsMergeEditor,
menu: [
{ id: MenuId.MergeInput2Toolbar, }
]
});
}
override runWithViewModel(viewModel: MergeEditorViewModel): void {
viewModel.acceptAll(2);
}
}
export class ResetToBaseAndAutoMergeCommand extends MergeEditorAction {
constructor() {
super({
id: 'mergeEditor.resetResultToBaseAndAutoMerge',
category: mergeEditorCategory,
title: {
value: localize(
'mergeEditor.resetResultToBaseAndAutoMerge',
'Reset Result'
),
original: 'Reset Result',
},
shortTitle: localize('mergeEditor.resetResultToBaseAndAutoMerge.short', 'Reset'),
f1: true,
precondition: ctxIsMergeEditor,
menu: { id: MenuId.MergeInputResultToolbar }
});
}
override runWithViewModel(viewModel: MergeEditorViewModel, accessor: ServicesAccessor): void {
viewModel.model.reset();
}
}
export class ResetCloseWithConflictsChoice extends Action2 {
constructor() {
super({
id: 'mergeEditor.resetCloseWithConflictsChoice',
category: mergeEditorCategory,
title: {
value: localize(
'mergeEditor.resetChoice',
'Reset Choice for \'Close with Conflicts\''
),
original: 'Reset Choice for \'Close with Conflicts\'',
},
f1: true,
});
}
run(accessor: ServicesAccessor): void {
accessor.get(IStorageService).remove(StorageCloseWithConflicts, StorageScope.PROFILE);
}
}
// this is an API command
export class AcceptMerge extends MergeEditorAction2 {
constructor() {
super({
id: 'mergeEditor.acceptMerge',
category: mergeEditorCategory,
title: {
value: localize(
'mergeEditor.acceptMerge',
'Complete Merge'
),
original: 'Complete Merge',
},
f1: false,
precondition: ctxIsMergeEditor
});
}
override async runWithMergeEditor({ inputModel, editorIdentifier, viewModel }: MergeEditorAction2Args, accessor: ServicesAccessor) {
const dialogService = accessor.get(IDialogService);
const editorService = accessor.get(IEditorService);
if (viewModel.model.unhandledConflictsCount.get() > 0) {
const confirmResult = await dialogService.confirm({
type: 'info',
message: localize('mergeEditor.acceptMerge.unhandledConflicts.message', "Do you want to complete the merge of {0}?", basename(inputModel.resultUri)),
detail: localize('mergeEditor.acceptMerge.unhandledConflicts.detail', "The file contains unhandled conflicts."),
primaryButton: localize('mergeEditor.acceptMerge.unhandledConflicts.accept', "Complete with Conflicts"),
secondaryButton: localize('mergeEditor.acceptMerge.unhandledConflicts.cancel', "Cancel"),
});
if (!confirmResult.confirmed) {
return {
successful: false
};
}
}
await inputModel.accept();
await editorService.closeEditor(editorIdentifier);
return {
successful: true
};
}
}
| src/vs/workbench/contrib/mergeEditor/browser/commands/commands.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017855795158538967,
0.00017376009782310575,
0.00016401114407926798,
0.0001742531603667885,
0.000003177677854182548
] |
{
"id": 7,
"code_window": [
"\t}\n",
"\n",
"\tprivate _renderNow(splice: NotebookCellOutputsSplice) {\n",
"\t\tif (splice.start >= this.options.limit) {\n",
"\t\t\t// splice items out of limit\n",
"\t\t\treturn;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _renderNow(splice: NotebookCellOutputsSplice, context: CellOutputUpdateContext) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 561
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
import { renderMarkdown } from 'vs/base/browser/markdownRenderer';
import { Action, IAction } from 'vs/base/common/actions';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import * as nls from 'vs/nls';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { WorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { IMenuService, MenuId } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSION_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellOutputViewModel, ICellViewModel, IInsetRenderOutput, INotebookEditorDelegate, JUPYTER_EXTENSION_ID, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { mimetypeIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';
import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
interface IRenderResult {
initRenderIsSynchronous: false;
}
// DOM structure
//
// #output
// |
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | | #output-element
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
class CellOutputElement extends Disposable {
private readonly _renderDisposableStore = this._register(new DisposableStore());
innerContainer?: HTMLElement;
renderedOutputContainer!: HTMLElement;
renderResult?: IInsetRenderOutput;
private readonly contextKeyService: IContextKeyService;
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private cellOutputContainer: CellOutputContainer,
private outputContainer: FastDomNode<HTMLElement>,
readonly output: ICellOutputViewModel,
@INotebookService private readonly notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@IContextKeyService parentContextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this.contextKeyService = parentContextKeyService;
this._register(this.output.model.onDidChangeData(() => {
this.rerender();
}));
this._register(this.output.onDidResetRenderer(() => {
this.rerender();
}));
}
detach() {
this.renderedOutputContainer?.parentElement?.removeChild(this.renderedOutputContainer);
let count = 0;
if (this.innerContainer) {
for (let i = 0; i < this.innerContainer.childNodes.length; i++) {
if ((this.innerContainer.childNodes[i] as HTMLElement).className === 'rendered-output') {
count++;
}
if (count > 1) {
break;
}
}
if (count === 0) {
this.innerContainer.parentElement?.removeChild(this.innerContainer);
}
}
this.notebookEditor.removeInset(this.output);
}
updateDOMTop(top: number) {
if (this.innerContainer) {
this.innerContainer.style.top = `${top}px`;
}
}
rerender() {
if (
this.notebookEditor.hasModel() &&
this.innerContainer &&
this.renderResult &&
this.renderResult.type === RenderOutputType.Extension
) {
// Output rendered by extension renderer got an update
const [mimeTypes, pick] = this.output.resolveMimeTypes(this.notebookEditor.textModel, this.notebookEditor.activeKernel?.preloadProvides);
const pickedMimeType = mimeTypes[pick];
if (pickedMimeType.mimeType === this.renderResult.mimeType && pickedMimeType.rendererId === this.renderResult.renderer.id) {
// Same mimetype, same renderer, call the extension renderer to update
const index = this.viewCell.outputsViewModels.indexOf(this.output);
this.notebookEditor.updateOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
return;
}
}
if (!this.innerContainer) {
// init rendering didn't happen
const currOutputIndex = this.cellOutputContainer.renderedOutputEntries.findIndex(entry => entry.element === this);
const previousSibling = currOutputIndex > 0 && !!(this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer?.parentElement)
? this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer
: undefined;
this.render(previousSibling);
} else {
// Another mimetype or renderer is picked, we need to clear the current output and re-render
const nextElement = this.innerContainer.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(this.output);
}
this.render(nextElement as HTMLElement);
}
this._relayoutCell();
}
// insert after previousSibling
private _generateInnerOutputContainer(previousSibling: HTMLElement | undefined, pickedMimeTypeRenderer: IOrderedMimeType) {
this.innerContainer = DOM.$('.output-inner-container');
if (previousSibling && previousSibling.nextElementSibling) {
this.outputContainer.domNode.insertBefore(this.innerContainer, previousSibling.nextElementSibling);
} else {
this.outputContainer.domNode.appendChild(this.innerContainer);
}
this.innerContainer.setAttribute('output-mime-type', pickedMimeTypeRenderer.mimeType);
return this.innerContainer;
}
render(previousSibling: HTMLElement | undefined): IRenderResult | undefined {
const index = this.viewCell.outputsViewModels.indexOf(this.output);
if (this.viewCell.isOutputCollapsed || !this.notebookEditor.hasModel()) {
return undefined;
}
const notebookUri = CellUri.parse(this.viewCell.uri)?.notebook;
if (!notebookUri) {
return undefined;
}
const notebookTextModel = this.notebookEditor.textModel;
const [mimeTypes, pick] = this.output.resolveMimeTypes(notebookTextModel, this.notebookEditor.activeKernel?.preloadProvides);
if (!mimeTypes.find(mimeType => mimeType.isTrusted) || mimeTypes.length === 0) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#noMimeType');
return undefined;
}
const pickedMimeTypeRenderer = mimeTypes[pick];
const innerContainer = this._generateInnerOutputContainer(previousSibling, pickedMimeTypeRenderer);
this._attachToolbar(innerContainer, notebookTextModel, this.notebookEditor.activeKernel, index, mimeTypes);
this.renderedOutputContainer = DOM.append(innerContainer, DOM.$('.rendered-output'));
const renderer = this.notebookService.getRendererInfo(pickedMimeTypeRenderer.rendererId);
this.renderResult = renderer
? { type: RenderOutputType.Extension, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType }
: this._renderMissingRenderer(this.output, pickedMimeTypeRenderer.mimeType);
this.output.pickedMimeType = pickedMimeTypeRenderer;
if (!this.renderResult) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#renderResultUndefined');
return undefined;
}
this.notebookEditor.createOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
innerContainer.classList.add('background');
return { initRenderIsSynchronous: false };
}
private _renderMissingRenderer(viewModel: ICellOutputViewModel, preferredMimeType: string | undefined): IInsetRenderOutput {
if (!viewModel.model.outputs.length) {
return this._renderMessage(viewModel, nls.localize('empty', "Cell has no output"));
}
if (!preferredMimeType) {
const mimeTypes = viewModel.model.outputs.map(op => op.mime);
const mimeTypesMessage = mimeTypes.join(', ');
return this._renderMessage(viewModel, nls.localize('noRenderer.2', "No renderer could be found for output. It has the following mimetypes: {0}", mimeTypesMessage));
}
return this._renderSearchForMimetype(viewModel, preferredMimeType);
}
private _renderSearchForMimetype(viewModel: ICellOutputViewModel, mimeType: string): IInsetRenderOutput {
const query = `@tag:notebookRenderer ${mimeType}`;
const p = DOM.$('p', undefined, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
const a = DOM.$('a', { href: `command:workbench.extensions.search?%22${query}%22`, class: 'monaco-button monaco-text-button', tabindex: 0, role: 'button', style: 'padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;' }, `Search Marketplace`);
return {
type: RenderOutputType.Html,
source: viewModel,
htmlContent: p.outerHTML + a.outerHTML
};
}
private _renderMessage(viewModel: ICellOutputViewModel, message: string): IInsetRenderOutput {
const el = DOM.$('p', undefined, message);
return { type: RenderOutputType.Html, source: viewModel, htmlContent: el.outerHTML };
}
private async _attachToolbar(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, index: number, mimeTypes: readonly IOrderedMimeType[]) {
const hasMultipleMimeTypes = mimeTypes.filter(mimeType => mimeType.isTrusted).length <= 1;
if (index > 0 && hasMultipleMimeTypes) {
return;
}
if (!this.notebookEditor.hasModel()) {
return;
}
const useConsolidatedButton = this.notebookEditor.notebookOptions.getLayoutConfiguration().consolidatedOutputButton;
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.cell-output-toolbar');
outputItemDiv.appendChild(mimeTypePicker);
const toolbar = this._renderDisposableStore.add(this.instantiationService.createInstance(WorkbenchToolBar, mimeTypePicker, {
renderDropdownAsChildElement: false
}));
toolbar.context = <INotebookCellActionContext>{
ui: true,
cell: this.output.cellViewModel as ICellViewModel,
notebookEditor: this.notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
};
// TODO: This could probably be a real registered action, but it has to talk to this output element
const pickAction = new Action('notebook.output.pickMimetype', nls.localize('pickMimeType', "Change Presentation"), ThemeIcon.asClassName(mimetypeIcon), undefined,
async _context => this._pickActiveMimeTypeRenderer(outputItemDiv, notebookTextModel, kernel, this.output));
if (index === 0 && useConsolidatedButton) {
const menu = this._renderDisposableStore.add(this.menuService.createMenu(MenuId.NotebookOutputToolbar, this.contextKeyService));
const updateMenuToolbar = () => {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, result, () => false);
toolbar.setActions([], [pickAction, ...secondary]);
};
updateMenuToolbar();
this._renderDisposableStore.add(menu.onDidChange(updateMenuToolbar));
} else {
toolbar.setActions([pickAction]);
}
}
private async _pickActiveMimeTypeRenderer(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, viewModel: ICellOutputViewModel) {
const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, kernel?.preloadProvides);
const items: IMimeTypeRenderer[] = [];
const unsupportedItems: IMimeTypeRenderer[] = [];
mimeTypes.forEach((mimeType, index) => {
if (mimeType.isTrusted) {
const arr = mimeType.rendererId === RENDERER_NOT_AVAILABLE ?
unsupportedItems :
items;
arr.push({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
detail: this._generateRendererInfo(mimeType.rendererId),
description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined
});
}
});
if (unsupportedItems.some(m => JUPYTER_RENDERER_MIMETYPES.includes(m.id!))) {
unsupportedItems.push({
label: nls.localize('installJupyterPrompt', "Install additional renderers from the marketplace"),
id: 'installRenderers',
index: mimeTypes.length
});
}
const picker = this.quickInputService.createQuickPick();
picker.items = [
...items,
{ type: 'separator' },
...unsupportedItems
];
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = items.length !== mimeTypes.length
? nls.localize('promptChooseMimeTypeInSecure.placeHolder', "Select mimetype to render for current output")
: nls.localize('promptChooseMimeType.placeHolder', "Select mimetype to render for current output");
const pick = await new Promise<IMimeTypeRenderer | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer) : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined || pick.index === currIndex) {
return;
}
if (pick.id === 'installRenderers') {
this._showJupyterExtension();
return;
}
// user chooses another mimetype
const nextElement = outputItemDiv.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(viewModel);
}
viewModel.pickedMimeType = mimeTypes[pick.index];
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
const { mimeType, rendererId } = mimeTypes[pick.index];
this.notebookService.updateMimePreferredRenderer(notebookTextModel.viewType, mimeType, rendererId, mimeTypes.map(m => m.mimeType));
this.render(nextElement as HTMLElement);
this._validateFinalOutputHeight(false);
this._relayoutCell();
}
private async _showJupyterExtension() {
const viewlet = await this.paneCompositeService.openPaneComposite(EXTENSION_VIEWLET_ID, ViewContainerLocation.Sidebar, true);
const view = viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer | undefined;
view?.search(`@id:${JUPYTER_EXTENSION_ID}`);
}
private _generateRendererInfo(renderId: string): string {
const renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
const displayName = renderInfo.displayName !== '' ? renderInfo.displayName : renderInfo.id;
return `${displayName} (${renderInfo.extensionId.value})`;
}
return nls.localize('unavailableRenderInfo', "renderer not available");
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
if (this._outputHeightTimer) {
this.viewCell.unlockOutputHeight();
clearTimeout(this._outputHeightTimer);
}
super.dispose();
}
}
class OutputEntryViewHandler {
constructor(
readonly model: ICellOutputViewModel,
readonly element: CellOutputElement
) {
}
}
export class CellOutputContainer extends CellContentPart {
private _outputEntries: OutputEntryViewHandler[] = [];
get renderedOutputEntries() {
return this._outputEntries;
}
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private readonly templateData: CodeCellRenderTemplate,
private options: { limit: number },
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._register(viewCell.onDidChangeOutputs(splice => {
this._updateOutputs(splice);
}));
this._register(viewCell.onDidChangeLayout(() => {
this.updateInternalLayoutNow(viewCell);
}));
}
override updateInternalLayoutNow(viewCell: CodeCellViewModel) {
this.templateData.outputContainer.setTop(viewCell.layoutInfo.outputContainerOffset);
this.templateData.outputShowMoreContainer.setTop(viewCell.layoutInfo.outputShowMoreContainerOffset);
this._outputEntries.forEach(entry => {
const index = this.viewCell.outputsViewModels.indexOf(entry.model);
if (index >= 0) {
const top = this.viewCell.getOutputOffsetInContainer(index);
entry.element.updateDOMTop(top);
}
});
}
render() {
if (this.viewCell.outputsViewModels.length > 0) {
if (this.viewCell.layoutInfo.outputTotalHeight !== 0) {
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
this._relayoutCell();
}
DOM.show(this.templateData.outputContainer.domNode);
for (let index = 0; index < Math.min(this.options.limit, this.viewCell.outputsViewModels.length); index++) {
const currOutput = this.viewCell.outputsViewModels[index];
const entry = this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, currOutput);
this._outputEntries.push(new OutputEntryViewHandler(currOutput, entry));
entry.render(undefined);
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(46);
}
this._relayoutCell();
this._validateFinalOutputHeight(false);
} else {
// noop
this._relayoutCell();
DOM.hide(this.templateData.outputContainer.domNode);
}
this.templateData.outputShowMoreContainer.domNode.innerText = '';
if (this.viewCell.outputsViewModels.length > this.options.limit) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(0);
}
}
viewUpdateShowOutputs(initRendering: boolean): void {
for (let index = 0; index < this._outputEntries.length; index++) {
const viewHandler = this._outputEntries[index];
const outputEntry = viewHandler.element;
if (outputEntry.renderResult) {
this.notebookEditor.createOutput(this.viewCell, outputEntry.renderResult as IInsetRenderOutput, this.viewCell.getOutputOffset(index));
} else {
outputEntry.render(undefined);
}
}
this._relayoutCell();
}
viewUpdateHideOuputs(): void {
for (let index = 0; index < this._outputEntries.length; index++) {
this.notebookEditor.hideInset(this._outputEntries[index].model);
}
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _updateOutputs(splice: NotebookCellOutputsSplice) {
const previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;
// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.
this.viewCell.updateOutputMinHeight(previousOutputHeight);
if (this.viewCell.outputsViewModels.length) {
DOM.show(this.templateData.outputContainer.domNode);
} else {
DOM.hide(this.templateData.outputContainer.domNode);
}
this.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));
this._renderNow(splice);
}
private _renderNow(splice: NotebookCellOutputsSplice) {
if (splice.start >= this.options.limit) {
// splice items out of limit
return;
}
const firstGroupEntries = this._outputEntries.slice(0, splice.start);
const deletedEntries = this._outputEntries.slice(splice.start, splice.start + splice.deleteCount);
const secondGroupEntries = this._outputEntries.slice(splice.start + splice.deleteCount);
let newlyInserted = this.viewCell.outputsViewModels.slice(splice.start, splice.start + splice.newOutputs.length);
// [...firstGroup, ...deletedEntries, ...secondGroupEntries] [...restInModel]
// [...firstGroup, ...newlyInserted, ...secondGroupEntries, restInModel]
if (firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length > this.options.limit) {
// exceeds limit again
if (firstGroupEntries.length + newlyInserted.length > this.options.limit) {
[...deletedEntries, ...secondGroupEntries].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
newlyInserted = newlyInserted.slice(0, this.options.limit - firstGroupEntries.length);
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries];
// render newly inserted outputs
for (let i = firstGroupEntries.length; i < this._outputEntries.length; i++) {
this._outputEntries[i].element.render(undefined);
}
} else {
// part of secondGroupEntries are pushed out of view
// now we have to be creative as secondGroupEntries might not use dedicated containers
const elementsPushedOutOfView = secondGroupEntries.slice(this.options.limit - firstGroupEntries.length - newlyInserted.length);
[...deletedEntries, ...elementsPushedOutOfView].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
// exclusive
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries.slice(0, this.options.limit - firstGroupEntries.length - newlyInserted.length)];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
}
} else {
// after splice, it doesn't exceed
deletedEntries.forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
let outputsNewlyAvailable: OutputEntryViewHandler[] = [];
if (firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length < this.viewCell.outputsViewModels.length) {
const last = Math.min(this.options.limit, this.viewCell.outputsViewModels.length);
outputsNewlyAvailable = this.viewCell.outputsViewModels.slice(firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length, last).map(output => {
return new OutputEntryViewHandler(output, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, output));
});
}
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries, ...outputsNewlyAvailable];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
for (let i = 0; i < outputsNewlyAvailable.length; i++) {
this._outputEntries[firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length + i].element.render(undefined);
}
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
if (!this.templateData.outputShowMoreContainer.domNode.hasChildNodes()) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
}
this.viewCell.updateOutputShowMoreContainerHeight(46);
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
}
const editorHeight = this.templateData.editor.getContentHeight();
this.viewCell.editorHeight = editorHeight;
this._relayoutCell();
// if it's clearing all outputs, or outputs are all rendered synchronously
// shrink immediately as the final output height will be zero.
this._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);
}
private _generateShowMoreElement(disposables: DisposableStore): HTMLElement {
const md: IMarkdownString = {
value: `There are more than ${this.options.limit} outputs, [show more (open the raw output data in a text editor) ...](command:workbench.action.openLargeOutput)`,
isTrusted: true,
supportThemeIcons: true
};
const rendered = renderMarkdown(md, {
actionHandler: {
callback: (content) => {
if (content === 'command:workbench.action.openLargeOutput') {
this.openerService.open(CellUri.generateCellOutputUri(this.notebookEditor.textModel!.uri));
}
return;
},
disposables
}
});
disposables.add(rendered);
rendered.element.classList.add('output-show-more');
return rendered.element;
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
this.viewCell.updateOutputMinHeight(0);
if (this._outputHeightTimer) {
clearTimeout(this._outputHeightTimer);
}
this._outputEntries.forEach(entry => {
entry.element.dispose();
});
super.dispose();
}
}
const JUPYTER_RENDERER_MIMETYPES = [
'application/geo+json',
'application/vdom.v1+json',
'application/vnd.dataresource+json',
'application/vnd.plotly.v1+json',
'application/vnd.vega.v2+json',
'application/vnd.vega.v3+json',
'application/vnd.vega.v4+json',
'application/vnd.vega.v5+json',
'application/vnd.vegalite.v1+json',
'application/vnd.vegalite.v2+json',
'application/vnd.vegalite.v3+json',
'application/vnd.vegalite.v4+json',
'application/x-nteract-model-debug+json',
'image/svg+xml',
'text/latex',
'text/vnd.plotly.v1+html',
'application/vnd.jupyter.widget-view+json',
'application/vnd.code.notebook.error'
];
| src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.998740017414093,
0.030506378039717674,
0.00016458405298180878,
0.00019524549134075642,
0.16078265011310577
] |
{
"id": 7,
"code_window": [
"\t}\n",
"\n",
"\tprivate _renderNow(splice: NotebookCellOutputsSplice) {\n",
"\t\tif (splice.start >= this.options.limit) {\n",
"\t\t\t// splice items out of limit\n",
"\t\t\treturn;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _renderNow(splice: NotebookCellOutputsSplice, context: CellOutputUpdateContext) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 561
} | {
"information_for_contributors": [
"This file has been converted from https://github.com/atom/language-coffee-script/blob/master/grammars/coffeescript.cson",
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/atom/language-coffee-script/commit/0f6db9143663e18b1ad00667820f46747dba495e",
"name": "CoffeeScript",
"scopeName": "source.coffee",
"patterns": [
{
"include": "#jsx"
},
{
"match": "(new)\\s+(?:(?:(class)\\s+(\\w+(?:\\.\\w*)*)?)|(\\w+(?:\\.\\w*)*))",
"name": "meta.class.instance.constructor.coffee",
"captures": {
"1": {
"name": "keyword.operator.new.coffee"
},
"2": {
"name": "storage.type.class.coffee"
},
"3": {
"name": "entity.name.type.instance.coffee"
},
"4": {
"name": "entity.name.type.instance.coffee"
}
}
},
{
"begin": "'''",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.coffee"
}
},
"end": "'''",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.coffee"
}
},
"name": "string.quoted.single.heredoc.coffee",
"patterns": [
{
"captures": {
"1": {
"name": "punctuation.definition.escape.backslash.coffee"
}
},
"match": "(\\\\).",
"name": "constant.character.escape.backslash.coffee"
}
]
},
{
"begin": "\"\"\"",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.coffee"
}
},
"end": "\"\"\"",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.coffee"
}
},
"name": "string.quoted.double.heredoc.coffee",
"patterns": [
{
"captures": {
"1": {
"name": "punctuation.definition.escape.backslash.coffee"
}
},
"match": "(\\\\).",
"name": "constant.character.escape.backslash.coffee"
},
{
"include": "#interpolated_coffee"
}
]
},
{
"match": "(`)(.*)(`)",
"name": "string.quoted.script.coffee",
"captures": {
"1": {
"name": "punctuation.definition.string.begin.coffee"
},
"2": {
"name": "source.js.embedded.coffee",
"patterns": [
{
"include": "source.js"
}
]
},
"3": {
"name": "punctuation.definition.string.end.coffee"
}
}
},
{
"begin": "(?<!#)###(?!#)",
"beginCaptures": {
"0": {
"name": "punctuation.definition.comment.coffee"
}
},
"end": "###",
"endCaptures": {
"0": {
"name": "punctuation.definition.comment.coffee"
}
},
"name": "comment.block.coffee",
"patterns": [
{
"match": "(?<=^|\\s)@\\w*(?=\\s)",
"name": "storage.type.annotation.coffee"
}
]
},
{
"begin": "#",
"beginCaptures": {
"0": {
"name": "punctuation.definition.comment.coffee"
}
},
"end": "$",
"name": "comment.line.number-sign.coffee"
},
{
"begin": "///",
"end": "(///)[gimuy]*",
"name": "string.regexp.multiline.coffee",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.coffee"
}
},
"endCaptures": {
"1": {
"name": "punctuation.definition.string.end.coffee"
}
},
"patterns": [
{
"include": "#heregexp"
}
]
},
{
"begin": "(?<![\\w$])(/)(?=(?![/*+?])(.+)(/)[gimuy]*(?!\\s*[\\w$/(]))",
"beginCaptures": {
"1": {
"name": "punctuation.definition.string.begin.coffee"
}
},
"end": "(/)[gimuy]*(?!\\s*[\\w$/(])",
"endCaptures": {
"1": {
"name": "punctuation.definition.string.end.coffee"
}
},
"name": "string.regexp.coffee",
"patterns": [
{
"include": "source.js.regexp"
}
]
},
{
"match": "\\b(?<![\\.\\$])(break|by|catch|continue|else|finally|for|in|of|if|return|switch|then|throw|try|unless|when|while|until|loop|do|export|import|default|from|as|yield|async|await|(?<=for)\\s+own)(?!\\s*:)\\b",
"name": "keyword.control.coffee"
},
{
"match": "\\b(?<![\\.\\$])(delete|instanceof|new|typeof)(?!\\s*:)\\b",
"name": "keyword.operator.$1.coffee"
},
{
"match": "\\b(?<![\\.\\$])(case|function|var|void|with|const|let|enum|native|__hasProp|__extends|__slice|__bind|__indexOf|implements|interface|package|private|protected|public|static)(?!\\s*:)\\b",
"name": "keyword.reserved.coffee"
},
{
"begin": "(?x)\n(?<=\\s|^)((@)?[a-zA-Z_$][\\w$]*)\n\\s*([:=])\\s*\n(?=(\\([^\\(\\)]*\\)\\s*)?[=-]>)",
"beginCaptures": {
"1": {
"name": "entity.name.function.coffee"
},
"2": {
"name": "variable.other.readwrite.instance.coffee"
},
"3": {
"name": "keyword.operator.assignment.coffee"
}
},
"end": "[=-]>",
"endCaptures": {
"0": {
"name": "storage.type.function.coffee"
}
},
"name": "meta.function.coffee",
"patterns": [
{
"include": "#function_params"
}
]
},
{
"begin": "(?x)\n(?<=\\s|^)(?:((')([^']*?)('))|((\")([^\"]*?)(\")))\n\\s*([:=])\\s*\n(?=(\\([^\\(\\)]*\\)\\s*)?[=-]>)",
"beginCaptures": {
"1": {
"name": "string.quoted.single.coffee"
},
"2": {
"name": "punctuation.definition.string.begin.coffee"
},
"3": {
"name": "entity.name.function.coffee"
},
"4": {
"name": "punctuation.definition.string.end.coffee"
},
"5": {
"name": "string.quoted.double.coffee"
},
"6": {
"name": "punctuation.definition.string.begin.coffee"
},
"7": {
"name": "entity.name.function.coffee"
},
"8": {
"name": "punctuation.definition.string.end.coffee"
},
"9": {
"name": "keyword.operator.assignment.coffee"
}
},
"end": "[=-]>",
"endCaptures": {
"0": {
"name": "storage.type.function.coffee"
}
},
"name": "meta.function.coffee",
"patterns": [
{
"include": "#function_params"
}
]
},
{
"begin": "(?=(\\([^\\(\\)]*\\)\\s*)?[=-]>)",
"end": "[=-]>",
"endCaptures": {
"0": {
"name": "storage.type.function.coffee"
}
},
"name": "meta.function.inline.coffee",
"patterns": [
{
"include": "#function_params"
}
]
},
{
"begin": "(?<=\\s|^)({)(?=[^'\"#]+?}[\\s\\]}]*=)",
"beginCaptures": {
"1": {
"name": "punctuation.definition.destructuring.begin.bracket.curly.coffee"
}
},
"end": "}",
"endCaptures": {
"0": {
"name": "punctuation.definition.destructuring.end.bracket.curly.coffee"
}
},
"name": "meta.variable.assignment.destructured.object.coffee",
"patterns": [
{
"include": "$self"
},
{
"match": "[a-zA-Z$_]\\w*",
"name": "variable.assignment.coffee"
}
]
},
{
"begin": "(?<=\\s|^)(\\[)(?=[^'\"#]+?\\][\\s\\]}]*=)",
"beginCaptures": {
"1": {
"name": "punctuation.definition.destructuring.begin.bracket.square.coffee"
}
},
"end": "\\]",
"endCaptures": {
"0": {
"name": "punctuation.definition.destructuring.end.bracket.square.coffee"
}
},
"name": "meta.variable.assignment.destructured.array.coffee",
"patterns": [
{
"include": "$self"
},
{
"match": "[a-zA-Z$_]\\w*",
"name": "variable.assignment.coffee"
}
]
},
{
"match": "\\b(?<!\\.|::)(true|on|yes)(?!\\s*[:=][^=])\\b",
"name": "constant.language.boolean.true.coffee"
},
{
"match": "\\b(?<!\\.|::)(false|off|no)(?!\\s*[:=][^=])\\b",
"name": "constant.language.boolean.false.coffee"
},
{
"match": "\\b(?<!\\.|::)null(?!\\s*[:=][^=])\\b",
"name": "constant.language.null.coffee"
},
{
"match": "\\b(?<!\\.|::)extends(?!\\s*[:=])\\b",
"name": "variable.language.coffee"
},
{
"match": "(?<!\\.)\\b(?<!\\$)(super|this|arguments)(?!\\s*[:=][^=]|\\$)\\b",
"name": "variable.language.$1.coffee"
},
{
"captures": {
"1": {
"name": "storage.type.class.coffee"
},
"2": {
"name": "keyword.control.inheritance.coffee"
},
"3": {
"name": "entity.other.inherited-class.coffee"
}
},
"match": "(?<=\\s|^|\\[|\\()(class)\\s+(extends)\\s+(@?[a-zA-Z\\$\\._][\\w\\.]*)",
"name": "meta.class.coffee"
},
{
"captures": {
"1": {
"name": "storage.type.class.coffee"
},
"2": {
"name": "entity.name.type.class.coffee"
},
"3": {
"name": "keyword.control.inheritance.coffee"
},
"4": {
"name": "entity.other.inherited-class.coffee"
}
},
"match": "(?<=\\s|^|\\[|\\()(class\\b)\\s+(@?[a-zA-Z\\$_][\\w\\.]*)?(?:\\s+(extends)\\s+(@?[a-zA-Z\\$\\._][\\w\\.]*))?",
"name": "meta.class.coffee"
},
{
"match": "\\b(debugger|\\\\)\\b",
"name": "keyword.other.coffee"
},
{
"match": "\\b(Array|ArrayBuffer|Blob|Boolean|Date|document|Function|Int(8|16|32|64)Array|Math|Map|Number|Object|Proxy|RegExp|Set|String|WeakMap|window|Uint(8|16|32|64)Array|XMLHttpRequest)\\b",
"name": "support.class.coffee"
},
{
"match": "\\b(console)\\b",
"name": "entity.name.type.object.coffee"
},
{
"match": "((?<=console\\.)(debug|warn|info|log|error|time|timeEnd|assert))\\b",
"name": "support.function.console.coffee"
},
{
"match": "((?<=\\.)(apply|call|concat|every|filter|forEach|from|hasOwnProperty|indexOf|isPrototypeOf|join|lastIndexOf|map|of|pop|propertyIsEnumerable|push|reduce(Right)?|reverse|shift|slice|some|sort|splice|to(Locale)?String|unshift|valueOf))\\b",
"name": "support.function.method.array.coffee"
},
{
"match": "((?<=Array\\.)(isArray))\\b",
"name": "support.function.static.array.coffee"
},
{
"match": "((?<=Object\\.)(create|definePropert(ies|y)|freeze|getOwnProperty(Descriptors?|Names)|getProperty(Descriptor|Names)|getPrototypeOf|is(Extensible|Frozen|Sealed)?|isnt|keys|preventExtensions|seal))\\b",
"name": "support.function.static.object.coffee"
},
{
"match": "((?<=Math\\.)(abs|acos|acosh|asin|asinh|atan|atan2|atanh|ceil|cos|cosh|exp|expm1|floor|hypot|log|log10|log1p|log2|max|min|pow|random|round|sign|sin|sinh|sqrt|tan|tanh|trunc))\\b",
"name": "support.function.static.math.coffee"
},
{
"match": "((?<=Number\\.)(is(Finite|Integer|NaN)|toInteger))\\b",
"name": "support.function.static.number.coffee"
},
{
"match": "(?<!\\.)\\b(module|exports|__filename|__dirname|global|process)(?!\\s*:)\\b",
"name": "support.variable.coffee"
},
{
"match": "\\b(Infinity|NaN|undefined)\\b",
"name": "constant.language.coffee"
},
{
"include": "#operators"
},
{
"include": "#method_calls"
},
{
"include": "#function_calls"
},
{
"include": "#numbers"
},
{
"include": "#objects"
},
{
"include": "#properties"
},
{
"match": "::",
"name": "keyword.operator.prototype.coffee"
},
{
"match": "(?<!\\$)\\b[0-9]+[\\w$]*",
"name": "invalid.illegal.identifier.coffee"
},
{
"match": ";",
"name": "punctuation.terminator.statement.coffee"
},
{
"match": ",",
"name": "punctuation.separator.delimiter.coffee"
},
{
"begin": "{",
"beginCaptures": {
"0": {
"name": "meta.brace.curly.coffee"
}
},
"end": "}",
"endCaptures": {
"0": {
"name": "meta.brace.curly.coffee"
}
},
"patterns": [
{
"include": "$self"
}
]
},
{
"begin": "\\[",
"beginCaptures": {
"0": {
"name": "punctuation.definition.array.begin.bracket.square.coffee"
}
},
"end": "\\]",
"endCaptures": {
"0": {
"name": "punctuation.definition.array.end.bracket.square.coffee"
}
},
"patterns": [
{
"match": "(?<!\\.)\\.{3}",
"name": "keyword.operator.slice.exclusive.coffee"
},
{
"match": "(?<!\\.)\\.{2}",
"name": "keyword.operator.slice.inclusive.coffee"
},
{
"include": "$self"
}
]
},
{
"begin": "\\(",
"beginCaptures": {
"0": {
"name": "meta.brace.round.coffee"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "meta.brace.round.coffee"
}
},
"patterns": [
{
"include": "$self"
}
]
},
{
"include": "#instance_variable"
},
{
"include": "#single_quoted_string"
},
{
"include": "#double_quoted_string"
}
],
"repository": {
"arguments": {
"patterns": [
{
"begin": "\\(",
"beginCaptures": {
"0": {
"name": "punctuation.definition.arguments.begin.bracket.round.coffee"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "punctuation.definition.arguments.end.bracket.round.coffee"
}
},
"name": "meta.arguments.coffee",
"patterns": [
{
"include": "$self"
}
]
},
{
"begin": "(?=(@|@?[\\w$]+|[=-]>|\\-\\d|\\[|{|\"|'))",
"end": "(?=\\s*(?<![\\w$])(of|in|then|is|isnt|and|or|for|else|when|if|unless|by|instanceof)(?![\\w$]))|(?=\\s*(}|\\]|\\)|#|$))",
"name": "meta.arguments.coffee",
"patterns": [
{
"include": "$self"
}
]
}
]
},
"double_quoted_string": {
"patterns": [
{
"begin": "\"",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.coffee"
}
},
"end": "\"",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.coffee"
}
},
"name": "string.quoted.double.coffee",
"patterns": [
{
"captures": {
"1": {
"name": "punctuation.definition.escape.backslash.coffee"
}
},
"match": "(\\\\)(x[0-9A-Fa-f]{2}|[0-2][0-7]{0,2}|3[0-6][0-7]|37[0-7]?|[4-7][0-7]?|.)",
"name": "constant.character.escape.backslash.coffee"
},
{
"include": "#interpolated_coffee"
}
]
}
]
},
"function_calls": {
"patterns": [
{
"begin": "(@)?([\\w$]+)(?=\\()",
"beginCaptures": {
"1": {
"name": "variable.other.readwrite.instance.coffee"
},
"2": {
"patterns": [
{
"include": "#function_names"
}
]
}
},
"end": "(?<=\\))",
"name": "meta.function-call.coffee",
"patterns": [
{
"include": "#arguments"
}
]
},
{
"begin": "(?x)\n(@)?([\\w$]+)\n\\s*\n(?=\\s+(?!(?<![\\w$])(of|in|then|is|isnt|and|or|for|else|when|if|unless|by|instanceof)(?![\\w$]))(?=(@?[\\w$]+|[=-]>|\\-\\d|\\[|{|\"|')))",
"beginCaptures": {
"1": {
"name": "variable.other.readwrite.instance.coffee"
},
"2": {
"patterns": [
{
"include": "#function_names"
}
]
}
},
"end": "(?=\\s*(?<![\\w$])(of|in|then|is|isnt|and|or|for|else|when|if|unless|by|instanceof)(?![\\w$]))|(?=\\s*(}|\\]|\\)|#|$))",
"name": "meta.function-call.coffee",
"patterns": [
{
"include": "#arguments"
}
]
}
]
},
"function_names": {
"patterns": [
{
"match": "(?x)\n\\b(isNaN|isFinite|eval|uneval|parseInt|parseFloat|decodeURI|\ndecodeURIComponent|encodeURI|encodeURIComponent|escape|unescape|\nrequire|set(Interval|Timeout)|clear(Interval|Timeout))\\b",
"name": "support.function.coffee"
},
{
"match": "[a-zA-Z_$][\\w$]*",
"name": "entity.name.function.coffee"
},
{
"match": "\\d[\\w$]*",
"name": "invalid.illegal.identifier.coffee"
}
]
},
"function_params": {
"patterns": [
{
"begin": "\\(",
"beginCaptures": {
"0": {
"name": "punctuation.definition.parameters.begin.bracket.round.coffee"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "punctuation.definition.parameters.end.bracket.round.coffee"
}
},
"name": "meta.parameters.coffee",
"patterns": [
{
"match": "([a-zA-Z_$][\\w$]*)(\\.\\.\\.)?",
"captures": {
"1": {
"name": "variable.parameter.function.coffee"
},
"2": {
"name": "keyword.operator.splat.coffee"
}
}
},
{
"match": "(@(?:[a-zA-Z_$][\\w$]*)?)(\\.\\.\\.)?",
"captures": {
"1": {
"name": "variable.parameter.function.readwrite.instance.coffee"
},
"2": {
"name": "keyword.operator.splat.coffee"
}
}
},
{
"include": "$self"
}
]
}
]
},
"embedded_comment": {
"patterns": [
{
"captures": {
"1": {
"name": "punctuation.definition.comment.coffee"
}
},
"match": "(?<!\\\\)(#).*$\\n?",
"name": "comment.line.number-sign.coffee"
}
]
},
"instance_variable": {
"patterns": [
{
"match": "(@)([a-zA-Z_\\$]\\w*)?",
"name": "variable.other.readwrite.instance.coffee"
}
]
},
"interpolated_coffee": {
"patterns": [
{
"begin": "\\#\\{",
"captures": {
"0": {
"name": "punctuation.section.embedded.coffee"
}
},
"end": "\\}",
"name": "source.coffee.embedded.source",
"patterns": [
{
"include": "$self"
}
]
}
]
},
"method_calls": {
"patterns": [
{
"begin": "(?:(\\.)|(::))\\s*([\\w$]+)\\s*(?=\\()",
"beginCaptures": {
"1": {
"name": "punctuation.separator.method.period.coffee"
},
"2": {
"name": "keyword.operator.prototype.coffee"
},
"3": {
"patterns": [
{
"include": "#method_names"
}
]
}
},
"end": "(?<=\\))",
"name": "meta.method-call.coffee",
"patterns": [
{
"include": "#arguments"
}
]
},
{
"begin": "(?:(\\.)|(::))\\s*([\\w$]+)\\s*(?=\\s+(?!(?<![\\w$])(of|in|then|is|isnt|and|or|for|else|when|if|unless|by|instanceof)(?![\\w$]))(?=(@|@?[\\w$]+|[=-]>|\\-\\d|\\[|{|\"|')))",
"beginCaptures": {
"1": {
"name": "punctuation.separator.method.period.coffee"
},
"2": {
"name": "keyword.operator.prototype.coffee"
},
"3": {
"patterns": [
{
"include": "#method_names"
}
]
}
},
"end": "(?=\\s*(?<![\\w$])(of|in|then|is|isnt|and|or|for|else|when|if|unless|by|instanceof)(?![\\w$]))|(?=\\s*(}|\\]|\\)|#|$))",
"name": "meta.method-call.coffee",
"patterns": [
{
"include": "#arguments"
}
]
}
]
},
"method_names": {
"patterns": [
{
"match": "(?x)\n\\bon(Rowsinserted|Rowsdelete|Rowenter|Rowexit|Resize|Resizestart|Resizeend|Reset|\nReadystatechange|Mouseout|Mouseover|Mousedown|Mouseup|Mousemove|\nBefore(cut|deactivate|unload|update|paste|print|editfocus|activate)|\nBlur|Scrolltop|Submit|Select|Selectstart|Selectionchange|Hover|Help|\nChange|Contextmenu|Controlselect|Cut|Cellchange|Clock|Close|Deactivate|\nDatasetchanged|Datasetcomplete|Dataavailable|Drop|Drag|Dragstart|Dragover|\nDragdrop|Dragenter|Dragend|Dragleave|Dblclick|Unload|Paste|Propertychange|Error|\nErrorupdate|Keydown|Keyup|Keypress|Focus|Load|Activate|Afterupdate|Afterprint|Abort)\\b",
"name": "support.function.event-handler.coffee"
},
{
"match": "(?x)\n\\b(shift|showModelessDialog|showModalDialog|showHelp|scroll|scrollX|scrollByPages|\nscrollByLines|scrollY|scrollTo|stop|strike|sizeToContent|sidebar|signText|sort|\nsup|sub|substr|substring|splice|split|send|set(Milliseconds|Seconds|Minutes|Hours|\nMonth|Year|FullYear|Date|UTC(Milliseconds|Seconds|Minutes|Hours|Month|FullYear|Date)|\nTime|Hotkeys|Cursor|ZOptions|Active|Resizable|RequestHeader)|search|slice|\nsavePreferences|small|home|handleEvent|navigate|char|charCodeAt|charAt|concat|\ncontextual|confirm|compile|clear|captureEvents|call|createStyleSheet|createPopup|\ncreateEventObject|to(GMTString|UTCString|String|Source|UpperCase|LowerCase|LocaleString)|\ntest|taint|taintEnabled|indexOf|italics|disableExternalCapture|dump|detachEvent|unshift|\nuntaint|unwatch|updateCommands|join|javaEnabled|pop|push|plugins.refresh|paddings|parse|\nprint|prompt|preference|enableExternalCapture|exec|execScript|valueOf|UTC|find|file|\nfileModifiedDate|fileSize|fileCreatedDate|fileUpdatedDate|fixed|fontsize|fontcolor|\nforward|fromCharCode|watch|link|load|lastIndexOf|anchor|attachEvent|atob|apply|alert|\nabort|routeEvents|resize|resizeBy|resizeTo|recalc|returnValue|replace|reverse|reload|\nreleaseCapture|releaseEvents|go|get(Milliseconds|Seconds|Minutes|Hours|Month|Day|Year|FullYear|\nTime|Date|TimezoneOffset|UTC(Milliseconds|Seconds|Minutes|Hours|Day|Month|FullYear|Date)|\nAttention|Selection|ResponseHeader|AllResponseHeaders)|moveBy|moveBelow|moveTo|\nmoveToAbsolute|moveAbove|mergeAttributes|match|margins|btoa|big|bold|borderWidths|blink|back)\\b",
"name": "support.function.coffee"
},
{
"match": "(?x)\n\\b(acceptNode|add|addEventListener|addTextTrack|adoptNode|after|animate|append|\nappendChild|appendData|before|blur|canPlayType|captureStream|\ncaretPositionFromPoint|caretRangeFromPoint|checkValidity|clear|click|\ncloneContents|cloneNode|cloneRange|close|closest|collapse|\ncompareBoundaryPoints|compareDocumentPosition|comparePoint|contains|\nconvertPointFromNode|convertQuadFromNode|convertRectFromNode|createAttribute|\ncreateAttributeNS|createCaption|createCDATASection|createComment|\ncreateContextualFragment|createDocument|createDocumentFragment|\ncreateDocumentType|createElement|createElementNS|createEntityReference|\ncreateEvent|createExpression|createHTMLDocument|createNodeIterator|\ncreateNSResolver|createProcessingInstruction|createRange|createShadowRoot|\ncreateTBody|createTextNode|createTFoot|createTHead|createTreeWalker|delete|\ndeleteCaption|deleteCell|deleteContents|deleteData|deleteRow|deleteTFoot|\ndeleteTHead|detach|disconnect|dispatchEvent|elementFromPoint|elementsFromPoint|\nenableStyleSheetsForSet|entries|evaluate|execCommand|exitFullscreen|\nexitPointerLock|expand|extractContents|fastSeek|firstChild|focus|forEach|get|\ngetAll|getAnimations|getAttribute|getAttributeNames|getAttributeNode|\ngetAttributeNodeNS|getAttributeNS|getBoundingClientRect|getBoxQuads|\ngetClientRects|getContext|getDestinationInsertionPoints|getElementById|\ngetElementsByClassName|getElementsByName|getElementsByTagName|\ngetElementsByTagNameNS|getItem|getNamedItem|getSelection|getStartDate|\ngetVideoPlaybackQuality|has|hasAttribute|hasAttributeNS|hasAttributes|\nhasChildNodes|hasFeature|hasFocus|importNode|initEvent|insertAdjacentElement|\ninsertAdjacentHTML|insertAdjacentText|insertBefore|insertCell|insertData|\ninsertNode|insertRow|intersectsNode|isDefaultNamespace|isEqualNode|\nisPointInRange|isSameNode|item|key|keys|lastChild|load|lookupNamespaceURI|\nlookupPrefix|matches|move|moveAttribute|moveAttributeNode|moveChild|\nmoveNamedItem|namedItem|nextNode|nextSibling|normalize|observe|open|\nparentNode|pause|play|postMessage|prepend|preventDefault|previousNode|\npreviousSibling|probablySupportsContext|queryCommandEnabled|\nqueryCommandIndeterm|queryCommandState|queryCommandSupported|queryCommandValue|\nquerySelector|querySelectorAll|registerContentHandler|registerElement|\nregisterProtocolHandler|releaseCapture|releaseEvents|remove|removeAttribute|\nremoveAttributeNode|removeAttributeNS|removeChild|removeEventListener|\nremoveItem|replace|replaceChild|replaceData|replaceWith|reportValidity|\nrequestFullscreen|requestPointerLock|reset|scroll|scrollBy|scrollIntoView|\nscrollTo|seekToNextFrame|select|selectNode|selectNodeContents|set|setAttribute|\nsetAttributeNode|setAttributeNodeNS|setAttributeNS|setCapture|\nsetCustomValidity|setEnd|setEndAfter|setEndBefore|setItem|setNamedItem|\nsetRangeText|setSelectionRange|setSinkId|setStart|setStartAfter|setStartBefore|\nslice|splitText|stepDown|stepUp|stopImmediatePropagation|stopPropagation|\nsubmit|substringData|supports|surroundContents|takeRecords|terminate|toBlob|\ntoDataURL|toggle|toString|values|write|writeln)\\b",
"name": "support.function.dom.coffee"
},
{
"match": "[a-zA-Z_$][\\w$]*",
"name": "entity.name.function.coffee"
},
{
"match": "\\d[\\w$]*",
"name": "invalid.illegal.identifier.coffee"
}
]
},
"numbers": {
"patterns": [
{
"match": "\\b(?<!\\$)0(x|X)[0-9a-fA-F]+\\b(?!\\$)",
"name": "constant.numeric.hex.coffee"
},
{
"match": "\\b(?<!\\$)0(b|B)[01]+\\b(?!\\$)",
"name": "constant.numeric.binary.coffee"
},
{
"match": "\\b(?<!\\$)0(o|O)?[0-7]+\\b(?!\\$)",
"name": "constant.numeric.octal.coffee"
},
{
"match": "(?x)\n(?<!\\$)(?:\n (?:\\b[0-9]+(\\.)[0-9]+[eE][+-]?[0-9]+\\b)| # 1.1E+3\n (?:\\b[0-9]+(\\.)[eE][+-]?[0-9]+\\b)| # 1.E+3\n (?:\\B(\\.)[0-9]+[eE][+-]?[0-9]+\\b)| # .1E+3\n (?:\\b[0-9]+[eE][+-]?[0-9]+\\b)| # 1E+3\n (?:\\b[0-9]+(\\.)[0-9]+\\b)| # 1.1\n (?:\\b[0-9]+(?=\\.{2,3}))| # 1 followed by a slice\n (?:\\b[0-9]+(\\.)\\B)| # 1.\n (?:\\B(\\.)[0-9]+\\b)| # .1\n (?:\\b[0-9]+\\b(?!\\.)) # 1\n)(?!\\$)",
"captures": {
"0": {
"name": "constant.numeric.decimal.coffee"
},
"1": {
"name": "punctuation.separator.decimal.period.coffee"
},
"2": {
"name": "punctuation.separator.decimal.period.coffee"
},
"3": {
"name": "punctuation.separator.decimal.period.coffee"
},
"4": {
"name": "punctuation.separator.decimal.period.coffee"
},
"5": {
"name": "punctuation.separator.decimal.period.coffee"
},
"6": {
"name": "punctuation.separator.decimal.period.coffee"
}
}
}
]
},
"objects": {
"patterns": [
{
"match": "[A-Z][A-Z0-9_$]*(?=\\s*\\??(\\.\\s*[a-zA-Z_$]\\w*|::))",
"name": "constant.other.object.coffee"
},
{
"match": "[a-zA-Z_$][\\w$]*(?=\\s*\\??(\\.\\s*[a-zA-Z_$]\\w*|::))",
"name": "variable.other.object.coffee"
}
]
},
"operators": {
"patterns": [
{
"match": "(?:([a-zA-Z$_][\\w$]*)?\\s+|(?<![\\w$]))(and=|or=)",
"captures": {
"1": {
"name": "variable.assignment.coffee"
},
"2": {
"name": "keyword.operator.assignment.compound.coffee"
}
}
},
{
"match": "([a-zA-Z$_][\\w$]*)?\\s*(%=|\\+=|-=|\\*=|&&=|\\|\\|=|\\?=|(?<!\\()/=)",
"captures": {
"1": {
"name": "variable.assignment.coffee"
},
"2": {
"name": "keyword.operator.assignment.compound.coffee"
}
}
},
{
"match": "([a-zA-Z$_][\\w$]*)?\\s*(&=|\\^=|<<=|>>=|>>>=|\\|=)",
"captures": {
"1": {
"name": "variable.assignment.coffee"
},
"2": {
"name": "keyword.operator.assignment.compound.bitwise.coffee"
}
}
},
{
"match": "<<|>>>|>>",
"name": "keyword.operator.bitwise.shift.coffee"
},
{
"match": "!=|<=|>=|==|<|>",
"name": "keyword.operator.comparison.coffee"
},
{
"match": "&&|!|\\|\\|",
"name": "keyword.operator.logical.coffee"
},
{
"match": "&|\\||\\^|~",
"name": "keyword.operator.bitwise.coffee"
},
{
"match": "([a-zA-Z$_][\\w$]*)?\\s*(=|:(?!:))(?![>=])",
"captures": {
"1": {
"name": "variable.assignment.coffee"
},
"2": {
"name": "keyword.operator.assignment.coffee"
}
}
},
{
"match": "--",
"name": "keyword.operator.decrement.coffee"
},
{
"match": "\\+\\+",
"name": "keyword.operator.increment.coffee"
},
{
"match": "\\.\\.\\.",
"name": "keyword.operator.splat.coffee"
},
{
"match": "\\?",
"name": "keyword.operator.existential.coffee"
},
{
"match": "%|\\*|/|-|\\+",
"name": "keyword.operator.coffee"
},
{
"match": "(?x)\n\\b(?<![\\.\\$])\n(?:\n (and|or|not) # logical\n |\n (is|isnt) # comparison\n)\n(?!\\s*:)\\b",
"captures": {
"1": {
"name": "keyword.operator.logical.coffee"
},
"2": {
"name": "keyword.operator.comparison.coffee"
}
}
}
]
},
"properties": {
"patterns": [
{
"match": "(?:(\\.)|(::))\\s*([A-Z][A-Z0-9_$]*\\b\\$*)(?=\\s*\\??(\\.\\s*[a-zA-Z_$]\\w*|::))",
"captures": {
"1": {
"name": "punctuation.separator.property.period.coffee"
},
"2": {
"name": "keyword.operator.prototype.coffee"
},
"3": {
"name": "constant.other.object.property.coffee"
}
}
},
{
"match": "(?:(\\.)|(::))\\s*(\\$*[a-zA-Z_$][\\w$]*)(?=\\s*\\??(\\.\\s*[a-zA-Z_$]\\w*|::))",
"captures": {
"1": {
"name": "punctuation.separator.property.period.coffee"
},
"2": {
"name": "keyword.operator.prototype.coffee"
},
"3": {
"name": "variable.other.object.property.coffee"
}
}
},
{
"match": "(?:(\\.)|(::))\\s*([A-Z][A-Z0-9_$]*\\b\\$*)",
"captures": {
"1": {
"name": "punctuation.separator.property.period.coffee"
},
"2": {
"name": "keyword.operator.prototype.coffee"
},
"3": {
"name": "constant.other.property.coffee"
}
}
},
{
"match": "(?:(\\.)|(::))\\s*(\\$*[a-zA-Z_$][\\w$]*)",
"captures": {
"1": {
"name": "punctuation.separator.property.period.coffee"
},
"2": {
"name": "keyword.operator.prototype.coffee"
},
"3": {
"name": "variable.other.property.coffee"
}
}
},
{
"match": "(?:(\\.)|(::))\\s*([0-9][\\w$]*)",
"captures": {
"1": {
"name": "punctuation.separator.property.period.coffee"
},
"2": {
"name": "keyword.operator.prototype.coffee"
},
"3": {
"name": "invalid.illegal.identifier.coffee"
}
}
}
]
},
"single_quoted_string": {
"patterns": [
{
"begin": "'",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.coffee"
}
},
"end": "'",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.coffee"
}
},
"name": "string.quoted.single.coffee",
"patterns": [
{
"captures": {
"1": {
"name": "punctuation.definition.escape.backslash.coffee"
}
},
"match": "(\\\\)(x[0-9A-Fa-f]{2}|[0-2][0-7]{0,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)",
"name": "constant.character.escape.backslash.coffee"
}
]
}
]
},
"regex-character-class": {
"patterns": [
{
"match": "\\\\[wWsSdD]|\\.",
"name": "constant.character.character-class.regexp"
},
{
"match": "\\\\([0-7]{3}|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4})",
"name": "constant.character.numeric.regexp"
},
{
"match": "\\\\c[A-Z]",
"name": "constant.character.control.regexp"
},
{
"match": "\\\\.",
"name": "constant.character.escape.backslash.regexp"
}
]
},
"heregexp": {
"patterns": [
{
"match": "\\\\[bB]|\\^|\\$",
"name": "keyword.control.anchor.regexp"
},
{
"match": "\\\\[1-9]\\d*",
"name": "keyword.other.back-reference.regexp"
},
{
"match": "[?+*]|\\{(\\d+,\\d+|\\d+,|,\\d+|\\d+)\\}\\??",
"name": "keyword.operator.quantifier.regexp"
},
{
"match": "\\|",
"name": "keyword.operator.or.regexp"
},
{
"begin": "(\\()((\\?=)|(\\?!))",
"beginCaptures": {
"1": {
"name": "punctuation.definition.group.regexp"
},
"3": {
"name": "meta.assertion.look-ahead.regexp"
},
"4": {
"name": "meta.assertion.negative-look-ahead.regexp"
}
},
"end": "(\\))",
"endCaptures": {
"1": {
"name": "punctuation.definition.group.regexp"
}
},
"name": "meta.group.assertion.regexp",
"patterns": [
{
"include": "#heregexp"
}
]
},
{
"begin": "\\((\\?:)?",
"beginCaptures": {
"0": {
"name": "punctuation.definition.group.regexp"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "punctuation.definition.group.regexp"
}
},
"name": "meta.group.regexp",
"patterns": [
{
"include": "#heregexp"
}
]
},
{
"begin": "(\\[)(\\^)?",
"beginCaptures": {
"1": {
"name": "punctuation.definition.character-class.regexp"
},
"2": {
"name": "keyword.operator.negation.regexp"
}
},
"end": "(\\])",
"endCaptures": {
"1": {
"name": "punctuation.definition.character-class.regexp"
}
},
"name": "constant.other.character-class.set.regexp",
"patterns": [
{
"captures": {
"1": {
"name": "constant.character.numeric.regexp"
},
"2": {
"name": "constant.character.control.regexp"
},
"3": {
"name": "constant.character.escape.backslash.regexp"
},
"4": {
"name": "constant.character.numeric.regexp"
},
"5": {
"name": "constant.character.control.regexp"
},
"6": {
"name": "constant.character.escape.backslash.regexp"
}
},
"match": "(?:.|(\\\\(?:[0-7]{3}|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}))|(\\\\c[A-Z])|(\\\\.))\\-(?:[^\\]\\\\]|(\\\\(?:[0-7]{3}|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}))|(\\\\c[A-Z])|(\\\\.))",
"name": "constant.other.character-class.range.regexp"
},
{
"include": "#regex-character-class"
}
]
},
{
"include": "#regex-character-class"
},
{
"include": "#interpolated_coffee"
},
{
"include": "#embedded_comment"
}
]
},
"jsx": {
"patterns": [
{
"include": "#jsx-tag"
},
{
"include": "#jsx-end-tag"
}
]
},
"jsx-expression": {
"begin": "{",
"beginCaptures": {
"0": {
"name": "meta.brace.curly.coffee"
}
},
"end": "}",
"endCaptures": {
"0": {
"name": "meta.brace.curly.coffee"
}
},
"patterns": [
{
"include": "#double_quoted_string"
},
{
"include": "$self"
}
]
},
"jsx-attribute": {
"patterns": [
{
"captures": {
"1": {
"name": "entity.other.attribute-name.coffee"
},
"2": {
"name": "keyword.operator.assignment.coffee"
}
},
"match": "(?:^|\\s+)([-\\w.]+)\\s*(=)"
},
{
"include": "#double_quoted_string"
},
{
"include": "#single_quoted_string"
},
{
"include": "#jsx-expression"
}
]
},
"jsx-tag": {
"patterns": [
{
"begin": "(<)([-\\w\\.]+)",
"beginCaptures": {
"1": {
"name": "punctuation.definition.tag.coffee"
},
"2": {
"name": "entity.name.tag.coffee"
}
},
"end": "(/?>)",
"name": "meta.tag.coffee",
"patterns": [
{
"include": "#jsx-attribute"
}
]
}
]
},
"jsx-end-tag": {
"patterns": [
{
"begin": "(</)([-\\w\\.]+)",
"beginCaptures": {
"1": {
"name": "punctuation.definition.tag.coffee"
},
"2": {
"name": "entity.name.tag.coffee"
}
},
"end": "(/?>)",
"name": "meta.tag.coffee"
}
]
}
}
} | extensions/coffeescript/syntaxes/coffeescript.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017648075299803168,
0.00017259945161640644,
0.0001638526446186006,
0.0001728754141367972,
0.0000018984326288773445
] |
{
"id": 7,
"code_window": [
"\t}\n",
"\n",
"\tprivate _renderNow(splice: NotebookCellOutputsSplice) {\n",
"\t\tif (splice.start >= this.options.limit) {\n",
"\t\t\t// splice items out of limit\n",
"\t\t\treturn;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _renderNow(splice: NotebookCellOutputsSplice, context: CellOutputUpdateContext) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 561
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-icon-label.file-icon.workspacetrusteditor-name-file-icon.ext-file-icon.tab-label::before {
font-family: 'codicon';
content: '\eb53';
background-image: none;
font-size: 16px;
line-height: 37px !important;
}
.workspace-trust-editor {
max-width: 1000px;
padding-top: 11px;
margin: auto;
height: calc(100% - 11px);
}
.workspace-trust-editor:focus {
outline: none !important;
}
.workspace-trust-editor > .workspace-trust-header {
padding: 14px;
display: flex;
flex-direction: column;
align-items: center;
}
.workspace-trust-editor .workspace-trust-header .workspace-trust-title {
font-size: 24px;
font-weight: 600;
line-height: 32px;
padding: 10px 0px;
display: flex;
}
.workspace-trust-editor .workspace-trust-header .workspace-trust-title .workspace-trust-title-icon {
font-size: 32px;
margin-right: 8px;
}
.workspace-trust-editor .workspace-trust-header .workspace-trust-title .workspace-trust-title-icon {
color: var(--workspace-trust-selected-color) !important;
}
.workspace-trust-editor .workspace-trust-header .workspace-trust-description {
cursor: default;
user-select: text;
max-width: 600px;
text-align: center;
padding: 14px 0;
}
.workspace-trust-editor .workspace-trust-section-title {
font-weight: 600;
font-size: 18px;
padding-bottom: 5px;
}
.workspace-trust-editor .workspace-trust-subsection-title {
font-size: 16px;
font-weight: 600;
line-height: 32px;
}
.workspace-trust-editor .workspace-trust-editor-body {
height: 100%;
}
/** Features List */
.workspace-trust-editor .workspace-trust-features {
padding: 14px;
cursor: default;
user-select: text;
display: flex;
flex-direction: row;
flex-flow: wrap;
justify-content: space-evenly;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations {
min-height: 315px;
border: 1px solid var(--workspace-trust-unselected-color);
margin: 4px 4px;
display: flex;
flex-direction: column;
padding: 10px 40px;
}
.workspace-trust-editor.trusted .workspace-trust-features .workspace-trust-limitations.trusted,
.workspace-trust-editor.untrusted .workspace-trust-features .workspace-trust-limitations.untrusted {
border-width: 2px;
border-color: var(--workspace-trust-selected-color) !important;
padding: 9px 39px;
outline-offset: 2px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations ul {
list-style: none;
padding-inline-start: 0px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations li {
display: flex;
padding-bottom: 10px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations .list-item-icon {
padding-right: 5px;
line-height: 24px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations.trusted .list-item-icon {
color: var(--workspace-trust-check-color) !important;
font-size: 18px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations.untrusted .list-item-icon {
color: var(--workspace-trust-x-color) !important;
font-size: 20px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations .list-item-text {
font-size: 16px;
line-height: 24px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations-header {
display: flex;
flex-direction: column;
align-items: center;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations-header .workspace-trust-limitations-title {
font-size: 16px;
font-weight: 600;
line-height: 24px;
padding: 10px 0px;
display: flex;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations-header .workspace-trust-limitations-title .workspace-trust-title-icon {
font-size: 24px;
margin-right: 8px;
display: none;
}
.workspace-trust-editor.trusted .workspace-trust-features .workspace-trust-limitations.trusted .workspace-trust-limitations-header .workspace-trust-limitations-title .workspace-trust-title-icon,
.workspace-trust-editor.untrusted .workspace-trust-features .workspace-trust-limitations.untrusted .workspace-trust-limitations-header .workspace-trust-limitations-title .workspace-trust-title-icon {
display: unset;
color: var(--workspace-trust-selected-color) !important;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-untrusted-description {
font-style: italic;
padding-bottom: 10px;
}
/** Buttons Container */
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row {
display: flex;
align-items: center;
justify-content: center;
padding: 5px 0 10px 0;
overflow: hidden; /* buttons row should never overflow */
white-space: nowrap;
margin-top: auto;
}
/** Buttons */
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons,
.workspace-trust-editor .workspace-trust-settings .trusted-uris-button-bar {
display: flex;
overflow: hidden;
}
.workspace-trust-editor .workspace-trust-settings .trusted-uris-button-bar {
margin-top: 5px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons .monaco-button,
.workspace-trust-editor .workspace-trust-settings .trusted-uris-button-bar .monaco-button {
width: fit-content;
padding: 5px 10px;
overflow: hidden;
text-overflow: ellipsis;
outline-offset: 2px !important;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons > .monaco-button,
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons > .monaco-button-dropdown,
.workspace-trust-editor .workspace-trust-settings .trusted-uris-button-bar .monaco-button {
margin: 4px 5px; /* allows button focus outline to be visible */
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons .monaco-button-dropdown .monaco-dropdown-button {
padding: 5px;
}
.workspace-trust-limitations {
width: 50%;
max-width: 350px;
min-width: 250px;
flex: 1;
}
.workspace-trust-intro-dialog {
min-width: min(50vw, 500px);
padding-right: 24px;
}
.workspace-trust-intro-dialog .workspace-trust-dialog-image-row p {
display: flex;
align-items: center;
}
.workspace-trust-intro-dialog .workspace-trust-dialog-image-row.badge-row img {
max-height: 40px;
padding-right: 10px;
}
.workspace-trust-intro-dialog .workspace-trust-dialog-image-row.status-bar img {
max-height: 32px;
padding-right: 10px;
}
.workspace-trust-editor .workspace-trust-settings {
padding: 20px 14px;
}
.workspace-trust-editor .workspace-trust-settings .workspace-trusted-folders-title {
font-weight: 600;
}
.workspace-trust-editor .empty > .trusted-uris-table {
display: none;
}
.workspace-trust-editor .monaco-table-tr .monaco-table-td .path {
width: 100%;
}
.workspace-trust-editor .monaco-table-tr .monaco-table-td .path:not(.input-mode) .monaco-inputbox,
.workspace-trust-editor .monaco-table-tr .monaco-table-td .path.input-mode .path-label {
display: none;
}
.workspace-trust-editor .monaco-table-tr .monaco-table-td .current-workspace-parent .path-label,
.workspace-trust-editor .monaco-table-tr .monaco-table-td .current-workspace-parent .host-label {
font-weight: bold;
font-style: italic;
}
.workspace-trust-editor .monaco-table-th,
.workspace-trust-editor .monaco-table-td {
padding-left: 5px;
}
.workspace-trust-editor .workspace-trust-settings .monaco-action-bar .action-item > .codicon {
display: flex;
align-items: center;
justify-content: center;
color: inherit;
}
.workspace-trust-editor .workspace-trust-settings .monaco-table-tr .monaco-table-td {
align-items: center;
display: flex;
overflow: hidden;
}
.workspace-trust-editor .workspace-trust-settings .monaco-table-tr .monaco-table-td .host,
.workspace-trust-editor .workspace-trust-settings .monaco-table-tr .monaco-table-td .path {
max-width: 100%;
}
.workspace-trust-editor .workspace-trust-settings .monaco-table-tr .monaco-table-td .actions {
width: 100%;
}
.workspace-trust-editor .workspace-trust-settings .monaco-table-tr .monaco-table-td .actions .actions-container {
justify-content: flex-end;
padding-right: 3px;
}
.workspace-trust-editor .workspace-trust-settings .monaco-table-tr .monaco-table-td .monaco-button {
height: 18px;
padding-left: 8px;
padding-right: 8px;
}
.workspace-trust-editor .workspace-trust-settings .monaco-table-tr .monaco-table-td .actions .monaco-action-bar {
display: none;
flex: 1;
}
.workspace-trust-editor .workspace-trust-settings .monaco-list-row.selected .monaco-table-tr .monaco-table-td .actions .monaco-action-bar,
.workspace-trust-editor .workspace-trust-settings .monaco-table .monaco-list-row.focused .monaco-table-tr .monaco-table-td .actions .monaco-action-bar,
.workspace-trust-editor .workspace-trust-settings .monaco-list-row:hover .monaco-table-tr .monaco-table-td .actions .monaco-action-bar {
display: flex;
}
| src/vs/workbench/contrib/workspace/browser/media/workspaceTrustEditor.css | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017604310414753854,
0.00017053604824468493,
0.00016452254203613847,
0.00017105290316976607,
0.00000269428574029007
] |
{
"id": 7,
"code_window": [
"\t}\n",
"\n",
"\tprivate _renderNow(splice: NotebookCellOutputsSplice) {\n",
"\t\tif (splice.start >= this.options.limit) {\n",
"\t\t\t// splice items out of limit\n",
"\t\t\treturn;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _renderNow(splice: NotebookCellOutputsSplice, context: CellOutputUpdateContext) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 561
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution';
KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({
layout: { id: 'com.apple.inputmethod.Kotoeri.Japanese', lang: 'ja', localizedName: 'Hiragana' },
secondaryLayouts: [],
mapping: {
KeyA: ['a', 'A', 'å', 'Å', 0],
KeyB: ['b', 'B', '∫', 'ı', 0],
KeyC: ['c', 'C', 'ç', 'Ç', 0],
KeyD: ['d', 'D', '∂', 'Î', 0],
KeyE: ['e', 'E', '´', '´', 4],
KeyF: ['f', 'F', 'ƒ', 'Ï', 0],
KeyG: ['g', 'G', '©', '˝', 0],
KeyH: ['h', 'H', '˙', 'Ó', 0],
KeyI: ['i', 'I', 'ˆ', 'ˆ', 4],
KeyJ: ['j', 'J', '∆', 'Ô', 0],
KeyK: ['k', 'K', '˚', '', 0],
KeyL: ['l', 'L', '¬', 'Ò', 0],
KeyM: ['m', 'M', 'µ', 'Â', 0],
KeyN: ['n', 'N', '˜', '˜', 4],
KeyO: ['o', 'O', 'ø', 'Ø', 0],
KeyP: ['p', 'P', 'π', '∏', 0],
KeyQ: ['q', 'Q', 'œ', 'Œ', 0],
KeyR: ['r', 'R', '®', '‰', 0],
KeyS: ['s', 'S', 'ß', 'Í', 0],
KeyT: ['t', 'T', '†', 'ˇ', 0],
KeyU: ['u', 'U', '¨', '¨', 4],
KeyV: ['v', 'V', '√', '◊', 0],
KeyW: ['w', 'W', '∑', '„', 0],
KeyX: ['x', 'X', '≈', '˛', 0],
KeyY: ['y', 'Y', '¥', 'Á', 0],
KeyZ: ['z', 'Z', 'Ω', '¸', 0],
Digit1: ['1', '!', '¡', '⁄', 0],
Digit2: ['2', '@', '™', '€', 0],
Digit3: ['3', '#', '£', '‹', 0],
Digit4: ['4', '$', '¢', '›', 0],
Digit5: ['5', '%', '∞', 'fi', 0],
Digit6: ['6', '^', '§', 'fl', 0],
Digit7: ['7', '&', '¶', '‡', 0],
Digit8: ['8', '*', '•', '°', 0],
Digit9: ['9', '(', 'ª', '·', 0],
Digit0: ['0', ')', 'º', '‚', 0],
Enter: [],
Escape: [],
Backspace: [],
Tab: [],
Space: [' ', ' ', ' ', ' ', 0],
Minus: ['-', '_', '–', '—', 0],
Equal: ['=', '+', '≠', '±', 0],
BracketLeft: ['[', '{', '“', '”', 0],
BracketRight: [']', '}', '‘', '’', 0],
Backslash: ['\\', '|', '«', '»', 0],
Semicolon: [';', ':', '…', 'Ú', 0],
Quote: ['\'', '"', 'æ', 'Æ', 0],
Backquote: ['`', '~', '`', '`', 4],
Comma: [',', '<', '≤', '¯', 0],
Period: ['.', '>', '≥', '˘', 0],
Slash: ['/', '?', '÷', '¿', 0],
CapsLock: [],
F1: [],
F2: [],
F3: [],
F4: [],
F5: [],
F6: [],
F7: [],
F8: [],
F9: [],
F10: [],
F11: [],
F12: [],
Insert: [],
Home: [],
PageUp: [],
Delete: [],
End: [],
PageDown: [],
ArrowRight: [],
ArrowLeft: [],
ArrowDown: [],
ArrowUp: [],
NumLock: [],
NumpadDivide: ['/', '/', '/', '/', 0],
NumpadMultiply: ['*', '*', '*', '*', 0],
NumpadSubtract: ['-', '-', '-', '-', 0],
NumpadAdd: ['+', '+', '+', '+', 0],
NumpadEnter: [],
Numpad1: ['1', '1', '1', '1', 0],
Numpad2: ['2', '2', '2', '2', 0],
Numpad3: ['3', '3', '3', '3', 0],
Numpad4: ['4', '4', '4', '4', 0],
Numpad5: ['5', '5', '5', '5', 0],
Numpad6: ['6', '6', '6', '6', 0],
Numpad7: ['7', '7', '7', '7', 0],
Numpad8: ['8', '8', '8', '8', 0],
Numpad9: ['9', '9', '9', '9', 0],
Numpad0: ['0', '0', '0', '0', 0],
NumpadDecimal: ['.', '.', '.', '.', 0],
IntlBackslash: ['§', '±', '§', '±', 0],
ContextMenu: [],
NumpadEqual: ['=', '=', '=', '=', 0],
F13: [],
F14: [],
F15: [],
F16: [],
F17: [],
F18: [],
F19: [],
F20: [],
AudioVolumeMute: [],
AudioVolumeUp: ['', '=', '', '=', 0],
AudioVolumeDown: [],
NumpadComma: [],
IntlRo: [],
KanaMode: [],
IntlYen: [],
ControlLeft: [],
ShiftLeft: [],
AltLeft: [],
MetaLeft: [],
ControlRight: [],
ShiftRight: [],
AltRight: [],
MetaRight: []
}
}); | src/vs/workbench/services/keybinding/browser/keyboardLayouts/jp.darwin.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0001791949907783419,
0.00017182274314109236,
0.00016542863158974797,
0.00017086893785744905,
0.0000034716845220827963
] |
{
"id": 8,
"code_window": [
"\n",
"\t\tthis._relayoutCell();\n",
"\t\t// if it's clearing all outputs, or outputs are all rendered synchronously\n",
"\t\t// shrink immediately as the final output height will be zero.\n",
"\t\tthis._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);\n",
"\t}\n",
"\n",
"\tprivate _generateShowMoreElement(disposables: DisposableStore): HTMLElement {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// if it's rerun, then the output clearing might be temporary, so we don't shrink immediately\n",
"\t\tthis._validateFinalOutputHeight(false || (context === CellOutputUpdateContext.Other && this.viewCell.outputsViewModels.length === 0));\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 666
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
import { renderMarkdown } from 'vs/base/browser/markdownRenderer';
import { Action, IAction } from 'vs/base/common/actions';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import * as nls from 'vs/nls';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { WorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { IMenuService, MenuId } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSION_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellOutputViewModel, ICellViewModel, IInsetRenderOutput, INotebookEditorDelegate, JUPYTER_EXTENSION_ID, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { mimetypeIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';
import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
interface IRenderResult {
initRenderIsSynchronous: false;
}
// DOM structure
//
// #output
// |
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | | #output-element
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
class CellOutputElement extends Disposable {
private readonly _renderDisposableStore = this._register(new DisposableStore());
innerContainer?: HTMLElement;
renderedOutputContainer!: HTMLElement;
renderResult?: IInsetRenderOutput;
private readonly contextKeyService: IContextKeyService;
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private cellOutputContainer: CellOutputContainer,
private outputContainer: FastDomNode<HTMLElement>,
readonly output: ICellOutputViewModel,
@INotebookService private readonly notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@IContextKeyService parentContextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this.contextKeyService = parentContextKeyService;
this._register(this.output.model.onDidChangeData(() => {
this.rerender();
}));
this._register(this.output.onDidResetRenderer(() => {
this.rerender();
}));
}
detach() {
this.renderedOutputContainer?.parentElement?.removeChild(this.renderedOutputContainer);
let count = 0;
if (this.innerContainer) {
for (let i = 0; i < this.innerContainer.childNodes.length; i++) {
if ((this.innerContainer.childNodes[i] as HTMLElement).className === 'rendered-output') {
count++;
}
if (count > 1) {
break;
}
}
if (count === 0) {
this.innerContainer.parentElement?.removeChild(this.innerContainer);
}
}
this.notebookEditor.removeInset(this.output);
}
updateDOMTop(top: number) {
if (this.innerContainer) {
this.innerContainer.style.top = `${top}px`;
}
}
rerender() {
if (
this.notebookEditor.hasModel() &&
this.innerContainer &&
this.renderResult &&
this.renderResult.type === RenderOutputType.Extension
) {
// Output rendered by extension renderer got an update
const [mimeTypes, pick] = this.output.resolveMimeTypes(this.notebookEditor.textModel, this.notebookEditor.activeKernel?.preloadProvides);
const pickedMimeType = mimeTypes[pick];
if (pickedMimeType.mimeType === this.renderResult.mimeType && pickedMimeType.rendererId === this.renderResult.renderer.id) {
// Same mimetype, same renderer, call the extension renderer to update
const index = this.viewCell.outputsViewModels.indexOf(this.output);
this.notebookEditor.updateOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
return;
}
}
if (!this.innerContainer) {
// init rendering didn't happen
const currOutputIndex = this.cellOutputContainer.renderedOutputEntries.findIndex(entry => entry.element === this);
const previousSibling = currOutputIndex > 0 && !!(this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer?.parentElement)
? this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer
: undefined;
this.render(previousSibling);
} else {
// Another mimetype or renderer is picked, we need to clear the current output and re-render
const nextElement = this.innerContainer.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(this.output);
}
this.render(nextElement as HTMLElement);
}
this._relayoutCell();
}
// insert after previousSibling
private _generateInnerOutputContainer(previousSibling: HTMLElement | undefined, pickedMimeTypeRenderer: IOrderedMimeType) {
this.innerContainer = DOM.$('.output-inner-container');
if (previousSibling && previousSibling.nextElementSibling) {
this.outputContainer.domNode.insertBefore(this.innerContainer, previousSibling.nextElementSibling);
} else {
this.outputContainer.domNode.appendChild(this.innerContainer);
}
this.innerContainer.setAttribute('output-mime-type', pickedMimeTypeRenderer.mimeType);
return this.innerContainer;
}
render(previousSibling: HTMLElement | undefined): IRenderResult | undefined {
const index = this.viewCell.outputsViewModels.indexOf(this.output);
if (this.viewCell.isOutputCollapsed || !this.notebookEditor.hasModel()) {
return undefined;
}
const notebookUri = CellUri.parse(this.viewCell.uri)?.notebook;
if (!notebookUri) {
return undefined;
}
const notebookTextModel = this.notebookEditor.textModel;
const [mimeTypes, pick] = this.output.resolveMimeTypes(notebookTextModel, this.notebookEditor.activeKernel?.preloadProvides);
if (!mimeTypes.find(mimeType => mimeType.isTrusted) || mimeTypes.length === 0) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#noMimeType');
return undefined;
}
const pickedMimeTypeRenderer = mimeTypes[pick];
const innerContainer = this._generateInnerOutputContainer(previousSibling, pickedMimeTypeRenderer);
this._attachToolbar(innerContainer, notebookTextModel, this.notebookEditor.activeKernel, index, mimeTypes);
this.renderedOutputContainer = DOM.append(innerContainer, DOM.$('.rendered-output'));
const renderer = this.notebookService.getRendererInfo(pickedMimeTypeRenderer.rendererId);
this.renderResult = renderer
? { type: RenderOutputType.Extension, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType }
: this._renderMissingRenderer(this.output, pickedMimeTypeRenderer.mimeType);
this.output.pickedMimeType = pickedMimeTypeRenderer;
if (!this.renderResult) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#renderResultUndefined');
return undefined;
}
this.notebookEditor.createOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
innerContainer.classList.add('background');
return { initRenderIsSynchronous: false };
}
private _renderMissingRenderer(viewModel: ICellOutputViewModel, preferredMimeType: string | undefined): IInsetRenderOutput {
if (!viewModel.model.outputs.length) {
return this._renderMessage(viewModel, nls.localize('empty', "Cell has no output"));
}
if (!preferredMimeType) {
const mimeTypes = viewModel.model.outputs.map(op => op.mime);
const mimeTypesMessage = mimeTypes.join(', ');
return this._renderMessage(viewModel, nls.localize('noRenderer.2', "No renderer could be found for output. It has the following mimetypes: {0}", mimeTypesMessage));
}
return this._renderSearchForMimetype(viewModel, preferredMimeType);
}
private _renderSearchForMimetype(viewModel: ICellOutputViewModel, mimeType: string): IInsetRenderOutput {
const query = `@tag:notebookRenderer ${mimeType}`;
const p = DOM.$('p', undefined, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
const a = DOM.$('a', { href: `command:workbench.extensions.search?%22${query}%22`, class: 'monaco-button monaco-text-button', tabindex: 0, role: 'button', style: 'padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;' }, `Search Marketplace`);
return {
type: RenderOutputType.Html,
source: viewModel,
htmlContent: p.outerHTML + a.outerHTML
};
}
private _renderMessage(viewModel: ICellOutputViewModel, message: string): IInsetRenderOutput {
const el = DOM.$('p', undefined, message);
return { type: RenderOutputType.Html, source: viewModel, htmlContent: el.outerHTML };
}
private async _attachToolbar(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, index: number, mimeTypes: readonly IOrderedMimeType[]) {
const hasMultipleMimeTypes = mimeTypes.filter(mimeType => mimeType.isTrusted).length <= 1;
if (index > 0 && hasMultipleMimeTypes) {
return;
}
if (!this.notebookEditor.hasModel()) {
return;
}
const useConsolidatedButton = this.notebookEditor.notebookOptions.getLayoutConfiguration().consolidatedOutputButton;
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.cell-output-toolbar');
outputItemDiv.appendChild(mimeTypePicker);
const toolbar = this._renderDisposableStore.add(this.instantiationService.createInstance(WorkbenchToolBar, mimeTypePicker, {
renderDropdownAsChildElement: false
}));
toolbar.context = <INotebookCellActionContext>{
ui: true,
cell: this.output.cellViewModel as ICellViewModel,
notebookEditor: this.notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
};
// TODO: This could probably be a real registered action, but it has to talk to this output element
const pickAction = new Action('notebook.output.pickMimetype', nls.localize('pickMimeType', "Change Presentation"), ThemeIcon.asClassName(mimetypeIcon), undefined,
async _context => this._pickActiveMimeTypeRenderer(outputItemDiv, notebookTextModel, kernel, this.output));
if (index === 0 && useConsolidatedButton) {
const menu = this._renderDisposableStore.add(this.menuService.createMenu(MenuId.NotebookOutputToolbar, this.contextKeyService));
const updateMenuToolbar = () => {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, result, () => false);
toolbar.setActions([], [pickAction, ...secondary]);
};
updateMenuToolbar();
this._renderDisposableStore.add(menu.onDidChange(updateMenuToolbar));
} else {
toolbar.setActions([pickAction]);
}
}
private async _pickActiveMimeTypeRenderer(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, viewModel: ICellOutputViewModel) {
const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, kernel?.preloadProvides);
const items: IMimeTypeRenderer[] = [];
const unsupportedItems: IMimeTypeRenderer[] = [];
mimeTypes.forEach((mimeType, index) => {
if (mimeType.isTrusted) {
const arr = mimeType.rendererId === RENDERER_NOT_AVAILABLE ?
unsupportedItems :
items;
arr.push({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
detail: this._generateRendererInfo(mimeType.rendererId),
description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined
});
}
});
if (unsupportedItems.some(m => JUPYTER_RENDERER_MIMETYPES.includes(m.id!))) {
unsupportedItems.push({
label: nls.localize('installJupyterPrompt', "Install additional renderers from the marketplace"),
id: 'installRenderers',
index: mimeTypes.length
});
}
const picker = this.quickInputService.createQuickPick();
picker.items = [
...items,
{ type: 'separator' },
...unsupportedItems
];
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = items.length !== mimeTypes.length
? nls.localize('promptChooseMimeTypeInSecure.placeHolder', "Select mimetype to render for current output")
: nls.localize('promptChooseMimeType.placeHolder', "Select mimetype to render for current output");
const pick = await new Promise<IMimeTypeRenderer | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer) : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined || pick.index === currIndex) {
return;
}
if (pick.id === 'installRenderers') {
this._showJupyterExtension();
return;
}
// user chooses another mimetype
const nextElement = outputItemDiv.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(viewModel);
}
viewModel.pickedMimeType = mimeTypes[pick.index];
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
const { mimeType, rendererId } = mimeTypes[pick.index];
this.notebookService.updateMimePreferredRenderer(notebookTextModel.viewType, mimeType, rendererId, mimeTypes.map(m => m.mimeType));
this.render(nextElement as HTMLElement);
this._validateFinalOutputHeight(false);
this._relayoutCell();
}
private async _showJupyterExtension() {
const viewlet = await this.paneCompositeService.openPaneComposite(EXTENSION_VIEWLET_ID, ViewContainerLocation.Sidebar, true);
const view = viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer | undefined;
view?.search(`@id:${JUPYTER_EXTENSION_ID}`);
}
private _generateRendererInfo(renderId: string): string {
const renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
const displayName = renderInfo.displayName !== '' ? renderInfo.displayName : renderInfo.id;
return `${displayName} (${renderInfo.extensionId.value})`;
}
return nls.localize('unavailableRenderInfo', "renderer not available");
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
if (this._outputHeightTimer) {
this.viewCell.unlockOutputHeight();
clearTimeout(this._outputHeightTimer);
}
super.dispose();
}
}
class OutputEntryViewHandler {
constructor(
readonly model: ICellOutputViewModel,
readonly element: CellOutputElement
) {
}
}
export class CellOutputContainer extends CellContentPart {
private _outputEntries: OutputEntryViewHandler[] = [];
get renderedOutputEntries() {
return this._outputEntries;
}
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private readonly templateData: CodeCellRenderTemplate,
private options: { limit: number },
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._register(viewCell.onDidChangeOutputs(splice => {
this._updateOutputs(splice);
}));
this._register(viewCell.onDidChangeLayout(() => {
this.updateInternalLayoutNow(viewCell);
}));
}
override updateInternalLayoutNow(viewCell: CodeCellViewModel) {
this.templateData.outputContainer.setTop(viewCell.layoutInfo.outputContainerOffset);
this.templateData.outputShowMoreContainer.setTop(viewCell.layoutInfo.outputShowMoreContainerOffset);
this._outputEntries.forEach(entry => {
const index = this.viewCell.outputsViewModels.indexOf(entry.model);
if (index >= 0) {
const top = this.viewCell.getOutputOffsetInContainer(index);
entry.element.updateDOMTop(top);
}
});
}
render() {
if (this.viewCell.outputsViewModels.length > 0) {
if (this.viewCell.layoutInfo.outputTotalHeight !== 0) {
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
this._relayoutCell();
}
DOM.show(this.templateData.outputContainer.domNode);
for (let index = 0; index < Math.min(this.options.limit, this.viewCell.outputsViewModels.length); index++) {
const currOutput = this.viewCell.outputsViewModels[index];
const entry = this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, currOutput);
this._outputEntries.push(new OutputEntryViewHandler(currOutput, entry));
entry.render(undefined);
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(46);
}
this._relayoutCell();
this._validateFinalOutputHeight(false);
} else {
// noop
this._relayoutCell();
DOM.hide(this.templateData.outputContainer.domNode);
}
this.templateData.outputShowMoreContainer.domNode.innerText = '';
if (this.viewCell.outputsViewModels.length > this.options.limit) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(0);
}
}
viewUpdateShowOutputs(initRendering: boolean): void {
for (let index = 0; index < this._outputEntries.length; index++) {
const viewHandler = this._outputEntries[index];
const outputEntry = viewHandler.element;
if (outputEntry.renderResult) {
this.notebookEditor.createOutput(this.viewCell, outputEntry.renderResult as IInsetRenderOutput, this.viewCell.getOutputOffset(index));
} else {
outputEntry.render(undefined);
}
}
this._relayoutCell();
}
viewUpdateHideOuputs(): void {
for (let index = 0; index < this._outputEntries.length; index++) {
this.notebookEditor.hideInset(this._outputEntries[index].model);
}
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _updateOutputs(splice: NotebookCellOutputsSplice) {
const previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;
// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.
this.viewCell.updateOutputMinHeight(previousOutputHeight);
if (this.viewCell.outputsViewModels.length) {
DOM.show(this.templateData.outputContainer.domNode);
} else {
DOM.hide(this.templateData.outputContainer.domNode);
}
this.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));
this._renderNow(splice);
}
private _renderNow(splice: NotebookCellOutputsSplice) {
if (splice.start >= this.options.limit) {
// splice items out of limit
return;
}
const firstGroupEntries = this._outputEntries.slice(0, splice.start);
const deletedEntries = this._outputEntries.slice(splice.start, splice.start + splice.deleteCount);
const secondGroupEntries = this._outputEntries.slice(splice.start + splice.deleteCount);
let newlyInserted = this.viewCell.outputsViewModels.slice(splice.start, splice.start + splice.newOutputs.length);
// [...firstGroup, ...deletedEntries, ...secondGroupEntries] [...restInModel]
// [...firstGroup, ...newlyInserted, ...secondGroupEntries, restInModel]
if (firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length > this.options.limit) {
// exceeds limit again
if (firstGroupEntries.length + newlyInserted.length > this.options.limit) {
[...deletedEntries, ...secondGroupEntries].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
newlyInserted = newlyInserted.slice(0, this.options.limit - firstGroupEntries.length);
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries];
// render newly inserted outputs
for (let i = firstGroupEntries.length; i < this._outputEntries.length; i++) {
this._outputEntries[i].element.render(undefined);
}
} else {
// part of secondGroupEntries are pushed out of view
// now we have to be creative as secondGroupEntries might not use dedicated containers
const elementsPushedOutOfView = secondGroupEntries.slice(this.options.limit - firstGroupEntries.length - newlyInserted.length);
[...deletedEntries, ...elementsPushedOutOfView].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
// exclusive
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries.slice(0, this.options.limit - firstGroupEntries.length - newlyInserted.length)];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
}
} else {
// after splice, it doesn't exceed
deletedEntries.forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
let outputsNewlyAvailable: OutputEntryViewHandler[] = [];
if (firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length < this.viewCell.outputsViewModels.length) {
const last = Math.min(this.options.limit, this.viewCell.outputsViewModels.length);
outputsNewlyAvailable = this.viewCell.outputsViewModels.slice(firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length, last).map(output => {
return new OutputEntryViewHandler(output, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, output));
});
}
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries, ...outputsNewlyAvailable];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
for (let i = 0; i < outputsNewlyAvailable.length; i++) {
this._outputEntries[firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length + i].element.render(undefined);
}
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
if (!this.templateData.outputShowMoreContainer.domNode.hasChildNodes()) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
}
this.viewCell.updateOutputShowMoreContainerHeight(46);
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
}
const editorHeight = this.templateData.editor.getContentHeight();
this.viewCell.editorHeight = editorHeight;
this._relayoutCell();
// if it's clearing all outputs, or outputs are all rendered synchronously
// shrink immediately as the final output height will be zero.
this._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);
}
private _generateShowMoreElement(disposables: DisposableStore): HTMLElement {
const md: IMarkdownString = {
value: `There are more than ${this.options.limit} outputs, [show more (open the raw output data in a text editor) ...](command:workbench.action.openLargeOutput)`,
isTrusted: true,
supportThemeIcons: true
};
const rendered = renderMarkdown(md, {
actionHandler: {
callback: (content) => {
if (content === 'command:workbench.action.openLargeOutput') {
this.openerService.open(CellUri.generateCellOutputUri(this.notebookEditor.textModel!.uri));
}
return;
},
disposables
}
});
disposables.add(rendered);
rendered.element.classList.add('output-show-more');
return rendered.element;
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
this.viewCell.updateOutputMinHeight(0);
if (this._outputHeightTimer) {
clearTimeout(this._outputHeightTimer);
}
this._outputEntries.forEach(entry => {
entry.element.dispose();
});
super.dispose();
}
}
const JUPYTER_RENDERER_MIMETYPES = [
'application/geo+json',
'application/vdom.v1+json',
'application/vnd.dataresource+json',
'application/vnd.plotly.v1+json',
'application/vnd.vega.v2+json',
'application/vnd.vega.v3+json',
'application/vnd.vega.v4+json',
'application/vnd.vega.v5+json',
'application/vnd.vegalite.v1+json',
'application/vnd.vegalite.v2+json',
'application/vnd.vegalite.v3+json',
'application/vnd.vegalite.v4+json',
'application/x-nteract-model-debug+json',
'image/svg+xml',
'text/latex',
'text/vnd.plotly.v1+html',
'application/vnd.jupyter.widget-view+json',
'application/vnd.code.notebook.error'
];
| src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.9991136193275452,
0.0434429869055748,
0.00016493030125275254,
0.00044475242611952126,
0.19632092118263245
] |
{
"id": 8,
"code_window": [
"\n",
"\t\tthis._relayoutCell();\n",
"\t\t// if it's clearing all outputs, or outputs are all rendered synchronously\n",
"\t\t// shrink immediately as the final output height will be zero.\n",
"\t\tthis._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);\n",
"\t}\n",
"\n",
"\tprivate _generateShowMoreElement(disposables: DisposableStore): HTMLElement {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// if it's rerun, then the output clearing might be temporary, so we don't shrink immediately\n",
"\t\tthis._validateFinalOutputHeight(false || (context === CellOutputUpdateContext.Other && this.viewCell.outputsViewModels.length === 0));\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 666
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DisposableStore, Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { ExtHostContext, ExtHostTerminalServiceShape, MainThreadTerminalServiceShape, MainContext, TerminalLaunchConfig, ITerminalDimensionsDto, ExtHostTerminalIdentifier, TerminalQuickFix } from 'vs/workbench/api/common/extHost.protocol';
import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers';
import { URI } from 'vs/base/common/uri';
import { StopWatch } from 'vs/base/common/stopwatch';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { IProcessProperty, IShellLaunchConfig, IShellLaunchConfigDto, ProcessPropertyType, TerminalExitReason, TerminalLocation } from 'vs/platform/terminal/common/terminal';
import { TerminalDataBufferer } from 'vs/platform/terminal/common/terminalDataBuffering';
import { ITerminalEditorService, ITerminalExternalLinkProvider, ITerminalGroupService, ITerminalInstance, ITerminalLink, ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal';
import { TerminalProcessExtHostProxy } from 'vs/workbench/contrib/terminal/browser/terminalProcessExtHostProxy';
import { IEnvironmentVariableService, ISerializableEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariable';
import { deserializeEnvironmentVariableCollection, serializeEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariableShared';
import { IStartExtensionTerminalRequest, ITerminalProcessExtHostProxy, ITerminalProfileResolverService, ITerminalProfileService, ITerminalQuickFixService } from 'vs/workbench/contrib/terminal/common/terminal';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { withNullAsUndefined } from 'vs/base/common/types';
import { OperatingSystem, OS } from 'vs/base/common/platform';
import { TerminalEditorLocationOptions } from 'vscode';
import { Promises } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { ITerminalCommand } from 'vs/platform/terminal/common/capabilities/capabilities';
import { ITerminalOutputMatch, ITerminalOutputMatcher, ITerminalQuickFix, ITerminalQuickFixOptions } from 'vs/platform/terminal/common/xterm/terminalQuickFix';
import { TerminalQuickFixType } from 'vs/workbench/api/common/extHostTypes';
@extHostNamedCustomer(MainContext.MainThreadTerminalService)
export class MainThreadTerminalService implements MainThreadTerminalServiceShape {
private _proxy: ExtHostTerminalServiceShape;
/**
* Stores a map from a temporary terminal id (a UUID generated on the extension host side)
* to a numeric terminal id (an id generated on the renderer side)
* This comes in play only when dealing with terminals created on the extension host side
*/
private _extHostTerminals = new Map<string, Promise<ITerminalInstance>>();
private readonly _toDispose = new DisposableStore();
private readonly _terminalProcessProxies = new Map<number, ITerminalProcessExtHostProxy>();
private readonly _profileProviders = new Map<string, IDisposable>();
private readonly _quickFixProviders = new Map<string, IDisposable>();
private _dataEventTracker: TerminalDataEventTracker | undefined;
/**
* A single shared terminal link provider for the exthost. When an ext registers a link
* provider, this is registered with the terminal on the renderer side and all links are
* provided through this, even from multiple ext link providers. Xterm should remove lower
* priority intersecting links itself.
*/
private _linkProvider: IDisposable | undefined;
private _os: OperatingSystem = OS;
constructor(
private readonly _extHostContext: IExtHostContext,
@ITerminalService private readonly _terminalService: ITerminalService,
@ITerminalQuickFixService private readonly _terminalQuickFixService: ITerminalQuickFixService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IEnvironmentVariableService private readonly _environmentVariableService: IEnvironmentVariableService,
@ILogService private readonly _logService: ILogService,
@ITerminalProfileResolverService private readonly _terminalProfileResolverService: ITerminalProfileResolverService,
@IRemoteAgentService remoteAgentService: IRemoteAgentService,
@ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService,
@ITerminalEditorService private readonly _terminalEditorService: ITerminalEditorService,
@ITerminalProfileService private readonly _terminalProfileService: ITerminalProfileService
) {
this._proxy = _extHostContext.getProxy(ExtHostContext.ExtHostTerminalService);
// ITerminalService listeners
this._toDispose.add(_terminalService.onDidCreateInstance((instance) => {
this._onTerminalOpened(instance);
this._onInstanceDimensionsChanged(instance);
}));
this._toDispose.add(_terminalService.onDidDisposeInstance(instance => this._onTerminalDisposed(instance)));
this._toDispose.add(_terminalService.onDidReceiveProcessId(instance => this._onTerminalProcessIdReady(instance)));
this._toDispose.add(_terminalService.onDidChangeInstanceDimensions(instance => this._onInstanceDimensionsChanged(instance)));
this._toDispose.add(_terminalService.onDidMaximumDimensionsChange(instance => this._onInstanceMaximumDimensionsChanged(instance)));
this._toDispose.add(_terminalService.onDidRequestStartExtensionTerminal(e => this._onRequestStartExtensionTerminal(e)));
this._toDispose.add(_terminalService.onDidChangeActiveInstance(instance => this._onActiveTerminalChanged(instance ? instance.instanceId : null)));
this._toDispose.add(_terminalService.onDidChangeInstanceTitle(instance => instance && this._onTitleChanged(instance.instanceId, instance.title)));
this._toDispose.add(_terminalService.onDidInputInstanceData(instance => this._proxy.$acceptTerminalInteraction(instance.instanceId)));
// Set initial ext host state
this._terminalService.instances.forEach(t => {
this._onTerminalOpened(t);
t.processReady.then(() => this._onTerminalProcessIdReady(t));
});
const activeInstance = this._terminalService.activeInstance;
if (activeInstance) {
this._proxy.$acceptActiveTerminalChanged(activeInstance.instanceId);
}
if (this._environmentVariableService.collections.size > 0) {
const collectionAsArray = [...this._environmentVariableService.collections.entries()];
const serializedCollections: [string, ISerializableEnvironmentVariableCollection][] = collectionAsArray.map(e => {
return [e[0], serializeEnvironmentVariableCollection(e[1].map)];
});
this._proxy.$initEnvironmentVariableCollections(serializedCollections);
}
remoteAgentService.getEnvironment().then(async env => {
this._os = env?.os || OS;
this._updateDefaultProfile();
});
this._terminalProfileService.onDidChangeAvailableProfiles(() => this._updateDefaultProfile());
}
public dispose(): void {
this._toDispose.dispose();
this._linkProvider?.dispose();
}
private async _updateDefaultProfile() {
const remoteAuthority = withNullAsUndefined(this._extHostContext.remoteAuthority);
const defaultProfile = this._terminalProfileResolverService.getDefaultProfile({ remoteAuthority, os: this._os });
const defaultAutomationProfile = this._terminalProfileResolverService.getDefaultProfile({ remoteAuthority, os: this._os, allowAutomationShell: true });
this._proxy.$acceptDefaultProfile(...await Promise.all([defaultProfile, defaultAutomationProfile]));
}
private async _getTerminalInstance(id: ExtHostTerminalIdentifier): Promise<ITerminalInstance | undefined> {
if (typeof id === 'string') {
return this._extHostTerminals.get(id);
}
return this._terminalService.getInstanceFromId(id);
}
public async $createTerminal(extHostTerminalId: string, launchConfig: TerminalLaunchConfig): Promise<void> {
const shellLaunchConfig: IShellLaunchConfig = {
name: launchConfig.name,
executable: launchConfig.shellPath,
args: launchConfig.shellArgs,
cwd: typeof launchConfig.cwd === 'string' ? launchConfig.cwd : URI.revive(launchConfig.cwd),
icon: launchConfig.icon,
color: launchConfig.color,
initialText: launchConfig.initialText,
waitOnExit: launchConfig.waitOnExit,
ignoreConfigurationCwd: true,
env: launchConfig.env,
strictEnv: launchConfig.strictEnv,
hideFromUser: launchConfig.hideFromUser,
customPtyImplementation: launchConfig.isExtensionCustomPtyTerminal
? (id, cols, rows) => new TerminalProcessExtHostProxy(id, cols, rows, this._terminalService)
: undefined,
extHostTerminalId,
isFeatureTerminal: launchConfig.isFeatureTerminal,
isExtensionOwnedTerminal: launchConfig.isExtensionOwnedTerminal,
useShellEnvironment: launchConfig.useShellEnvironment,
isTransient: launchConfig.isTransient
};
const terminal = Promises.withAsyncBody<ITerminalInstance>(async r => {
const terminal = await this._terminalService.createTerminal({
config: shellLaunchConfig,
location: await this._deserializeParentTerminal(launchConfig.location)
});
r(terminal);
});
this._extHostTerminals.set(extHostTerminalId, terminal);
const terminalInstance = await terminal;
this._toDispose.add(terminalInstance.onDisposed(() => {
this._extHostTerminals.delete(extHostTerminalId);
}));
}
private async _deserializeParentTerminal(location?: TerminalLocation | TerminalEditorLocationOptions | { parentTerminal: ExtHostTerminalIdentifier } | { splitActiveTerminal: boolean; location?: TerminalLocation }): Promise<TerminalLocation | TerminalEditorLocationOptions | { parentTerminal: ITerminalInstance } | { splitActiveTerminal: boolean } | undefined> {
if (typeof location === 'object' && 'parentTerminal' in location) {
const parentTerminal = await this._extHostTerminals.get(location.parentTerminal.toString());
return parentTerminal ? { parentTerminal } : undefined;
}
return location;
}
public async $show(id: ExtHostTerminalIdentifier, preserveFocus: boolean): Promise<void> {
const terminalInstance = await this._getTerminalInstance(id);
if (terminalInstance) {
this._terminalService.setActiveInstance(terminalInstance);
if (terminalInstance.target === TerminalLocation.Editor) {
await this._terminalEditorService.revealActiveEditor(preserveFocus);
} else {
await this._terminalGroupService.showPanel(!preserveFocus);
}
}
}
public async $hide(id: ExtHostTerminalIdentifier): Promise<void> {
const instanceToHide = await this._getTerminalInstance(id);
const activeInstance = this._terminalService.activeInstance;
if (activeInstance && activeInstance.instanceId === instanceToHide?.instanceId && activeInstance.target !== TerminalLocation.Editor) {
this._terminalGroupService.hidePanel();
}
}
public async $dispose(id: ExtHostTerminalIdentifier): Promise<void> {
(await this._getTerminalInstance(id))?.dispose(TerminalExitReason.Extension);
}
public async $sendText(id: ExtHostTerminalIdentifier, text: string, addNewLine: boolean): Promise<void> {
const instance = await this._getTerminalInstance(id);
await instance?.sendText(text, addNewLine);
}
public $sendProcessExit(terminalId: number, exitCode: number | undefined): void {
this._terminalProcessProxies.get(terminalId)?.emitExit(exitCode);
}
public $startSendingDataEvents(): void {
if (!this._dataEventTracker) {
this._dataEventTracker = this._instantiationService.createInstance(TerminalDataEventTracker, (id, data) => {
this._onTerminalData(id, data);
});
// Send initial events if they exist
this._terminalService.instances.forEach(t => {
t.initialDataEvents?.forEach(d => this._onTerminalData(t.instanceId, d));
});
}
}
public $stopSendingDataEvents(): void {
this._dataEventTracker?.dispose();
this._dataEventTracker = undefined;
}
public $startLinkProvider(): void {
this._linkProvider?.dispose();
this._linkProvider = this._terminalService.registerLinkProvider(new ExtensionTerminalLinkProvider(this._proxy));
}
public $stopLinkProvider(): void {
this._linkProvider?.dispose();
this._linkProvider = undefined;
}
public $registerProcessSupport(isSupported: boolean): void {
this._terminalService.registerProcessSupport(isSupported);
}
public $registerProfileProvider(id: string, extensionIdentifier: string): void {
// Proxy profile provider requests through the extension host
this._profileProviders.set(id, this._terminalProfileService.registerTerminalProfileProvider(extensionIdentifier, id, {
createContributedTerminalProfile: async (options) => {
return this._proxy.$createContributedProfileTerminal(id, options);
}
}));
}
public $unregisterProfileProvider(id: string): void {
this._profileProviders.get(id)?.dispose();
this._profileProviders.delete(id);
}
public async $registerQuickFixProvider(id: string, extensionId: string): Promise<void> {
this._quickFixProviders.set(id, this._terminalQuickFixService.registerQuickFixProvider(id,
{
provideTerminalQuickFixes: async (terminalCommand: ITerminalCommand, lines: string[], option: ITerminalQuickFixOptions, token: CancellationToken) => {
if (token.isCancellationRequested) {
return;
}
if (option.outputMatcher?.length && option.outputMatcher.length > 40) {
option.outputMatcher.length = 40;
this._logService.warn('Cannot exceed output matcher length of 40');
}
const commandLineMatch = terminalCommand.command.match(option.commandLineMatcher);
if (!commandLineMatch) {
return;
}
const outputMatcher = option.outputMatcher;
let outputMatch;
if (outputMatcher) {
outputMatch = getOutputMatchForLines(lines, outputMatcher);
}
if (!outputMatch) {
return;
}
const matchResult = { commandLineMatch, outputMatch, commandLine: terminalCommand.command };
if (matchResult) {
const result = await this._proxy.$provideTerminalQuickFixes(id, matchResult, token);
if (result && Array.isArray(result)) {
return result.map(r => parseQuickFix(id, extensionId, r));
} else if (result) {
return parseQuickFix(id, extensionId, result);
}
}
return;
}
})
);
}
public $unregisterQuickFixProvider(id: string): void {
this._quickFixProviders.get(id)?.dispose();
this._quickFixProviders.delete(id);
}
private _onActiveTerminalChanged(terminalId: number | null): void {
this._proxy.$acceptActiveTerminalChanged(terminalId);
}
private _onTerminalData(terminalId: number, data: string): void {
this._proxy.$acceptTerminalProcessData(terminalId, data);
}
private _onTitleChanged(terminalId: number, name: string): void {
this._proxy.$acceptTerminalTitleChange(terminalId, name);
}
private _onTerminalDisposed(terminalInstance: ITerminalInstance): void {
this._proxy.$acceptTerminalClosed(terminalInstance.instanceId, terminalInstance.exitCode, terminalInstance.exitReason ?? TerminalExitReason.Unknown);
}
private _onTerminalOpened(terminalInstance: ITerminalInstance): void {
const extHostTerminalId = terminalInstance.shellLaunchConfig.extHostTerminalId;
const shellLaunchConfigDto: IShellLaunchConfigDto = {
name: terminalInstance.shellLaunchConfig.name,
executable: terminalInstance.shellLaunchConfig.executable,
args: terminalInstance.shellLaunchConfig.args,
cwd: terminalInstance.shellLaunchConfig.cwd,
env: terminalInstance.shellLaunchConfig.env,
hideFromUser: terminalInstance.shellLaunchConfig.hideFromUser
};
this._proxy.$acceptTerminalOpened(terminalInstance.instanceId, extHostTerminalId, terminalInstance.title, shellLaunchConfigDto);
}
private _onTerminalProcessIdReady(terminalInstance: ITerminalInstance): void {
if (terminalInstance.processId === undefined) {
return;
}
this._proxy.$acceptTerminalProcessId(terminalInstance.instanceId, terminalInstance.processId);
}
private _onInstanceDimensionsChanged(instance: ITerminalInstance): void {
this._proxy.$acceptTerminalDimensions(instance.instanceId, instance.cols, instance.rows);
}
private _onInstanceMaximumDimensionsChanged(instance: ITerminalInstance): void {
this._proxy.$acceptTerminalMaximumDimensions(instance.instanceId, instance.maxCols, instance.maxRows);
}
private _onRequestStartExtensionTerminal(request: IStartExtensionTerminalRequest): void {
const proxy = request.proxy;
this._terminalProcessProxies.set(proxy.instanceId, proxy);
// Note that onResize is not being listened to here as it needs to fire when max dimensions
// change, excluding the dimension override
const initialDimensions: ITerminalDimensionsDto | undefined = request.cols && request.rows ? {
columns: request.cols,
rows: request.rows
} : undefined;
this._proxy.$startExtensionTerminal(
proxy.instanceId,
initialDimensions
).then(request.callback);
proxy.onInput(data => this._proxy.$acceptProcessInput(proxy.instanceId, data));
proxy.onShutdown(immediate => this._proxy.$acceptProcessShutdown(proxy.instanceId, immediate));
proxy.onRequestCwd(() => this._proxy.$acceptProcessRequestCwd(proxy.instanceId));
proxy.onRequestInitialCwd(() => this._proxy.$acceptProcessRequestInitialCwd(proxy.instanceId));
proxy.onRequestLatency(() => this._onRequestLatency(proxy.instanceId));
}
public $sendProcessData(terminalId: number, data: string): void {
this._terminalProcessProxies.get(terminalId)?.emitData(data);
}
public $sendProcessReady(terminalId: number, pid: number, cwd: string): void {
this._terminalProcessProxies.get(terminalId)?.emitReady(pid, cwd);
}
public $sendProcessProperty(terminalId: number, property: IProcessProperty<any>): void {
if (property.type === ProcessPropertyType.Title) {
const instance = this._terminalService.getInstanceFromId(terminalId);
instance?.rename(property.value);
}
this._terminalProcessProxies.get(terminalId)?.emitProcessProperty(property);
}
private async _onRequestLatency(terminalId: number): Promise<void> {
const COUNT = 2;
let sum = 0;
for (let i = 0; i < COUNT; i++) {
const sw = StopWatch.create(true);
await this._proxy.$acceptProcessRequestLatency(terminalId);
sw.stop();
sum += sw.elapsed();
}
this._getTerminalProcess(terminalId)?.emitLatency(sum / COUNT);
}
private _getTerminalProcess(terminalId: number): ITerminalProcessExtHostProxy | undefined {
const terminal = this._terminalProcessProxies.get(terminalId);
if (!terminal) {
this._logService.error(`Unknown terminal: ${terminalId}`);
return undefined;
}
return terminal;
}
$setEnvironmentVariableCollection(extensionIdentifier: string, persistent: boolean, collection: ISerializableEnvironmentVariableCollection | undefined): void {
if (collection) {
const translatedCollection = {
persistent,
map: deserializeEnvironmentVariableCollection(collection)
};
this._environmentVariableService.set(extensionIdentifier, translatedCollection);
} else {
this._environmentVariableService.delete(extensionIdentifier);
}
}
}
/**
* Encapsulates temporary tracking of data events from terminal instances, once disposed all
* listeners are removed.
*/
class TerminalDataEventTracker extends Disposable {
private readonly _bufferer: TerminalDataBufferer;
constructor(
private readonly _callback: (id: number, data: string) => void,
@ITerminalService private readonly _terminalService: ITerminalService
) {
super();
this._register(this._bufferer = new TerminalDataBufferer(this._callback));
this._terminalService.instances.forEach(instance => this._registerInstance(instance));
this._register(this._terminalService.onDidCreateInstance(instance => this._registerInstance(instance)));
this._register(this._terminalService.onDidDisposeInstance(instance => this._bufferer.stopBuffering(instance.instanceId)));
}
private _registerInstance(instance: ITerminalInstance): void {
// Buffer data events to reduce the amount of messages going to the extension host
this._register(this._bufferer.startBuffering(instance.instanceId, instance.onData));
}
}
class ExtensionTerminalLinkProvider implements ITerminalExternalLinkProvider {
constructor(
private readonly _proxy: ExtHostTerminalServiceShape
) {
}
async provideLinks(instance: ITerminalInstance, line: string): Promise<ITerminalLink[] | undefined> {
const proxy = this._proxy;
const extHostLinks = await proxy.$provideLinks(instance.instanceId, line);
return extHostLinks.map(dto => ({
id: dto.id,
startIndex: dto.startIndex,
length: dto.length,
label: dto.label,
activate: () => proxy.$activateLink(instance.instanceId, dto.id)
}));
}
}
export function getOutputMatchForLines(lines: string[], outputMatcher: ITerminalOutputMatcher): ITerminalOutputMatch | undefined {
const match: RegExpMatchArray | null | undefined = lines.join('\n').match(outputMatcher.lineMatcher);
return match ? { regexMatch: match, outputLines: lines } : undefined;
}
function parseQuickFix(id: string, source: string, fix: TerminalQuickFix): ITerminalQuickFix {
let type = TerminalQuickFixType.Command;
if ('uri' in fix) {
fix.uri = URI.revive(fix.uri);
type = TerminalQuickFixType.Opener;
}
return { id, type, source, ...fix };
}
| src/vs/workbench/api/browser/mainThreadTerminalService.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00022888390230946243,
0.00017368064436595887,
0.0001645038864808157,
0.00017289223615080118,
0.000009359575415146537
] |
{
"id": 8,
"code_window": [
"\n",
"\t\tthis._relayoutCell();\n",
"\t\t// if it's clearing all outputs, or outputs are all rendered synchronously\n",
"\t\t// shrink immediately as the final output height will be zero.\n",
"\t\tthis._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);\n",
"\t}\n",
"\n",
"\tprivate _generateShowMoreElement(disposables: DisposableStore): HTMLElement {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// if it's rerun, then the output clearing might be temporary, so we don't shrink immediately\n",
"\t\tthis._validateFinalOutputHeight(false || (context === CellOutputUpdateContext.Other && this.viewCell.outputsViewModels.length === 0));\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 666
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import { CSSIcon } from 'vs/base/common/codicons';
const labelWithIconsRegex = new RegExp(`(\\\\)?\\$\\((${CSSIcon.iconNameExpression}(?:${CSSIcon.iconModifierExpression})?)\\)`, 'g');
export function renderLabelWithIcons(text: string): Array<HTMLSpanElement | string> {
const elements = new Array<HTMLSpanElement | string>();
let match: RegExpExecArray | null;
let textStart = 0, textStop = 0;
while ((match = labelWithIconsRegex.exec(text)) !== null) {
textStop = match.index || 0;
if (textStart < textStop) {
elements.push(text.substring(textStart, textStop));
}
textStart = (match.index || 0) + match[0].length;
const [, escaped, codicon] = match;
elements.push(escaped ? `$(${codicon})` : renderIcon({ id: codicon }));
}
if (textStart < text.length) {
elements.push(text.substring(textStart));
}
return elements;
}
export function renderIcon(icon: CSSIcon): HTMLSpanElement {
const node = dom.$(`span`);
node.classList.add(...CSSIcon.asClassNameArray(icon));
return node;
}
| src/vs/base/browser/ui/iconLabel/iconLabels.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017422757809981704,
0.00017142208525910974,
0.0001685527531662956,
0.00017145401216112077,
0.000002214613232354168
] |
{
"id": 8,
"code_window": [
"\n",
"\t\tthis._relayoutCell();\n",
"\t\t// if it's clearing all outputs, or outputs are all rendered synchronously\n",
"\t\t// shrink immediately as the final output height will be zero.\n",
"\t\tthis._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);\n",
"\t}\n",
"\n",
"\tprivate _generateShowMoreElement(disposables: DisposableStore): HTMLElement {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// if it's rerun, then the output clearing might be temporary, so we don't shrink immediately\n",
"\t\tthis._validateFinalOutputHeight(false || (context === CellOutputUpdateContext.Other && this.viewCell.outputsViewModels.length === 0));\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 666
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { ILogger } from '../logging';
import { MarkdownContributionProvider } from '../markdownExtensions';
import { Disposable, disposeAll } from '../util/dispose';
import { isMarkdownFile } from '../util/file';
import { MdLinkOpener } from '../util/openDocumentLink';
import { MdDocumentRenderer } from './documentRenderer';
import { DynamicMarkdownPreview, IManagedMarkdownPreview, StaticMarkdownPreview } from './preview';
import { MarkdownPreviewConfigurationManager } from './previewConfig';
import { scrollEditorToLine, StartingScrollFragment } from './scrolling';
import { TopmostLineMonitor } from './topmostLineMonitor';
export interface DynamicPreviewSettings {
readonly resourceColumn: vscode.ViewColumn;
readonly previewColumn: vscode.ViewColumn;
readonly locked: boolean;
}
class PreviewStore<T extends IManagedMarkdownPreview> extends Disposable {
private readonly _previews = new Set<T>();
public override dispose(): void {
super.dispose();
for (const preview of this._previews) {
preview.dispose();
}
this._previews.clear();
}
[Symbol.iterator](): Iterator<T> {
return this._previews[Symbol.iterator]();
}
public get(resource: vscode.Uri, previewSettings: DynamicPreviewSettings): T | undefined {
const previewColumn = this._resolvePreviewColumn(previewSettings);
for (const preview of this._previews) {
if (preview.matchesResource(resource, previewColumn, previewSettings.locked)) {
return preview;
}
}
return undefined;
}
public add(preview: T) {
this._previews.add(preview);
}
public delete(preview: T) {
this._previews.delete(preview);
}
private _resolvePreviewColumn(previewSettings: DynamicPreviewSettings): vscode.ViewColumn | undefined {
if (previewSettings.previewColumn === vscode.ViewColumn.Active) {
return vscode.window.tabGroups.activeTabGroup.viewColumn;
}
if (previewSettings.previewColumn === vscode.ViewColumn.Beside) {
return vscode.window.tabGroups.activeTabGroup.viewColumn + 1;
}
return previewSettings.previewColumn;
}
}
export class MarkdownPreviewManager extends Disposable implements vscode.WebviewPanelSerializer, vscode.CustomTextEditorProvider {
private readonly _topmostLineMonitor = new TopmostLineMonitor();
private readonly _previewConfigurations = new MarkdownPreviewConfigurationManager();
private readonly _dynamicPreviews = this._register(new PreviewStore<DynamicMarkdownPreview>());
private readonly _staticPreviews = this._register(new PreviewStore<StaticMarkdownPreview>());
private _activePreview: IManagedMarkdownPreview | undefined = undefined;
public constructor(
private readonly _contentProvider: MdDocumentRenderer,
private readonly _logger: ILogger,
private readonly _contributions: MarkdownContributionProvider,
private readonly _opener: MdLinkOpener,
) {
super();
this._register(vscode.window.registerWebviewPanelSerializer(DynamicMarkdownPreview.viewType, this));
this._register(vscode.window.registerCustomEditorProvider(StaticMarkdownPreview.customEditorViewType, this, {
webviewOptions: { enableFindWidget: true }
}));
this._register(vscode.window.onDidChangeActiveTextEditor(textEditor => {
// When at a markdown file, apply existing scroll settings
if (textEditor?.document && isMarkdownFile(textEditor.document)) {
const line = this._topmostLineMonitor.getPreviousStaticEditorLineByUri(textEditor.document.uri);
if (typeof line === 'number') {
scrollEditorToLine(line, textEditor);
}
}
}));
}
public refresh() {
for (const preview of this._dynamicPreviews) {
preview.refresh();
}
for (const preview of this._staticPreviews) {
preview.refresh();
}
}
public updateConfiguration() {
for (const preview of this._dynamicPreviews) {
preview.updateConfiguration();
}
for (const preview of this._staticPreviews) {
preview.updateConfiguration();
}
}
public openDynamicPreview(
resource: vscode.Uri,
settings: DynamicPreviewSettings
): void {
let preview = this._dynamicPreviews.get(resource, settings);
if (preview) {
preview.reveal(settings.previewColumn);
} else {
preview = this._createNewDynamicPreview(resource, settings);
}
preview.update(
resource,
resource.fragment ? new StartingScrollFragment(resource.fragment) : undefined
);
}
public get activePreviewResource() {
return this._activePreview?.resource;
}
public get activePreviewResourceColumn() {
return this._activePreview?.resourceColumn;
}
public toggleLock() {
const preview = this._activePreview;
if (preview instanceof DynamicMarkdownPreview) {
preview.toggleLock();
// Close any previews that are now redundant, such as having two dynamic previews in the same editor group
for (const otherPreview of this._dynamicPreviews) {
if (otherPreview !== preview && preview.matches(otherPreview)) {
otherPreview.dispose();
}
}
}
}
public async deserializeWebviewPanel(
webview: vscode.WebviewPanel,
state: any
): Promise<void> {
try {
const resource = vscode.Uri.parse(state.resource);
const locked = state.locked;
const line = state.line;
const resourceColumn = state.resourceColumn;
const preview = DynamicMarkdownPreview.revive(
{ resource, locked, line, resourceColumn },
webview,
this._contentProvider,
this._previewConfigurations,
this._logger,
this._topmostLineMonitor,
this._contributions,
this._opener);
this._registerDynamicPreview(preview);
} catch (e) {
console.error(e);
webview.webview.html = /* html */`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- Disable pinch zooming -->
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title>Markdown Preview</title>
<style>
html, body {
min-height: 100%;
height: 100%;
}
.error-container {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
</style>
<meta http-equiv="Content-Security-Policy" content="default-src 'none';">
</head>
<body class="error-container">
<p>${vscode.l10n.t("An unexpected error occurred while restoring the Markdown preview.")}</p>
</body>
</html>`;
}
}
public async resolveCustomTextEditor(
document: vscode.TextDocument,
webview: vscode.WebviewPanel
): Promise<void> {
const lineNumber = this._topmostLineMonitor.getPreviousStaticTextEditorLineByUri(document.uri);
const preview = StaticMarkdownPreview.revive(
document.uri,
webview,
this._contentProvider,
this._previewConfigurations,
this._topmostLineMonitor,
this._logger,
this._contributions,
this._opener,
lineNumber
);
this._registerStaticPreview(preview);
}
private _createNewDynamicPreview(
resource: vscode.Uri,
previewSettings: DynamicPreviewSettings
): DynamicMarkdownPreview {
const activeTextEditorURI = vscode.window.activeTextEditor?.document.uri;
const scrollLine = (activeTextEditorURI?.toString() === resource.toString()) ? vscode.window.activeTextEditor?.visibleRanges[0].start.line : undefined;
const preview = DynamicMarkdownPreview.create(
{
resource,
resourceColumn: previewSettings.resourceColumn,
locked: previewSettings.locked,
line: scrollLine,
},
previewSettings.previewColumn,
this._contentProvider,
this._previewConfigurations,
this._logger,
this._topmostLineMonitor,
this._contributions,
this._opener);
this._activePreview = preview;
return this._registerDynamicPreview(preview);
}
private _registerDynamicPreview(preview: DynamicMarkdownPreview): DynamicMarkdownPreview {
this._dynamicPreviews.add(preview);
preview.onDispose(() => {
this._dynamicPreviews.delete(preview);
});
this._trackActive(preview);
preview.onDidChangeViewState(() => {
// Remove other dynamic previews in our column
disposeAll(Array.from(this._dynamicPreviews).filter(otherPreview => preview !== otherPreview && preview.matches(otherPreview)));
});
return preview;
}
private _registerStaticPreview(preview: StaticMarkdownPreview): StaticMarkdownPreview {
this._staticPreviews.add(preview);
preview.onDispose(() => {
this._staticPreviews.delete(preview);
});
this._trackActive(preview);
return preview;
}
private _trackActive(preview: IManagedMarkdownPreview): void {
preview.onDidChangeViewState(({ webviewPanel }) => {
this._activePreview = webviewPanel.active ? preview : undefined;
});
preview.onDispose(() => {
if (this._activePreview === preview) {
this._activePreview = undefined;
}
});
}
}
| extensions/markdown-language-features/src/preview/previewManager.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.003550885710865259,
0.00028038161690346897,
0.00016333382518496364,
0.0001724669273244217,
0.0005971193313598633
] |
{
"id": 9,
"code_window": [
"import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n",
"import { BaseCellViewModel } from './baseCellViewModel';\n",
"import { NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';\n",
"\n",
"export class CodeCellViewModel extends BaseCellViewModel implements ICellViewModel {\n",
"\treadonly cellKind = CellKind.Code;\n",
"\n",
"\tprotected readonly _onLayoutInfoRead = this._register(new Emitter<void>());\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
import { renderMarkdown } from 'vs/base/browser/markdownRenderer';
import { Action, IAction } from 'vs/base/common/actions';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import * as nls from 'vs/nls';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { WorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { IMenuService, MenuId } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSION_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellOutputViewModel, ICellViewModel, IInsetRenderOutput, INotebookEditorDelegate, JUPYTER_EXTENSION_ID, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { mimetypeIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';
import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
interface IRenderResult {
initRenderIsSynchronous: false;
}
// DOM structure
//
// #output
// |
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | | #output-element
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
class CellOutputElement extends Disposable {
private readonly _renderDisposableStore = this._register(new DisposableStore());
innerContainer?: HTMLElement;
renderedOutputContainer!: HTMLElement;
renderResult?: IInsetRenderOutput;
private readonly contextKeyService: IContextKeyService;
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private cellOutputContainer: CellOutputContainer,
private outputContainer: FastDomNode<HTMLElement>,
readonly output: ICellOutputViewModel,
@INotebookService private readonly notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@IContextKeyService parentContextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this.contextKeyService = parentContextKeyService;
this._register(this.output.model.onDidChangeData(() => {
this.rerender();
}));
this._register(this.output.onDidResetRenderer(() => {
this.rerender();
}));
}
detach() {
this.renderedOutputContainer?.parentElement?.removeChild(this.renderedOutputContainer);
let count = 0;
if (this.innerContainer) {
for (let i = 0; i < this.innerContainer.childNodes.length; i++) {
if ((this.innerContainer.childNodes[i] as HTMLElement).className === 'rendered-output') {
count++;
}
if (count > 1) {
break;
}
}
if (count === 0) {
this.innerContainer.parentElement?.removeChild(this.innerContainer);
}
}
this.notebookEditor.removeInset(this.output);
}
updateDOMTop(top: number) {
if (this.innerContainer) {
this.innerContainer.style.top = `${top}px`;
}
}
rerender() {
if (
this.notebookEditor.hasModel() &&
this.innerContainer &&
this.renderResult &&
this.renderResult.type === RenderOutputType.Extension
) {
// Output rendered by extension renderer got an update
const [mimeTypes, pick] = this.output.resolveMimeTypes(this.notebookEditor.textModel, this.notebookEditor.activeKernel?.preloadProvides);
const pickedMimeType = mimeTypes[pick];
if (pickedMimeType.mimeType === this.renderResult.mimeType && pickedMimeType.rendererId === this.renderResult.renderer.id) {
// Same mimetype, same renderer, call the extension renderer to update
const index = this.viewCell.outputsViewModels.indexOf(this.output);
this.notebookEditor.updateOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
return;
}
}
if (!this.innerContainer) {
// init rendering didn't happen
const currOutputIndex = this.cellOutputContainer.renderedOutputEntries.findIndex(entry => entry.element === this);
const previousSibling = currOutputIndex > 0 && !!(this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer?.parentElement)
? this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer
: undefined;
this.render(previousSibling);
} else {
// Another mimetype or renderer is picked, we need to clear the current output and re-render
const nextElement = this.innerContainer.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(this.output);
}
this.render(nextElement as HTMLElement);
}
this._relayoutCell();
}
// insert after previousSibling
private _generateInnerOutputContainer(previousSibling: HTMLElement | undefined, pickedMimeTypeRenderer: IOrderedMimeType) {
this.innerContainer = DOM.$('.output-inner-container');
if (previousSibling && previousSibling.nextElementSibling) {
this.outputContainer.domNode.insertBefore(this.innerContainer, previousSibling.nextElementSibling);
} else {
this.outputContainer.domNode.appendChild(this.innerContainer);
}
this.innerContainer.setAttribute('output-mime-type', pickedMimeTypeRenderer.mimeType);
return this.innerContainer;
}
render(previousSibling: HTMLElement | undefined): IRenderResult | undefined {
const index = this.viewCell.outputsViewModels.indexOf(this.output);
if (this.viewCell.isOutputCollapsed || !this.notebookEditor.hasModel()) {
return undefined;
}
const notebookUri = CellUri.parse(this.viewCell.uri)?.notebook;
if (!notebookUri) {
return undefined;
}
const notebookTextModel = this.notebookEditor.textModel;
const [mimeTypes, pick] = this.output.resolveMimeTypes(notebookTextModel, this.notebookEditor.activeKernel?.preloadProvides);
if (!mimeTypes.find(mimeType => mimeType.isTrusted) || mimeTypes.length === 0) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#noMimeType');
return undefined;
}
const pickedMimeTypeRenderer = mimeTypes[pick];
const innerContainer = this._generateInnerOutputContainer(previousSibling, pickedMimeTypeRenderer);
this._attachToolbar(innerContainer, notebookTextModel, this.notebookEditor.activeKernel, index, mimeTypes);
this.renderedOutputContainer = DOM.append(innerContainer, DOM.$('.rendered-output'));
const renderer = this.notebookService.getRendererInfo(pickedMimeTypeRenderer.rendererId);
this.renderResult = renderer
? { type: RenderOutputType.Extension, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType }
: this._renderMissingRenderer(this.output, pickedMimeTypeRenderer.mimeType);
this.output.pickedMimeType = pickedMimeTypeRenderer;
if (!this.renderResult) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#renderResultUndefined');
return undefined;
}
this.notebookEditor.createOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
innerContainer.classList.add('background');
return { initRenderIsSynchronous: false };
}
private _renderMissingRenderer(viewModel: ICellOutputViewModel, preferredMimeType: string | undefined): IInsetRenderOutput {
if (!viewModel.model.outputs.length) {
return this._renderMessage(viewModel, nls.localize('empty', "Cell has no output"));
}
if (!preferredMimeType) {
const mimeTypes = viewModel.model.outputs.map(op => op.mime);
const mimeTypesMessage = mimeTypes.join(', ');
return this._renderMessage(viewModel, nls.localize('noRenderer.2', "No renderer could be found for output. It has the following mimetypes: {0}", mimeTypesMessage));
}
return this._renderSearchForMimetype(viewModel, preferredMimeType);
}
private _renderSearchForMimetype(viewModel: ICellOutputViewModel, mimeType: string): IInsetRenderOutput {
const query = `@tag:notebookRenderer ${mimeType}`;
const p = DOM.$('p', undefined, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
const a = DOM.$('a', { href: `command:workbench.extensions.search?%22${query}%22`, class: 'monaco-button monaco-text-button', tabindex: 0, role: 'button', style: 'padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;' }, `Search Marketplace`);
return {
type: RenderOutputType.Html,
source: viewModel,
htmlContent: p.outerHTML + a.outerHTML
};
}
private _renderMessage(viewModel: ICellOutputViewModel, message: string): IInsetRenderOutput {
const el = DOM.$('p', undefined, message);
return { type: RenderOutputType.Html, source: viewModel, htmlContent: el.outerHTML };
}
private async _attachToolbar(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, index: number, mimeTypes: readonly IOrderedMimeType[]) {
const hasMultipleMimeTypes = mimeTypes.filter(mimeType => mimeType.isTrusted).length <= 1;
if (index > 0 && hasMultipleMimeTypes) {
return;
}
if (!this.notebookEditor.hasModel()) {
return;
}
const useConsolidatedButton = this.notebookEditor.notebookOptions.getLayoutConfiguration().consolidatedOutputButton;
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.cell-output-toolbar');
outputItemDiv.appendChild(mimeTypePicker);
const toolbar = this._renderDisposableStore.add(this.instantiationService.createInstance(WorkbenchToolBar, mimeTypePicker, {
renderDropdownAsChildElement: false
}));
toolbar.context = <INotebookCellActionContext>{
ui: true,
cell: this.output.cellViewModel as ICellViewModel,
notebookEditor: this.notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
};
// TODO: This could probably be a real registered action, but it has to talk to this output element
const pickAction = new Action('notebook.output.pickMimetype', nls.localize('pickMimeType', "Change Presentation"), ThemeIcon.asClassName(mimetypeIcon), undefined,
async _context => this._pickActiveMimeTypeRenderer(outputItemDiv, notebookTextModel, kernel, this.output));
if (index === 0 && useConsolidatedButton) {
const menu = this._renderDisposableStore.add(this.menuService.createMenu(MenuId.NotebookOutputToolbar, this.contextKeyService));
const updateMenuToolbar = () => {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, result, () => false);
toolbar.setActions([], [pickAction, ...secondary]);
};
updateMenuToolbar();
this._renderDisposableStore.add(menu.onDidChange(updateMenuToolbar));
} else {
toolbar.setActions([pickAction]);
}
}
private async _pickActiveMimeTypeRenderer(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, viewModel: ICellOutputViewModel) {
const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, kernel?.preloadProvides);
const items: IMimeTypeRenderer[] = [];
const unsupportedItems: IMimeTypeRenderer[] = [];
mimeTypes.forEach((mimeType, index) => {
if (mimeType.isTrusted) {
const arr = mimeType.rendererId === RENDERER_NOT_AVAILABLE ?
unsupportedItems :
items;
arr.push({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
detail: this._generateRendererInfo(mimeType.rendererId),
description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined
});
}
});
if (unsupportedItems.some(m => JUPYTER_RENDERER_MIMETYPES.includes(m.id!))) {
unsupportedItems.push({
label: nls.localize('installJupyterPrompt', "Install additional renderers from the marketplace"),
id: 'installRenderers',
index: mimeTypes.length
});
}
const picker = this.quickInputService.createQuickPick();
picker.items = [
...items,
{ type: 'separator' },
...unsupportedItems
];
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = items.length !== mimeTypes.length
? nls.localize('promptChooseMimeTypeInSecure.placeHolder', "Select mimetype to render for current output")
: nls.localize('promptChooseMimeType.placeHolder', "Select mimetype to render for current output");
const pick = await new Promise<IMimeTypeRenderer | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer) : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined || pick.index === currIndex) {
return;
}
if (pick.id === 'installRenderers') {
this._showJupyterExtension();
return;
}
// user chooses another mimetype
const nextElement = outputItemDiv.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(viewModel);
}
viewModel.pickedMimeType = mimeTypes[pick.index];
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
const { mimeType, rendererId } = mimeTypes[pick.index];
this.notebookService.updateMimePreferredRenderer(notebookTextModel.viewType, mimeType, rendererId, mimeTypes.map(m => m.mimeType));
this.render(nextElement as HTMLElement);
this._validateFinalOutputHeight(false);
this._relayoutCell();
}
private async _showJupyterExtension() {
const viewlet = await this.paneCompositeService.openPaneComposite(EXTENSION_VIEWLET_ID, ViewContainerLocation.Sidebar, true);
const view = viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer | undefined;
view?.search(`@id:${JUPYTER_EXTENSION_ID}`);
}
private _generateRendererInfo(renderId: string): string {
const renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
const displayName = renderInfo.displayName !== '' ? renderInfo.displayName : renderInfo.id;
return `${displayName} (${renderInfo.extensionId.value})`;
}
return nls.localize('unavailableRenderInfo', "renderer not available");
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
if (this._outputHeightTimer) {
this.viewCell.unlockOutputHeight();
clearTimeout(this._outputHeightTimer);
}
super.dispose();
}
}
class OutputEntryViewHandler {
constructor(
readonly model: ICellOutputViewModel,
readonly element: CellOutputElement
) {
}
}
export class CellOutputContainer extends CellContentPart {
private _outputEntries: OutputEntryViewHandler[] = [];
get renderedOutputEntries() {
return this._outputEntries;
}
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private readonly templateData: CodeCellRenderTemplate,
private options: { limit: number },
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._register(viewCell.onDidChangeOutputs(splice => {
this._updateOutputs(splice);
}));
this._register(viewCell.onDidChangeLayout(() => {
this.updateInternalLayoutNow(viewCell);
}));
}
override updateInternalLayoutNow(viewCell: CodeCellViewModel) {
this.templateData.outputContainer.setTop(viewCell.layoutInfo.outputContainerOffset);
this.templateData.outputShowMoreContainer.setTop(viewCell.layoutInfo.outputShowMoreContainerOffset);
this._outputEntries.forEach(entry => {
const index = this.viewCell.outputsViewModels.indexOf(entry.model);
if (index >= 0) {
const top = this.viewCell.getOutputOffsetInContainer(index);
entry.element.updateDOMTop(top);
}
});
}
render() {
if (this.viewCell.outputsViewModels.length > 0) {
if (this.viewCell.layoutInfo.outputTotalHeight !== 0) {
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
this._relayoutCell();
}
DOM.show(this.templateData.outputContainer.domNode);
for (let index = 0; index < Math.min(this.options.limit, this.viewCell.outputsViewModels.length); index++) {
const currOutput = this.viewCell.outputsViewModels[index];
const entry = this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, currOutput);
this._outputEntries.push(new OutputEntryViewHandler(currOutput, entry));
entry.render(undefined);
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(46);
}
this._relayoutCell();
this._validateFinalOutputHeight(false);
} else {
// noop
this._relayoutCell();
DOM.hide(this.templateData.outputContainer.domNode);
}
this.templateData.outputShowMoreContainer.domNode.innerText = '';
if (this.viewCell.outputsViewModels.length > this.options.limit) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(0);
}
}
viewUpdateShowOutputs(initRendering: boolean): void {
for (let index = 0; index < this._outputEntries.length; index++) {
const viewHandler = this._outputEntries[index];
const outputEntry = viewHandler.element;
if (outputEntry.renderResult) {
this.notebookEditor.createOutput(this.viewCell, outputEntry.renderResult as IInsetRenderOutput, this.viewCell.getOutputOffset(index));
} else {
outputEntry.render(undefined);
}
}
this._relayoutCell();
}
viewUpdateHideOuputs(): void {
for (let index = 0; index < this._outputEntries.length; index++) {
this.notebookEditor.hideInset(this._outputEntries[index].model);
}
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _updateOutputs(splice: NotebookCellOutputsSplice) {
const previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;
// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.
this.viewCell.updateOutputMinHeight(previousOutputHeight);
if (this.viewCell.outputsViewModels.length) {
DOM.show(this.templateData.outputContainer.domNode);
} else {
DOM.hide(this.templateData.outputContainer.domNode);
}
this.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));
this._renderNow(splice);
}
private _renderNow(splice: NotebookCellOutputsSplice) {
if (splice.start >= this.options.limit) {
// splice items out of limit
return;
}
const firstGroupEntries = this._outputEntries.slice(0, splice.start);
const deletedEntries = this._outputEntries.slice(splice.start, splice.start + splice.deleteCount);
const secondGroupEntries = this._outputEntries.slice(splice.start + splice.deleteCount);
let newlyInserted = this.viewCell.outputsViewModels.slice(splice.start, splice.start + splice.newOutputs.length);
// [...firstGroup, ...deletedEntries, ...secondGroupEntries] [...restInModel]
// [...firstGroup, ...newlyInserted, ...secondGroupEntries, restInModel]
if (firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length > this.options.limit) {
// exceeds limit again
if (firstGroupEntries.length + newlyInserted.length > this.options.limit) {
[...deletedEntries, ...secondGroupEntries].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
newlyInserted = newlyInserted.slice(0, this.options.limit - firstGroupEntries.length);
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries];
// render newly inserted outputs
for (let i = firstGroupEntries.length; i < this._outputEntries.length; i++) {
this._outputEntries[i].element.render(undefined);
}
} else {
// part of secondGroupEntries are pushed out of view
// now we have to be creative as secondGroupEntries might not use dedicated containers
const elementsPushedOutOfView = secondGroupEntries.slice(this.options.limit - firstGroupEntries.length - newlyInserted.length);
[...deletedEntries, ...elementsPushedOutOfView].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
// exclusive
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries.slice(0, this.options.limit - firstGroupEntries.length - newlyInserted.length)];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
}
} else {
// after splice, it doesn't exceed
deletedEntries.forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
let outputsNewlyAvailable: OutputEntryViewHandler[] = [];
if (firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length < this.viewCell.outputsViewModels.length) {
const last = Math.min(this.options.limit, this.viewCell.outputsViewModels.length);
outputsNewlyAvailable = this.viewCell.outputsViewModels.slice(firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length, last).map(output => {
return new OutputEntryViewHandler(output, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, output));
});
}
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries, ...outputsNewlyAvailable];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
for (let i = 0; i < outputsNewlyAvailable.length; i++) {
this._outputEntries[firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length + i].element.render(undefined);
}
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
if (!this.templateData.outputShowMoreContainer.domNode.hasChildNodes()) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
}
this.viewCell.updateOutputShowMoreContainerHeight(46);
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
}
const editorHeight = this.templateData.editor.getContentHeight();
this.viewCell.editorHeight = editorHeight;
this._relayoutCell();
// if it's clearing all outputs, or outputs are all rendered synchronously
// shrink immediately as the final output height will be zero.
this._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);
}
private _generateShowMoreElement(disposables: DisposableStore): HTMLElement {
const md: IMarkdownString = {
value: `There are more than ${this.options.limit} outputs, [show more (open the raw output data in a text editor) ...](command:workbench.action.openLargeOutput)`,
isTrusted: true,
supportThemeIcons: true
};
const rendered = renderMarkdown(md, {
actionHandler: {
callback: (content) => {
if (content === 'command:workbench.action.openLargeOutput') {
this.openerService.open(CellUri.generateCellOutputUri(this.notebookEditor.textModel!.uri));
}
return;
},
disposables
}
});
disposables.add(rendered);
rendered.element.classList.add('output-show-more');
return rendered.element;
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
this.viewCell.updateOutputMinHeight(0);
if (this._outputHeightTimer) {
clearTimeout(this._outputHeightTimer);
}
this._outputEntries.forEach(entry => {
entry.element.dispose();
});
super.dispose();
}
}
const JUPYTER_RENDERER_MIMETYPES = [
'application/geo+json',
'application/vdom.v1+json',
'application/vnd.dataresource+json',
'application/vnd.plotly.v1+json',
'application/vnd.vega.v2+json',
'application/vnd.vega.v3+json',
'application/vnd.vega.v4+json',
'application/vnd.vega.v5+json',
'application/vnd.vegalite.v1+json',
'application/vnd.vegalite.v2+json',
'application/vnd.vegalite.v3+json',
'application/vnd.vegalite.v4+json',
'application/x-nteract-model-debug+json',
'image/svg+xml',
'text/latex',
'text/vnd.plotly.v1+html',
'application/vnd.jupyter.widget-view+json',
'application/vnd.code.notebook.error'
];
| src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.9990932941436768,
0.05433841049671173,
0.0001628657046239823,
0.0001725030888337642,
0.22580529749393463
] |
{
"id": 9,
"code_window": [
"import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n",
"import { BaseCellViewModel } from './baseCellViewModel';\n",
"import { NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';\n",
"\n",
"export class CodeCellViewModel extends BaseCellViewModel implements ICellViewModel {\n",
"\treadonly cellKind = CellKind.Code;\n",
"\n",
"\tprotected readonly _onLayoutInfoRead = this._register(new Emitter<void>());\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type { IV8Profile, IV8ProfileNode } from 'vs/platform/profiling/common/profiling';
// #region
// https://github.com/microsoft/vscode-js-profile-visualizer/blob/6e7401128ee860be113a916f80fcfe20ac99418e/packages/vscode-js-profile-core/src/cpu/model.ts#L4
export interface IProfileModel {
nodes: ReadonlyArray<IComputedNode>;
locations: ReadonlyArray<ILocation>;
samples: ReadonlyArray<number>;
timeDeltas: ReadonlyArray<number>;
rootPath?: string;
duration: number;
}
export interface IComputedNode {
id: number;
selfTime: number;
aggregateTime: number;
children: number[];
parent?: number;
locationId: number;
}
export interface ISourceLocation {
lineNumber: number;
columnNumber: number;
// source: Dap.Source;
relativePath?: string;
}
export interface CdpCallFrame {
functionName: string;
scriptId: string;
url: string;
lineNumber: number;
columnNumber: number;
}
export interface CdpPositionTickInfo {
line: number;
ticks: number;
}
export interface INode {
id: number;
// category: Category;
callFrame: CdpCallFrame;
src?: ISourceLocation;
}
export interface ILocation extends INode {
selfTime: number;
aggregateTime: number;
ticks: number;
}
export interface IAnnotationLocation {
callFrame: CdpCallFrame;
locations: ISourceLocation[];
}
export interface IProfileNode extends IV8ProfileNode {
locationId?: number;
positionTicks?: (CdpPositionTickInfo & {
startLocationId?: number;
endLocationId?: number;
})[];
}
export interface ICpuProfileRaw extends IV8Profile {
// $vscode?: IJsDebugAnnotations;
nodes: IProfileNode[];
}
/**
* Recursive function that computes and caches the aggregate time for the
* children of the computed now.
*/
const computeAggregateTime = (index: number, nodes: IComputedNode[]): number => {
const row = nodes[index];
if (row.aggregateTime) {
return row.aggregateTime;
}
let total = row.selfTime;
for (const child of row.children) {
total += computeAggregateTime(child, nodes);
}
return (row.aggregateTime = total);
};
const ensureSourceLocations = (profile: ICpuProfileRaw): ReadonlyArray<IAnnotationLocation> => {
let locationIdCounter = 0;
const locationsByRef = new Map<string, { id: number; callFrame: CdpCallFrame; location: ISourceLocation }>();
const getLocationIdFor = (callFrame: CdpCallFrame) => {
const ref = [
callFrame.functionName,
callFrame.url,
callFrame.scriptId,
callFrame.lineNumber,
callFrame.columnNumber,
].join(':');
const existing = locationsByRef.get(ref);
if (existing) {
return existing.id;
}
const id = locationIdCounter++;
locationsByRef.set(ref, {
id,
callFrame,
location: {
lineNumber: callFrame.lineNumber + 1,
columnNumber: callFrame.columnNumber + 1,
// source: {
// name: maybeFileUrlToPath(callFrame.url),
// path: maybeFileUrlToPath(callFrame.url),
// sourceReference: 0,
// },
},
});
return id;
};
for (const node of profile.nodes) {
node.locationId = getLocationIdFor(node.callFrame);
node.positionTicks = node.positionTicks?.map(tick => ({
...tick,
// weirdly, line numbers here are 1-based, not 0-based. The position tick
// only gives line-level granularity, so 'mark' the entire range of source
// code the tick refers to
startLocationId: getLocationIdFor({
...node.callFrame,
lineNumber: tick.line - 1,
columnNumber: 0,
}),
endLocationId: getLocationIdFor({
...node.callFrame,
lineNumber: tick.line,
columnNumber: 0,
}),
}));
}
return [...locationsByRef.values()]
.sort((a, b) => a.id - b.id)
.map(l => ({ locations: [l.location], callFrame: l.callFrame }));
};
/**
* Computes the model for the given profile.
*/
export const buildModel = (profile: ICpuProfileRaw): IProfileModel => {
if (!profile.timeDeltas || !profile.samples) {
return {
nodes: [],
locations: [],
samples: profile.samples || [],
timeDeltas: profile.timeDeltas || [],
// rootPath: profile.$vscode?.rootPath,
duration: profile.endTime - profile.startTime,
};
}
const { samples, timeDeltas } = profile;
const sourceLocations = ensureSourceLocations(profile);
const locations: ILocation[] = sourceLocations.map((l, id) => {
const src = l.locations[0]; //getBestLocation(profile, l.locations);
return {
id,
selfTime: 0,
aggregateTime: 0,
ticks: 0,
// category: categorize(l.callFrame, src),
callFrame: l.callFrame,
src,
};
});
const idMap = new Map<number /* id in profile */, number /* incrementing ID */>();
const mapId = (nodeId: number) => {
let id = idMap.get(nodeId);
if (id === undefined) {
id = idMap.size;
idMap.set(nodeId, id);
}
return id;
};
// 1. Created a sorted list of nodes. It seems that the profile always has
// incrementing IDs, although they are just not initially sorted.
const nodes = new Array<IComputedNode>(profile.nodes.length);
for (let i = 0; i < profile.nodes.length; i++) {
const node = profile.nodes[i];
// make them 0-based:
const id = mapId(node.id);
nodes[id] = {
id,
selfTime: 0,
aggregateTime: 0,
locationId: node.locationId as number,
children: node.children?.map(mapId) || [],
};
for (const child of node.positionTicks || []) {
if (child.startLocationId) {
locations[child.startLocationId].ticks += child.ticks;
}
}
}
for (const node of nodes) {
for (const child of node.children) {
nodes[child].parent = node.id;
}
}
// 2. The profile samples are the 'bottom-most' node, the currently running
// code. Sum of these in the self time.
const duration = profile.endTime - profile.startTime;
let lastNodeTime = duration - timeDeltas[0];
for (let i = 0; i < timeDeltas.length - 1; i++) {
const d = timeDeltas[i + 1];
nodes[mapId(samples[i])].selfTime += d;
lastNodeTime -= d;
}
// Add in an extra time delta for the last sample. `timeDeltas[0]` is the
// time before the first sample, and the time of the last sample is only
// derived (approximately) by the missing time in the sum of deltas. Save
// some work by calculating it here.
if (nodes.length) {
nodes[mapId(samples[timeDeltas.length - 1])].selfTime += lastNodeTime;
timeDeltas.push(lastNodeTime);
}
// 3. Add the aggregate times for all node children and locations
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
const location = locations[node.locationId];
location.aggregateTime += computeAggregateTime(i, nodes);
location.selfTime += node.selfTime;
}
return {
nodes,
locations,
samples: samples.map(mapId),
timeDeltas,
// rootPath: profile.$vscode?.rootPath,
duration,
};
};
export class BottomUpNode {
public static root() {
return new BottomUpNode({
id: -1,
selfTime: 0,
aggregateTime: 0,
ticks: 0,
callFrame: {
functionName: '(root)',
lineNumber: -1,
columnNumber: -1,
scriptId: '0',
url: '',
},
});
}
public children: { [id: number]: BottomUpNode } = {};
public aggregateTime = 0;
public selfTime = 0;
public ticks = 0;
public childrenSize = 0;
public get id() {
return this.location.id;
}
public get callFrame() {
return this.location.callFrame;
}
public get src() {
return this.location.src;
}
constructor(public readonly location: ILocation, public readonly parent?: BottomUpNode) { }
public addNode(node: IComputedNode) {
this.selfTime += node.selfTime;
this.aggregateTime += node.aggregateTime;
}
}
export const processNode = (aggregate: BottomUpNode, node: IComputedNode, model: IProfileModel, initialNode = node) => {
let child = aggregate.children[node.locationId];
if (!child) {
child = new BottomUpNode(model.locations[node.locationId], aggregate);
aggregate.childrenSize++;
aggregate.children[node.locationId] = child;
}
child.addNode(initialNode);
if (node.parent) {
processNode(child, model.nodes[node.parent], model, initialNode);
}
};
//#endregion
export interface BottomUpSample {
selfTime: number;
totalTime: number;
location: string;
url: string;
caller: { percentage: number; location: string }[];
percentage: number;
isSpecial: boolean;
}
| src/vs/platform/profiling/common/profilingModel.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0001779949525371194,
0.00017310930707026273,
0.00016407870862167329,
0.0001741794985719025,
0.0000031118502192839514
] |
{
"id": 9,
"code_window": [
"import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n",
"import { BaseCellViewModel } from './baseCellViewModel';\n",
"import { NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';\n",
"\n",
"export class CodeCellViewModel extends BaseCellViewModel implements ICellViewModel {\n",
"\treadonly cellKind = CellKind.Code;\n",
"\n",
"\tprotected readonly _onLayoutInfoRead = this._register(new Emitter<void>());\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { BrowserWindow, Rectangle } from 'electron';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { ISerializableCommandAction } from 'vs/platform/action/common/action';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
import { IUserDataProfile } from 'vs/platform/userDataProfile/common/userDataProfile';
import { INativeWindowConfiguration } from 'vs/platform/window/common/window';
import { ISingleFolderWorkspaceIdentifier, IWorkspaceIdentifier } from 'vs/platform/workspace/common/workspace';
export interface ICodeWindow extends IDisposable {
readonly onWillLoad: Event<ILoadEvent>;
readonly onDidSignalReady: Event<void>;
readonly onDidTriggerSystemContextMenu: Event<{ x: number; y: number }>;
readonly onDidClose: Event<void>;
readonly onDidDestroy: Event<void>;
readonly whenClosedOrLoaded: Promise<void>;
readonly id: number;
readonly win: BrowserWindow | null; /* `null` after being disposed */
readonly config: INativeWindowConfiguration | undefined;
readonly openedWorkspace?: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier;
readonly profile?: IUserDataProfile;
readonly backupPath?: string;
readonly remoteAuthority?: string;
readonly isExtensionDevelopmentHost: boolean;
readonly isExtensionTestHost: boolean;
readonly lastFocusTime: number;
readonly isReady: boolean;
ready(): Promise<ICodeWindow>;
setReady(): void;
addTabbedWindow(window: ICodeWindow): void;
load(config: INativeWindowConfiguration, options?: { isReload?: boolean }): void;
reload(cli?: NativeParsedArgs): void;
focus(options?: { force: boolean }): void;
close(): void;
getBounds(): Rectangle;
send(channel: string, ...args: any[]): void;
sendWhenReady(channel: string, token: CancellationToken, ...args: any[]): void;
readonly isFullScreen: boolean;
toggleFullScreen(): void;
isMinimized(): boolean;
setRepresentedFilename(name: string): void;
getRepresentedFilename(): string | undefined;
setDocumentEdited(edited: boolean): void;
isDocumentEdited(): boolean;
handleTitleDoubleClick(): void;
updateTouchBar(items: ISerializableCommandAction[][]): void;
serializeWindowState(): IWindowState;
updateWindowControls(options: { height?: number; backgroundColor?: string; foregroundColor?: string }): void;
}
export const enum LoadReason {
/**
* The window is loaded for the first time.
*/
INITIAL = 1,
/**
* The window is loaded into a different workspace context.
*/
LOAD,
/**
* The window is reloaded.
*/
RELOAD
}
export const enum UnloadReason {
/**
* The window is closed.
*/
CLOSE = 1,
/**
* All windows unload because the application quits.
*/
QUIT,
/**
* The window is reloaded.
*/
RELOAD,
/**
* The window is loaded into a different workspace context.
*/
LOAD
}
export interface IWindowState {
width?: number;
height?: number;
x?: number;
y?: number;
mode?: WindowMode;
readonly display?: number;
}
export const defaultWindowState = function (mode = WindowMode.Normal): IWindowState {
return {
width: 1024,
height: 768,
mode
};
};
export const enum WindowMode {
Maximized,
Normal,
Minimized, // not used anymore, but also cannot remove due to existing stored UI state (needs migration)
Fullscreen
}
export interface ILoadEvent {
readonly workspace: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | undefined;
readonly reason: LoadReason;
}
export const enum WindowError {
/**
* Maps to the `unresponsive` event on a `BrowserWindow`.
*/
UNRESPONSIVE = 1,
/**
* Maps to the `render-process-gone` event on a `WebContents`.
*/
PROCESS_GONE = 2,
/**
* Maps to the `did-fail-load` event on a `WebContents`.
*/
LOAD = 3
}
| src/vs/platform/window/electron-main/window.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017556000966578722,
0.0001728840870782733,
0.00016944257367867976,
0.00017260957974940538,
0.0000018504697436583228
] |
{
"id": 9,
"code_window": [
"import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n",
"import { BaseCellViewModel } from './baseCellViewModel';\n",
"import { NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';\n",
"\n",
"export class CodeCellViewModel extends BaseCellViewModel implements ICellViewModel {\n",
"\treadonly cellKind = CellKind.Code;\n",
"\n",
"\tprotected readonly _onLayoutInfoRead = this._register(new Emitter<void>());\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { RunOnceScheduler } from 'vs/base/common/async';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { extUriBiasedIgnorePathCase } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { ConfigurationTarget, IConfigurationChange, IConfigurationChangeEvent, IConfigurationData, IConfigurationOverrides, IConfigurationService, IConfigurationValue, isConfigurationOverrides } from 'vs/platform/configuration/common/configuration';
import { Configuration, ConfigurationChangeEvent, ConfigurationModel, UserSettings } from 'vs/platform/configuration/common/configurationModels';
import { DefaultConfiguration, IPolicyConfiguration, NullPolicyConfiguration, PolicyConfiguration } from 'vs/platform/configuration/common/configurations';
import { IFileService } from 'vs/platform/files/common/files';
import { ILogService } from 'vs/platform/log/common/log';
import { IPolicyService, NullPolicyService } from 'vs/platform/policy/common/policy';
export class ConfigurationService extends Disposable implements IConfigurationService, IDisposable {
declare readonly _serviceBrand: undefined;
private configuration: Configuration;
private readonly defaultConfiguration: DefaultConfiguration;
private readonly policyConfiguration: IPolicyConfiguration;
private readonly userConfiguration: UserSettings;
private readonly reloadConfigurationScheduler: RunOnceScheduler;
private readonly _onDidChangeConfiguration: Emitter<IConfigurationChangeEvent> = this._register(new Emitter<IConfigurationChangeEvent>());
readonly onDidChangeConfiguration: Event<IConfigurationChangeEvent> = this._onDidChangeConfiguration.event;
constructor(
private readonly settingsResource: URI,
fileService: IFileService,
policyService: IPolicyService,
logService: ILogService,
) {
super();
this.defaultConfiguration = this._register(new DefaultConfiguration());
this.policyConfiguration = policyService instanceof NullPolicyService ? new NullPolicyConfiguration() : this._register(new PolicyConfiguration(this.defaultConfiguration, policyService, logService));
this.userConfiguration = this._register(new UserSettings(this.settingsResource, undefined, extUriBiasedIgnorePathCase, fileService));
this.configuration = new Configuration(this.defaultConfiguration.configurationModel, this.policyConfiguration.configurationModel, new ConfigurationModel(), new ConfigurationModel());
this.reloadConfigurationScheduler = this._register(new RunOnceScheduler(() => this.reloadConfiguration(), 50));
this._register(this.defaultConfiguration.onDidChangeConfiguration(({ defaults, properties }) => this.onDidDefaultConfigurationChange(defaults, properties)));
this._register(this.policyConfiguration.onDidChangeConfiguration(model => this.onDidPolicyConfigurationChange(model)));
this._register(this.userConfiguration.onDidChange(() => this.reloadConfigurationScheduler.schedule()));
}
async initialize(): Promise<void> {
const [defaultModel, policyModel, userModel] = await Promise.all([this.defaultConfiguration.initialize(), this.policyConfiguration.initialize(), this.userConfiguration.loadConfiguration()]);
this.configuration = new Configuration(defaultModel, policyModel, new ConfigurationModel(), userModel);
}
getConfigurationData(): IConfigurationData {
return this.configuration.toData();
}
getValue<T>(): T;
getValue<T>(section: string): T;
getValue<T>(overrides: IConfigurationOverrides): T;
getValue<T>(section: string, overrides: IConfigurationOverrides): T;
getValue(arg1?: any, arg2?: any): any {
const section = typeof arg1 === 'string' ? arg1 : undefined;
const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {};
return this.configuration.getValue(section, overrides, undefined);
}
updateValue(key: string, value: any): Promise<void>;
updateValue(key: string, value: any, overrides: IConfigurationOverrides): Promise<void>;
updateValue(key: string, value: any, target: ConfigurationTarget): Promise<void>;
updateValue(key: string, value: any, overrides: IConfigurationOverrides, target: ConfigurationTarget): Promise<void>;
updateValue(key: string, value: any, arg3?: any, arg4?: any): Promise<void> {
return Promise.reject(new Error('not supported'));
}
inspect<T>(key: string): IConfigurationValue<T> {
return this.configuration.inspect<T>(key, {}, undefined);
}
keys(): {
default: string[];
user: string[];
workspace: string[];
workspaceFolder: string[];
} {
return this.configuration.keys(undefined);
}
async reloadConfiguration(): Promise<void> {
const configurationModel = await this.userConfiguration.loadConfiguration();
this.onDidChangeUserConfiguration(configurationModel);
}
private onDidChangeUserConfiguration(userConfigurationModel: ConfigurationModel): void {
const previous = this.configuration.toData();
const change = this.configuration.compareAndUpdateLocalUserConfiguration(userConfigurationModel);
this.trigger(change, previous, ConfigurationTarget.USER);
}
private onDidDefaultConfigurationChange(defaultConfigurationModel: ConfigurationModel, properties: string[]): void {
const previous = this.configuration.toData();
const change = this.configuration.compareAndUpdateDefaultConfiguration(defaultConfigurationModel, properties);
this.trigger(change, previous, ConfigurationTarget.DEFAULT);
}
private onDidPolicyConfigurationChange(policyConfiguration: ConfigurationModel): void {
const previous = this.configuration.toData();
const change = this.configuration.compareAndUpdatePolicyConfiguration(policyConfiguration);
this.trigger(change, previous, ConfigurationTarget.DEFAULT);
}
private trigger(configurationChange: IConfigurationChange, previous: IConfigurationData, source: ConfigurationTarget): void {
const event = new ConfigurationChangeEvent(configurationChange, { data: previous }, this.configuration);
event.source = source;
event.sourceConfig = this.getTargetConfiguration(source);
this._onDidChangeConfiguration.fire(event);
}
private getTargetConfiguration(target: ConfigurationTarget): any {
switch (target) {
case ConfigurationTarget.DEFAULT:
return this.configuration.defaults.contents;
case ConfigurationTarget.USER:
return this.configuration.localUserConfiguration.contents;
}
return {};
}
}
| src/vs/platform/configuration/common/configurationService.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017593773372936994,
0.00017234202823601663,
0.00016581143427174538,
0.00017290493997279555,
0.0000030223473004298285
] |
{
"id": 10,
"code_window": [
"\treadonly cellKind = CellKind.Code;\n",
"\n",
"\tprotected readonly _onLayoutInfoRead = this._register(new Emitter<void>());\n",
"\treadonly onLayoutInfoRead = this._onLayoutInfoRead.event;\n",
"\n",
"\tprotected readonly _onDidChangeOutputs = this._register(new Emitter<NotebookCellOutputsSplice>());\n",
"\treadonly onDidChangeOutputs = this._onDidChangeOutputs.event;\n",
"\n",
"\tprivate readonly _onDidRemoveOutputs = this._register(new Emitter<readonly ICellOutputViewModel[]>());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprotected readonly _onDidStartExecution = this._register(new Emitter<void>());\n",
"\treadonly onDidStartExecution = this._onDidStartExecution.event;\n",
"\tprotected readonly _onDidStopExecution = this._register(new Emitter<void>());\n",
"\treadonly onDidStopExecution = this._onDidStopExecution.event;\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 30
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
import { renderMarkdown } from 'vs/base/browser/markdownRenderer';
import { Action, IAction } from 'vs/base/common/actions';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import * as nls from 'vs/nls';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { WorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { IMenuService, MenuId } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSION_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellOutputViewModel, ICellViewModel, IInsetRenderOutput, INotebookEditorDelegate, JUPYTER_EXTENSION_ID, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { mimetypeIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';
import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
interface IRenderResult {
initRenderIsSynchronous: false;
}
// DOM structure
//
// #output
// |
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | | #output-element
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
class CellOutputElement extends Disposable {
private readonly _renderDisposableStore = this._register(new DisposableStore());
innerContainer?: HTMLElement;
renderedOutputContainer!: HTMLElement;
renderResult?: IInsetRenderOutput;
private readonly contextKeyService: IContextKeyService;
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private cellOutputContainer: CellOutputContainer,
private outputContainer: FastDomNode<HTMLElement>,
readonly output: ICellOutputViewModel,
@INotebookService private readonly notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@IContextKeyService parentContextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this.contextKeyService = parentContextKeyService;
this._register(this.output.model.onDidChangeData(() => {
this.rerender();
}));
this._register(this.output.onDidResetRenderer(() => {
this.rerender();
}));
}
detach() {
this.renderedOutputContainer?.parentElement?.removeChild(this.renderedOutputContainer);
let count = 0;
if (this.innerContainer) {
for (let i = 0; i < this.innerContainer.childNodes.length; i++) {
if ((this.innerContainer.childNodes[i] as HTMLElement).className === 'rendered-output') {
count++;
}
if (count > 1) {
break;
}
}
if (count === 0) {
this.innerContainer.parentElement?.removeChild(this.innerContainer);
}
}
this.notebookEditor.removeInset(this.output);
}
updateDOMTop(top: number) {
if (this.innerContainer) {
this.innerContainer.style.top = `${top}px`;
}
}
rerender() {
if (
this.notebookEditor.hasModel() &&
this.innerContainer &&
this.renderResult &&
this.renderResult.type === RenderOutputType.Extension
) {
// Output rendered by extension renderer got an update
const [mimeTypes, pick] = this.output.resolveMimeTypes(this.notebookEditor.textModel, this.notebookEditor.activeKernel?.preloadProvides);
const pickedMimeType = mimeTypes[pick];
if (pickedMimeType.mimeType === this.renderResult.mimeType && pickedMimeType.rendererId === this.renderResult.renderer.id) {
// Same mimetype, same renderer, call the extension renderer to update
const index = this.viewCell.outputsViewModels.indexOf(this.output);
this.notebookEditor.updateOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
return;
}
}
if (!this.innerContainer) {
// init rendering didn't happen
const currOutputIndex = this.cellOutputContainer.renderedOutputEntries.findIndex(entry => entry.element === this);
const previousSibling = currOutputIndex > 0 && !!(this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer?.parentElement)
? this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer
: undefined;
this.render(previousSibling);
} else {
// Another mimetype or renderer is picked, we need to clear the current output and re-render
const nextElement = this.innerContainer.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(this.output);
}
this.render(nextElement as HTMLElement);
}
this._relayoutCell();
}
// insert after previousSibling
private _generateInnerOutputContainer(previousSibling: HTMLElement | undefined, pickedMimeTypeRenderer: IOrderedMimeType) {
this.innerContainer = DOM.$('.output-inner-container');
if (previousSibling && previousSibling.nextElementSibling) {
this.outputContainer.domNode.insertBefore(this.innerContainer, previousSibling.nextElementSibling);
} else {
this.outputContainer.domNode.appendChild(this.innerContainer);
}
this.innerContainer.setAttribute('output-mime-type', pickedMimeTypeRenderer.mimeType);
return this.innerContainer;
}
render(previousSibling: HTMLElement | undefined): IRenderResult | undefined {
const index = this.viewCell.outputsViewModels.indexOf(this.output);
if (this.viewCell.isOutputCollapsed || !this.notebookEditor.hasModel()) {
return undefined;
}
const notebookUri = CellUri.parse(this.viewCell.uri)?.notebook;
if (!notebookUri) {
return undefined;
}
const notebookTextModel = this.notebookEditor.textModel;
const [mimeTypes, pick] = this.output.resolveMimeTypes(notebookTextModel, this.notebookEditor.activeKernel?.preloadProvides);
if (!mimeTypes.find(mimeType => mimeType.isTrusted) || mimeTypes.length === 0) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#noMimeType');
return undefined;
}
const pickedMimeTypeRenderer = mimeTypes[pick];
const innerContainer = this._generateInnerOutputContainer(previousSibling, pickedMimeTypeRenderer);
this._attachToolbar(innerContainer, notebookTextModel, this.notebookEditor.activeKernel, index, mimeTypes);
this.renderedOutputContainer = DOM.append(innerContainer, DOM.$('.rendered-output'));
const renderer = this.notebookService.getRendererInfo(pickedMimeTypeRenderer.rendererId);
this.renderResult = renderer
? { type: RenderOutputType.Extension, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType }
: this._renderMissingRenderer(this.output, pickedMimeTypeRenderer.mimeType);
this.output.pickedMimeType = pickedMimeTypeRenderer;
if (!this.renderResult) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#renderResultUndefined');
return undefined;
}
this.notebookEditor.createOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
innerContainer.classList.add('background');
return { initRenderIsSynchronous: false };
}
private _renderMissingRenderer(viewModel: ICellOutputViewModel, preferredMimeType: string | undefined): IInsetRenderOutput {
if (!viewModel.model.outputs.length) {
return this._renderMessage(viewModel, nls.localize('empty', "Cell has no output"));
}
if (!preferredMimeType) {
const mimeTypes = viewModel.model.outputs.map(op => op.mime);
const mimeTypesMessage = mimeTypes.join(', ');
return this._renderMessage(viewModel, nls.localize('noRenderer.2', "No renderer could be found for output. It has the following mimetypes: {0}", mimeTypesMessage));
}
return this._renderSearchForMimetype(viewModel, preferredMimeType);
}
private _renderSearchForMimetype(viewModel: ICellOutputViewModel, mimeType: string): IInsetRenderOutput {
const query = `@tag:notebookRenderer ${mimeType}`;
const p = DOM.$('p', undefined, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
const a = DOM.$('a', { href: `command:workbench.extensions.search?%22${query}%22`, class: 'monaco-button monaco-text-button', tabindex: 0, role: 'button', style: 'padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;' }, `Search Marketplace`);
return {
type: RenderOutputType.Html,
source: viewModel,
htmlContent: p.outerHTML + a.outerHTML
};
}
private _renderMessage(viewModel: ICellOutputViewModel, message: string): IInsetRenderOutput {
const el = DOM.$('p', undefined, message);
return { type: RenderOutputType.Html, source: viewModel, htmlContent: el.outerHTML };
}
private async _attachToolbar(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, index: number, mimeTypes: readonly IOrderedMimeType[]) {
const hasMultipleMimeTypes = mimeTypes.filter(mimeType => mimeType.isTrusted).length <= 1;
if (index > 0 && hasMultipleMimeTypes) {
return;
}
if (!this.notebookEditor.hasModel()) {
return;
}
const useConsolidatedButton = this.notebookEditor.notebookOptions.getLayoutConfiguration().consolidatedOutputButton;
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.cell-output-toolbar');
outputItemDiv.appendChild(mimeTypePicker);
const toolbar = this._renderDisposableStore.add(this.instantiationService.createInstance(WorkbenchToolBar, mimeTypePicker, {
renderDropdownAsChildElement: false
}));
toolbar.context = <INotebookCellActionContext>{
ui: true,
cell: this.output.cellViewModel as ICellViewModel,
notebookEditor: this.notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
};
// TODO: This could probably be a real registered action, but it has to talk to this output element
const pickAction = new Action('notebook.output.pickMimetype', nls.localize('pickMimeType', "Change Presentation"), ThemeIcon.asClassName(mimetypeIcon), undefined,
async _context => this._pickActiveMimeTypeRenderer(outputItemDiv, notebookTextModel, kernel, this.output));
if (index === 0 && useConsolidatedButton) {
const menu = this._renderDisposableStore.add(this.menuService.createMenu(MenuId.NotebookOutputToolbar, this.contextKeyService));
const updateMenuToolbar = () => {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, result, () => false);
toolbar.setActions([], [pickAction, ...secondary]);
};
updateMenuToolbar();
this._renderDisposableStore.add(menu.onDidChange(updateMenuToolbar));
} else {
toolbar.setActions([pickAction]);
}
}
private async _pickActiveMimeTypeRenderer(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, viewModel: ICellOutputViewModel) {
const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, kernel?.preloadProvides);
const items: IMimeTypeRenderer[] = [];
const unsupportedItems: IMimeTypeRenderer[] = [];
mimeTypes.forEach((mimeType, index) => {
if (mimeType.isTrusted) {
const arr = mimeType.rendererId === RENDERER_NOT_AVAILABLE ?
unsupportedItems :
items;
arr.push({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
detail: this._generateRendererInfo(mimeType.rendererId),
description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined
});
}
});
if (unsupportedItems.some(m => JUPYTER_RENDERER_MIMETYPES.includes(m.id!))) {
unsupportedItems.push({
label: nls.localize('installJupyterPrompt', "Install additional renderers from the marketplace"),
id: 'installRenderers',
index: mimeTypes.length
});
}
const picker = this.quickInputService.createQuickPick();
picker.items = [
...items,
{ type: 'separator' },
...unsupportedItems
];
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = items.length !== mimeTypes.length
? nls.localize('promptChooseMimeTypeInSecure.placeHolder', "Select mimetype to render for current output")
: nls.localize('promptChooseMimeType.placeHolder', "Select mimetype to render for current output");
const pick = await new Promise<IMimeTypeRenderer | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer) : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined || pick.index === currIndex) {
return;
}
if (pick.id === 'installRenderers') {
this._showJupyterExtension();
return;
}
// user chooses another mimetype
const nextElement = outputItemDiv.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(viewModel);
}
viewModel.pickedMimeType = mimeTypes[pick.index];
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
const { mimeType, rendererId } = mimeTypes[pick.index];
this.notebookService.updateMimePreferredRenderer(notebookTextModel.viewType, mimeType, rendererId, mimeTypes.map(m => m.mimeType));
this.render(nextElement as HTMLElement);
this._validateFinalOutputHeight(false);
this._relayoutCell();
}
private async _showJupyterExtension() {
const viewlet = await this.paneCompositeService.openPaneComposite(EXTENSION_VIEWLET_ID, ViewContainerLocation.Sidebar, true);
const view = viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer | undefined;
view?.search(`@id:${JUPYTER_EXTENSION_ID}`);
}
private _generateRendererInfo(renderId: string): string {
const renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
const displayName = renderInfo.displayName !== '' ? renderInfo.displayName : renderInfo.id;
return `${displayName} (${renderInfo.extensionId.value})`;
}
return nls.localize('unavailableRenderInfo', "renderer not available");
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
if (this._outputHeightTimer) {
this.viewCell.unlockOutputHeight();
clearTimeout(this._outputHeightTimer);
}
super.dispose();
}
}
class OutputEntryViewHandler {
constructor(
readonly model: ICellOutputViewModel,
readonly element: CellOutputElement
) {
}
}
export class CellOutputContainer extends CellContentPart {
private _outputEntries: OutputEntryViewHandler[] = [];
get renderedOutputEntries() {
return this._outputEntries;
}
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private readonly templateData: CodeCellRenderTemplate,
private options: { limit: number },
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._register(viewCell.onDidChangeOutputs(splice => {
this._updateOutputs(splice);
}));
this._register(viewCell.onDidChangeLayout(() => {
this.updateInternalLayoutNow(viewCell);
}));
}
override updateInternalLayoutNow(viewCell: CodeCellViewModel) {
this.templateData.outputContainer.setTop(viewCell.layoutInfo.outputContainerOffset);
this.templateData.outputShowMoreContainer.setTop(viewCell.layoutInfo.outputShowMoreContainerOffset);
this._outputEntries.forEach(entry => {
const index = this.viewCell.outputsViewModels.indexOf(entry.model);
if (index >= 0) {
const top = this.viewCell.getOutputOffsetInContainer(index);
entry.element.updateDOMTop(top);
}
});
}
render() {
if (this.viewCell.outputsViewModels.length > 0) {
if (this.viewCell.layoutInfo.outputTotalHeight !== 0) {
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
this._relayoutCell();
}
DOM.show(this.templateData.outputContainer.domNode);
for (let index = 0; index < Math.min(this.options.limit, this.viewCell.outputsViewModels.length); index++) {
const currOutput = this.viewCell.outputsViewModels[index];
const entry = this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, currOutput);
this._outputEntries.push(new OutputEntryViewHandler(currOutput, entry));
entry.render(undefined);
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(46);
}
this._relayoutCell();
this._validateFinalOutputHeight(false);
} else {
// noop
this._relayoutCell();
DOM.hide(this.templateData.outputContainer.domNode);
}
this.templateData.outputShowMoreContainer.domNode.innerText = '';
if (this.viewCell.outputsViewModels.length > this.options.limit) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(0);
}
}
viewUpdateShowOutputs(initRendering: boolean): void {
for (let index = 0; index < this._outputEntries.length; index++) {
const viewHandler = this._outputEntries[index];
const outputEntry = viewHandler.element;
if (outputEntry.renderResult) {
this.notebookEditor.createOutput(this.viewCell, outputEntry.renderResult as IInsetRenderOutput, this.viewCell.getOutputOffset(index));
} else {
outputEntry.render(undefined);
}
}
this._relayoutCell();
}
viewUpdateHideOuputs(): void {
for (let index = 0; index < this._outputEntries.length; index++) {
this.notebookEditor.hideInset(this._outputEntries[index].model);
}
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _updateOutputs(splice: NotebookCellOutputsSplice) {
const previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;
// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.
this.viewCell.updateOutputMinHeight(previousOutputHeight);
if (this.viewCell.outputsViewModels.length) {
DOM.show(this.templateData.outputContainer.domNode);
} else {
DOM.hide(this.templateData.outputContainer.domNode);
}
this.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));
this._renderNow(splice);
}
private _renderNow(splice: NotebookCellOutputsSplice) {
if (splice.start >= this.options.limit) {
// splice items out of limit
return;
}
const firstGroupEntries = this._outputEntries.slice(0, splice.start);
const deletedEntries = this._outputEntries.slice(splice.start, splice.start + splice.deleteCount);
const secondGroupEntries = this._outputEntries.slice(splice.start + splice.deleteCount);
let newlyInserted = this.viewCell.outputsViewModels.slice(splice.start, splice.start + splice.newOutputs.length);
// [...firstGroup, ...deletedEntries, ...secondGroupEntries] [...restInModel]
// [...firstGroup, ...newlyInserted, ...secondGroupEntries, restInModel]
if (firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length > this.options.limit) {
// exceeds limit again
if (firstGroupEntries.length + newlyInserted.length > this.options.limit) {
[...deletedEntries, ...secondGroupEntries].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
newlyInserted = newlyInserted.slice(0, this.options.limit - firstGroupEntries.length);
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries];
// render newly inserted outputs
for (let i = firstGroupEntries.length; i < this._outputEntries.length; i++) {
this._outputEntries[i].element.render(undefined);
}
} else {
// part of secondGroupEntries are pushed out of view
// now we have to be creative as secondGroupEntries might not use dedicated containers
const elementsPushedOutOfView = secondGroupEntries.slice(this.options.limit - firstGroupEntries.length - newlyInserted.length);
[...deletedEntries, ...elementsPushedOutOfView].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
// exclusive
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries.slice(0, this.options.limit - firstGroupEntries.length - newlyInserted.length)];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
}
} else {
// after splice, it doesn't exceed
deletedEntries.forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
let outputsNewlyAvailable: OutputEntryViewHandler[] = [];
if (firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length < this.viewCell.outputsViewModels.length) {
const last = Math.min(this.options.limit, this.viewCell.outputsViewModels.length);
outputsNewlyAvailable = this.viewCell.outputsViewModels.slice(firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length, last).map(output => {
return new OutputEntryViewHandler(output, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, output));
});
}
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries, ...outputsNewlyAvailable];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
for (let i = 0; i < outputsNewlyAvailable.length; i++) {
this._outputEntries[firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length + i].element.render(undefined);
}
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
if (!this.templateData.outputShowMoreContainer.domNode.hasChildNodes()) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
}
this.viewCell.updateOutputShowMoreContainerHeight(46);
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
}
const editorHeight = this.templateData.editor.getContentHeight();
this.viewCell.editorHeight = editorHeight;
this._relayoutCell();
// if it's clearing all outputs, or outputs are all rendered synchronously
// shrink immediately as the final output height will be zero.
this._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);
}
private _generateShowMoreElement(disposables: DisposableStore): HTMLElement {
const md: IMarkdownString = {
value: `There are more than ${this.options.limit} outputs, [show more (open the raw output data in a text editor) ...](command:workbench.action.openLargeOutput)`,
isTrusted: true,
supportThemeIcons: true
};
const rendered = renderMarkdown(md, {
actionHandler: {
callback: (content) => {
if (content === 'command:workbench.action.openLargeOutput') {
this.openerService.open(CellUri.generateCellOutputUri(this.notebookEditor.textModel!.uri));
}
return;
},
disposables
}
});
disposables.add(rendered);
rendered.element.classList.add('output-show-more');
return rendered.element;
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
this.viewCell.updateOutputMinHeight(0);
if (this._outputHeightTimer) {
clearTimeout(this._outputHeightTimer);
}
this._outputEntries.forEach(entry => {
entry.element.dispose();
});
super.dispose();
}
}
const JUPYTER_RENDERER_MIMETYPES = [
'application/geo+json',
'application/vdom.v1+json',
'application/vnd.dataresource+json',
'application/vnd.plotly.v1+json',
'application/vnd.vega.v2+json',
'application/vnd.vega.v3+json',
'application/vnd.vega.v4+json',
'application/vnd.vega.v5+json',
'application/vnd.vegalite.v1+json',
'application/vnd.vegalite.v2+json',
'application/vnd.vegalite.v3+json',
'application/vnd.vegalite.v4+json',
'application/x-nteract-model-debug+json',
'image/svg+xml',
'text/latex',
'text/vnd.plotly.v1+html',
'application/vnd.jupyter.widget-view+json',
'application/vnd.code.notebook.error'
];
| src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.9986995458602905,
0.01498833391815424,
0.00016564060933887959,
0.00017388186824973673,
0.11527878791093826
] |
{
"id": 10,
"code_window": [
"\treadonly cellKind = CellKind.Code;\n",
"\n",
"\tprotected readonly _onLayoutInfoRead = this._register(new Emitter<void>());\n",
"\treadonly onLayoutInfoRead = this._onLayoutInfoRead.event;\n",
"\n",
"\tprotected readonly _onDidChangeOutputs = this._register(new Emitter<NotebookCellOutputsSplice>());\n",
"\treadonly onDidChangeOutputs = this._onDidChangeOutputs.event;\n",
"\n",
"\tprivate readonly _onDidRemoveOutputs = this._register(new Emitter<readonly ICellOutputViewModel[]>());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprotected readonly _onDidStartExecution = this._register(new Emitter<void>());\n",
"\treadonly onDidStartExecution = this._onDidStartExecution.event;\n",
"\tprotected readonly _onDidStopExecution = this._register(new Emitter<void>());\n",
"\treadonly onDidStopExecution = this._onDidStopExecution.event;\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 30
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-editor .margin-view-overlays .codicon-folding-manual-collapsed,
.monaco-editor .margin-view-overlays .codicon-folding-manual-expanded,
.monaco-editor .margin-view-overlays .codicon-folding-expanded,
.monaco-editor .margin-view-overlays .codicon-folding-collapsed {
cursor: pointer;
opacity: 0;
transition: opacity 0.5s;
display: flex;
align-items: center;
justify-content: center;
font-size: 140%;
margin-left: 2px;
}
.monaco-editor .margin-view-overlays:hover .codicon,
.monaco-editor .margin-view-overlays .codicon.codicon-folding-collapsed,
.monaco-editor .margin-view-overlays .codicon.codicon-folding-manual-collapsed,
.monaco-editor .margin-view-overlays .codicon.alwaysShowFoldIcons {
opacity: 1;
}
.monaco-editor .inline-folded:after {
color: grey;
margin: 0.1em 0.2em 0 0.2em;
content: "\22EF"; /* ellipses unicode character */
display: inline;
line-height: 1em;
cursor: pointer;
}
.monaco-editor .folded-background {
background-color: var(--vscode-editor-foldBackground);
}
.monaco-editor .cldr.codicon.codicon-folding-expanded,
.monaco-editor .cldr.codicon.codicon-folding-collapsed,
.monaco-editor .cldr.codicon.codicon-folding-manual-expanded,
.monaco-editor .cldr.codicon.codicon-folding-manual-collapsed {
color: var(--vscode-editorGutter-foldingControlForeground) !important;
}
| src/vs/editor/contrib/folding/browser/folding.css | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017420397489331663,
0.00017242316971533,
0.00017056689830496907,
0.0001729495998006314,
0.0000013143442174623488
] |
{
"id": 10,
"code_window": [
"\treadonly cellKind = CellKind.Code;\n",
"\n",
"\tprotected readonly _onLayoutInfoRead = this._register(new Emitter<void>());\n",
"\treadonly onLayoutInfoRead = this._onLayoutInfoRead.event;\n",
"\n",
"\tprotected readonly _onDidChangeOutputs = this._register(new Emitter<NotebookCellOutputsSplice>());\n",
"\treadonly onDidChangeOutputs = this._onDidChangeOutputs.event;\n",
"\n",
"\tprivate readonly _onDidRemoveOutputs = this._register(new Emitter<readonly ICellOutputViewModel[]>());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprotected readonly _onDidStartExecution = this._register(new Emitter<void>());\n",
"\treadonly onDidStartExecution = this._onDidStartExecution.event;\n",
"\tprotected readonly _onDidStopExecution = this._register(new Emitter<void>());\n",
"\treadonly onDidStopExecution = this._onDidStopExecution.event;\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 30
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { FoldingModel, updateFoldingStateAtIndex } from 'vs/workbench/contrib/notebook/browser/viewModel/foldingModel';
import { runDeleteAction } from 'vs/workbench/contrib/notebook/browser/controller/cellOperations';
import { NotebookCellSelectionCollection } from 'vs/workbench/contrib/notebook/browser/viewModel/cellSelectionCollection';
import { CellEditType, CellKind, SelectionStateType } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { createNotebookCellList, setupInstantiationService, TestCell, withTestNotebook } from 'vs/workbench/contrib/notebook/test/browser/testNotebookEditor';
suite('NotebookSelection', () => {
test('focus is never empty', function () {
const selectionCollection = new NotebookCellSelectionCollection();
assert.deepStrictEqual(selectionCollection.focus, { start: 0, end: 0 });
selectionCollection.setState(null, [], true, 'model');
assert.deepStrictEqual(selectionCollection.focus, { start: 0, end: 0 });
});
});
suite('NotebookCellList focus/selection', () => {
let disposables: DisposableStore;
let instantiationService: TestInstantiationService;
let languageService: ILanguageService;
suiteSetup(() => {
disposables = new DisposableStore();
instantiationService = setupInstantiationService(disposables);
languageService = instantiationService.get(ILanguageService);
});
suiteTeardown(() => disposables.dispose());
test('notebook cell list setFocus', async function () {
await withTestNotebook(
[
['var a = 1;', 'javascript', CellKind.Code, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}]
],
(editor, viewModel) => {
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
assert.strictEqual(cellList.length, 2);
cellList.setFocus([0]);
assert.deepStrictEqual(viewModel.getFocus(), { start: 0, end: 1 });
cellList.setFocus([1]);
assert.deepStrictEqual(viewModel.getFocus(), { start: 1, end: 2 });
cellList.detachViewModel();
});
});
test('notebook cell list setSelections', async function () {
await withTestNotebook(
[
['var a = 1;', 'javascript', CellKind.Code, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}]
],
(editor, viewModel) => {
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
assert.strictEqual(cellList.length, 2);
cellList.setSelection([0]);
// the only selection is also the focus
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 0, end: 1 }]);
// set selection does not modify focus
cellList.setSelection([1]);
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 1, end: 2 }]);
});
});
test('notebook cell list setFocus', async function () {
await withTestNotebook(
[
['var a = 1;', 'javascript', CellKind.Code, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}]
],
(editor, viewModel) => {
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
assert.strictEqual(cellList.length, 2);
cellList.setFocus([0]);
assert.deepStrictEqual(viewModel.getFocus(), { start: 0, end: 1 });
cellList.setFocus([1]);
assert.deepStrictEqual(viewModel.getFocus(), { start: 1, end: 2 });
cellList.setSelection([1]);
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 1, end: 2 }]);
});
});
test('notebook cell list focus/selection from UI', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
(editor, viewModel) => {
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
assert.deepStrictEqual(viewModel.getFocus(), { start: 0, end: 1 });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 0, end: 1 }]);
// arrow down, move both focus and selections
cellList.setFocus([1], new KeyboardEvent('keydown'), undefined);
cellList.setSelection([1], new KeyboardEvent('keydown'), undefined);
assert.deepStrictEqual(viewModel.getFocus(), { start: 1, end: 2 });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 1, end: 2 }]);
// shift+arrow down, expands selection
cellList.setFocus([2], new KeyboardEvent('keydown'), undefined);
cellList.setSelection([1, 2]);
assert.deepStrictEqual(viewModel.getFocus(), { start: 2, end: 3 });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 1, end: 3 }]);
// arrow down, will move focus but not expand selection
cellList.setFocus([3], new KeyboardEvent('keydown'), undefined);
assert.deepStrictEqual(viewModel.getFocus(), { start: 3, end: 4 });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 1, end: 3 }]);
});
});
test('notebook cell list focus/selection with folding regions', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
(editor, viewModel) => {
const foldingModel = new FoldingModel();
foldingModel.attachViewModel(viewModel);
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
assert.strictEqual(cellList.length, 5);
assert.deepStrictEqual(viewModel.getFocus(), { start: 0, end: 1 });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 0, end: 1 }]);
cellList.setFocus([0]);
updateFoldingStateAtIndex(foldingModel, 0, true);
updateFoldingStateAtIndex(foldingModel, 2, true);
viewModel.updateFoldingRanges(foldingModel.regions);
cellList.setHiddenAreas(viewModel.getHiddenRanges(), true);
assert.strictEqual(cellList.length, 3);
// currently, focus on a folded cell will only focus the cell itself, excluding its "inner" cells
assert.deepStrictEqual(viewModel.getFocus(), { start: 0, end: 1 });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 0, end: 1 }]);
cellList.focusNext(1, false);
// focus next should skip the folded items
assert.deepStrictEqual(viewModel.getFocus(), { start: 2, end: 3 });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 0, end: 1 }]);
// unfold
updateFoldingStateAtIndex(foldingModel, 2, false);
viewModel.updateFoldingRanges(foldingModel.regions);
cellList.setHiddenAreas(viewModel.getHiddenRanges(), true);
assert.strictEqual(cellList.length, 4);
assert.deepStrictEqual(viewModel.getFocus(), { start: 2, end: 3 });
});
});
test('notebook cell list focus/selection with folding regions and applyEdits', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['var c = 3', 'javascript', CellKind.Markup, [], {}],
['# header d', 'markdown', CellKind.Markup, [], {}],
['var e = 4;', 'javascript', CellKind.Code, [], {}],
],
(editor, viewModel) => {
const foldingModel = new FoldingModel();
foldingModel.attachViewModel(viewModel);
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
cellList.setFocus([0]);
cellList.setSelection([0]);
updateFoldingStateAtIndex(foldingModel, 0, true);
updateFoldingStateAtIndex(foldingModel, 2, true);
viewModel.updateFoldingRanges(foldingModel.regions);
cellList.setHiddenAreas(viewModel.getHiddenRanges(), true);
assert.strictEqual(cellList.getModelIndex2(0), 0);
assert.strictEqual(cellList.getModelIndex2(1), 2);
editor.textModel.applyEdits([{
editType: CellEditType.Replace, index: 0, count: 2, cells: []
}], true, undefined, () => undefined, undefined, false);
viewModel.updateFoldingRanges(foldingModel.regions);
cellList.setHiddenAreas(viewModel.getHiddenRanges(), true);
assert.strictEqual(cellList.getModelIndex2(0), 0);
assert.strictEqual(cellList.getModelIndex2(1), 3);
// mimic undo
editor.textModel.applyEdits([{
editType: CellEditType.Replace, index: 0, count: 0, cells: [
new TestCell(viewModel.viewType, 7, '# header f', 'markdown', CellKind.Code, [], languageService),
new TestCell(viewModel.viewType, 8, 'var g = 5;', 'javascript', CellKind.Code, [], languageService)
]
}], true, undefined, () => undefined, undefined, false);
viewModel.updateFoldingRanges(foldingModel.regions);
cellList.setHiddenAreas(viewModel.getHiddenRanges(), true);
assert.strictEqual(cellList.getModelIndex2(0), 0);
assert.strictEqual(cellList.getModelIndex2(1), 1);
assert.strictEqual(cellList.getModelIndex2(2), 2);
});
});
test('notebook cell list getModelIndex', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
(editor, viewModel) => {
const foldingModel = new FoldingModel();
foldingModel.attachViewModel(viewModel);
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
updateFoldingStateAtIndex(foldingModel, 0, true);
updateFoldingStateAtIndex(foldingModel, 2, true);
viewModel.updateFoldingRanges(foldingModel.regions);
cellList.setHiddenAreas(viewModel.getHiddenRanges(), true);
assert.deepStrictEqual(cellList.getModelIndex2(-1), 0);
assert.deepStrictEqual(cellList.getModelIndex2(0), 0);
assert.deepStrictEqual(cellList.getModelIndex2(1), 2);
assert.deepStrictEqual(cellList.getModelIndex2(2), 4);
});
});
test('notebook validate range', async () => {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}]
],
(editor, viewModel) => {
assert.deepStrictEqual(viewModel.validateRange(null), null);
assert.deepStrictEqual(viewModel.validateRange(undefined), null);
assert.deepStrictEqual(viewModel.validateRange({ start: 0, end: 0 }), null);
assert.deepStrictEqual(viewModel.validateRange({ start: 0, end: 2 }), { start: 0, end: 2 });
assert.deepStrictEqual(viewModel.validateRange({ start: 0, end: 3 }), { start: 0, end: 2 });
assert.deepStrictEqual(viewModel.validateRange({ start: -1, end: 3 }), { start: 0, end: 2 });
assert.deepStrictEqual(viewModel.validateRange({ start: -1, end: 1 }), { start: 0, end: 1 });
assert.deepStrictEqual(viewModel.validateRange({ start: 2, end: 1 }), { start: 1, end: 2 });
assert.deepStrictEqual(viewModel.validateRange({ start: 2, end: -1 }), { start: 0, end: 2 });
});
});
test('notebook updateSelectionState', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}]
],
(editor, viewModel) => {
viewModel.updateSelectionsState({ kind: SelectionStateType.Index, focus: { start: 1, end: 2 }, selections: [{ start: 1, end: 2 }, { start: -1, end: 0 }] });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 1, end: 2 }]);
});
});
test('notebook cell selection w/ cell deletion', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}]
],
(editor, viewModel) => {
viewModel.updateSelectionsState({ kind: SelectionStateType.Index, focus: { start: 1, end: 2 }, selections: [{ start: 1, end: 2 }] });
runDeleteAction(editor, viewModel.cellAt(1)!);
// viewModel.deleteCell(1, true, false);
assert.deepStrictEqual(viewModel.getFocus(), { start: 0, end: 1 });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 0, end: 1 }]);
});
});
test('notebook cell selection w/ cell deletion from applyEdits', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['var c = 2;', 'javascript', CellKind.Code, [], {}]
],
async (editor, viewModel) => {
viewModel.updateSelectionsState({ kind: SelectionStateType.Index, focus: { start: 1, end: 2 }, selections: [{ start: 1, end: 2 }] });
editor.textModel.applyEdits([{
editType: CellEditType.Replace,
index: 1,
count: 1,
cells: []
}], true, undefined, () => undefined, undefined, true);
assert.deepStrictEqual(viewModel.getFocus(), { start: 1, end: 2 });
assert.deepStrictEqual(viewModel.getSelections(), [{ start: 1, end: 2 }]);
});
});
});
| src/vs/workbench/contrib/notebook/test/browser/notebookSelection.test.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0020229858346283436,
0.0002747519756667316,
0.0001659188128542155,
0.00017450971063226461,
0.000314456905471161
] |
{
"id": 10,
"code_window": [
"\treadonly cellKind = CellKind.Code;\n",
"\n",
"\tprotected readonly _onLayoutInfoRead = this._register(new Emitter<void>());\n",
"\treadonly onLayoutInfoRead = this._onLayoutInfoRead.event;\n",
"\n",
"\tprotected readonly _onDidChangeOutputs = this._register(new Emitter<NotebookCellOutputsSplice>());\n",
"\treadonly onDidChangeOutputs = this._onDidChangeOutputs.event;\n",
"\n",
"\tprivate readonly _onDidRemoveOutputs = this._register(new Emitter<readonly ICellOutputViewModel[]>());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprotected readonly _onDidStartExecution = this._register(new Emitter<void>());\n",
"\treadonly onDidStartExecution = this._onDidStartExecution.event;\n",
"\tprotected readonly _onDidStopExecution = this._register(new Emitter<void>());\n",
"\treadonly onDidStopExecution = this._onDidStopExecution.event;\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 30
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Code } from './code';
export abstract class Viewlet {
constructor(protected code: Code) { }
async waitForTitle(fn: (title: string) => boolean): Promise<void> {
await this.code.waitForTextContent('.monaco-workbench .part.sidebar > .title > .title-label > h2', undefined, fn);
}
}
| test/automation/src/viewlet.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017074770585168153,
0.00016946930554695427,
0.0001681908906903118,
0.00016946930554695427,
0.0000012784075806848705
] |
{
"id": 11,
"code_window": [
"\t\tinitialNotebookLayoutInfo: NotebookLayoutInfo | null,\n",
"\t\treadonly viewContext: ViewContext,\n",
"\t\t@IConfigurationService configurationService: IConfigurationService,\n",
"\t\t@INotebookService private readonly _notebookService: INotebookService,\n",
"\t\t@ITextModelService modelService: ITextModelService,\n",
"\t\t@IUndoRedoService undoRedoService: IUndoRedoService,\n",
"\t\t@ICodeEditorService codeEditorService: ICodeEditorService\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event';
import { dispose } from 'vs/base/common/lifecycle';
import * as UUID from 'vs/base/common/uuid';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { PrefixSumComputer } from 'vs/editor/common/model/prefixSumComputer';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { CellEditState, CellFindMatch, CodeCellLayoutChangeEvent, CodeCellLayoutInfo, CellLayoutState, ICellOutputViewModel, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CellOutputViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/cellOutputViewModel';
import { ViewContext } from 'vs/workbench/contrib/notebook/browser/viewModel/viewContext';
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { CellKind, INotebookSearchOptions, NotebookCellOutputsSplice } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptionsChangeEvent } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { BaseCellViewModel } from './baseCellViewModel';
import { NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
export class CodeCellViewModel extends BaseCellViewModel implements ICellViewModel {
readonly cellKind = CellKind.Code;
protected readonly _onLayoutInfoRead = this._register(new Emitter<void>());
readonly onLayoutInfoRead = this._onLayoutInfoRead.event;
protected readonly _onDidChangeOutputs = this._register(new Emitter<NotebookCellOutputsSplice>());
readonly onDidChangeOutputs = this._onDidChangeOutputs.event;
private readonly _onDidRemoveOutputs = this._register(new Emitter<readonly ICellOutputViewModel[]>());
readonly onDidRemoveOutputs = this._onDidRemoveOutputs.event;
private _outputCollection: number[] = [];
private _outputsTop: PrefixSumComputer | null = null;
protected _pauseableEmitter = this._register(new PauseableEmitter<CodeCellLayoutChangeEvent>());
readonly onDidChangeLayout = this._pauseableEmitter.event;
private _editorHeight = 0;
set editorHeight(height: number) {
this._editorHeight = height;
this.layoutChange({ editorHeight: true }, 'CodeCellViewModel#editorHeight');
}
get editorHeight() {
throw new Error('editorHeight is write-only');
}
private _commentHeight = 0;
set commentHeight(height: number) {
if (this._commentHeight === height) {
return;
}
this._commentHeight = height;
this.layoutChange({ commentHeight: true }, 'CodeCellViewModel#commentHeight');
}
private _hoveringOutput: boolean = false;
public get outputIsHovered(): boolean {
return this._hoveringOutput;
}
public set outputIsHovered(v: boolean) {
this._hoveringOutput = v;
this._onDidChangeState.fire({ outputIsHoveredChanged: true });
}
private _focusOnOutput: boolean = false;
public get outputIsFocused(): boolean {
return this._focusOnOutput;
}
public set outputIsFocused(v: boolean) {
this._focusOnOutput = v;
this._onDidChangeState.fire({ outputIsFocusedChanged: true });
}
private _outputMinHeight: number = 0;
private get outputMinHeight() {
return this._outputMinHeight;
}
/**
* The minimum height of the output region. It's only set to non-zero temporarily when replacing an output with a new one.
* It's reset to 0 when the new output is rendered, or in one second.
*/
private set outputMinHeight(newMin: number) {
this._outputMinHeight = newMin;
}
private _layoutInfo: CodeCellLayoutInfo;
get layoutInfo() {
return this._layoutInfo;
}
private _outputViewModels: ICellOutputViewModel[];
get outputsViewModels() {
return this._outputViewModels;
}
constructor(
viewType: string,
model: NotebookCellTextModel,
initialNotebookLayoutInfo: NotebookLayoutInfo | null,
readonly viewContext: ViewContext,
@IConfigurationService configurationService: IConfigurationService,
@INotebookService private readonly _notebookService: INotebookService,
@ITextModelService modelService: ITextModelService,
@IUndoRedoService undoRedoService: IUndoRedoService,
@ICodeEditorService codeEditorService: ICodeEditorService
) {
super(viewType, model, UUID.generateUuid(), viewContext, configurationService, modelService, undoRedoService, codeEditorService);
this._outputViewModels = this.model.outputs.map(output => new CellOutputViewModel(this, output, this._notebookService));
this._register(this.model.onDidChangeOutputs((splice) => {
const removedOutputs: ICellOutputViewModel[] = [];
let outputLayoutChange = false;
for (let i = splice.start; i < splice.start + splice.deleteCount; i++) {
if (this._outputCollection[i] !== undefined && this._outputCollection[i] !== 0) {
outputLayoutChange = true;
}
}
this._outputCollection.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(() => 0));
removedOutputs.push(...this._outputViewModels.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(output => new CellOutputViewModel(this, output, this._notebookService))));
this._outputsTop = null;
this._onDidChangeOutputs.fire(splice);
this._onDidRemoveOutputs.fire(removedOutputs);
if (outputLayoutChange) {
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#model.onDidChangeOutputs');
}
dispose(removedOutputs);
}));
this._outputCollection = new Array(this.model.outputs.length);
this._layoutInfo = {
fontInfo: initialNotebookLayoutInfo?.fontInfo || null,
editorHeight: 0,
editorWidth: initialNotebookLayoutInfo
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(initialNotebookLayoutInfo.width)
: 0,
statusBarHeight: 0,
commentHeight: 0,
outputContainerOffset: 0,
outputTotalHeight: 0,
outputShowMoreContainerHeight: 0,
outputShowMoreContainerOffset: 0,
totalHeight: this.computeTotalHeight(17, 0, 0),
codeIndicatorHeight: 0,
outputIndicatorHeight: 0,
bottomToolbarOffset: 0,
layoutState: CellLayoutState.Uninitialized,
estimatedHasHorizontalScrolling: false
};
}
updateOptions(e: NotebookOptionsChangeEvent) {
if (e.cellStatusBarVisibility || e.insertToolbarPosition || e.cellToolbarLocation) {
this.layoutChange({});
}
}
pauseLayout() {
this._pauseableEmitter.pause();
}
resumeLayout() {
this._pauseableEmitter.resume();
}
layoutChange(state: CodeCellLayoutChangeEvent, source?: string) {
// recompute
this._ensureOutputsTop();
const notebookLayoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const bottomToolbarDimensions = this.viewContext.notebookOptions.computeBottomToolbarDimensions();
const outputShowMoreContainerHeight = state.outputShowMoreContainerHeight ? state.outputShowMoreContainerHeight : this._layoutInfo.outputShowMoreContainerHeight;
const outputTotalHeight = Math.max(this._outputMinHeight, this.isOutputCollapsed ? notebookLayoutConfiguration.collapsedIndicatorHeight : this._outputsTop!.getTotalSum());
const commentHeight = state.commentHeight ? this._commentHeight : this._layoutInfo.commentHeight;
const originalLayout = this.layoutInfo;
if (!this.isInputCollapsed) {
let newState: CellLayoutState;
let editorHeight: number;
let totalHeight: number;
let hasHorizontalScrolling = false;
if (!state.editorHeight && this._layoutInfo.layoutState === CellLayoutState.FromCache && !state.outputHeight) {
// No new editorHeight info - keep cached totalHeight and estimate editorHeight
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this._layoutInfo.totalHeight;
newState = CellLayoutState.FromCache;
} else if (state.editorHeight || this._layoutInfo.layoutState === CellLayoutState.Measured) {
// Editor has been measured
editorHeight = this._editorHeight;
totalHeight = this.computeTotalHeight(this._editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Measured;
hasHorizontalScrolling = this._layoutInfo.estimatedHasHorizontalScrolling;
} else {
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this.computeTotalHeight(editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Estimated;
}
const statusBarHeight = this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri);
const codeIndicatorHeight = editorHeight + statusBarHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.editorToolbarHeight
+ notebookLayoutConfiguration.cellTopMargin // CELL_TOP_MARGIN
+ editorHeight
+ statusBarHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight,
editorWidth,
statusBarHeight,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: newState,
estimatedHasHorizontalScrolling: hasHorizontalScrolling
};
} else {
const codeIndicatorHeight = notebookLayoutConfiguration.collapsedIndicatorHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.cellTopMargin + notebookLayoutConfiguration.collapsedIndicatorHeight;
const totalHeight =
notebookLayoutConfiguration.cellTopMargin
+ notebookLayoutConfiguration.collapsedIndicatorHeight
+ notebookLayoutConfiguration.cellBottomMargin //CELL_BOTTOM_MARGIN
+ bottomToolbarDimensions.bottomToolbarGap //BOTTOM_CELL_TOOLBAR_GAP
+ commentHeight
+ outputTotalHeight + outputShowMoreContainerHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight: this._layoutInfo.editorHeight,
editorWidth,
statusBarHeight: 0,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: this._layoutInfo.layoutState,
estimatedHasHorizontalScrolling: false
};
}
this._fireOnDidChangeLayout({
...state,
totalHeight: this.layoutInfo.totalHeight !== originalLayout.totalHeight,
source,
});
}
private _fireOnDidChangeLayout(state: CodeCellLayoutChangeEvent) {
this._pauseableEmitter.fire(state);
}
override restoreEditorViewState(editorViewStates: editorCommon.ICodeEditorViewState | null, totalHeight?: number) {
super.restoreEditorViewState(editorViewStates);
if (totalHeight !== undefined && this._layoutInfo.layoutState !== CellLayoutState.Measured) {
this._layoutInfo = {
fontInfo: this._layoutInfo.fontInfo,
editorHeight: this._layoutInfo.editorHeight,
editorWidth: this._layoutInfo.editorWidth,
statusBarHeight: this.layoutInfo.statusBarHeight,
commentHeight: this.layoutInfo.commentHeight,
outputContainerOffset: this._layoutInfo.outputContainerOffset,
outputTotalHeight: this._layoutInfo.outputTotalHeight,
outputShowMoreContainerHeight: this._layoutInfo.outputShowMoreContainerHeight,
outputShowMoreContainerOffset: this._layoutInfo.outputShowMoreContainerOffset,
totalHeight: totalHeight,
codeIndicatorHeight: this._layoutInfo.codeIndicatorHeight,
outputIndicatorHeight: this._layoutInfo.outputIndicatorHeight,
bottomToolbarOffset: this._layoutInfo.bottomToolbarOffset,
layoutState: CellLayoutState.FromCache,
estimatedHasHorizontalScrolling: this._layoutInfo.estimatedHasHorizontalScrolling
};
}
}
hasDynamicHeight() {
// CodeCellVM always measures itself and controls its cell's height
return false;
}
getDynamicHeight() {
this._onLayoutInfoRead.fire();
return this._layoutInfo.totalHeight;
}
getHeight(lineHeight: number) {
if (this._layoutInfo.layoutState === CellLayoutState.Uninitialized) {
const estimate = this.estimateEditorHeight(lineHeight);
return this.computeTotalHeight(estimate.editorHeight, 0, 0);
} else {
return this._layoutInfo.totalHeight;
}
}
private estimateEditorHeight(lineHeight: number | undefined = 20): { editorHeight: number; hasHorizontalScrolling: boolean } {
let hasHorizontalScrolling = false;
const cellEditorOptions = this.viewContext.getBaseCellEditorOptions(this.language);
if (this.layoutInfo.fontInfo && cellEditorOptions.value.wordWrap === 'off') {
for (let i = 0; i < this.lineCount; i++) {
const max = this.textBuffer.getLineLastNonWhitespaceColumn(i + 1);
const estimatedWidth = max * (this.layoutInfo.fontInfo.typicalHalfwidthCharacterWidth + this.layoutInfo.fontInfo.letterSpacing);
if (estimatedWidth > this.layoutInfo.editorWidth) {
hasHorizontalScrolling = true;
break;
}
}
}
const verticalScrollbarHeight = hasHorizontalScrolling ? 12 : 0; // take zoom level into account
const editorPadding = this.viewContext.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
const editorHeight = this.lineCount * lineHeight
+ editorPadding.top
+ editorPadding.bottom // EDITOR_BOTTOM_PADDING
+ verticalScrollbarHeight;
return {
editorHeight,
hasHorizontalScrolling
};
}
private computeTotalHeight(editorHeight: number, outputsTotalHeight: number, outputShowMoreContainerHeight: number): number {
const layoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const { bottomToolbarGap } = this.viewContext.notebookOptions.computeBottomToolbarDimensions(this.viewType);
return layoutConfiguration.editorToolbarHeight
+ layoutConfiguration.cellTopMargin
+ editorHeight
+ this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri)
+ this._commentHeight
+ outputsTotalHeight
+ outputShowMoreContainerHeight
+ bottomToolbarGap
+ layoutConfiguration.cellBottomMargin;
}
protected onDidChangeTextModelContent(): void {
if (this.getEditState() !== CellEditState.Editing) {
this.updateEditState(CellEditState.Editing, 'onDidChangeTextModelContent');
this._onDidChangeState.fire({ contentChanged: true });
}
}
onDeselect() {
this.updateEditState(CellEditState.Preview, 'onDeselect');
}
updateOutputShowMoreContainerHeight(height: number) {
this.layoutChange({ outputShowMoreContainerHeight: height }, 'CodeCellViewModel#updateOutputShowMoreContainerHeight');
}
updateOutputMinHeight(height: number) {
this.outputMinHeight = height;
}
unlockOutputHeight() {
this.outputMinHeight = 0;
this.layoutChange({ outputHeight: true });
}
updateOutputHeight(index: number, height: number, source?: string) {
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
this._ensureOutputsTop();
if (height < 28 && this._outputViewModels[index].hasMultiMimeType()) {
height = 28;
}
this._outputCollection[index] = height;
if (this._outputsTop!.setValue(index, height)) {
this.layoutChange({ outputHeight: true }, source);
}
}
getOutputOffsetInContainer(index: number) {
this._ensureOutputsTop();
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
return this._outputsTop!.getPrefixSum(index - 1);
}
getOutputOffset(index: number): number {
return this.layoutInfo.outputContainerOffset + this.getOutputOffsetInContainer(index);
}
spliceOutputHeights(start: number, deleteCnt: number, heights: number[]) {
this._ensureOutputsTop();
this._outputsTop!.removeValues(start, deleteCnt);
if (heights.length) {
const values = new Uint32Array(heights.length);
for (let i = 0; i < heights.length; i++) {
values[i] = heights[i];
}
this._outputsTop!.insertValues(start, values);
}
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#spliceOutputs');
}
private _ensureOutputsTop(): void {
if (!this._outputsTop) {
const values = new Uint32Array(this._outputCollection.length);
for (let i = 0; i < this._outputCollection.length; i++) {
values[i] = this._outputCollection[i];
}
this._outputsTop = new PrefixSumComputer(values);
}
}
private readonly _hasFindResult = this._register(new Emitter<boolean>());
public readonly hasFindResult: Event<boolean> = this._hasFindResult.event;
startFind(value: string, options: INotebookSearchOptions): CellFindMatch | null {
const matches = super.cellStartFind(value, options);
if (matches === null) {
return null;
}
return {
cell: this,
contentMatches: matches
};
}
override dispose() {
super.dispose();
this._outputCollection = [];
this._outputsTop = null;
dispose(this._outputViewModels);
}
}
| src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.7601872086524963,
0.02251282148063183,
0.00016408637748099864,
0.00024695333559066057,
0.11146695911884308
] |
{
"id": 11,
"code_window": [
"\t\tinitialNotebookLayoutInfo: NotebookLayoutInfo | null,\n",
"\t\treadonly viewContext: ViewContext,\n",
"\t\t@IConfigurationService configurationService: IConfigurationService,\n",
"\t\t@INotebookService private readonly _notebookService: INotebookService,\n",
"\t\t@ITextModelService modelService: ITextModelService,\n",
"\t\t@IUndoRedoService undoRedoService: IUndoRedoService,\n",
"\t\t@ICodeEditorService codeEditorService: ICodeEditorService\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IIntegrityService, IntegrityTestResult } from 'vs/workbench/services/integrity/common/integrity';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
export class IntegrityService implements IIntegrityService {
declare readonly _serviceBrand: undefined;
async isPure(): Promise<IntegrityTestResult> {
return { isPure: true, proof: [] };
}
}
registerSingleton(IIntegrityService, IntegrityService, InstantiationType.Delayed);
| src/vs/workbench/services/integrity/browser/integrityService.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0001697550032986328,
0.00016946301911957562,
0.00016917103494051844,
0.00016946301911957562,
2.919841790571809e-7
] |
{
"id": 11,
"code_window": [
"\t\tinitialNotebookLayoutInfo: NotebookLayoutInfo | null,\n",
"\t\treadonly viewContext: ViewContext,\n",
"\t\t@IConfigurationService configurationService: IConfigurationService,\n",
"\t\t@INotebookService private readonly _notebookService: INotebookService,\n",
"\t\t@ITextModelService modelService: ITextModelService,\n",
"\t\t@IUndoRedoService undoRedoService: IUndoRedoService,\n",
"\t\t@ICodeEditorService codeEditorService: ICodeEditorService\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ILoggerService, LogLevel } from 'vs/platform/log/common/log';
import { Emitter, Event } from 'vs/base/common/event';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { Disposable } from 'vs/base/common/lifecycle';
import { IOutputService } from 'vs/workbench/services/output/common/output';
export const ILogLevelService = createDecorator<ILogLevelService>('ILogLevelService');
export interface ILogLevelService {
readonly _serviceBrand: undefined;
readonly onDidChangeLogLevel: Event<{ readonly id: string; logLevel: LogLevel }>;
setLogLevel(id: string, logLevel: LogLevel): void;
getLogLevel(id: string): LogLevel | undefined;
}
export class LogLevelService extends Disposable implements ILogLevelService {
readonly _serviceBrand: undefined;
private readonly _onDidChangeLogLevel = this._register(new Emitter<{ readonly id: string; logLevel: LogLevel }>());
readonly onDidChangeLogLevel = this._onDidChangeLogLevel.event;
private readonly logLevels = new Map<string, LogLevel>();
constructor(
@IOutputService protected readonly outputService: IOutputService,
@ILoggerService private readonly loggerService: ILoggerService
) {
super();
}
getLogLevel(id: string): LogLevel | undefined {
return this.logLevels.get(id);
}
setLogLevel(id: string, logLevel: LogLevel): boolean {
if (this.getLogLevel(id) === logLevel) {
return false;
}
this.logLevels.set(id, logLevel);
const channel = this.outputService.getChannelDescriptor(id);
const resource = channel?.log ? channel.file : undefined;
if (resource) {
this.loggerService.setLevel(resource, logLevel);
}
this._onDidChangeLogLevel.fire({ id, logLevel });
return true;
}
}
| src/vs/workbench/contrib/logs/common/logLevelService.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.002868252107873559,
0.0006216593319550157,
0.00016931093705352396,
0.0001726308255456388,
0.001004708232358098
] |
{
"id": 11,
"code_window": [
"\t\tinitialNotebookLayoutInfo: NotebookLayoutInfo | null,\n",
"\t\treadonly viewContext: ViewContext,\n",
"\t\t@IConfigurationService configurationService: IConfigurationService,\n",
"\t\t@INotebookService private readonly _notebookService: INotebookService,\n",
"\t\t@ITextModelService modelService: ITextModelService,\n",
"\t\t@IUndoRedoService undoRedoService: IUndoRedoService,\n",
"\t\t@ICodeEditorService codeEditorService: ICodeEditorService\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { once } from 'vs/base/common/functional';
import { IReference } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { ICustomEditorModel, ICustomEditorModelManager } from 'vs/workbench/contrib/customEditor/common/customEditor';
export class CustomEditorModelManager implements ICustomEditorModelManager {
private readonly _references = new Map<string, {
readonly viewType: string;
readonly model: Promise<ICustomEditorModel>;
counter: number;
}>();
public async getAllModels(resource: URI): Promise<ICustomEditorModel[]> {
const keyStart = `${resource.toString()}@@@`;
const models = [];
for (const [key, entry] of this._references) {
if (key.startsWith(keyStart) && entry.model) {
models.push(await entry.model);
}
}
return models;
}
public async get(resource: URI, viewType: string): Promise<ICustomEditorModel | undefined> {
const key = this.key(resource, viewType);
const entry = this._references.get(key);
return entry?.model;
}
public tryRetain(resource: URI, viewType: string): Promise<IReference<ICustomEditorModel>> | undefined {
const key = this.key(resource, viewType);
const entry = this._references.get(key);
if (!entry) {
return undefined;
}
entry.counter++;
return entry.model.then(model => {
return {
object: model,
dispose: once(() => {
if (--entry!.counter <= 0) {
entry.model.then(x => x.dispose());
this._references.delete(key);
}
}),
};
});
}
public add(resource: URI, viewType: string, model: Promise<ICustomEditorModel>): Promise<IReference<ICustomEditorModel>> {
const key = this.key(resource, viewType);
const existing = this._references.get(key);
if (existing) {
throw new Error('Model already exists');
}
this._references.set(key, { viewType, model, counter: 0 });
return this.tryRetain(resource, viewType)!;
}
public disposeAllModelsForView(viewType: string): void {
for (const [key, value] of this._references) {
if (value.viewType === viewType) {
value.model.then(x => x.dispose());
this._references.delete(key);
}
}
}
private key(resource: URI, viewType: string): string {
return `${resource.toString()}@@@${viewType}`;
}
}
| src/vs/workbench/contrib/customEditor/common/customEditorModelManager.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0003624468226917088,
0.0001906070247059688,
0.00016293810040224344,
0.00016921426868066192,
0.00006090789975132793
] |
{
"id": 12,
"code_window": [
"\t\t\t}\n",
"\t\t\tdispose(removedOutputs);\n",
"\t\t}));\n",
"\n",
"\t\tthis._outputCollection = new Array(this.model.outputs.length);\n",
"\n",
"\t\tthis._layoutInfo = {\n",
"\t\t\tfontInfo: initialNotebookLayoutInfo?.fontInfo || null,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this._notebookExecutionStateService.onDidChangeCellExecution(e => {\n",
"\t\t\tif (e.affectsCell(model.uri)) {\n",
"\t\t\t\tif (e.changed) {\n",
"\t\t\t\t\tthis._onDidStartExecution.fire();\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tthis._onDidStopExecution.fire();\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 146
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
import { renderMarkdown } from 'vs/base/browser/markdownRenderer';
import { Action, IAction } from 'vs/base/common/actions';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import * as nls from 'vs/nls';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { WorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { IMenuService, MenuId } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSION_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellOutputViewModel, ICellViewModel, IInsetRenderOutput, INotebookEditorDelegate, JUPYTER_EXTENSION_ID, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { mimetypeIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';
import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
interface IRenderResult {
initRenderIsSynchronous: false;
}
// DOM structure
//
// #output
// |
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | | #output-element
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
class CellOutputElement extends Disposable {
private readonly _renderDisposableStore = this._register(new DisposableStore());
innerContainer?: HTMLElement;
renderedOutputContainer!: HTMLElement;
renderResult?: IInsetRenderOutput;
private readonly contextKeyService: IContextKeyService;
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private cellOutputContainer: CellOutputContainer,
private outputContainer: FastDomNode<HTMLElement>,
readonly output: ICellOutputViewModel,
@INotebookService private readonly notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@IContextKeyService parentContextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this.contextKeyService = parentContextKeyService;
this._register(this.output.model.onDidChangeData(() => {
this.rerender();
}));
this._register(this.output.onDidResetRenderer(() => {
this.rerender();
}));
}
detach() {
this.renderedOutputContainer?.parentElement?.removeChild(this.renderedOutputContainer);
let count = 0;
if (this.innerContainer) {
for (let i = 0; i < this.innerContainer.childNodes.length; i++) {
if ((this.innerContainer.childNodes[i] as HTMLElement).className === 'rendered-output') {
count++;
}
if (count > 1) {
break;
}
}
if (count === 0) {
this.innerContainer.parentElement?.removeChild(this.innerContainer);
}
}
this.notebookEditor.removeInset(this.output);
}
updateDOMTop(top: number) {
if (this.innerContainer) {
this.innerContainer.style.top = `${top}px`;
}
}
rerender() {
if (
this.notebookEditor.hasModel() &&
this.innerContainer &&
this.renderResult &&
this.renderResult.type === RenderOutputType.Extension
) {
// Output rendered by extension renderer got an update
const [mimeTypes, pick] = this.output.resolveMimeTypes(this.notebookEditor.textModel, this.notebookEditor.activeKernel?.preloadProvides);
const pickedMimeType = mimeTypes[pick];
if (pickedMimeType.mimeType === this.renderResult.mimeType && pickedMimeType.rendererId === this.renderResult.renderer.id) {
// Same mimetype, same renderer, call the extension renderer to update
const index = this.viewCell.outputsViewModels.indexOf(this.output);
this.notebookEditor.updateOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
return;
}
}
if (!this.innerContainer) {
// init rendering didn't happen
const currOutputIndex = this.cellOutputContainer.renderedOutputEntries.findIndex(entry => entry.element === this);
const previousSibling = currOutputIndex > 0 && !!(this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer?.parentElement)
? this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer
: undefined;
this.render(previousSibling);
} else {
// Another mimetype or renderer is picked, we need to clear the current output and re-render
const nextElement = this.innerContainer.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(this.output);
}
this.render(nextElement as HTMLElement);
}
this._relayoutCell();
}
// insert after previousSibling
private _generateInnerOutputContainer(previousSibling: HTMLElement | undefined, pickedMimeTypeRenderer: IOrderedMimeType) {
this.innerContainer = DOM.$('.output-inner-container');
if (previousSibling && previousSibling.nextElementSibling) {
this.outputContainer.domNode.insertBefore(this.innerContainer, previousSibling.nextElementSibling);
} else {
this.outputContainer.domNode.appendChild(this.innerContainer);
}
this.innerContainer.setAttribute('output-mime-type', pickedMimeTypeRenderer.mimeType);
return this.innerContainer;
}
render(previousSibling: HTMLElement | undefined): IRenderResult | undefined {
const index = this.viewCell.outputsViewModels.indexOf(this.output);
if (this.viewCell.isOutputCollapsed || !this.notebookEditor.hasModel()) {
return undefined;
}
const notebookUri = CellUri.parse(this.viewCell.uri)?.notebook;
if (!notebookUri) {
return undefined;
}
const notebookTextModel = this.notebookEditor.textModel;
const [mimeTypes, pick] = this.output.resolveMimeTypes(notebookTextModel, this.notebookEditor.activeKernel?.preloadProvides);
if (!mimeTypes.find(mimeType => mimeType.isTrusted) || mimeTypes.length === 0) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#noMimeType');
return undefined;
}
const pickedMimeTypeRenderer = mimeTypes[pick];
const innerContainer = this._generateInnerOutputContainer(previousSibling, pickedMimeTypeRenderer);
this._attachToolbar(innerContainer, notebookTextModel, this.notebookEditor.activeKernel, index, mimeTypes);
this.renderedOutputContainer = DOM.append(innerContainer, DOM.$('.rendered-output'));
const renderer = this.notebookService.getRendererInfo(pickedMimeTypeRenderer.rendererId);
this.renderResult = renderer
? { type: RenderOutputType.Extension, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType }
: this._renderMissingRenderer(this.output, pickedMimeTypeRenderer.mimeType);
this.output.pickedMimeType = pickedMimeTypeRenderer;
if (!this.renderResult) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#renderResultUndefined');
return undefined;
}
this.notebookEditor.createOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
innerContainer.classList.add('background');
return { initRenderIsSynchronous: false };
}
private _renderMissingRenderer(viewModel: ICellOutputViewModel, preferredMimeType: string | undefined): IInsetRenderOutput {
if (!viewModel.model.outputs.length) {
return this._renderMessage(viewModel, nls.localize('empty', "Cell has no output"));
}
if (!preferredMimeType) {
const mimeTypes = viewModel.model.outputs.map(op => op.mime);
const mimeTypesMessage = mimeTypes.join(', ');
return this._renderMessage(viewModel, nls.localize('noRenderer.2', "No renderer could be found for output. It has the following mimetypes: {0}", mimeTypesMessage));
}
return this._renderSearchForMimetype(viewModel, preferredMimeType);
}
private _renderSearchForMimetype(viewModel: ICellOutputViewModel, mimeType: string): IInsetRenderOutput {
const query = `@tag:notebookRenderer ${mimeType}`;
const p = DOM.$('p', undefined, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
const a = DOM.$('a', { href: `command:workbench.extensions.search?%22${query}%22`, class: 'monaco-button monaco-text-button', tabindex: 0, role: 'button', style: 'padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;' }, `Search Marketplace`);
return {
type: RenderOutputType.Html,
source: viewModel,
htmlContent: p.outerHTML + a.outerHTML
};
}
private _renderMessage(viewModel: ICellOutputViewModel, message: string): IInsetRenderOutput {
const el = DOM.$('p', undefined, message);
return { type: RenderOutputType.Html, source: viewModel, htmlContent: el.outerHTML };
}
private async _attachToolbar(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, index: number, mimeTypes: readonly IOrderedMimeType[]) {
const hasMultipleMimeTypes = mimeTypes.filter(mimeType => mimeType.isTrusted).length <= 1;
if (index > 0 && hasMultipleMimeTypes) {
return;
}
if (!this.notebookEditor.hasModel()) {
return;
}
const useConsolidatedButton = this.notebookEditor.notebookOptions.getLayoutConfiguration().consolidatedOutputButton;
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.cell-output-toolbar');
outputItemDiv.appendChild(mimeTypePicker);
const toolbar = this._renderDisposableStore.add(this.instantiationService.createInstance(WorkbenchToolBar, mimeTypePicker, {
renderDropdownAsChildElement: false
}));
toolbar.context = <INotebookCellActionContext>{
ui: true,
cell: this.output.cellViewModel as ICellViewModel,
notebookEditor: this.notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
};
// TODO: This could probably be a real registered action, but it has to talk to this output element
const pickAction = new Action('notebook.output.pickMimetype', nls.localize('pickMimeType', "Change Presentation"), ThemeIcon.asClassName(mimetypeIcon), undefined,
async _context => this._pickActiveMimeTypeRenderer(outputItemDiv, notebookTextModel, kernel, this.output));
if (index === 0 && useConsolidatedButton) {
const menu = this._renderDisposableStore.add(this.menuService.createMenu(MenuId.NotebookOutputToolbar, this.contextKeyService));
const updateMenuToolbar = () => {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, result, () => false);
toolbar.setActions([], [pickAction, ...secondary]);
};
updateMenuToolbar();
this._renderDisposableStore.add(menu.onDidChange(updateMenuToolbar));
} else {
toolbar.setActions([pickAction]);
}
}
private async _pickActiveMimeTypeRenderer(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, viewModel: ICellOutputViewModel) {
const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, kernel?.preloadProvides);
const items: IMimeTypeRenderer[] = [];
const unsupportedItems: IMimeTypeRenderer[] = [];
mimeTypes.forEach((mimeType, index) => {
if (mimeType.isTrusted) {
const arr = mimeType.rendererId === RENDERER_NOT_AVAILABLE ?
unsupportedItems :
items;
arr.push({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
detail: this._generateRendererInfo(mimeType.rendererId),
description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined
});
}
});
if (unsupportedItems.some(m => JUPYTER_RENDERER_MIMETYPES.includes(m.id!))) {
unsupportedItems.push({
label: nls.localize('installJupyterPrompt', "Install additional renderers from the marketplace"),
id: 'installRenderers',
index: mimeTypes.length
});
}
const picker = this.quickInputService.createQuickPick();
picker.items = [
...items,
{ type: 'separator' },
...unsupportedItems
];
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = items.length !== mimeTypes.length
? nls.localize('promptChooseMimeTypeInSecure.placeHolder', "Select mimetype to render for current output")
: nls.localize('promptChooseMimeType.placeHolder', "Select mimetype to render for current output");
const pick = await new Promise<IMimeTypeRenderer | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer) : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined || pick.index === currIndex) {
return;
}
if (pick.id === 'installRenderers') {
this._showJupyterExtension();
return;
}
// user chooses another mimetype
const nextElement = outputItemDiv.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(viewModel);
}
viewModel.pickedMimeType = mimeTypes[pick.index];
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
const { mimeType, rendererId } = mimeTypes[pick.index];
this.notebookService.updateMimePreferredRenderer(notebookTextModel.viewType, mimeType, rendererId, mimeTypes.map(m => m.mimeType));
this.render(nextElement as HTMLElement);
this._validateFinalOutputHeight(false);
this._relayoutCell();
}
private async _showJupyterExtension() {
const viewlet = await this.paneCompositeService.openPaneComposite(EXTENSION_VIEWLET_ID, ViewContainerLocation.Sidebar, true);
const view = viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer | undefined;
view?.search(`@id:${JUPYTER_EXTENSION_ID}`);
}
private _generateRendererInfo(renderId: string): string {
const renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
const displayName = renderInfo.displayName !== '' ? renderInfo.displayName : renderInfo.id;
return `${displayName} (${renderInfo.extensionId.value})`;
}
return nls.localize('unavailableRenderInfo', "renderer not available");
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
if (this._outputHeightTimer) {
this.viewCell.unlockOutputHeight();
clearTimeout(this._outputHeightTimer);
}
super.dispose();
}
}
class OutputEntryViewHandler {
constructor(
readonly model: ICellOutputViewModel,
readonly element: CellOutputElement
) {
}
}
export class CellOutputContainer extends CellContentPart {
private _outputEntries: OutputEntryViewHandler[] = [];
get renderedOutputEntries() {
return this._outputEntries;
}
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private readonly templateData: CodeCellRenderTemplate,
private options: { limit: number },
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._register(viewCell.onDidChangeOutputs(splice => {
this._updateOutputs(splice);
}));
this._register(viewCell.onDidChangeLayout(() => {
this.updateInternalLayoutNow(viewCell);
}));
}
override updateInternalLayoutNow(viewCell: CodeCellViewModel) {
this.templateData.outputContainer.setTop(viewCell.layoutInfo.outputContainerOffset);
this.templateData.outputShowMoreContainer.setTop(viewCell.layoutInfo.outputShowMoreContainerOffset);
this._outputEntries.forEach(entry => {
const index = this.viewCell.outputsViewModels.indexOf(entry.model);
if (index >= 0) {
const top = this.viewCell.getOutputOffsetInContainer(index);
entry.element.updateDOMTop(top);
}
});
}
render() {
if (this.viewCell.outputsViewModels.length > 0) {
if (this.viewCell.layoutInfo.outputTotalHeight !== 0) {
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
this._relayoutCell();
}
DOM.show(this.templateData.outputContainer.domNode);
for (let index = 0; index < Math.min(this.options.limit, this.viewCell.outputsViewModels.length); index++) {
const currOutput = this.viewCell.outputsViewModels[index];
const entry = this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, currOutput);
this._outputEntries.push(new OutputEntryViewHandler(currOutput, entry));
entry.render(undefined);
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(46);
}
this._relayoutCell();
this._validateFinalOutputHeight(false);
} else {
// noop
this._relayoutCell();
DOM.hide(this.templateData.outputContainer.domNode);
}
this.templateData.outputShowMoreContainer.domNode.innerText = '';
if (this.viewCell.outputsViewModels.length > this.options.limit) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(0);
}
}
viewUpdateShowOutputs(initRendering: boolean): void {
for (let index = 0; index < this._outputEntries.length; index++) {
const viewHandler = this._outputEntries[index];
const outputEntry = viewHandler.element;
if (outputEntry.renderResult) {
this.notebookEditor.createOutput(this.viewCell, outputEntry.renderResult as IInsetRenderOutput, this.viewCell.getOutputOffset(index));
} else {
outputEntry.render(undefined);
}
}
this._relayoutCell();
}
viewUpdateHideOuputs(): void {
for (let index = 0; index < this._outputEntries.length; index++) {
this.notebookEditor.hideInset(this._outputEntries[index].model);
}
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _updateOutputs(splice: NotebookCellOutputsSplice) {
const previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;
// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.
this.viewCell.updateOutputMinHeight(previousOutputHeight);
if (this.viewCell.outputsViewModels.length) {
DOM.show(this.templateData.outputContainer.domNode);
} else {
DOM.hide(this.templateData.outputContainer.domNode);
}
this.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));
this._renderNow(splice);
}
private _renderNow(splice: NotebookCellOutputsSplice) {
if (splice.start >= this.options.limit) {
// splice items out of limit
return;
}
const firstGroupEntries = this._outputEntries.slice(0, splice.start);
const deletedEntries = this._outputEntries.slice(splice.start, splice.start + splice.deleteCount);
const secondGroupEntries = this._outputEntries.slice(splice.start + splice.deleteCount);
let newlyInserted = this.viewCell.outputsViewModels.slice(splice.start, splice.start + splice.newOutputs.length);
// [...firstGroup, ...deletedEntries, ...secondGroupEntries] [...restInModel]
// [...firstGroup, ...newlyInserted, ...secondGroupEntries, restInModel]
if (firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length > this.options.limit) {
// exceeds limit again
if (firstGroupEntries.length + newlyInserted.length > this.options.limit) {
[...deletedEntries, ...secondGroupEntries].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
newlyInserted = newlyInserted.slice(0, this.options.limit - firstGroupEntries.length);
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries];
// render newly inserted outputs
for (let i = firstGroupEntries.length; i < this._outputEntries.length; i++) {
this._outputEntries[i].element.render(undefined);
}
} else {
// part of secondGroupEntries are pushed out of view
// now we have to be creative as secondGroupEntries might not use dedicated containers
const elementsPushedOutOfView = secondGroupEntries.slice(this.options.limit - firstGroupEntries.length - newlyInserted.length);
[...deletedEntries, ...elementsPushedOutOfView].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
// exclusive
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries.slice(0, this.options.limit - firstGroupEntries.length - newlyInserted.length)];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
}
} else {
// after splice, it doesn't exceed
deletedEntries.forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
let outputsNewlyAvailable: OutputEntryViewHandler[] = [];
if (firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length < this.viewCell.outputsViewModels.length) {
const last = Math.min(this.options.limit, this.viewCell.outputsViewModels.length);
outputsNewlyAvailable = this.viewCell.outputsViewModels.slice(firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length, last).map(output => {
return new OutputEntryViewHandler(output, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, output));
});
}
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries, ...outputsNewlyAvailable];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
for (let i = 0; i < outputsNewlyAvailable.length; i++) {
this._outputEntries[firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length + i].element.render(undefined);
}
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
if (!this.templateData.outputShowMoreContainer.domNode.hasChildNodes()) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
}
this.viewCell.updateOutputShowMoreContainerHeight(46);
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
}
const editorHeight = this.templateData.editor.getContentHeight();
this.viewCell.editorHeight = editorHeight;
this._relayoutCell();
// if it's clearing all outputs, or outputs are all rendered synchronously
// shrink immediately as the final output height will be zero.
this._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);
}
private _generateShowMoreElement(disposables: DisposableStore): HTMLElement {
const md: IMarkdownString = {
value: `There are more than ${this.options.limit} outputs, [show more (open the raw output data in a text editor) ...](command:workbench.action.openLargeOutput)`,
isTrusted: true,
supportThemeIcons: true
};
const rendered = renderMarkdown(md, {
actionHandler: {
callback: (content) => {
if (content === 'command:workbench.action.openLargeOutput') {
this.openerService.open(CellUri.generateCellOutputUri(this.notebookEditor.textModel!.uri));
}
return;
},
disposables
}
});
disposables.add(rendered);
rendered.element.classList.add('output-show-more');
return rendered.element;
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
this.viewCell.updateOutputMinHeight(0);
if (this._outputHeightTimer) {
clearTimeout(this._outputHeightTimer);
}
this._outputEntries.forEach(entry => {
entry.element.dispose();
});
super.dispose();
}
}
const JUPYTER_RENDERER_MIMETYPES = [
'application/geo+json',
'application/vdom.v1+json',
'application/vnd.dataresource+json',
'application/vnd.plotly.v1+json',
'application/vnd.vega.v2+json',
'application/vnd.vega.v3+json',
'application/vnd.vega.v4+json',
'application/vnd.vega.v5+json',
'application/vnd.vegalite.v1+json',
'application/vnd.vegalite.v2+json',
'application/vnd.vegalite.v3+json',
'application/vnd.vegalite.v4+json',
'application/x-nteract-model-debug+json',
'image/svg+xml',
'text/latex',
'text/vnd.plotly.v1+html',
'application/vnd.jupyter.widget-view+json',
'application/vnd.code.notebook.error'
];
| src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.007154200691729784,
0.0005409110453911126,
0.00016411018441431224,
0.00020586054597515613,
0.0009596850140951574
] |
{
"id": 12,
"code_window": [
"\t\t\t}\n",
"\t\t\tdispose(removedOutputs);\n",
"\t\t}));\n",
"\n",
"\t\tthis._outputCollection = new Array(this.model.outputs.length);\n",
"\n",
"\t\tthis._layoutInfo = {\n",
"\t\t\tfontInfo: initialNotebookLayoutInfo?.fontInfo || null,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this._notebookExecutionStateService.onDidChangeCellExecution(e => {\n",
"\t\t\tif (e.affectsCell(model.uri)) {\n",
"\t\t\t\tif (e.changed) {\n",
"\t\t\t\t\tthis._onDidStartExecution.fire();\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tthis._onDidStopExecution.fire();\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 146
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/notificationsCenter';
import 'vs/css!./media/notificationsActions';
import { NOTIFICATIONS_CENTER_HEADER_FOREGROUND, NOTIFICATIONS_CENTER_HEADER_BACKGROUND, NOTIFICATIONS_CENTER_BORDER } from 'vs/workbench/common/theme';
import { IThemeService, Themable } from 'vs/platform/theme/common/themeService';
import { INotificationsModel, INotificationChangeEvent, NotificationChangeType, NotificationViewItemContentChangeKind } from 'vs/workbench/common/notifications';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { Emitter } from 'vs/base/common/event';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { INotificationsCenterController } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { NotificationsList } from 'vs/workbench/browser/parts/notifications/notificationsList';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { isAncestor, Dimension } from 'vs/base/browser/dom';
import { widgetShadow } from 'vs/platform/theme/common/colorRegistry';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { localize } from 'vs/nls';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { ClearAllNotificationsAction, HideNotificationsCenterAction, NotificationActionRunner, ToggleDoNotDisturbAction } from 'vs/workbench/browser/parts/notifications/notificationsActions';
import { IAction } from 'vs/base/common/actions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { assertAllDefined, assertIsDefined } from 'vs/base/common/types';
import { NotificationsCenterVisibleContext } from 'vs/workbench/common/contextkeys';
import { INotificationService } from 'vs/platform/notification/common/notification';
export class NotificationsCenter extends Themable implements INotificationsCenterController {
private static readonly MAX_DIMENSIONS = new Dimension(450, 400);
private readonly _onDidChangeVisibility = this._register(new Emitter<void>());
readonly onDidChangeVisibility = this._onDidChangeVisibility.event;
private notificationsCenterContainer: HTMLElement | undefined;
private notificationsCenterHeader: HTMLElement | undefined;
private notificationsCenterTitle: HTMLSpanElement | undefined;
private notificationsList: NotificationsList | undefined;
private _isVisible: boolean | undefined;
private workbenchDimensions: Dimension | undefined;
private readonly notificationsCenterVisibleContextKey = NotificationsCenterVisibleContext.bindTo(this.contextKeyService);
private clearAllAction: ClearAllNotificationsAction | undefined;
private toggleDoNotDisturbAction: ToggleDoNotDisturbAction | undefined;
constructor(
private readonly container: HTMLElement,
private readonly model: INotificationsModel,
@IThemeService themeService: IThemeService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@INotificationService private readonly notificationService: INotificationService,
) {
super(themeService);
this.notificationsCenterVisibleContextKey = NotificationsCenterVisibleContext.bindTo(contextKeyService);
this.registerListeners();
}
private registerListeners(): void {
this._register(this.model.onDidChangeNotification(e => this.onDidChangeNotification(e)));
this._register(this.layoutService.onDidLayout(dimension => this.layout(Dimension.lift(dimension))));
this._register(this.notificationService.onDidChangeDoNotDisturbMode(() => this.onDidChangeDoNotDisturbMode()));
}
private onDidChangeDoNotDisturbMode(): void {
this.hide(); // hide the notification center when do not disturb is toggled
}
get isVisible(): boolean {
return !!this._isVisible;
}
show(): void {
if (this._isVisible) {
const notificationsList = assertIsDefined(this.notificationsList);
notificationsList.show(true /* focus */);
return; // already visible
}
// Lazily create if showing for the first time
if (!this.notificationsCenterContainer) {
this.create();
}
// Title
this.updateTitle();
// Make visible
const [notificationsList, notificationsCenterContainer] = assertAllDefined(this.notificationsList, this.notificationsCenterContainer);
this._isVisible = true;
notificationsCenterContainer.classList.add('visible');
notificationsList.show();
// Layout
this.layout(this.workbenchDimensions);
// Show all notifications that are present now
notificationsList.updateNotificationsList(0, 0, this.model.notifications);
// Focus first
notificationsList.focusFirst();
// Theming
this.updateStyles();
// Mark as visible
this.model.notifications.forEach(notification => notification.updateVisibility(true));
// Context Key
this.notificationsCenterVisibleContextKey.set(true);
// Event
this._onDidChangeVisibility.fire();
}
private updateTitle(): void {
const [notificationsCenterTitle, clearAllAction] = assertAllDefined(this.notificationsCenterTitle, this.clearAllAction);
if (this.model.notifications.length === 0) {
notificationsCenterTitle.textContent = localize('notificationsEmpty', "No new notifications");
clearAllAction.enabled = false;
} else {
notificationsCenterTitle.textContent = localize('notifications', "Notifications");
clearAllAction.enabled = this.model.notifications.some(notification => !notification.hasProgress);
}
}
private create(): void {
// Container
this.notificationsCenterContainer = document.createElement('div');
this.notificationsCenterContainer.classList.add('notifications-center');
// Header
this.notificationsCenterHeader = document.createElement('div');
this.notificationsCenterHeader.classList.add('notifications-center-header');
this.notificationsCenterContainer.appendChild(this.notificationsCenterHeader);
// Header Title
this.notificationsCenterTitle = document.createElement('span');
this.notificationsCenterTitle.classList.add('notifications-center-header-title');
this.notificationsCenterHeader.appendChild(this.notificationsCenterTitle);
// Header Toolbar
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('notifications-center-header-toolbar');
this.notificationsCenterHeader.appendChild(toolbarContainer);
const actionRunner = this._register(this.instantiationService.createInstance(NotificationActionRunner));
const notificationsToolBar = this._register(new ActionBar(toolbarContainer, {
ariaLabel: localize('notificationsToolbar', "Notification Center Actions"),
actionRunner
}));
this.clearAllAction = this._register(this.instantiationService.createInstance(ClearAllNotificationsAction, ClearAllNotificationsAction.ID, ClearAllNotificationsAction.LABEL));
notificationsToolBar.push(this.clearAllAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(this.clearAllAction) });
this.toggleDoNotDisturbAction = this._register(this.instantiationService.createInstance(ToggleDoNotDisturbAction, ToggleDoNotDisturbAction.ID, ToggleDoNotDisturbAction.LABEL));
notificationsToolBar.push(this.toggleDoNotDisturbAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(this.toggleDoNotDisturbAction) });
const hideAllAction = this._register(this.instantiationService.createInstance(HideNotificationsCenterAction, HideNotificationsCenterAction.ID, HideNotificationsCenterAction.LABEL));
notificationsToolBar.push(hideAllAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(hideAllAction) });
// Notifications List
this.notificationsList = this.instantiationService.createInstance(NotificationsList, this.notificationsCenterContainer, {
widgetAriaLabel: localize('notificationsCenterWidgetAriaLabel', "Notifications Center")
});
this.container.appendChild(this.notificationsCenterContainer);
}
private getKeybindingLabel(action: IAction): string | null {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
return keybinding ? keybinding.getLabel() : null;
}
private onDidChangeNotification(e: INotificationChangeEvent): void {
if (!this._isVisible) {
return; // only if visible
}
let focusEditor = false;
// Update notifications list based on event kind
const [notificationsList, notificationsCenterContainer] = assertAllDefined(this.notificationsList, this.notificationsCenterContainer);
switch (e.kind) {
case NotificationChangeType.ADD:
notificationsList.updateNotificationsList(e.index, 0, [e.item]);
e.item.updateVisibility(true);
break;
case NotificationChangeType.CHANGE:
// Handle content changes
// - actions: re-draw to properly show them
// - message: update notification height unless collapsed
switch (e.detail) {
case NotificationViewItemContentChangeKind.ACTIONS:
notificationsList.updateNotificationsList(e.index, 1, [e.item]);
break;
case NotificationViewItemContentChangeKind.MESSAGE:
if (e.item.expanded) {
notificationsList.updateNotificationHeight(e.item);
}
break;
}
break;
case NotificationChangeType.EXPAND_COLLAPSE:
// Re-draw entire item when expansion changes to reveal or hide details
notificationsList.updateNotificationsList(e.index, 1, [e.item]);
break;
case NotificationChangeType.REMOVE:
focusEditor = isAncestor(document.activeElement, notificationsCenterContainer);
notificationsList.updateNotificationsList(e.index, 1);
e.item.updateVisibility(false);
break;
}
// Update title
this.updateTitle();
// Hide if no more notifications to show
if (this.model.notifications.length === 0) {
this.hide();
// Restore focus to editor group if we had focus
if (focusEditor) {
this.editorGroupService.activeGroup.focus();
}
}
}
hide(): void {
if (!this._isVisible || !this.notificationsCenterContainer || !this.notificationsList) {
return; // already hidden
}
const focusEditor = isAncestor(document.activeElement, this.notificationsCenterContainer);
// Hide
this._isVisible = false;
this.notificationsCenterContainer.classList.remove('visible');
this.notificationsList.hide();
// Mark as hidden
this.model.notifications.forEach(notification => notification.updateVisibility(false));
// Context Key
this.notificationsCenterVisibleContextKey.set(false);
// Event
this._onDidChangeVisibility.fire();
// Restore focus to editor group if we had focus
if (focusEditor) {
this.editorGroupService.activeGroup.focus();
}
}
override updateStyles(): void {
if (this.notificationsCenterContainer && this.notificationsCenterHeader) {
const widgetShadowColor = this.getColor(widgetShadow);
this.notificationsCenterContainer.style.boxShadow = widgetShadowColor ? `0 0 8px 2px ${widgetShadowColor}` : '';
const borderColor = this.getColor(NOTIFICATIONS_CENTER_BORDER);
this.notificationsCenterContainer.style.border = borderColor ? `1px solid ${borderColor}` : '';
const headerForeground = this.getColor(NOTIFICATIONS_CENTER_HEADER_FOREGROUND);
this.notificationsCenterHeader.style.color = headerForeground ? headerForeground.toString() : '';
const headerBackground = this.getColor(NOTIFICATIONS_CENTER_HEADER_BACKGROUND);
this.notificationsCenterHeader.style.background = headerBackground ? headerBackground.toString() : '';
}
}
layout(dimension: Dimension | undefined): void {
this.workbenchDimensions = dimension;
if (this._isVisible && this.notificationsCenterContainer) {
const maxWidth = NotificationsCenter.MAX_DIMENSIONS.width;
const maxHeight = NotificationsCenter.MAX_DIMENSIONS.height;
let availableWidth = maxWidth;
let availableHeight = maxHeight;
if (this.workbenchDimensions) {
// Make sure notifications are not exceding available width
availableWidth = this.workbenchDimensions.width;
availableWidth -= (2 * 8); // adjust for paddings left and right
// Make sure notifications are not exceeding available height
availableHeight = this.workbenchDimensions.height - 35 /* header */;
if (this.layoutService.isVisible(Parts.STATUSBAR_PART)) {
availableHeight -= 22; // adjust for status bar
}
if (this.layoutService.isVisible(Parts.TITLEBAR_PART)) {
availableHeight -= 22; // adjust for title bar
}
availableHeight -= (2 * 12); // adjust for paddings top and bottom
}
// Apply to list
const notificationsList = assertIsDefined(this.notificationsList);
notificationsList.layout(Math.min(maxWidth, availableWidth), Math.min(maxHeight, availableHeight));
}
}
clearAll(): void {
// Hide notifications center first
this.hide();
// Close all
for (const notification of [...this.model.notifications] /* copy array since we modify it from closing */) {
if (!notification.hasProgress) {
notification.close();
}
}
}
}
| src/vs/workbench/browser/parts/notifications/notificationsCenter.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0006392773357219994,
0.0002218928566435352,
0.00016230173059739172,
0.00017333542928099632,
0.00010457445750944316
] |
{
"id": 12,
"code_window": [
"\t\t\t}\n",
"\t\t\tdispose(removedOutputs);\n",
"\t\t}));\n",
"\n",
"\t\tthis._outputCollection = new Array(this.model.outputs.length);\n",
"\n",
"\t\tthis._layoutInfo = {\n",
"\t\t\tfontInfo: initialNotebookLayoutInfo?.fontInfo || null,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this._notebookExecutionStateService.onDidChangeCellExecution(e => {\n",
"\t\t\tif (e.affectsCell(model.uri)) {\n",
"\t\t\t\tif (e.changed) {\n",
"\t\t\t\t\tthis._onDidStartExecution.fire();\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tthis._onDidStopExecution.fire();\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 146
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { EditorAction, ServicesAccessor, IActionOptions } from 'vs/editor/browser/editorExtensions';
import { grammarsExtPoint, ITMSyntaxExtensionPoint } from 'vs/workbench/services/textMate/common/TMGrammars';
import { IExtensionService, ExtensionPointContribution } from 'vs/workbench/services/extensions/common/extensions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
interface ModeScopeMap {
[key: string]: string;
}
export interface IGrammarContributions {
getGrammar(mode: string): string;
}
class GrammarContributions implements IGrammarContributions {
private static _grammars: ModeScopeMap = {};
constructor(contributions: ExtensionPointContribution<ITMSyntaxExtensionPoint[]>[]) {
if (!Object.keys(GrammarContributions._grammars).length) {
this.fillModeScopeMap(contributions);
}
}
private fillModeScopeMap(contributions: ExtensionPointContribution<ITMSyntaxExtensionPoint[]>[]) {
contributions.forEach((contribution) => {
contribution.value.forEach((grammar) => {
if (grammar.language && grammar.scopeName) {
GrammarContributions._grammars[grammar.language] = grammar.scopeName;
}
});
});
}
public getGrammar(mode: string): string {
return GrammarContributions._grammars[mode];
}
}
interface IEmmetActionOptions extends IActionOptions {
actionName: string;
}
export abstract class EmmetEditorAction extends EditorAction {
protected emmetActionName: string;
constructor(opts: IEmmetActionOptions) {
super(opts);
this.emmetActionName = opts.actionName;
}
private static readonly emmetSupportedModes = ['html', 'css', 'xml', 'xsl', 'haml', 'jade', 'jsx', 'slim', 'scss', 'sass', 'less', 'stylus', 'styl', 'svg'];
private _lastGrammarContributions: Promise<GrammarContributions> | null = null;
private _lastExtensionService: IExtensionService | null = null;
private _withGrammarContributions(extensionService: IExtensionService): Promise<GrammarContributions | null> {
if (this._lastExtensionService !== extensionService) {
this._lastExtensionService = extensionService;
this._lastGrammarContributions = extensionService.readExtensionPointContributions(grammarsExtPoint).then((contributions) => {
return new GrammarContributions(contributions);
});
}
return this._lastGrammarContributions || Promise.resolve(null);
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
const extensionService = accessor.get(IExtensionService);
const commandService = accessor.get(ICommandService);
return this._withGrammarContributions(extensionService).then((grammarContributions) => {
if (this.id === 'editor.emmet.action.expandAbbreviation' && grammarContributions) {
return commandService.executeCommand<void>('emmet.expandAbbreviation', EmmetEditorAction.getLanguage(editor, grammarContributions));
}
return undefined;
});
}
public static getLanguage(editor: ICodeEditor, grammars: IGrammarContributions) {
const model = editor.getModel();
const selection = editor.getSelection();
if (!model || !selection) {
return null;
}
const position = selection.getStartPosition();
model.tokenization.tokenizeIfCheap(position.lineNumber);
const languageId = model.getLanguageIdAtPosition(position.lineNumber, position.column);
const syntax = languageId.split('.').pop();
if (!syntax) {
return null;
}
const checkParentMode = (): string => {
const languageGrammar = grammars.getGrammar(syntax);
if (!languageGrammar) {
return syntax;
}
const languages = languageGrammar.split('.');
if (languages.length < 2) {
return syntax;
}
for (let i = 1; i < languages.length; i++) {
const language = languages[languages.length - i];
if (this.emmetSupportedModes.indexOf(language) !== -1) {
return language;
}
}
return syntax;
};
return {
language: syntax,
parentMode: checkParentMode()
};
}
}
| src/vs/workbench/contrib/emmet/browser/emmetActions.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0003216354816686362,
0.00018456399266142398,
0.0001630873157409951,
0.00017422973178327084,
0.00004011980854556896
] |
{
"id": 12,
"code_window": [
"\t\t\t}\n",
"\t\t\tdispose(removedOutputs);\n",
"\t\t}));\n",
"\n",
"\t\tthis._outputCollection = new Array(this.model.outputs.length);\n",
"\n",
"\t\tthis._layoutInfo = {\n",
"\t\t\tfontInfo: initialNotebookLayoutInfo?.fontInfo || null,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this._notebookExecutionStateService.onDidChangeCellExecution(e => {\n",
"\t\t\tif (e.affectsCell(model.uri)) {\n",
"\t\t\t\tif (e.changed) {\n",
"\t\t\t\t\tthis._onDidStartExecution.fire();\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tthis._onDidStopExecution.fire();\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 146
} | {
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "./out",
"types": [
"node"
]
},
"include": [
"src/**/*",
"../../src/vscode-dts/vscode.d.ts"
]
}
| extensions/merge-conflict/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017664099868852645,
0.00017519804532639682,
0.00017375507741235197,
0.00017519804532639682,
0.0000014429606380872428
] |
{
"id": 1,
"code_window": [
"\t\tconst onInputFontFamilyChanged = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.inputFontFamily'));\n",
"\t\tthis._register(onInputFontFamilyChanged(() => this.inputEditor.updateOptions({ fontFamily: this.getInputEditorFontFamily() })));\n",
"\n",
"\t\tthis.onDidChangeContentHeight = Event.signal(Event.filter(this.inputEditor.onDidContentSizeChange, e => e.contentHeightChanged));\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst onInputFontSizeChanged = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.inputFontSize'));\n",
"\t\tthis._register(onInputFontSizeChanged(() => this.inputEditor.updateOptions({ fontSize: this.getInputEditorFontSize() })));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "add",
"edit_start_line_idx": 1000
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { Registry } from 'vs/platform/registry/common/platform';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { DirtyDiffWorkbenchController } from './dirtydiffDecorator';
import { VIEWLET_ID, ISCMRepository, ISCMService, VIEW_PANE_ID, ISCMProvider, ISCMViewService, REPOSITORIES_VIEW_PANE_ID } from 'vs/workbench/contrib/scm/common/scm';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { SCMStatusController } from './activity';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
import { IContextKeyService, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { SCMService } from 'vs/workbench/contrib/scm/common/scmService';
import { IViewContainersRegistry, ViewContainerLocation, Extensions as ViewContainerExtensions, IViewsRegistry } from 'vs/workbench/common/views';
import { SCMViewPaneContainer } from 'vs/workbench/contrib/scm/browser/scmViewPaneContainer';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ModesRegistry } from 'vs/editor/common/modes/modesRegistry';
import { Codicon } from 'vs/base/common/codicons';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import { SCMViewPane } from 'vs/workbench/contrib/scm/browser/scmViewPane';
import { SCMViewService } from 'vs/workbench/contrib/scm/browser/scmViewService';
import { SCMRepositoriesViewPane } from 'vs/workbench/contrib/scm/browser/scmRepositoriesViewPane';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { Context as SuggestContext } from 'vs/editor/contrib/suggest/suggest';
ModesRegistry.registerLanguage({
id: 'scminput',
extensions: [],
mimetypes: ['text/x-scm-input']
});
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench)
.registerWorkbenchContribution(DirtyDiffWorkbenchController, LifecyclePhase.Restored);
const sourceControlViewIcon = registerIcon('source-control-view-icon', Codicon.sourceControl, localize('sourceControlViewIcon', 'View icon of the Source Control view.'));
const viewContainer = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).registerViewContainer({
id: VIEWLET_ID,
title: localize('source control', "Source Control"),
ctorDescriptor: new SyncDescriptor(SCMViewPaneContainer),
storageId: 'workbench.scm.views.state',
icon: sourceControlViewIcon,
alwaysUseContainerInfo: true,
order: 2,
hideIfEmpty: true,
}, ViewContainerLocation.Sidebar, { donotRegisterOpenCommand: true });
const viewsRegistry = Registry.as<IViewsRegistry>(ViewContainerExtensions.ViewsRegistry);
viewsRegistry.registerViewWelcomeContent(VIEW_PANE_ID, {
content: localize('no open repo', "No source control providers registered."),
when: 'default'
});
viewsRegistry.registerViews([{
id: VIEW_PANE_ID,
name: localize('source control', "Source Control"),
ctorDescriptor: new SyncDescriptor(SCMViewPane),
canToggleVisibility: true,
workspace: true,
canMoveView: true,
weight: 80,
order: -999,
containerIcon: sourceControlViewIcon,
openCommandActionDescriptor: {
id: viewContainer.id,
mnemonicTitle: localize({ key: 'miViewSCM', comment: ['&& denotes a mnemonic'] }, "S&&CM"),
keybindings: {
primary: 0,
win: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G },
linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G },
mac: { primary: KeyMod.WinCtrl | KeyMod.Shift | KeyCode.KEY_G },
},
order: 2,
}
}], viewContainer);
viewsRegistry.registerViews([{
id: REPOSITORIES_VIEW_PANE_ID,
name: localize('source control repositories', "Source Control Repositories"),
ctorDescriptor: new SyncDescriptor(SCMRepositoriesViewPane),
canToggleVisibility: true,
hideByDefault: true,
workspace: true,
canMoveView: true,
weight: 20,
order: -1000,
when: ContextKeyExpr.and(ContextKeyExpr.has('scm.providerCount'), ContextKeyExpr.notEquals('scm.providerCount', 0)),
// readonly when = ContextKeyExpr.or(ContextKeyExpr.equals('config.scm.alwaysShowProviders', true), ContextKeyExpr.and(ContextKeyExpr.notEquals('scm.providerCount', 0), ContextKeyExpr.notEquals('scm.providerCount', 1)));
containerIcon: sourceControlViewIcon
}], viewContainer);
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench)
.registerWorkbenchContribution(SCMStatusController, LifecyclePhase.Restored);
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({
id: 'scm',
order: 5,
title: localize('scmConfigurationTitle', "SCM"),
type: 'object',
scope: ConfigurationScope.RESOURCE,
properties: {
'scm.diffDecorations': {
type: 'string',
enum: ['all', 'gutter', 'overview', 'minimap', 'none'],
enumDescriptions: [
localize('scm.diffDecorations.all', "Show the diff decorations in all available locations."),
localize('scm.diffDecorations.gutter', "Show the diff decorations only in the editor gutter."),
localize('scm.diffDecorations.overviewRuler', "Show the diff decorations only in the overview ruler."),
localize('scm.diffDecorations.minimap', "Show the diff decorations only in the minimap."),
localize('scm.diffDecorations.none', "Do not show the diff decorations.")
],
default: 'all',
description: localize('diffDecorations', "Controls diff decorations in the editor.")
},
'scm.diffDecorationsGutterWidth': {
type: 'number',
enum: [1, 2, 3, 4, 5],
default: 3,
description: localize('diffGutterWidth', "Controls the width(px) of diff decorations in gutter (added & modified).")
},
'scm.diffDecorationsGutterVisibility': {
type: 'string',
enum: ['always', 'hover'],
enumDescriptions: [
localize('scm.diffDecorationsGutterVisibility.always', "Show the diff decorator in the gutter at all times."),
localize('scm.diffDecorationsGutterVisibility.hover', "Show the diff decorator in the gutter only on hover.")
],
description: localize('scm.diffDecorationsGutterVisibility', "Controls the visibility of the Source Control diff decorator in the gutter."),
default: 'always'
},
'scm.diffDecorationsGutterAction': {
type: 'string',
enum: ['diff', 'none'],
enumDescriptions: [
localize('scm.diffDecorationsGutterAction.diff', "Show the inline diff peek view on click."),
localize('scm.diffDecorationsGutterAction.none', "Do nothing.")
],
description: localize('scm.diffDecorationsGutterAction', "Controls the behavior of Source Control diff gutter decorations."),
default: 'diff'
},
'scm.alwaysShowActions': {
type: 'boolean',
description: localize('alwaysShowActions', "Controls whether inline actions are always visible in the Source Control view."),
default: false
},
'scm.countBadge': {
type: 'string',
enum: ['all', 'focused', 'off'],
enumDescriptions: [
localize('scm.countBadge.all', "Show the sum of all Source Control Provider count badges."),
localize('scm.countBadge.focused', "Show the count badge of the focused Source Control Provider."),
localize('scm.countBadge.off', "Disable the Source Control count badge.")
],
description: localize('scm.countBadge', "Controls the count badge on the Source Control icon on the Activity Bar."),
default: 'all'
},
'scm.providerCountBadge': {
type: 'string',
enum: ['hidden', 'auto', 'visible'],
enumDescriptions: [
localize('scm.providerCountBadge.hidden', "Hide Source Control Provider count badges."),
localize('scm.providerCountBadge.auto', "Only show count badge for Source Control Provider when non-zero."),
localize('scm.providerCountBadge.visible', "Show Source Control Provider count badges.")
],
description: localize('scm.providerCountBadge', "Controls the count badges on Source Control Provider headers. These headers only appear when there is more than one provider."),
default: 'hidden'
},
'scm.defaultViewMode': {
type: 'string',
enum: ['tree', 'list'],
enumDescriptions: [
localize('scm.defaultViewMode.tree', "Show the repository changes as a tree."),
localize('scm.defaultViewMode.list', "Show the repository changes as a list.")
],
description: localize('scm.defaultViewMode', "Controls the default Source Control repository view mode."),
default: 'list'
},
'scm.autoReveal': {
type: 'boolean',
description: localize('autoReveal', "Controls whether the SCM view should automatically reveal and select files when opening them."),
default: true
},
'scm.inputFontFamily': {
type: 'string',
markdownDescription: localize('inputFontFamily', "Controls the font for the input message. Use `default` for the workbench user interface font family, `editor` for the `#editor.fontFamily#`'s value, or a custom font family."),
default: 'default'
},
'scm.alwaysShowRepositories': {
type: 'boolean',
markdownDescription: localize('alwaysShowRepository', "Controls whether repositories should always be visible in the SCM view."),
default: false
},
'scm.repositories.visible': {
type: 'number',
description: localize('providersVisible', "Controls how many repositories are visible in the Source Control Repositories section. Set to `0` to be able to manually resize the view."),
default: 10
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'scm.acceptInput',
description: { description: localize('scm accept', "SCM: Accept Input"), args: [] },
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.has('scmRepository'),
primary: KeyMod.CtrlCmd | KeyCode.Enter,
handler: accessor => {
const contextKeyService = accessor.get(IContextKeyService);
const context = contextKeyService.getContext(document.activeElement);
const repository = context.getValue<ISCMRepository>('scmRepository');
if (!repository || !repository.provider.acceptInputCommand) {
return Promise.resolve(null);
}
const id = repository.provider.acceptInputCommand.id;
const args = repository.provider.acceptInputCommand.arguments;
const commandService = accessor.get(ICommandService);
return commandService.executeCommand(id, ...(args || []));
}
});
const viewNextCommitCommand = {
description: { description: localize('scm view next commit', "SCM: View Next Commit"), args: [] },
weight: KeybindingWeight.WorkbenchContrib,
handler: (accessor: ServicesAccessor) => {
const contextKeyService = accessor.get(IContextKeyService);
const context = contextKeyService.getContext(document.activeElement);
const repository = context.getValue<ISCMRepository>('scmRepository');
repository?.input.showNextHistoryValue();
}
};
const viewPreviousCommitCommand = {
description: { description: localize('scm view previous commit', "SCM: View Previous Commit"), args: [] },
weight: KeybindingWeight.WorkbenchContrib,
handler: (accessor: ServicesAccessor) => {
const contextKeyService = accessor.get(IContextKeyService);
const context = contextKeyService.getContext(document.activeElement);
const repository = context.getValue<ISCMRepository>('scmRepository');
repository?.input.showPreviousHistoryValue();
}
};
KeybindingsRegistry.registerCommandAndKeybindingRule({
...viewNextCommitCommand,
id: 'scm.viewNextCommit',
when: ContextKeyExpr.and(ContextKeyExpr.has('scmRepository'), ContextKeyExpr.has('scmInputIsInLastPosition'), SuggestContext.Visible.toNegated()),
primary: KeyCode.DownArrow
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
...viewPreviousCommitCommand,
id: 'scm.viewPreviousCommit',
when: ContextKeyExpr.and(ContextKeyExpr.has('scmRepository'), ContextKeyExpr.has('scmInputIsInFirstPosition'), SuggestContext.Visible.toNegated()),
primary: KeyCode.UpArrow
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
...viewNextCommitCommand,
id: 'scm.forceViewNextCommit',
when: ContextKeyExpr.has('scmRepository'),
primary: KeyMod.Alt | KeyCode.DownArrow
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
...viewPreviousCommitCommand,
id: 'scm.forceViewPreviousCommit',
when: ContextKeyExpr.has('scmRepository'),
primary: KeyMod.Alt | KeyCode.UpArrow
});
CommandsRegistry.registerCommand('scm.openInTerminal', async (accessor, provider: ISCMProvider) => {
if (!provider || !provider.rootUri) {
return;
}
const commandService = accessor.get(ICommandService);
await commandService.executeCommand('openInTerminal', provider.rootUri);
});
MenuRegistry.appendMenuItem(MenuId.SCMSourceControl, {
group: '100_end',
command: {
id: 'scm.openInTerminal',
title: localize('open in terminal', "Open In Terminal")
},
when: ContextKeyExpr.equals('scmProviderHasRootUri', true)
});
registerSingleton(ISCMService, SCMService);
registerSingleton(ISCMViewService, SCMViewService);
| src/vs/workbench/contrib/scm/browser/scm.contribution.ts | 1 | https://github.com/microsoft/vscode/commit/6480a6f20ea86b23b1c8d92c7ef37b20fcad18ec | [
0.00017781887436285615,
0.00017428825958631933,
0.00016467117529828101,
0.00017500779358670115,
0.0000029954544515931047
] |
{
"id": 1,
"code_window": [
"\t\tconst onInputFontFamilyChanged = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.inputFontFamily'));\n",
"\t\tthis._register(onInputFontFamilyChanged(() => this.inputEditor.updateOptions({ fontFamily: this.getInputEditorFontFamily() })));\n",
"\n",
"\t\tthis.onDidChangeContentHeight = Event.signal(Event.filter(this.inputEditor.onDidContentSizeChange, e => e.contentHeightChanged));\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst onInputFontSizeChanged = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.inputFontSize'));\n",
"\t\tthis._register(onInputFontSizeChanged(() => this.inputEditor.updateOptions({ fontSize: this.getInputEditorFontSize() })));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "add",
"edit_start_line_idx": 1000
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IChannel } from 'vs/base/parts/ipc/common/ipc';
import { IExtensionManagementService, ILocalExtension, IGalleryExtension, IExtensionGalleryService, InstallOperation, InstallOptions } from 'vs/platform/extensionManagement/common/extensionManagement';
import { URI } from 'vs/base/common/uri';
import { ExtensionType, IExtensionManifest } from 'vs/platform/extensions/common/extensions';
import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { ILogService } from 'vs/platform/log/common/log';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { localize } from 'vs/nls';
import { IProductService } from 'vs/platform/product/common/productService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { generateUuid } from 'vs/base/common/uuid';
import { joinPath } from 'vs/base/common/resources';
import { WebRemoteExtensionManagementService } from 'vs/workbench/services/extensionManagement/common/remoteExtensionManagementService';
import { IExtensionManagementServer } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { Promises } from 'vs/base/common/async';
export class NativeRemoteExtensionManagementService extends WebRemoteExtensionManagementService implements IExtensionManagementService {
private readonly localExtensionManagementService: IExtensionManagementService;
constructor(
channel: IChannel,
localExtensionManagementServer: IExtensionManagementServer,
@ILogService private readonly logService: ILogService,
@IExtensionGalleryService galleryService: IExtensionGalleryService,
@IConfigurationService configurationService: IConfigurationService,
@IProductService productService: IProductService,
@INativeWorkbenchEnvironmentService private readonly environmentService: INativeWorkbenchEnvironmentService
) {
super(channel, galleryService, configurationService, productService);
this.localExtensionManagementService = localExtensionManagementServer.extensionManagementService;
}
async install(vsix: URI): Promise<ILocalExtension> {
const local = await super.install(vsix);
await this.installUIDependenciesAndPackedExtensions(local);
return local;
}
async installFromGallery(extension: IGalleryExtension, installOptions?: InstallOptions): Promise<ILocalExtension> {
const local = await this.doInstallFromGallery(extension, installOptions);
await this.installUIDependenciesAndPackedExtensions(local);
return local;
}
private async doInstallFromGallery(extension: IGalleryExtension, installOptions?: InstallOptions): Promise<ILocalExtension> {
if (this.configurationService.getValue<boolean>('remote.downloadExtensionsLocally')) {
this.logService.trace(`Download '${extension.identifier.id}' extension locally and install`);
return this.downloadCompatibleAndInstall(extension);
}
try {
const local = await super.installFromGallery(extension, installOptions);
return local;
} catch (error) {
try {
this.logService.error(`Error while installing '${extension.identifier.id}' extension in the remote server.`, toErrorMessage(error));
this.logService.info(`Trying to download '${extension.identifier.id}' extension locally and install`);
const local = await this.downloadCompatibleAndInstall(extension);
this.logService.info(`Successfully installed '${extension.identifier.id}' extension`);
return local;
} catch (e) {
this.logService.error(e);
throw error;
}
}
}
private async downloadCompatibleAndInstall(extension: IGalleryExtension): Promise<ILocalExtension> {
const installed = await this.getInstalled(ExtensionType.User);
const compatible = await this.galleryService.getCompatibleExtension(extension);
if (!compatible) {
return Promise.reject(new Error(localize('incompatible', "Unable to install extension '{0}' as it is not compatible with VS Code '{1}'.", extension.identifier.id, this.productService.version)));
}
const manifest = await this.galleryService.getManifest(compatible, CancellationToken.None);
if (manifest) {
const workspaceExtensions = await this.getAllWorkspaceDependenciesAndPackedExtensions(manifest, CancellationToken.None);
await Promises.settled(workspaceExtensions.map(e => this.downloadAndInstall(e, installed)));
}
return this.downloadAndInstall(extension, installed);
}
private async downloadAndInstall(extension: IGalleryExtension, installed: ILocalExtension[]): Promise<ILocalExtension> {
const location = joinPath(this.environmentService.tmpDir, generateUuid());
await this.galleryService.download(extension, location, installed.filter(i => areSameExtensions(i.identifier, extension.identifier))[0] ? InstallOperation.Update : InstallOperation.Install);
return super.install(location);
}
private async installUIDependenciesAndPackedExtensions(local: ILocalExtension): Promise<void> {
const uiExtensions = await this.getAllUIDependenciesAndPackedExtensions(local.manifest, CancellationToken.None);
const installed = await this.localExtensionManagementService.getInstalled();
const toInstall = uiExtensions.filter(e => installed.every(i => !areSameExtensions(i.identifier, e.identifier)));
await Promises.settled(toInstall.map(d => this.localExtensionManagementService.installFromGallery(d)));
}
private async getAllUIDependenciesAndPackedExtensions(manifest: IExtensionManifest, token: CancellationToken): Promise<IGalleryExtension[]> {
const result = new Map<string, IGalleryExtension>();
const extensions = [...(manifest.extensionPack || []), ...(manifest.extensionDependencies || [])];
await this.getDependenciesAndPackedExtensionsRecursively(extensions, result, true, token);
return [...result.values()];
}
private async getAllWorkspaceDependenciesAndPackedExtensions(manifest: IExtensionManifest, token: CancellationToken): Promise<IGalleryExtension[]> {
const result = new Map<string, IGalleryExtension>();
const extensions = [...(manifest.extensionPack || []), ...(manifest.extensionDependencies || [])];
await this.getDependenciesAndPackedExtensionsRecursively(extensions, result, false, token);
return [...result.values()];
}
private async getDependenciesAndPackedExtensionsRecursively(toGet: string[], result: Map<string, IGalleryExtension>, uiExtension: boolean, token: CancellationToken): Promise<void> {
if (toGet.length === 0) {
return Promise.resolve();
}
const extensions = (await this.galleryService.query({ names: toGet, pageSize: toGet.length }, token)).firstPage;
const manifests = await Promise.all(extensions.map(e => this.galleryService.getManifest(e, token)));
const extensionsManifests: IExtensionManifest[] = [];
for (let idx = 0; idx < extensions.length; idx++) {
const extension = extensions[idx];
const manifest = manifests[idx];
if (manifest && this.extensionKindController.prefersExecuteOnUI(manifest) === uiExtension) {
result.set(extension.identifier.id.toLowerCase(), extension);
extensionsManifests.push(manifest);
}
}
toGet = [];
for (const extensionManifest of extensionsManifests) {
if (isNonEmptyArray(extensionManifest.extensionDependencies)) {
for (const id of extensionManifest.extensionDependencies) {
if (!result.has(id.toLowerCase())) {
toGet.push(id);
}
}
}
if (isNonEmptyArray(extensionManifest.extensionPack)) {
for (const id of extensionManifest.extensionPack) {
if (!result.has(id.toLowerCase())) {
toGet.push(id);
}
}
}
}
return this.getDependenciesAndPackedExtensionsRecursively(toGet, result, uiExtension, token);
}
}
| src/vs/workbench/services/extensionManagement/electron-sandbox/remoteExtensionManagementService.ts | 0 | https://github.com/microsoft/vscode/commit/6480a6f20ea86b23b1c8d92c7ef37b20fcad18ec | [
0.00017802006914280355,
0.00017470750026404858,
0.00016643491107970476,
0.00017567758914083242,
0.0000031618621960660676
] |
{
"id": 1,
"code_window": [
"\t\tconst onInputFontFamilyChanged = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.inputFontFamily'));\n",
"\t\tthis._register(onInputFontFamilyChanged(() => this.inputEditor.updateOptions({ fontFamily: this.getInputEditorFontFamily() })));\n",
"\n",
"\t\tthis.onDidChangeContentHeight = Event.signal(Event.filter(this.inputEditor.onDidContentSizeChange, e => e.contentHeightChanged));\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst onInputFontSizeChanged = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.inputFontSize'));\n",
"\t\tthis._register(onInputFontSizeChanged(() => this.inputEditor.updateOptions({ fontSize: this.getInputEditorFontSize() })));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "add",
"edit_start_line_idx": 1000
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MarkdownIt, Token } from 'markdown-it';
import * as path from 'path';
import * as vscode from 'vscode';
import { MarkdownContributionProvider as MarkdownContributionProvider } from './markdownExtensions';
import { Slugifier } from './slugify';
import { SkinnyTextDocument } from './tableOfContentsProvider';
import { hash } from './util/hash';
import { isOfScheme, MarkdownFileExtensions, Schemes } from './util/links';
const UNICODE_NEWLINE_REGEX = /\u2028|\u2029/g;
interface MarkdownItConfig {
readonly breaks: boolean;
readonly linkify: boolean;
}
class TokenCache {
private cachedDocument?: {
readonly uri: vscode.Uri;
readonly version: number;
readonly config: MarkdownItConfig;
};
private tokens?: Token[];
public tryGetCached(document: SkinnyTextDocument, config: MarkdownItConfig): Token[] | undefined {
if (this.cachedDocument
&& this.cachedDocument.uri.toString() === document.uri.toString()
&& this.cachedDocument.version === document.version
&& this.cachedDocument.config.breaks === config.breaks
&& this.cachedDocument.config.linkify === config.linkify
) {
return this.tokens;
}
return undefined;
}
public update(document: SkinnyTextDocument, config: MarkdownItConfig, tokens: Token[]) {
this.cachedDocument = {
uri: document.uri,
version: document.version,
config,
};
this.tokens = tokens;
}
public clean(): void {
this.cachedDocument = undefined;
this.tokens = undefined;
}
}
export interface RenderOutput {
html: string;
containingImages: { src: string }[];
}
interface RenderEnv {
containingImages: { src: string }[];
}
export class MarkdownEngine {
private md?: Promise<MarkdownIt>;
private currentDocument?: vscode.Uri;
private _slugCount = new Map<string, number>();
private _tokenCache = new TokenCache();
public constructor(
private readonly contributionProvider: MarkdownContributionProvider,
private readonly slugifier: Slugifier,
) {
contributionProvider.onContributionsChanged(() => {
// Markdown plugin contributions may have changed
this.md = undefined;
});
}
private async getEngine(config: MarkdownItConfig): Promise<MarkdownIt> {
if (!this.md) {
this.md = import('markdown-it').then(async markdownIt => {
let md: MarkdownIt = markdownIt(await getMarkdownOptions(() => md));
for (const plugin of this.contributionProvider.contributions.markdownItPlugins.values()) {
try {
md = (await plugin)(md);
} catch {
// noop
}
}
const frontMatterPlugin = require('markdown-it-front-matter');
// Extract rules from front matter plugin and apply at a lower precedence
let fontMatterRule: any;
frontMatterPlugin({
block: {
ruler: {
before: (_id: any, _id2: any, rule: any) => { fontMatterRule = rule; }
}
}
}, () => { /* noop */ });
md.block.ruler.before('fence', 'front_matter', fontMatterRule, {
alt: ['paragraph', 'reference', 'blockquote', 'list']
});
for (const renderName of ['paragraph_open', 'heading_open', 'image', 'code_block', 'fence', 'blockquote_open', 'list_item_open']) {
this.addLineNumberRenderer(md, renderName);
}
this.addImageStabilizer(md);
this.addFencedRenderer(md);
this.addLinkNormalizer(md);
this.addLinkValidator(md);
this.addNamedHeaders(md);
this.addLinkRenderer(md);
return md;
});
}
const md = await this.md!;
md.set(config);
return md;
}
private tokenizeDocument(
document: SkinnyTextDocument,
config: MarkdownItConfig,
engine: MarkdownIt
): Token[] {
const cached = this._tokenCache.tryGetCached(document, config);
if (cached) {
return cached;
}
this.currentDocument = document.uri;
const tokens = this.tokenizeString(document.getText(), engine);
this._tokenCache.update(document, config, tokens);
return tokens;
}
private tokenizeString(text: string, engine: MarkdownIt) {
this._slugCount = new Map<string, number>();
return engine.parse(text.replace(UNICODE_NEWLINE_REGEX, ''), {});
}
public async render(input: SkinnyTextDocument | string): Promise<RenderOutput> {
const config = this.getConfig(typeof input === 'string' ? undefined : input.uri);
const engine = await this.getEngine(config);
const tokens = typeof input === 'string'
? this.tokenizeString(input, engine)
: this.tokenizeDocument(input, config, engine);
const env: RenderEnv = {
containingImages: []
};
const html = engine.renderer.render(tokens, {
...(engine as any).options,
...config
}, env);
return {
html,
containingImages: env.containingImages
};
}
public async parse(document: SkinnyTextDocument): Promise<Token[]> {
const config = this.getConfig(document.uri);
const engine = await this.getEngine(config);
return this.tokenizeDocument(document, config, engine);
}
public cleanCache(): void {
this._tokenCache.clean();
}
private getConfig(resource?: vscode.Uri): MarkdownItConfig {
const config = vscode.workspace.getConfiguration('markdown', resource);
return {
breaks: config.get<boolean>('preview.breaks', false),
linkify: config.get<boolean>('preview.linkify', true)
};
}
private addLineNumberRenderer(md: any, ruleName: string): void {
const original = md.renderer.rules[ruleName];
md.renderer.rules[ruleName] = (tokens: any, idx: number, options: any, env: any, self: any) => {
const token = tokens[idx];
if (token.map && token.map.length) {
token.attrSet('data-line', token.map[0]);
token.attrJoin('class', 'code-line');
}
if (original) {
return original(tokens, idx, options, env, self);
} else {
return self.renderToken(tokens, idx, options, env, self);
}
};
}
private addImageStabilizer(md: any): void {
const original = md.renderer.rules.image;
md.renderer.rules.image = (tokens: any, idx: number, options: any, env: RenderEnv, self: any) => {
const token = tokens[idx];
token.attrJoin('class', 'loading');
const src = token.attrGet('src');
if (src) {
env.containingImages?.push({ src });
const imgHash = hash(src);
token.attrSet('id', `image-hash-${imgHash}`);
}
if (original) {
return original(tokens, idx, options, env, self);
} else {
return self.renderToken(tokens, idx, options, env, self);
}
};
}
private addFencedRenderer(md: any): void {
const original = md.renderer.rules['fenced'];
md.renderer.rules['fenced'] = (tokens: any, idx: number, options: any, env: any, self: any) => {
const token = tokens[idx];
if (token.map && token.map.length) {
token.attrJoin('class', 'hljs');
}
return original(tokens, idx, options, env, self);
};
}
private addLinkNormalizer(md: any): void {
const normalizeLink = md.normalizeLink;
md.normalizeLink = (link: string) => {
try {
// Normalize VS Code schemes to target the current version
if (isOfScheme(Schemes.vscode, link) || isOfScheme(Schemes['vscode-insiders'], link)) {
return normalizeLink(vscode.Uri.parse(link).with({ scheme: vscode.env.uriScheme }).toString());
}
// Support file:// links
if (isOfScheme(Schemes.file, link)) {
// Ensure link is relative by prepending `/` so that it uses the <base> element URI
// when resolving the absolute URL
return normalizeLink('/' + link.replace(/^file:/, 'file'));
}
// If original link doesn't look like a url with a scheme, assume it must be a link to a file in workspace
if (!/^[a-z\-]+:/i.test(link)) {
// Use a fake scheme for parsing
let uri = vscode.Uri.parse('markdown-link:' + link);
// Relative paths should be resolved correctly inside the preview but we need to
// handle absolute paths specially (for images) to resolve them relative to the workspace root
if (uri.path[0] === '/') {
const root = vscode.workspace.getWorkspaceFolder(this.currentDocument!);
if (root) {
const fileUri = vscode.Uri.joinPath(root.uri, uri.fsPath).with({
fragment: uri.fragment,
query: uri.query,
});
// Ensure fileUri is relative by prepending `/` so that it uses the <base> element URI
// when resolving the absolute URL
uri = vscode.Uri.parse('markdown-link:' + '/' + fileUri.toString(true).replace(/^\S+?:/, fileUri.scheme));
}
}
const extname = path.extname(uri.fsPath);
if (uri.fragment && (extname === '' || MarkdownFileExtensions.includes(extname))) {
uri = uri.with({
fragment: this.slugifier.fromHeading(uri.fragment).value
});
}
return normalizeLink(uri.toString(true).replace(/^markdown-link:/, ''));
}
} catch (e) {
// noop
}
return normalizeLink(link);
};
}
private addLinkValidator(md: any): void {
const validateLink = md.validateLink;
md.validateLink = (link: string) => {
return validateLink(link)
|| isOfScheme(Schemes.vscode, link)
|| isOfScheme(Schemes['vscode-insiders'], link)
|| /^data:image\/.*?;/.test(link);
};
}
private addNamedHeaders(md: any): void {
const original = md.renderer.rules.heading_open;
md.renderer.rules.heading_open = (tokens: any, idx: number, options: any, env: any, self: any) => {
const title = tokens[idx + 1].children.reduce((acc: string, t: any) => acc + t.content, '');
let slug = this.slugifier.fromHeading(title);
if (this._slugCount.has(slug.value)) {
const count = this._slugCount.get(slug.value)!;
this._slugCount.set(slug.value, count + 1);
slug = this.slugifier.fromHeading(slug.value + '-' + (count + 1));
} else {
this._slugCount.set(slug.value, 0);
}
tokens[idx].attrs = tokens[idx].attrs || [];
tokens[idx].attrs.push(['id', slug.value]);
if (original) {
return original(tokens, idx, options, env, self);
} else {
return self.renderToken(tokens, idx, options, env, self);
}
};
}
private addLinkRenderer(md: any): void {
const old_render = md.renderer.rules.link_open || ((tokens: any, idx: number, options: any, _env: any, self: any) => {
return self.renderToken(tokens, idx, options);
});
md.renderer.rules.link_open = (tokens: any, idx: number, options: any, env: any, self: any) => {
const token = tokens[idx];
const hrefIndex = token.attrIndex('href');
if (hrefIndex >= 0) {
const href = token.attrs[hrefIndex][1];
token.attrPush(['data-href', href]);
}
return old_render(tokens, idx, options, env, self);
};
}
}
async function getMarkdownOptions(md: () => MarkdownIt) {
const hljs = await import('highlight.js');
return {
html: true,
highlight: (str: string, lang?: string) => {
lang = normalizeHighlightLang(lang);
if (lang && hljs.getLanguage(lang)) {
try {
return `<div>${hljs.highlight(lang, str, true).value}</div>`;
}
catch (error) { }
}
return `<code><div>${md().utils.escapeHtml(str)}</div></code>`;
}
};
}
function normalizeHighlightLang(lang: string | undefined) {
switch (lang && lang.toLowerCase()) {
case 'tsx':
case 'typescriptreact':
// Workaround for highlight not supporting tsx: https://github.com/isagalaev/highlight.js/issues/1155
return 'jsx';
case 'json5':
case 'jsonc':
return 'json';
case 'c#':
case 'csharp':
return 'cs';
default:
return lang;
}
}
| extensions/markdown-language-features/src/markdownEngine.ts | 0 | https://github.com/microsoft/vscode/commit/6480a6f20ea86b23b1c8d92c7ef37b20fcad18ec | [
0.00017862996901385486,
0.00017432529421057552,
0.00016890330880414695,
0.00017489635501988232,
0.000002373496045038337
] |
{
"id": 1,
"code_window": [
"\t\tconst onInputFontFamilyChanged = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.inputFontFamily'));\n",
"\t\tthis._register(onInputFontFamilyChanged(() => this.inputEditor.updateOptions({ fontFamily: this.getInputEditorFontFamily() })));\n",
"\n",
"\t\tthis.onDidChangeContentHeight = Event.signal(Event.filter(this.inputEditor.onDidContentSizeChange, e => e.contentHeightChanged));\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst onInputFontSizeChanged = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.inputFontSize'));\n",
"\t\tthis._register(onInputFontSizeChanged(() => this.inputEditor.updateOptions({ fontSize: this.getInputEditorFontSize() })));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "add",
"edit_start_line_idx": 1000
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./codicon/codicon';
import 'vs/css!./codicon/codicon-modifiers';
import { Codicon } from 'vs/base/common/codicons';
export function formatRule(c: Codicon) {
let def = c.definition;
while (def instanceof Codicon) {
def = def.definition;
}
return `.codicon-${c.id}:before { content: '${def.fontCharacter}'; }`;
}
| src/vs/base/browser/ui/codicons/codiconStyles.ts | 0 | https://github.com/microsoft/vscode/commit/6480a6f20ea86b23b1c8d92c7ef37b20fcad18ec | [
0.00017851147276815027,
0.00017245937488041818,
0.0001664072769926861,
0.00017245937488041818,
0.0000060520978877320886
] |
{
"id": 2,
"code_window": [
"\t\treturn this.defaultInputFontFamily;\n",
"\t}\n",
"\n",
"\tclearValidation(): void {\n",
"\t\tthis.validationDisposable.dispose();\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate getInputEditorFontSize(): number {\n",
"\t\treturn this.configurationService.getValue<number>('scm.inputFontSize');\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "add",
"edit_start_line_idx": 1082
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { Registry } from 'vs/platform/registry/common/platform';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { DirtyDiffWorkbenchController } from './dirtydiffDecorator';
import { VIEWLET_ID, ISCMRepository, ISCMService, VIEW_PANE_ID, ISCMProvider, ISCMViewService, REPOSITORIES_VIEW_PANE_ID } from 'vs/workbench/contrib/scm/common/scm';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { SCMStatusController } from './activity';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
import { IContextKeyService, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { SCMService } from 'vs/workbench/contrib/scm/common/scmService';
import { IViewContainersRegistry, ViewContainerLocation, Extensions as ViewContainerExtensions, IViewsRegistry } from 'vs/workbench/common/views';
import { SCMViewPaneContainer } from 'vs/workbench/contrib/scm/browser/scmViewPaneContainer';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ModesRegistry } from 'vs/editor/common/modes/modesRegistry';
import { Codicon } from 'vs/base/common/codicons';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import { SCMViewPane } from 'vs/workbench/contrib/scm/browser/scmViewPane';
import { SCMViewService } from 'vs/workbench/contrib/scm/browser/scmViewService';
import { SCMRepositoriesViewPane } from 'vs/workbench/contrib/scm/browser/scmRepositoriesViewPane';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { Context as SuggestContext } from 'vs/editor/contrib/suggest/suggest';
ModesRegistry.registerLanguage({
id: 'scminput',
extensions: [],
mimetypes: ['text/x-scm-input']
});
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench)
.registerWorkbenchContribution(DirtyDiffWorkbenchController, LifecyclePhase.Restored);
const sourceControlViewIcon = registerIcon('source-control-view-icon', Codicon.sourceControl, localize('sourceControlViewIcon', 'View icon of the Source Control view.'));
const viewContainer = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).registerViewContainer({
id: VIEWLET_ID,
title: localize('source control', "Source Control"),
ctorDescriptor: new SyncDescriptor(SCMViewPaneContainer),
storageId: 'workbench.scm.views.state',
icon: sourceControlViewIcon,
alwaysUseContainerInfo: true,
order: 2,
hideIfEmpty: true,
}, ViewContainerLocation.Sidebar, { donotRegisterOpenCommand: true });
const viewsRegistry = Registry.as<IViewsRegistry>(ViewContainerExtensions.ViewsRegistry);
viewsRegistry.registerViewWelcomeContent(VIEW_PANE_ID, {
content: localize('no open repo', "No source control providers registered."),
when: 'default'
});
viewsRegistry.registerViews([{
id: VIEW_PANE_ID,
name: localize('source control', "Source Control"),
ctorDescriptor: new SyncDescriptor(SCMViewPane),
canToggleVisibility: true,
workspace: true,
canMoveView: true,
weight: 80,
order: -999,
containerIcon: sourceControlViewIcon,
openCommandActionDescriptor: {
id: viewContainer.id,
mnemonicTitle: localize({ key: 'miViewSCM', comment: ['&& denotes a mnemonic'] }, "S&&CM"),
keybindings: {
primary: 0,
win: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G },
linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G },
mac: { primary: KeyMod.WinCtrl | KeyMod.Shift | KeyCode.KEY_G },
},
order: 2,
}
}], viewContainer);
viewsRegistry.registerViews([{
id: REPOSITORIES_VIEW_PANE_ID,
name: localize('source control repositories', "Source Control Repositories"),
ctorDescriptor: new SyncDescriptor(SCMRepositoriesViewPane),
canToggleVisibility: true,
hideByDefault: true,
workspace: true,
canMoveView: true,
weight: 20,
order: -1000,
when: ContextKeyExpr.and(ContextKeyExpr.has('scm.providerCount'), ContextKeyExpr.notEquals('scm.providerCount', 0)),
// readonly when = ContextKeyExpr.or(ContextKeyExpr.equals('config.scm.alwaysShowProviders', true), ContextKeyExpr.and(ContextKeyExpr.notEquals('scm.providerCount', 0), ContextKeyExpr.notEquals('scm.providerCount', 1)));
containerIcon: sourceControlViewIcon
}], viewContainer);
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench)
.registerWorkbenchContribution(SCMStatusController, LifecyclePhase.Restored);
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({
id: 'scm',
order: 5,
title: localize('scmConfigurationTitle', "SCM"),
type: 'object',
scope: ConfigurationScope.RESOURCE,
properties: {
'scm.diffDecorations': {
type: 'string',
enum: ['all', 'gutter', 'overview', 'minimap', 'none'],
enumDescriptions: [
localize('scm.diffDecorations.all', "Show the diff decorations in all available locations."),
localize('scm.diffDecorations.gutter', "Show the diff decorations only in the editor gutter."),
localize('scm.diffDecorations.overviewRuler', "Show the diff decorations only in the overview ruler."),
localize('scm.diffDecorations.minimap', "Show the diff decorations only in the minimap."),
localize('scm.diffDecorations.none', "Do not show the diff decorations.")
],
default: 'all',
description: localize('diffDecorations', "Controls diff decorations in the editor.")
},
'scm.diffDecorationsGutterWidth': {
type: 'number',
enum: [1, 2, 3, 4, 5],
default: 3,
description: localize('diffGutterWidth', "Controls the width(px) of diff decorations in gutter (added & modified).")
},
'scm.diffDecorationsGutterVisibility': {
type: 'string',
enum: ['always', 'hover'],
enumDescriptions: [
localize('scm.diffDecorationsGutterVisibility.always', "Show the diff decorator in the gutter at all times."),
localize('scm.diffDecorationsGutterVisibility.hover', "Show the diff decorator in the gutter only on hover.")
],
description: localize('scm.diffDecorationsGutterVisibility', "Controls the visibility of the Source Control diff decorator in the gutter."),
default: 'always'
},
'scm.diffDecorationsGutterAction': {
type: 'string',
enum: ['diff', 'none'],
enumDescriptions: [
localize('scm.diffDecorationsGutterAction.diff', "Show the inline diff peek view on click."),
localize('scm.diffDecorationsGutterAction.none', "Do nothing.")
],
description: localize('scm.diffDecorationsGutterAction', "Controls the behavior of Source Control diff gutter decorations."),
default: 'diff'
},
'scm.alwaysShowActions': {
type: 'boolean',
description: localize('alwaysShowActions', "Controls whether inline actions are always visible in the Source Control view."),
default: false
},
'scm.countBadge': {
type: 'string',
enum: ['all', 'focused', 'off'],
enumDescriptions: [
localize('scm.countBadge.all', "Show the sum of all Source Control Provider count badges."),
localize('scm.countBadge.focused', "Show the count badge of the focused Source Control Provider."),
localize('scm.countBadge.off', "Disable the Source Control count badge.")
],
description: localize('scm.countBadge', "Controls the count badge on the Source Control icon on the Activity Bar."),
default: 'all'
},
'scm.providerCountBadge': {
type: 'string',
enum: ['hidden', 'auto', 'visible'],
enumDescriptions: [
localize('scm.providerCountBadge.hidden', "Hide Source Control Provider count badges."),
localize('scm.providerCountBadge.auto', "Only show count badge for Source Control Provider when non-zero."),
localize('scm.providerCountBadge.visible', "Show Source Control Provider count badges.")
],
description: localize('scm.providerCountBadge', "Controls the count badges on Source Control Provider headers. These headers only appear when there is more than one provider."),
default: 'hidden'
},
'scm.defaultViewMode': {
type: 'string',
enum: ['tree', 'list'],
enumDescriptions: [
localize('scm.defaultViewMode.tree', "Show the repository changes as a tree."),
localize('scm.defaultViewMode.list', "Show the repository changes as a list.")
],
description: localize('scm.defaultViewMode', "Controls the default Source Control repository view mode."),
default: 'list'
},
'scm.autoReveal': {
type: 'boolean',
description: localize('autoReveal', "Controls whether the SCM view should automatically reveal and select files when opening them."),
default: true
},
'scm.inputFontFamily': {
type: 'string',
markdownDescription: localize('inputFontFamily', "Controls the font for the input message. Use `default` for the workbench user interface font family, `editor` for the `#editor.fontFamily#`'s value, or a custom font family."),
default: 'default'
},
'scm.alwaysShowRepositories': {
type: 'boolean',
markdownDescription: localize('alwaysShowRepository', "Controls whether repositories should always be visible in the SCM view."),
default: false
},
'scm.repositories.visible': {
type: 'number',
description: localize('providersVisible', "Controls how many repositories are visible in the Source Control Repositories section. Set to `0` to be able to manually resize the view."),
default: 10
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'scm.acceptInput',
description: { description: localize('scm accept', "SCM: Accept Input"), args: [] },
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.has('scmRepository'),
primary: KeyMod.CtrlCmd | KeyCode.Enter,
handler: accessor => {
const contextKeyService = accessor.get(IContextKeyService);
const context = contextKeyService.getContext(document.activeElement);
const repository = context.getValue<ISCMRepository>('scmRepository');
if (!repository || !repository.provider.acceptInputCommand) {
return Promise.resolve(null);
}
const id = repository.provider.acceptInputCommand.id;
const args = repository.provider.acceptInputCommand.arguments;
const commandService = accessor.get(ICommandService);
return commandService.executeCommand(id, ...(args || []));
}
});
const viewNextCommitCommand = {
description: { description: localize('scm view next commit', "SCM: View Next Commit"), args: [] },
weight: KeybindingWeight.WorkbenchContrib,
handler: (accessor: ServicesAccessor) => {
const contextKeyService = accessor.get(IContextKeyService);
const context = contextKeyService.getContext(document.activeElement);
const repository = context.getValue<ISCMRepository>('scmRepository');
repository?.input.showNextHistoryValue();
}
};
const viewPreviousCommitCommand = {
description: { description: localize('scm view previous commit', "SCM: View Previous Commit"), args: [] },
weight: KeybindingWeight.WorkbenchContrib,
handler: (accessor: ServicesAccessor) => {
const contextKeyService = accessor.get(IContextKeyService);
const context = contextKeyService.getContext(document.activeElement);
const repository = context.getValue<ISCMRepository>('scmRepository');
repository?.input.showPreviousHistoryValue();
}
};
KeybindingsRegistry.registerCommandAndKeybindingRule({
...viewNextCommitCommand,
id: 'scm.viewNextCommit',
when: ContextKeyExpr.and(ContextKeyExpr.has('scmRepository'), ContextKeyExpr.has('scmInputIsInLastPosition'), SuggestContext.Visible.toNegated()),
primary: KeyCode.DownArrow
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
...viewPreviousCommitCommand,
id: 'scm.viewPreviousCommit',
when: ContextKeyExpr.and(ContextKeyExpr.has('scmRepository'), ContextKeyExpr.has('scmInputIsInFirstPosition'), SuggestContext.Visible.toNegated()),
primary: KeyCode.UpArrow
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
...viewNextCommitCommand,
id: 'scm.forceViewNextCommit',
when: ContextKeyExpr.has('scmRepository'),
primary: KeyMod.Alt | KeyCode.DownArrow
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
...viewPreviousCommitCommand,
id: 'scm.forceViewPreviousCommit',
when: ContextKeyExpr.has('scmRepository'),
primary: KeyMod.Alt | KeyCode.UpArrow
});
CommandsRegistry.registerCommand('scm.openInTerminal', async (accessor, provider: ISCMProvider) => {
if (!provider || !provider.rootUri) {
return;
}
const commandService = accessor.get(ICommandService);
await commandService.executeCommand('openInTerminal', provider.rootUri);
});
MenuRegistry.appendMenuItem(MenuId.SCMSourceControl, {
group: '100_end',
command: {
id: 'scm.openInTerminal',
title: localize('open in terminal', "Open In Terminal")
},
when: ContextKeyExpr.equals('scmProviderHasRootUri', true)
});
registerSingleton(ISCMService, SCMService);
registerSingleton(ISCMViewService, SCMViewService);
| src/vs/workbench/contrib/scm/browser/scm.contribution.ts | 1 | https://github.com/microsoft/vscode/commit/6480a6f20ea86b23b1c8d92c7ef37b20fcad18ec | [
0.0007461878121830523,
0.00018885833560489118,
0.00016424981004092842,
0.0001706222101347521,
0.0001017903268802911
] |
{
"id": 2,
"code_window": [
"\t\treturn this.defaultInputFontFamily;\n",
"\t}\n",
"\n",
"\tclearValidation(): void {\n",
"\t\tthis.validationDisposable.dispose();\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate getInputEditorFontSize(): number {\n",
"\t\treturn this.configurationService.getValue<number>('scm.inputFontSize');\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "add",
"edit_start_line_idx": 1082
} | {
"registrations": [
{
"component": {
"type": "git",
"git": {
"name": "vscode-logfile-highlighter",
"repositoryUrl": "https://github.com/emilast/vscode-logfile-highlighter",
"commitHash": "19807c6a80d29b03ad69e02ffe39e5869a9ce107"
}
},
"license": "MIT",
"version": "2.11.0"
}
],
"version": 1
} | extensions/log/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/6480a6f20ea86b23b1c8d92c7ef37b20fcad18ec | [
0.0001746820198604837,
0.00017290213145315647,
0.00017112224304582924,
0.00017290213145315647,
0.0000017798884073272347
] |
{
"id": 2,
"code_window": [
"\t\treturn this.defaultInputFontFamily;\n",
"\t}\n",
"\n",
"\tclearValidation(): void {\n",
"\t\tthis.validationDisposable.dispose();\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate getInputEditorFontSize(): number {\n",
"\t\treturn this.configurationService.getValue<number>('scm.inputFontSize');\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "add",
"edit_start_line_idx": 1082
} | {
"information_for_contributors": [
"This file has been converted from https://github.com/demyte/language-cshtml/blob/master/grammars/cshtml.json",
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/demyte/language-cshtml/commit/e6e54d5a86a28cc1e44609a32aaa10a244cd3f81",
"name": "ASP.NET Razor",
"scopeName": "text.html.cshtml",
"patterns": [
{
"include": "#razor-directives"
},
{
"include": "#razor-code-block"
},
{
"include": "#razor-else-if"
},
{
"include": "#razor-if"
},
{
"include": "#razor-else"
},
{
"include": "#razor-foreach"
},
{
"include": "#explicit-razor-expression"
},
{
"include": "#implicit-razor-expression"
},
{
"include": "text.html.basic"
}
],
"repository": {
"comments": {
"begin": "@\\*",
"captures": {
"0": {
"name": "punctuation.definition.comment.source.cshtml"
}
},
"end": "\\*@",
"name": "comment.block.cshtml"
},
"razor-directives": {
"name": "meta.directive.cshtml",
"patterns": [
{
"include": "#using-directive"
},
{
"include": "#model-directive"
},
{
"include": "#inherits-directive"
},
{
"include": "#inject-directive"
},
{
"include": "#implements-directive"
},
{
"include": "#layout-directive"
},
{
"include": "#page-directive"
},
{
"include": "#functions-directive"
}
]
},
"explicit-razor-expression": {
"name": "meta.expression.explicit.cshtml",
"begin": "(@)\\(",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "source.cs"
}
],
"end": "\\)"
},
"implicit-razor-expression": {
"name": "meta.expression.implicit.cshtml",
"begin": "(@)([a-zA-Z0-9\\.\\_\\(\\)]+)",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"end": "$"
},
"using-directive": {
"name": "meta.directive.using.cshtml",
"begin": "(@using)\\s+",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "#csharp-namespace-identifier"
}
],
"end": "$"
},
"model-directive": {
"name": "meta.directive.model.cshtml",
"begin": "(@model)\\s+",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "#csharp-type-name"
}
],
"end": "$"
},
"inherits-directive": {
"name": "meta.directive.inherits.cshtml",
"begin": "(@inherits)\\s+",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "#csharp-type-name"
}
],
"end": "$"
},
"inject-directive": {
"name": "meta.directive.inject.cshtml",
"begin": "(@inject)\\s+",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "#csharp-type-name"
}
],
"end": "$"
},
"implements-directive": {
"name": "meta.directive.implements.cshtml",
"begin": "(@implements)\\s+",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "#csharp-type-name"
}
],
"end": "$"
},
"layout-directive": {
"name": "meta.directive.layout.cshtml",
"begin": "(@layout)\\s+",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "#csharp-type-name"
}
],
"end": "$"
},
"page-directive": {
"name": "meta.directive.page.cshtml",
"begin": "(@page)\\s+",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "source.cs"
}
],
"end": "$"
},
"functions-directive": {
"name": "meta.directive.functions.cshtml",
"match": "(@functions)",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
}
},
"razor-if": {
"begin": "(@if)",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "source.cs"
}
],
"end": "$"
},
"razor-else": {
"begin": "(else)",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "source.cs"
}
],
"end": "$"
},
"razor-else-if": {
"begin": "(else\\s+if)",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "source.cs"
}
],
"end": "$"
},
"razor-foreach": {
"begin": "(@foreach)\\s+\\(",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "source.cs"
}
],
"end": "\\)"
},
"razor-code-block": {
"begin": "@?\\{",
"captures": {
"0": {
"name": "keyword.control.cshtml"
}
},
"patterns": [
{
"include": "text.html.cshtml"
},
{
"include": "source.cs"
}
],
"end": "\\}"
},
"csharp-namespace-identifier": {
"patterns": [
{
"name": "entity.name.type.namespace.cs",
"match": "[_[:alpha:]][_[:alnum:]]*"
}
]
},
"csharp-type-name": {
"patterns": [
{
"match": "([_[:alpha:]][_[:alnum:]]*)\\s*(\\:\\:)",
"captures": {
"1": {
"name": "entity.name.type.alias.cs"
},
"2": {
"name": "punctuation.separator.coloncolon.cs"
}
}
},
{
"match": "([_[:alpha:]][_[:alnum:]]*)\\s*(\\.)",
"captures": {
"1": {
"name": "storage.type.cs"
},
"2": {
"name": "punctuation.accessor.cs"
}
}
},
{
"match": "(\\.)\\s*([_[:alpha:]][_[:alnum:]]*)",
"captures": {
"1": {
"name": "punctuation.accessor.cs"
},
"2": {
"name": "storage.type.cs"
}
}
},
{
"name": "storage.type.cs",
"match": "[_[:alpha:]][_[:alnum:]]*"
}
]
}
}
} | extensions/razor/syntaxes/cshtml.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/6480a6f20ea86b23b1c8d92c7ef37b20fcad18ec | [
0.00017922626284416765,
0.0001712425146251917,
0.0001686334580881521,
0.00017120857955887914,
0.0000017942348904398386
] |
{
"id": 2,
"code_window": [
"\t\treturn this.defaultInputFontFamily;\n",
"\t}\n",
"\n",
"\tclearValidation(): void {\n",
"\t\tthis.validationDisposable.dispose();\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate getInputEditorFontSize(): number {\n",
"\t\treturn this.configurationService.getValue<number>('scm.inputFontSize');\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "add",
"edit_start_line_idx": 1082
} | {
"information_for_contributors": [
"This file has been converted from https://github.com/textmate/lua.tmbundle/blob/master/Syntaxes/Lua.plist",
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/textmate/lua.tmbundle/commit/8ae5641365b28f697121ba1133890e8d81f5b00e",
"name": "Lua",
"scopeName": "source.lua",
"patterns": [
{
"begin": "\\b(?:(local)\\s+)?(function)\\s*(?:\\s+([a-zA-Z_][a-zA-Z0-9_]*(?:([\\.:])[a-zA-Z_][a-zA-Z0-9_]*)?)\\s*)?(\\()",
"beginCaptures": {
"1": {
"name": "storage.modifier.local.lua"
},
"2": {
"name": "keyword.control.lua"
},
"3": {
"name": "entity.name.function.lua"
},
"4": {
"name": "punctuation.separator.parameter.lua"
},
"5": {
"name": "punctuation.definition.parameters.begin.lua"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "punctuation.definition.parameters.end.lua"
}
},
"name": "meta.function.lua",
"patterns": [
{
"match": "[a-zA-Z_][a-zA-Z0-9_]*",
"name": "variable.parameter.function.lua"
},
{
"match": ",",
"name": "punctuation.separator.arguments.lua"
}
]
},
{
"match": "(?<![\\w\\d.])0[xX][0-9A-Fa-f]+(?![pPeE.0-9])",
"name": "constant.numeric.integer.hexadecimal.lua"
},
{
"match": "(?<![\\w\\d.])0[xX][0-9A-Fa-f]+(\\.[0-9A-Fa-f]+)?([eE]-?\\d*)?([pP][-+]\\d+)?",
"name": "constant.numeric.float.hexadecimal.lua"
},
{
"match": "(?<![\\w\\d.])\\d+(?![pPeE.0-9])",
"name": "constant.numeric.integer.lua"
},
{
"match": "(?<![\\w\\d.])\\d+(\\.\\d+)?([eE]-?\\d*)?",
"name": "constant.numeric.float.lua"
},
{
"begin": "'",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.lua"
}
},
"end": "'",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.lua"
}
},
"name": "string.quoted.single.lua",
"patterns": [
{
"include": "#escaped_char"
}
]
},
{
"begin": "\"",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.lua"
}
},
"end": "\"",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.lua"
}
},
"name": "string.quoted.double.lua",
"patterns": [
{
"include": "#escaped_char"
}
]
},
{
"begin": "(?<=\\.cdef)\\s*(\\[(=*)\\[)",
"beginCaptures": {
"0": {
"name": "string.quoted.other.multiline.lua"
},
"1": {
"name": "punctuation.definition.string.begin.lua"
}
},
"contentName": "meta.embedded.lua",
"end": "(\\]\\2\\])",
"endCaptures": {
"0": {
"name": "string.quoted.other.multiline.lua"
},
"1": {
"name": "punctuation.definition.string.end.lua"
}
},
"patterns": [
{
"include": "source.c"
}
]
},
{
"begin": "(?<!--)\\[(=*)\\[",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.lua"
}
},
"end": "\\]\\1\\]",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.lua"
}
},
"name": "string.quoted.other.multiline.lua"
},
{
"captures": {
"1": {
"name": "punctuation.definition.comment.lua"
}
},
"match": "\\A(#!).*$\\n?",
"name": "comment.line.shebang.lua"
},
{
"begin": "(^[ \\t]+)?(?=--)",
"beginCaptures": {
"1": {
"name": "punctuation.whitespace.comment.leading.lua"
}
},
"end": "(?!\\G)((?!^)[ \\t]+\\n)?",
"endCaptures": {
"1": {
"name": "punctuation.whitespace.comment.trailing.lua"
}
},
"patterns": [
{
"begin": "--\\[(=*)\\[",
"beginCaptures": {
"0": {
"name": "punctuation.definition.comment.begin.lua"
}
},
"end": "\\]\\1\\]",
"endCaptures": {
"0": {
"name": "punctuation.definition.comment.end.lua"
}
},
"name": "comment.block.lua"
},
{
"begin": "--",
"beginCaptures": {
"0": {
"name": "punctuation.definition.comment.lua"
}
},
"end": "\\n",
"name": "comment.line.double-dash.lua"
}
]
},
{
"captures": {
"1": {
"name": "keyword.control.goto.lua"
},
"2": {
"name": "constant.other.placeholder.lua"
}
},
"match": "\\b(goto)\\s+([a-zA-Z_][a-zA-Z0-9_]*)"
},
{
"captures": {
"1": {
"name": "punctuation.definition.label.begin.lua"
},
"2": {
"name": "punctuation.definition.label.end.lua"
}
},
"match": "(::)[a-zA-Z_][a-zA-Z0-9_]*(::)",
"name": "constant.other.placeholder.lua"
},
{
"match": "\\b(break|do|else|for|if|elseif|goto|return|then|repeat|while|until|end|function|local|in)\\b",
"name": "keyword.control.lua"
},
{
"match": "(?<![^.]\\.|:)\\b(false|nil|true|_G|_VERSION|math\\.(pi|huge))\\b|(?<![.])\\.{3}(?!\\.)",
"name": "constant.language.lua"
},
{
"match": "(?<![^.]\\.|:)\\b(self)\\b",
"name": "variable.language.self.lua"
},
{
"match": "(?<![^.]\\.|:)\\b(assert|collectgarbage|dofile|error|getfenv|getmetatable|ipairs|loadfile|loadstring|module|next|pairs|pcall|print|rawequal|rawget|rawset|require|select|setfenv|setmetatable|tonumber|tostring|type|unpack|xpcall)\\b(?=\\s*(?:[({\"']|\\[\\[))",
"name": "support.function.lua"
},
{
"match": "(?<![^.]\\.|:)\\b(coroutine\\.(create|resume|running|status|wrap|yield)|string\\.(byte|char|dump|find|format|gmatch|gsub|len|lower|match|rep|reverse|sub|upper)|table\\.(concat|insert|maxn|remove|sort)|math\\.(abs|acos|asin|atan2?|ceil|cosh?|deg|exp|floor|fmod|frexp|ldexp|log|log10|max|min|modf|pow|rad|random|randomseed|sinh?|sqrt|tanh?)|io\\.(close|flush|input|lines|open|output|popen|read|tmpfile|type|write)|os\\.(clock|date|difftime|execute|exit|getenv|remove|rename|setlocale|time|tmpname)|package\\.(cpath|loaded|loadlib|path|preload|seeall)|debug\\.(debug|[gs]etfenv|[gs]ethook|getinfo|[gs]etlocal|[gs]etmetatable|getregistry|[gs]etupvalue|traceback))\\b(?=\\s*(?:[({\"']|\\[\\[))",
"name": "support.function.library.lua"
},
{
"match": "\\b(and|or|not)\\b",
"name": "keyword.operator.lua"
},
{
"match": "\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b(?=\\s*(?:[({\"']|\\[\\[))",
"name": "support.function.any-method.lua"
},
{
"match": "(?<=[^.]\\.|:)\\b([a-zA-Z_][a-zA-Z0-9_]*)",
"name": "variable.other.lua"
},
{
"match": "\\+|-|%|#|\\*|\\/|\\^|==?|~=|<=?|>=?|(?<!\\.)\\.{2}(?!\\.)",
"name": "keyword.operator.lua"
}
],
"repository": {
"escaped_char": {
"patterns": [
{
"match": "\\\\[abfnrtvz\\\\\"'\\n]",
"name": "constant.character.escape.lua"
},
{
"match": "\\\\\\d{1,3}",
"name": "constant.character.escape.byte.lua"
},
{
"match": "\\\\x[0-9A-Fa-f][0-9A-Fa-f]",
"name": "constant.character.escape.byte.lua"
},
{
"match": "\\\\u\\{[0-9A-Fa-f]+\\}",
"name": "constant.character.escape.unicode.lua"
},
{
"match": "\\\\.",
"name": "invalid.illegal.character.escape.lua"
}
]
}
}
} | extensions/lua/syntaxes/lua.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/6480a6f20ea86b23b1c8d92c7ef37b20fcad18ec | [
0.00020302587654441595,
0.0001719564461382106,
0.00016794762632343918,
0.00017016306810546666,
0.000006262192073336337
] |
{
"id": 0,
"code_window": [
" // in order to access it statically. e.g.\n",
" // (1) queries used in the \"ngOnInit\" lifecycle hook are static.\n",
" // (2) inputs with setters can access queries statically.\n",
" return classDecl.members\n",
" .filter(m => {\n",
" if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&\n",
" STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" } else if (\n",
" knownInputNames && ts.isSetAccessor(m) && m.body && hasPropertyNameText(m.name) &&\n",
" knownInputNames.indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" }\n",
" return false;\n",
" })\n",
" .map((member: ts.SetAccessorDeclaration | ts.MethodDeclaration) => member.body !);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" .filter(\n",
" (m):\n",
" m is(ts.SetAccessorDeclaration | ts.MethodDeclaration) => {\n",
" if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&\n",
" STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" } else if (\n",
" knownInputNames && ts.isSetAccessor(m) && m.body &&\n",
" hasPropertyNameText(m.name) && knownInputNames.indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" }\n",
" return false;\n",
" })\n",
" .map(member => member.body !);\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts",
"type": "replace",
"edit_start_line_idx": 168
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {parseHtmlGracefully} from '../../../../utils/parse_html';
import {hasPropertyNameText} from '../../../../utils/typescript/property_name';
import {ClassMetadataMap} from '../../angular/ng_query_visitor';
import {NgQueryDefinition, QueryTiming, QueryType} from '../../angular/query-definition';
import {TimingResult, TimingStrategy} from '../timing-strategy';
import {DeclarationUsageVisitor, FunctionContext, ResolvedUsage} from './declaration_usage_visitor';
import {updateSuperClassAbstractMembersContext} from './super_class_context';
import {TemplateUsageVisitor} from './template_usage_visitor';
/**
* Object that maps a given type of query to a list of lifecycle hooks that
* could be used to access such a query statically.
*/
const STATIC_QUERY_LIFECYCLE_HOOKS = {
[QueryType.ViewChild]:
['ngOnChanges', 'ngOnInit', 'ngDoCheck', 'ngAfterContentInit', 'ngAfterContentChecked'],
[QueryType.ContentChild]: ['ngOnChanges', 'ngOnInit', 'ngDoCheck'],
};
/**
* Query timing strategy that determines the timing of a given query by inspecting how
* the query is accessed within the project's TypeScript source files. Read more about
* this strategy here: https://hackmd.io/s/Hymvc2OKE
*/
export class QueryUsageStrategy implements TimingStrategy {
constructor(private classMetadata: ClassMetadataMap, private typeChecker: ts.TypeChecker) {}
setup() {}
/**
* Analyzes the usage of the given query and determines the query timing based
* on the current usage of the query.
*/
detectTiming(query: NgQueryDefinition): TimingResult {
if (query.property === null) {
return {timing: null, message: 'Queries defined on accessors cannot be analyzed.'};
}
const usage = this.analyzeQueryUsage(query.container, query, []);
if (usage === ResolvedUsage.AMBIGUOUS) {
return {
timing: QueryTiming.STATIC,
message: 'Query timing is ambiguous. Please check if the query can be marked as dynamic.'
};
} else if (usage === ResolvedUsage.SYNCHRONOUS) {
return {timing: QueryTiming.STATIC};
} else {
return {timing: QueryTiming.DYNAMIC};
}
}
/**
* Checks whether a given query is used statically within the given class, its super
* class or derived classes.
*/
private analyzeQueryUsage(
classDecl: ts.ClassDeclaration, query: NgQueryDefinition, knownInputNames: string[],
functionCtx: FunctionContext = new Map(), visitInheritedClasses = true): ResolvedUsage {
const usageVisitor =
new DeclarationUsageVisitor(query.property !, this.typeChecker, functionCtx);
const classMetadata = this.classMetadata.get(classDecl);
let usage: ResolvedUsage = ResolvedUsage.ASYNCHRONOUS;
// In case there is metadata for the current class, we collect all resolved Angular input
// names and add them to the list of known inputs that need to be checked for usages of
// the current query. e.g. queries used in an @Input() *setter* are always static.
if (classMetadata) {
knownInputNames.push(...classMetadata.ngInputNames);
}
// Array of TypeScript nodes which can contain usages of the given query in
// order to access it statically.
const possibleStaticQueryNodes = filterQueryClassMemberNodes(classDecl, query, knownInputNames);
// In case nodes that can possibly access a query statically have been found, check
// if the query declaration is synchronously used within any of these nodes.
if (possibleStaticQueryNodes.length) {
possibleStaticQueryNodes.forEach(
n => usage = combineResolvedUsage(usage, usageVisitor.getResolvedNodeUsage(n)));
}
if (!classMetadata) {
return usage;
}
// In case there is a component template for the current class, we check if the
// template statically accesses the current query. In case that's true, the query
// can be marked as static.
if (classMetadata.template && hasPropertyNameText(query.property !.name)) {
const template = classMetadata.template;
const parsedHtml = parseHtmlGracefully(template.content, template.filePath);
const htmlVisitor = new TemplateUsageVisitor(query.property !.name.text);
if (parsedHtml && htmlVisitor.isQueryUsedStatically(parsedHtml)) {
return ResolvedUsage.SYNCHRONOUS;
}
}
// In case derived classes should also be analyzed, we determine the classes that derive
// from the current class and check if these have input setters or lifecycle hooks that
// use the query statically.
if (visitInheritedClasses) {
classMetadata.derivedClasses.forEach(derivedClass => {
usage = combineResolvedUsage(
usage, this.analyzeQueryUsage(derivedClass, query, knownInputNames));
});
}
// In case the current class has a super class, we determine declared abstract function-like
// declarations in the super-class that are implemented in the current class. The super class
// will then be analyzed with the abstract declarations mapped to the implemented TypeScript
// nodes. This allows us to handle queries which are used in super classes through derived
// abstract method declarations.
if (classMetadata.superClass) {
const superClassDecl = classMetadata.superClass;
// Update the function context to map abstract declaration nodes to their implementation
// node in the base class. This ensures that the declaration usage visitor can analyze
// abstract class member declarations.
updateSuperClassAbstractMembersContext(classDecl, functionCtx, this.classMetadata);
usage = combineResolvedUsage(
usage, this.analyzeQueryUsage(superClassDecl, query, [], functionCtx, false));
}
return usage;
}
}
/**
* Combines two resolved usages based on a fixed priority. "Synchronous" takes
* precedence over "Ambiguous" whereas ambiguous takes precedence over "Asynchronous".
*/
function combineResolvedUsage(base: ResolvedUsage, target: ResolvedUsage): ResolvedUsage {
if (base === ResolvedUsage.SYNCHRONOUS) {
return base;
} else if (target !== ResolvedUsage.ASYNCHRONOUS) {
return target;
} else {
return ResolvedUsage.ASYNCHRONOUS;
}
}
/**
* Filters all class members from the class declaration that can access the
* given query statically (e.g. ngOnInit lifecycle hook or @Input setters)
*/
function filterQueryClassMemberNodes(
classDecl: ts.ClassDeclaration, query: NgQueryDefinition,
knownInputNames: string[]): ts.Block[] {
// Returns an array of TypeScript nodes which can contain usages of the given query
// in order to access it statically. e.g.
// (1) queries used in the "ngOnInit" lifecycle hook are static.
// (2) inputs with setters can access queries statically.
return classDecl.members
.filter(m => {
if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&
STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {
return true;
} else if (
knownInputNames && ts.isSetAccessor(m) && m.body && hasPropertyNameText(m.name) &&
knownInputNames.indexOf(m.name.text) !== -1) {
return true;
}
return false;
})
.map((member: ts.SetAccessorDeclaration | ts.MethodDeclaration) => member.body !);
}
| packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts | 1 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.9969691634178162,
0.09825577586889267,
0.0001618677342776209,
0.00032486606505699456,
0.28288203477859497
] |
{
"id": 0,
"code_window": [
" // in order to access it statically. e.g.\n",
" // (1) queries used in the \"ngOnInit\" lifecycle hook are static.\n",
" // (2) inputs with setters can access queries statically.\n",
" return classDecl.members\n",
" .filter(m => {\n",
" if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&\n",
" STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" } else if (\n",
" knownInputNames && ts.isSetAccessor(m) && m.body && hasPropertyNameText(m.name) &&\n",
" knownInputNames.indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" }\n",
" return false;\n",
" })\n",
" .map((member: ts.SetAccessorDeclaration | ts.MethodDeclaration) => member.body !);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" .filter(\n",
" (m):\n",
" m is(ts.SetAccessorDeclaration | ts.MethodDeclaration) => {\n",
" if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&\n",
" STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" } else if (\n",
" knownInputNames && ts.isSetAccessor(m) && m.body &&\n",
" hasPropertyNameText(m.name) && knownInputNames.indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" }\n",
" return false;\n",
" })\n",
" .map(member => member.body !);\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts",
"type": "replace",
"edit_start_line_idx": 168
} | # `indexer`
The `indexer` module generates semantic analysis about components used in an
Angular project. The module is consumed by a semantic analysis API on an Angular
program, which can be invoked separately from the regular Angular compilation
pipeline.
The module is _not_ a fully-featured source code indexer. Rather, it is designed
to produce semantic information about an Angular project that can then be used
by language analysis tools to generate, for example, cross-references in Angular
templates.
The `indexer` module is developed primarily with the
[Kythe](https://github.com/kythe/kythe) ecosystem in mind as an indexing
service.
### Scope of Analysis
The scope of analysis performed by the module includes
- indexing template syntax identifiers in a component template
- generating information about directives used in a template
- generating metadata about component and template source files
The module does not support indexing TypeScript source code.
| packages/compiler-cli/src/ngtsc/indexer/README.md | 0 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.00016673367645125836,
0.00016417261213064194,
0.00016183473053388298,
0.0001639493857510388,
0.0000020062045678059803
] |
{
"id": 0,
"code_window": [
" // in order to access it statically. e.g.\n",
" // (1) queries used in the \"ngOnInit\" lifecycle hook are static.\n",
" // (2) inputs with setters can access queries statically.\n",
" return classDecl.members\n",
" .filter(m => {\n",
" if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&\n",
" STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" } else if (\n",
" knownInputNames && ts.isSetAccessor(m) && m.body && hasPropertyNameText(m.name) &&\n",
" knownInputNames.indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" }\n",
" return false;\n",
" })\n",
" .map((member: ts.SetAccessorDeclaration | ts.MethodDeclaration) => member.body !);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" .filter(\n",
" (m):\n",
" m is(ts.SetAccessorDeclaration | ts.MethodDeclaration) => {\n",
" if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&\n",
" STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" } else if (\n",
" knownInputNames && ts.isSetAccessor(m) && m.body &&\n",
" hasPropertyNameText(m.name) && knownInputNames.indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" }\n",
" return false;\n",
" })\n",
" .map(member => member.body !);\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts",
"type": "replace",
"edit_start_line_idx": 168
} | aio/content/examples/property-binding/example-config.json | 0 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.00016278793918900192,
0.00016278793918900192,
0.00016278793918900192,
0.00016278793918900192,
0
] |
|
{
"id": 0,
"code_window": [
" // in order to access it statically. e.g.\n",
" // (1) queries used in the \"ngOnInit\" lifecycle hook are static.\n",
" // (2) inputs with setters can access queries statically.\n",
" return classDecl.members\n",
" .filter(m => {\n",
" if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&\n",
" STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" } else if (\n",
" knownInputNames && ts.isSetAccessor(m) && m.body && hasPropertyNameText(m.name) &&\n",
" knownInputNames.indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" }\n",
" return false;\n",
" })\n",
" .map((member: ts.SetAccessorDeclaration | ts.MethodDeclaration) => member.body !);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" .filter(\n",
" (m):\n",
" m is(ts.SetAccessorDeclaration | ts.MethodDeclaration) => {\n",
" if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&\n",
" STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" } else if (\n",
" knownInputNames && ts.isSetAccessor(m) && m.body &&\n",
" hasPropertyNameText(m.name) && knownInputNames.indexOf(m.name.text) !== -1) {\n",
" return true;\n",
" }\n",
" return false;\n",
" })\n",
" .map(member => member.body !);\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts",
"type": "replace",
"edit_start_line_idx": 168
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
function plural(n: number): number {
if (n === 1) return 1;
return 5;
}
export default [
'lb', [['mo.', 'nomë.'], ['moies', 'nomëttes'], u], [['moies', 'nomëttes'], u, u],
[
['S', 'M', 'D', 'M', 'D', 'F', 'S'],
['Son.', 'Méi.', 'Dën.', 'Mët.', 'Don.', 'Fre.', 'Sam.'],
['Sonndeg', 'Méindeg', 'Dënschdeg', 'Mëttwoch', 'Donneschdeg', 'Freideg', 'Samschdeg'],
['So.', 'Mé.', 'Dë.', 'Më.', 'Do.', 'Fr.', 'Sa.']
],
[
['S', 'M', 'D', 'M', 'D', 'F', 'S'], ['Son', 'Méi', 'Dën', 'Mët', 'Don', 'Fre', 'Sam'],
['Sonndeg', 'Méindeg', 'Dënschdeg', 'Mëttwoch', 'Donneschdeg', 'Freideg', 'Samschdeg'],
['So.', 'Mé.', 'Dë.', 'Më.', 'Do.', 'Fr.', 'Sa.']
],
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'Jan.', 'Feb.', 'Mäe.', 'Abr.', 'Mee', 'Juni', 'Juli', 'Aug.', 'Sep.', 'Okt.', 'Nov.', 'Dez.'
],
[
'Januar', 'Februar', 'Mäerz', 'Abrëll', 'Mee', 'Juni', 'Juli', 'August', 'September',
'Oktober', 'November', 'Dezember'
]
],
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mäe', 'Abr', 'Mee', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
[
'Januar', 'Februar', 'Mäerz', 'Abrëll', 'Mee', 'Juni', 'Juli', 'August', 'September',
'Oktober', 'November', 'Dezember'
]
],
[['v. Chr.', 'n. Chr.'], u, u], 1, [6, 0],
['dd.MM.yy', 'd. MMM y', 'd. MMMM y', 'EEEE, d. MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u],
[',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], '€', 'Euro',
{'ATS': ['öS'], 'AUD': ['AU$', '$'], 'THB': ['฿'], 'TWD': ['NT$']}, plural
];
| packages/common/locales/lb.ts | 0 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.00017389097774866968,
0.0001719661959214136,
0.00017059716628864408,
0.00017148390179499984,
0.0000013009344002057333
] |
{
"id": 1,
"code_window": [
"{\n",
" \"compilerOptions\": {\n",
" \"noImplicitReturns\": true,\n",
" \"noImplicitAny\": true,\n",
" \"noFallthroughCasesInSwitch\": true,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/core/schematics/tsconfig.json",
"type": "replace",
"edit_start_line_idx": 3
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {parseHtmlGracefully} from '../../../../utils/parse_html';
import {hasPropertyNameText} from '../../../../utils/typescript/property_name';
import {ClassMetadataMap} from '../../angular/ng_query_visitor';
import {NgQueryDefinition, QueryTiming, QueryType} from '../../angular/query-definition';
import {TimingResult, TimingStrategy} from '../timing-strategy';
import {DeclarationUsageVisitor, FunctionContext, ResolvedUsage} from './declaration_usage_visitor';
import {updateSuperClassAbstractMembersContext} from './super_class_context';
import {TemplateUsageVisitor} from './template_usage_visitor';
/**
* Object that maps a given type of query to a list of lifecycle hooks that
* could be used to access such a query statically.
*/
const STATIC_QUERY_LIFECYCLE_HOOKS = {
[QueryType.ViewChild]:
['ngOnChanges', 'ngOnInit', 'ngDoCheck', 'ngAfterContentInit', 'ngAfterContentChecked'],
[QueryType.ContentChild]: ['ngOnChanges', 'ngOnInit', 'ngDoCheck'],
};
/**
* Query timing strategy that determines the timing of a given query by inspecting how
* the query is accessed within the project's TypeScript source files. Read more about
* this strategy here: https://hackmd.io/s/Hymvc2OKE
*/
export class QueryUsageStrategy implements TimingStrategy {
constructor(private classMetadata: ClassMetadataMap, private typeChecker: ts.TypeChecker) {}
setup() {}
/**
* Analyzes the usage of the given query and determines the query timing based
* on the current usage of the query.
*/
detectTiming(query: NgQueryDefinition): TimingResult {
if (query.property === null) {
return {timing: null, message: 'Queries defined on accessors cannot be analyzed.'};
}
const usage = this.analyzeQueryUsage(query.container, query, []);
if (usage === ResolvedUsage.AMBIGUOUS) {
return {
timing: QueryTiming.STATIC,
message: 'Query timing is ambiguous. Please check if the query can be marked as dynamic.'
};
} else if (usage === ResolvedUsage.SYNCHRONOUS) {
return {timing: QueryTiming.STATIC};
} else {
return {timing: QueryTiming.DYNAMIC};
}
}
/**
* Checks whether a given query is used statically within the given class, its super
* class or derived classes.
*/
private analyzeQueryUsage(
classDecl: ts.ClassDeclaration, query: NgQueryDefinition, knownInputNames: string[],
functionCtx: FunctionContext = new Map(), visitInheritedClasses = true): ResolvedUsage {
const usageVisitor =
new DeclarationUsageVisitor(query.property !, this.typeChecker, functionCtx);
const classMetadata = this.classMetadata.get(classDecl);
let usage: ResolvedUsage = ResolvedUsage.ASYNCHRONOUS;
// In case there is metadata for the current class, we collect all resolved Angular input
// names and add them to the list of known inputs that need to be checked for usages of
// the current query. e.g. queries used in an @Input() *setter* are always static.
if (classMetadata) {
knownInputNames.push(...classMetadata.ngInputNames);
}
// Array of TypeScript nodes which can contain usages of the given query in
// order to access it statically.
const possibleStaticQueryNodes = filterQueryClassMemberNodes(classDecl, query, knownInputNames);
// In case nodes that can possibly access a query statically have been found, check
// if the query declaration is synchronously used within any of these nodes.
if (possibleStaticQueryNodes.length) {
possibleStaticQueryNodes.forEach(
n => usage = combineResolvedUsage(usage, usageVisitor.getResolvedNodeUsage(n)));
}
if (!classMetadata) {
return usage;
}
// In case there is a component template for the current class, we check if the
// template statically accesses the current query. In case that's true, the query
// can be marked as static.
if (classMetadata.template && hasPropertyNameText(query.property !.name)) {
const template = classMetadata.template;
const parsedHtml = parseHtmlGracefully(template.content, template.filePath);
const htmlVisitor = new TemplateUsageVisitor(query.property !.name.text);
if (parsedHtml && htmlVisitor.isQueryUsedStatically(parsedHtml)) {
return ResolvedUsage.SYNCHRONOUS;
}
}
// In case derived classes should also be analyzed, we determine the classes that derive
// from the current class and check if these have input setters or lifecycle hooks that
// use the query statically.
if (visitInheritedClasses) {
classMetadata.derivedClasses.forEach(derivedClass => {
usage = combineResolvedUsage(
usage, this.analyzeQueryUsage(derivedClass, query, knownInputNames));
});
}
// In case the current class has a super class, we determine declared abstract function-like
// declarations in the super-class that are implemented in the current class. The super class
// will then be analyzed with the abstract declarations mapped to the implemented TypeScript
// nodes. This allows us to handle queries which are used in super classes through derived
// abstract method declarations.
if (classMetadata.superClass) {
const superClassDecl = classMetadata.superClass;
// Update the function context to map abstract declaration nodes to their implementation
// node in the base class. This ensures that the declaration usage visitor can analyze
// abstract class member declarations.
updateSuperClassAbstractMembersContext(classDecl, functionCtx, this.classMetadata);
usage = combineResolvedUsage(
usage, this.analyzeQueryUsage(superClassDecl, query, [], functionCtx, false));
}
return usage;
}
}
/**
* Combines two resolved usages based on a fixed priority. "Synchronous" takes
* precedence over "Ambiguous" whereas ambiguous takes precedence over "Asynchronous".
*/
function combineResolvedUsage(base: ResolvedUsage, target: ResolvedUsage): ResolvedUsage {
if (base === ResolvedUsage.SYNCHRONOUS) {
return base;
} else if (target !== ResolvedUsage.ASYNCHRONOUS) {
return target;
} else {
return ResolvedUsage.ASYNCHRONOUS;
}
}
/**
* Filters all class members from the class declaration that can access the
* given query statically (e.g. ngOnInit lifecycle hook or @Input setters)
*/
function filterQueryClassMemberNodes(
classDecl: ts.ClassDeclaration, query: NgQueryDefinition,
knownInputNames: string[]): ts.Block[] {
// Returns an array of TypeScript nodes which can contain usages of the given query
// in order to access it statically. e.g.
// (1) queries used in the "ngOnInit" lifecycle hook are static.
// (2) inputs with setters can access queries statically.
return classDecl.members
.filter(m => {
if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&
STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {
return true;
} else if (
knownInputNames && ts.isSetAccessor(m) && m.body && hasPropertyNameText(m.name) &&
knownInputNames.indexOf(m.name.text) !== -1) {
return true;
}
return false;
})
.map((member: ts.SetAccessorDeclaration | ts.MethodDeclaration) => member.body !);
}
| packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts | 1 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.0006968798115849495,
0.00019916522433049977,
0.00016651806072331965,
0.0001699610147625208,
0.00011739360343199223
] |
{
"id": 1,
"code_window": [
"{\n",
" \"compilerOptions\": {\n",
" \"noImplicitReturns\": true,\n",
" \"noImplicitAny\": true,\n",
" \"noFallthroughCasesInSwitch\": true,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/core/schematics/tsconfig.json",
"type": "replace",
"edit_start_line_idx": 3
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {registerLocaleData} from '@angular/common';
import {Component} from '@angular/core';
// we need to import data for the french locale
import localeFr from './locale-fr';
// registering french data
registerLocaleData(localeFr);
// #docregion PercentPipe
@Component({
selector: 'percent-pipe',
template: `<div>
<!--output '26%'-->
<p>A: {{a | percent}}</p>
<!--output '0,134.950%'-->
<p>B: {{b | percent:'4.3-5'}}</p>
<!--output '0 134,950 %'-->
<p>B: {{b | percent:'4.3-5':'fr'}}</p>
</div>`
})
export class PercentPipeComponent {
a: number = 0.259;
b: number = 1.3495;
}
// #enddocregion
// #docregion DeprecatedPercentPipe
@Component({
selector: 'deprecated-percent-pipe',
template: `<div>
<!--output '25.9%'-->
<p>A: {{a | percent}}</p>
<!--output '0,134.95%'-->
<p>B: {{b | percent:'4.3-5'}}</p>
</div>`
})
export class DeprecatedPercentPipeComponent {
a: number = 0.259;
b: number = 1.3495;
}
// #enddocregion
| packages/examples/common/pipes/ts/percent_pipe.ts | 0 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.00017520147957839072,
0.0001720464788377285,
0.000169231861946173,
0.0001719857973512262,
0.0000024667024263180792
] |
{
"id": 1,
"code_window": [
"{\n",
" \"compilerOptions\": {\n",
" \"noImplicitReturns\": true,\n",
" \"noImplicitAny\": true,\n",
" \"noFallthroughCasesInSwitch\": true,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/core/schematics/tsconfig.json",
"type": "replace",
"edit_start_line_idx": 3
} | {% if doc.members.length %}
<section class="meta-data">
<h2>Metadata properties</h2>
{% for metadata in doc.members %}{% if not metadata.internal %}
<div class="metadata-member">
<a name="{$ metadata.name $}" class="anchor-offset"></a>
<code-example language="ts" hideCopy="true">{$ metadata.name $}{$ params.paramList(metadata.parameters) | trim $}{$ params.returnType(metadata.type) $}</code-example>
{%- if not metadata.notYetDocumented %}{$ metadata.description | marked $}{% endif -%}
</div>
{% if not loop.last %}<hr class="hr-margin">{% endif %}
{% endif %}{% endfor %}
</section>
{% endif %}
| aio/tools/transforms/templates/api/includes/metadata.html | 0 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.0001708130002953112,
0.0001706753100734204,
0.00017053763440344483,
0.0001706753100734204,
1.3768294593319297e-7
] |
{
"id": 1,
"code_window": [
"{\n",
" \"compilerOptions\": {\n",
" \"noImplicitReturns\": true,\n",
" \"noImplicitAny\": true,\n",
" \"noFallthroughCasesInSwitch\": true,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/core/schematics/tsconfig.json",
"type": "replace",
"edit_start_line_idx": 3
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import MagicString from 'magic-string';
import * as ts from 'typescript';
import {Import, ImportManager} from '../../../src/ngtsc/translator';
import {ExportInfo} from '../analysis/private_declarations_analyzer';
import {CompiledClass} from '../analysis/types';
import {SwitchableVariableDeclaration} from '../host/ngcc_host';
import {ModuleWithProvidersInfo} from '../analysis/module_with_providers_analyzer';
/**
* The collected decorators that have become redundant after the compilation
* of Ivy static fields. The map is keyed by the container node, such that we
* can tell if we should remove the entire decorator property
*/
export type RedundantDecoratorMap = Map<ts.Node, ts.Node[]>;
export const RedundantDecoratorMap = Map;
/**
* Implement this interface with methods that know how to render a specific format,
* such as ESM5 or UMD.
*/
export interface RenderingFormatter {
addConstants(output: MagicString, constants: string, file: ts.SourceFile): void;
addImports(output: MagicString, imports: Import[], sf: ts.SourceFile): void;
addExports(
output: MagicString, entryPointBasePath: string, exports: ExportInfo[],
importManager: ImportManager, file: ts.SourceFile): void;
addDefinitions(output: MagicString, compiledClass: CompiledClass, definitions: string): void;
removeDecorators(output: MagicString, decoratorsToRemove: RedundantDecoratorMap): void;
rewriteSwitchableDeclarations(
outputText: MagicString, sourceFile: ts.SourceFile,
declarations: SwitchableVariableDeclaration[]): void;
addModuleWithProvidersParams(
outputText: MagicString, moduleWithProviders: ModuleWithProvidersInfo[],
importManager: ImportManager): void;
}
| packages/compiler-cli/ngcc/src/rendering/rendering_formatter.ts | 0 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.00018772348994389176,
0.00017579316045157611,
0.00016866691294126213,
0.00017402617959305644,
0.00000654412269796012
] |
{
"id": 2,
"code_window": [
" \"noFallthroughCasesInSwitch\": true,\n",
" \"strictNullChecks\": true,\n",
" \"strictPropertyInitialization\": true,\n",
" \"lib\": [\"es2015\"],\n",
" \"types\": [],\n",
" \"baseUrl\": \".\",\n",
" \"paths\": {\n",
" \"@angular/compiler\": [\"../../compiler\"],\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"strict\": true,\n"
],
"file_path": "packages/core/schematics/tsconfig.json",
"type": "replace",
"edit_start_line_idx": 5
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {parseHtmlGracefully} from '../../../../utils/parse_html';
import {hasPropertyNameText} from '../../../../utils/typescript/property_name';
import {ClassMetadataMap} from '../../angular/ng_query_visitor';
import {NgQueryDefinition, QueryTiming, QueryType} from '../../angular/query-definition';
import {TimingResult, TimingStrategy} from '../timing-strategy';
import {DeclarationUsageVisitor, FunctionContext, ResolvedUsage} from './declaration_usage_visitor';
import {updateSuperClassAbstractMembersContext} from './super_class_context';
import {TemplateUsageVisitor} from './template_usage_visitor';
/**
* Object that maps a given type of query to a list of lifecycle hooks that
* could be used to access such a query statically.
*/
const STATIC_QUERY_LIFECYCLE_HOOKS = {
[QueryType.ViewChild]:
['ngOnChanges', 'ngOnInit', 'ngDoCheck', 'ngAfterContentInit', 'ngAfterContentChecked'],
[QueryType.ContentChild]: ['ngOnChanges', 'ngOnInit', 'ngDoCheck'],
};
/**
* Query timing strategy that determines the timing of a given query by inspecting how
* the query is accessed within the project's TypeScript source files. Read more about
* this strategy here: https://hackmd.io/s/Hymvc2OKE
*/
export class QueryUsageStrategy implements TimingStrategy {
constructor(private classMetadata: ClassMetadataMap, private typeChecker: ts.TypeChecker) {}
setup() {}
/**
* Analyzes the usage of the given query and determines the query timing based
* on the current usage of the query.
*/
detectTiming(query: NgQueryDefinition): TimingResult {
if (query.property === null) {
return {timing: null, message: 'Queries defined on accessors cannot be analyzed.'};
}
const usage = this.analyzeQueryUsage(query.container, query, []);
if (usage === ResolvedUsage.AMBIGUOUS) {
return {
timing: QueryTiming.STATIC,
message: 'Query timing is ambiguous. Please check if the query can be marked as dynamic.'
};
} else if (usage === ResolvedUsage.SYNCHRONOUS) {
return {timing: QueryTiming.STATIC};
} else {
return {timing: QueryTiming.DYNAMIC};
}
}
/**
* Checks whether a given query is used statically within the given class, its super
* class or derived classes.
*/
private analyzeQueryUsage(
classDecl: ts.ClassDeclaration, query: NgQueryDefinition, knownInputNames: string[],
functionCtx: FunctionContext = new Map(), visitInheritedClasses = true): ResolvedUsage {
const usageVisitor =
new DeclarationUsageVisitor(query.property !, this.typeChecker, functionCtx);
const classMetadata = this.classMetadata.get(classDecl);
let usage: ResolvedUsage = ResolvedUsage.ASYNCHRONOUS;
// In case there is metadata for the current class, we collect all resolved Angular input
// names and add them to the list of known inputs that need to be checked for usages of
// the current query. e.g. queries used in an @Input() *setter* are always static.
if (classMetadata) {
knownInputNames.push(...classMetadata.ngInputNames);
}
// Array of TypeScript nodes which can contain usages of the given query in
// order to access it statically.
const possibleStaticQueryNodes = filterQueryClassMemberNodes(classDecl, query, knownInputNames);
// In case nodes that can possibly access a query statically have been found, check
// if the query declaration is synchronously used within any of these nodes.
if (possibleStaticQueryNodes.length) {
possibleStaticQueryNodes.forEach(
n => usage = combineResolvedUsage(usage, usageVisitor.getResolvedNodeUsage(n)));
}
if (!classMetadata) {
return usage;
}
// In case there is a component template for the current class, we check if the
// template statically accesses the current query. In case that's true, the query
// can be marked as static.
if (classMetadata.template && hasPropertyNameText(query.property !.name)) {
const template = classMetadata.template;
const parsedHtml = parseHtmlGracefully(template.content, template.filePath);
const htmlVisitor = new TemplateUsageVisitor(query.property !.name.text);
if (parsedHtml && htmlVisitor.isQueryUsedStatically(parsedHtml)) {
return ResolvedUsage.SYNCHRONOUS;
}
}
// In case derived classes should also be analyzed, we determine the classes that derive
// from the current class and check if these have input setters or lifecycle hooks that
// use the query statically.
if (visitInheritedClasses) {
classMetadata.derivedClasses.forEach(derivedClass => {
usage = combineResolvedUsage(
usage, this.analyzeQueryUsage(derivedClass, query, knownInputNames));
});
}
// In case the current class has a super class, we determine declared abstract function-like
// declarations in the super-class that are implemented in the current class. The super class
// will then be analyzed with the abstract declarations mapped to the implemented TypeScript
// nodes. This allows us to handle queries which are used in super classes through derived
// abstract method declarations.
if (classMetadata.superClass) {
const superClassDecl = classMetadata.superClass;
// Update the function context to map abstract declaration nodes to their implementation
// node in the base class. This ensures that the declaration usage visitor can analyze
// abstract class member declarations.
updateSuperClassAbstractMembersContext(classDecl, functionCtx, this.classMetadata);
usage = combineResolvedUsage(
usage, this.analyzeQueryUsage(superClassDecl, query, [], functionCtx, false));
}
return usage;
}
}
/**
* Combines two resolved usages based on a fixed priority. "Synchronous" takes
* precedence over "Ambiguous" whereas ambiguous takes precedence over "Asynchronous".
*/
function combineResolvedUsage(base: ResolvedUsage, target: ResolvedUsage): ResolvedUsage {
if (base === ResolvedUsage.SYNCHRONOUS) {
return base;
} else if (target !== ResolvedUsage.ASYNCHRONOUS) {
return target;
} else {
return ResolvedUsage.ASYNCHRONOUS;
}
}
/**
* Filters all class members from the class declaration that can access the
* given query statically (e.g. ngOnInit lifecycle hook or @Input setters)
*/
function filterQueryClassMemberNodes(
classDecl: ts.ClassDeclaration, query: NgQueryDefinition,
knownInputNames: string[]): ts.Block[] {
// Returns an array of TypeScript nodes which can contain usages of the given query
// in order to access it statically. e.g.
// (1) queries used in the "ngOnInit" lifecycle hook are static.
// (2) inputs with setters can access queries statically.
return classDecl.members
.filter(m => {
if (ts.isMethodDeclaration(m) && m.body && hasPropertyNameText(m.name) &&
STATIC_QUERY_LIFECYCLE_HOOKS[query.type].indexOf(m.name.text) !== -1) {
return true;
} else if (
knownInputNames && ts.isSetAccessor(m) && m.body && hasPropertyNameText(m.name) &&
knownInputNames.indexOf(m.name.text) !== -1) {
return true;
}
return false;
})
.map((member: ts.SetAccessorDeclaration | ts.MethodDeclaration) => member.body !);
}
| packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts | 1 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.0003656869230326265,
0.00018039994756691158,
0.00016355872503481805,
0.00017055893840733916,
0.000043775882659247145
] |
{
"id": 2,
"code_window": [
" \"noFallthroughCasesInSwitch\": true,\n",
" \"strictNullChecks\": true,\n",
" \"strictPropertyInitialization\": true,\n",
" \"lib\": [\"es2015\"],\n",
" \"types\": [],\n",
" \"baseUrl\": \".\",\n",
" \"paths\": {\n",
" \"@angular/compiler\": [\"../../compiler\"],\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"strict\": true,\n"
],
"file_path": "packages/core/schematics/tsconfig.json",
"type": "replace",
"edit_start_line_idx": 5
} | import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class MessageService {
messages: string[] = [];
add(message: string) {
this.messages.push(message);
}
clear() {
this.messages = [];
}
}
| aio/content/examples/toh-pt4/src/app/message.service.ts | 0 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.000174266955582425,
0.00017350017151329666,
0.00017273338744416833,
0.00017350017151329666,
7.667840691283345e-7
] |
{
"id": 2,
"code_window": [
" \"noFallthroughCasesInSwitch\": true,\n",
" \"strictNullChecks\": true,\n",
" \"strictPropertyInitialization\": true,\n",
" \"lib\": [\"es2015\"],\n",
" \"types\": [],\n",
" \"baseUrl\": \".\",\n",
" \"paths\": {\n",
" \"@angular/compiler\": [\"../../compiler\"],\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"strict\": true,\n"
],
"file_path": "packages/core/schematics/tsconfig.json",
"type": "replace",
"edit_start_line_idx": 5
} | # App shell
App shell is a way to render a portion of your application via a route at build time.
It can improve the user experience by quickly launching a static rendered page (a skeleton common to all pages) while the browser downloads the full client version and switches to it automatically after the code loads.
This gives users a meaningful first paint of your application that appears quickly because the browser can simply render the HTML and CSS without the need to initialize any JavaScript.
Learn more in [The App Shell Model](https://developers.google.com/web/fundamentals/architecture/app-shell).
## Step 1: Prepare the application
You can do this with the following CLI command:
<code-example language="bash">
ng new my-app --routing
</code-example>
For an existing application, you have to manually add the `RouterModule` and defining a `<router-outlet>` within your application.
## Step 2: Create the app shell
Use the CLI to automatically create the app shell.
<code-example language="bash">
ng generate app-shell --client-project my-app --universal-project server-app
</code-example>
* `my-app` takes the name of your client application.
* `server-app` takes the name of the Universal (or server) application.
After running this command you will notice that the `angular.json` configuration file has been updated to add two new targets, with a few other changes.
<code-example language="json">
"server": {
"builder": "@angular-devkit/build-angular:server",
"options": {
"outputPath": "dist/my-app-server",
"main": "src/main.server.ts",
"tsConfig": "tsconfig.server.json"
}
},
"app-shell": {
"builder": "@angular-devkit/build-angular:app-shell",
"options": {
"browserTarget": "my-app:build",
"serverTarget": "my-app:server",
"route": "shell"
}
}
</code-example>
## Step 3: Verify the app is built with the shell content
Use the CLI to build the `app-shell` target.
<code-example language="bash">
ng run my-app:app-shell
</code-example>
To verify the build output, open `dist/my-app/index.html`. Look for default text `app-shell works!` to show that the app shell route was rendered as part of the output.
| aio/content/guide/app-shell.md | 0 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.00017054674390237778,
0.00016679077816661447,
0.0001634668733458966,
0.0001665047457208857,
0.0000025565841497154906
] |
{
"id": 2,
"code_window": [
" \"noFallthroughCasesInSwitch\": true,\n",
" \"strictNullChecks\": true,\n",
" \"strictPropertyInitialization\": true,\n",
" \"lib\": [\"es2015\"],\n",
" \"types\": [],\n",
" \"baseUrl\": \".\",\n",
" \"paths\": {\n",
" \"@angular/compiler\": [\"../../compiler\"],\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"strict\": true,\n"
],
"file_path": "packages/core/schematics/tsconfig.json",
"type": "replace",
"edit_start_line_idx": 5
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export const toh = {
'foo.ts': `export * from './app/app.component.ts';`,
app: {
'app.component.ts': `import { Component } from '@angular/core';
export class Hero {
id: number;
name: string;
}
@Component({
selector: 'my-app',
template: \`~{empty}
<~{start-tag}h~{start-tag-after-h}1~{start-tag-h1} ~{h1-after-space}>~{h1-content} {{~{sub-start}title~{sub-end}}}</h1>
~{after-h1}<h2>{{~{h2-hero}hero.~{h2-name}name}} details!</h2>
<div><label>id: </label>{{~{label-hero}hero.~{label-id}id}}</div>
<div ~{div-attributes}>
<label>name: </label>
</div>
&~{entity-amp}amp;
\`
})
export class AppComponent {
title = 'Tour of Heroes';
hero: Hero = {
id: 1,
name: 'Windstorm'
};
private internal: string;
}`,
'main.ts': `
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { CaseIncompleteOpen, CaseMissingClosing, CaseUnknown, Pipes, TemplateReference, NoValueAttribute,
AttributeBinding, StringModel, NumberModel, PropertyBinding, EventBinding, TwoWayBinding, EmptyInterpolation,
ForOfEmpty, ForLetIEqual, ForOfLetEmpty, ForUsingComponent, References, TestComponent} from './parsing-cases';
import { WrongFieldReference, WrongSubFieldReference, PrivateReference, ExpectNumericType, LowercasePipe } from './expression-cases';
import { UnknownPeople, UnknownEven, UnknownTrackBy } from './ng-for-cases';
import { ShowIf } from './ng-if-cases';
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [AppComponent, CaseIncompleteOpen, CaseMissingClosing, CaseUnknown, Pipes, TemplateReference, NoValueAttribute,
AttributeBinding, StringModel, NumberModel, PropertyBinding, EventBinding, TwoWayBinding, EmptyInterpolation, ForOfEmpty, ForOfLetEmpty,
ForLetIEqual, ForUsingComponent, References, TestComponent, WrongFieldReference, WrongSubFieldReference, PrivateReference,
ExpectNumericType, UnknownPeople, UnknownEven, UnknownTrackBy, ShowIf, LowercasePipe]
})
export class AppModule {}
declare function bootstrap(v: any): void;
bootstrap(AppComponent);
`,
'parsing-cases.ts': `
import {Component, Directive, Input, Output, EventEmitter} from '@angular/core';
import {Hero} from './app.component';
@Component({template: '<h1>Some <~{incomplete-open-lt}a~{incomplete-open-a} ~{incomplete-open-attr} text</h1>'})
export class CaseIncompleteOpen {}
@Component({template: '<h1>Some <a> ~{missing-closing} text</h1>'})
export class CaseMissingClosing {}
@Component({template: '<h1>Some <unknown ~{unknown-element}> text</h1>'})
export class CaseUnknown {}
@Component({template: '<h1>{{data | ~{before-pipe}lowe~{in-pipe}rcase~{after-pipe} }}'})
export class Pipes {
data = 'Some string';
}
@Component({template: '<h1 h~{no-value-attribute}></h1>'})
export class NoValueAttribute {}
@Component({template: '<h1 model="~{attribute-binding-model}test"></h1>'})
export class AttributeBinding {
test: string;
}
@Component({template: '<h1 [model]="~{property-binding-model}test"></h1>'})
export class PropertyBinding {
test: string;
}
@Component({template: '<h1 (model)="~{event-binding-model}modelChanged()"></h1>'})
export class EventBinding {
test: string;
modelChanged() {}
}
@Component({template: '<h1 [(model)]="~{two-way-binding-model}test"></h1>'})
export class TwoWayBinding {
test: string;
}
@Directive({selector: '[string-model]'})
export class StringModel {
@Input() model: string;
@Output() modelChanged: EventEmitter<string>;
}
@Directive({selector: '[number-model]'})
export class NumberModel {
@Input('inputAlias') model: number;
@Output('outputAlias') modelChanged: EventEmitter<number>;
}
interface Person {
name: string;
age: number
}
@Component({template: '<div *ngFor="~{for-empty}"></div>'})
export class ForOfEmpty {}
@Component({template: '<div *ngFor="let ~{for-let-empty}"></div>'})
export class ForOfLetEmpty {}
@Component({template: '<div *ngFor="let i = ~{for-let-i-equal}"></div>'})
export class ForLetIEqual {}
@Component({template: '<div *ngFor="~{for-let}let ~{for-person}person ~{for-of}of ~{for-people}people"> <span>Name: {{~{for-interp-person}person.~{for-interp-name}name}}</span><span>Age: {{person.~{for-interp-age}age}}</span></div>'})
export class ForUsingComponent {
people: Person[];
}
@Component({template: '<div #div> <test-comp #test1> {{~{test-comp-content}}} {{test1.~{test-comp-after-test}name}} {{div.~{test-comp-after-div}.innerText}} </test-comp> </div> <test-comp #test2></test-comp>'})
export class References {}
~{start-test-comp}@Component({selector: 'test-comp', template: '<div>Testing: {{name}}</div>'})
export class TestComponent {
«@Input('ᐱtcNameᐱ') name = 'test';»
«@Output('ᐱtestᐱ') testEvent = new EventEmitter();»
}~{end-test-comp}
@Component({templateUrl: 'test.ng'})
export class TemplateReference {
title = 'Some title';
hero: Hero = {
id: 1,
name: 'Windstorm'
};
anyValue: any;
myClick(event: any) {
}
}
@Component({template: '{{~{empty-interpolation}}}'})
export class EmptyInterpolation {
title = 'Some title';
subTitle = 'Some sub title';
}
`,
'expression-cases.ts': `
import {Component} from '@angular/core';
export interface Person {
name: string;
age: number;
}
@Component({template: '{{~{foo}foo~{foo-end}}}'})
export class WrongFieldReference {
bar = 'bar';
}
@Component({template: '{{~{nam}person.nam~{nam-end}}}'})
export class WrongSubFieldReference {
person: Person = { name: 'Bob', age: 23 };
}
@Component({template: '{{~{myField}myField~{myField-end}}}'})
export class PrivateReference {
private myField = 'My Field';
}
@Component({template: '{{~{mod}"a" ~{mod-end}% 2}}'})
export class ExpectNumericType {}
@Component({template: '{{ (name | lowercase).~{string-pipe}substring }}'})
export class LowercasePipe {
name: string;
}
`,
'ng-for-cases.ts': `
import {Component} from '@angular/core';
export interface Person {
name: string;
age: number;
}
@Component({template: '<div *ngFor="let person of ~{people_1}people_1~{people_1-end}"> <span>{{person.name}}</span> </div>'})
export class UnknownPeople {}
@Component({template: '<div ~{even_1}*ngFor="let person of people; let e = even_1"~{even_1-end}><span>{{person.name}}</span> </div>'})
export class UnknownEven {
people: Person[];
}
@Component({template: '<div *ngFor="let person of people; trackBy ~{trackBy_1}trackBy_1~{trackBy_1-end}"><span>{{person.name}}</span> </div>'})
export class UnknownTrackBy {
people: Person[];
}
`,
'ng-if-cases.ts': `
import {Component} from '@angular/core';
@Component({template: '<div ~{implicit}*ngIf="show; let l=unknown"~{implicit-end}>Showing now!</div>'})
export class ShowIf {
show = false;
}
`,
'test.ng': `~{empty}
<~{start-tag}h~{start-tag-after-h}1~{start-tag-h1} ~{h1-after-space}>~{h1-content} {{~{sub-start}title~{sub-end}}}</h1>
~{after-h1}<h2>{{~{h2-hero}hero.~{h2-name}name}} details!</h2>
<div><label>id: </label>{{~{label-hero}hero.~{label-id}id}}</div>
<div ~{div-attributes}>
<label>name: </label>
</div>
&~{entity-amp}amp;
`
}
};
| packages/language-service/test/test_data.ts | 0 | https://github.com/angular/angular/commit/e4d5102b17b9d2b9bb6132ace46dae6697343da8 | [
0.00017765075608622283,
0.00017180170107167214,
0.00016636017244309187,
0.00017295891302637756,
0.000003106882786596543
] |
{
"id": 0,
"code_window": [
"import angular from 'angular';\n",
"\n",
"export class SoloPanelCtrl {\n",
" /** @ngInject */\n",
" constructor($scope, $routeParams, $location, dashboardLoaderSrv, contextSrv) {\n",
" var panelId;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import appEvents from 'app/core/app_events';\n"
],
"file_path": "public/app/features/panel/solo_panel_ctrl.ts",
"type": "add",
"edit_start_line_idx": 1
} | import angular from 'angular';
export class SoloPanelCtrl {
/** @ngInject */
constructor($scope, $routeParams, $location, dashboardLoaderSrv, contextSrv) {
var panelId;
$scope.init = function() {
contextSrv.sidemenu = false;
var params = $location.search();
panelId = parseInt(params.panelId);
$scope.onAppEvent('dashboard-initialized', $scope.initPanelScope);
dashboardLoaderSrv.loadDashboard($routeParams.type, $routeParams.slug).then(function(result) {
result.meta.soloMode = true;
$scope.initDashboard(result, $scope);
});
};
$scope.initPanelScope = function() {
let panelInfo = $scope.dashboard.getPanelInfoById(panelId);
// fake row ctrl scope
$scope.ctrl = {
dashboard: $scope.dashboard,
};
$scope.panel = panelInfo.panel;
$scope.panel.soloMode = true;
$scope.$index = 0;
if (!$scope.panel) {
$scope.appEvent('alert-error', ['Panel not found', '']);
return;
}
};
$scope.init();
}
}
angular.module('grafana.routes').controller('SoloPanelCtrl', SoloPanelCtrl);
| public/app/features/panel/solo_panel_ctrl.ts | 1 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.9991523027420044,
0.8003284335136414,
0.010274051688611507,
0.9981687068939209,
0.39502885937690735
] |
{
"id": 0,
"code_window": [
"import angular from 'angular';\n",
"\n",
"export class SoloPanelCtrl {\n",
" /** @ngInject */\n",
" constructor($scope, $routeParams, $location, dashboardLoaderSrv, contextSrv) {\n",
" var panelId;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import appEvents from 'app/core/app_events';\n"
],
"file_path": "public/app/features/panel/solo_panel_ctrl.ts",
"type": "add",
"edit_start_line_idx": 1
} | {
"type": "datasource",
"name": "CloudWatch",
"id": "cloudwatch",
"metrics": true,
"alerting": true,
"annotations": true,
"info": {
"author": {
"name": "Grafana Project",
"url": "https://grafana.com"
},
"logos": {
"small": "img/amazon-web-services.png",
"large": "img/amazon-web-services.png"
}
}
}
| public/app/plugins/datasource/cloudwatch/plugin.json | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.0001798156154109165,
0.00017747572564985603,
0.0001760496525093913,
0.00017656187992542982,
0.0000016677213352522813
] |
{
"id": 0,
"code_window": [
"import angular from 'angular';\n",
"\n",
"export class SoloPanelCtrl {\n",
" /** @ngInject */\n",
" constructor($scope, $routeParams, $location, dashboardLoaderSrv, contextSrv) {\n",
" var panelId;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import appEvents from 'app/core/app_events';\n"
],
"file_path": "public/app/features/panel/solo_panel_ctrl.ts",
"type": "add",
"edit_start_line_idx": 1
} | // Variables
// --------------------------
$fa-font-path: "../fonts" !default;
$fa-font-size-base: 14px !default;
$fa-line-height-base: 1 !default;
//$fa-font-path: "//netdna.bootstrapcdn.com/font-awesome/4.7.0/fonts" !default; // for referencing Bootstrap CDN font files directly
$fa-css-prefix: fa !default;
$fa-version: "4.7.0" !default;
$fa-border-color: #eee !default;
$fa-inverse: #fff !default;
$fa-li-width: (30em / 14) !default;
$fa-var-500px: "\f26e";
$fa-var-address-book: "\f2b9";
$fa-var-address-book-o: "\f2ba";
$fa-var-address-card: "\f2bb";
$fa-var-address-card-o: "\f2bc";
$fa-var-adjust: "\f042";
$fa-var-adn: "\f170";
$fa-var-align-center: "\f037";
$fa-var-align-justify: "\f039";
$fa-var-align-left: "\f036";
$fa-var-align-right: "\f038";
$fa-var-amazon: "\f270";
$fa-var-ambulance: "\f0f9";
$fa-var-american-sign-language-interpreting: "\f2a3";
$fa-var-anchor: "\f13d";
$fa-var-android: "\f17b";
$fa-var-angellist: "\f209";
$fa-var-angle-double-down: "\f103";
$fa-var-angle-double-left: "\f100";
$fa-var-angle-double-right: "\f101";
$fa-var-angle-double-up: "\f102";
$fa-var-angle-down: "\f107";
$fa-var-angle-left: "\f104";
$fa-var-angle-right: "\f105";
$fa-var-angle-up: "\f106";
$fa-var-apple: "\f179";
$fa-var-archive: "\f187";
$fa-var-area-chart: "\f1fe";
$fa-var-arrow-circle-down: "\f0ab";
$fa-var-arrow-circle-left: "\f0a8";
$fa-var-arrow-circle-o-down: "\f01a";
$fa-var-arrow-circle-o-left: "\f190";
$fa-var-arrow-circle-o-right: "\f18e";
$fa-var-arrow-circle-o-up: "\f01b";
$fa-var-arrow-circle-right: "\f0a9";
$fa-var-arrow-circle-up: "\f0aa";
$fa-var-arrow-down: "\f063";
$fa-var-arrow-left: "\f060";
$fa-var-arrow-right: "\f061";
$fa-var-arrow-up: "\f062";
$fa-var-arrows: "\f047";
$fa-var-arrows-alt: "\f0b2";
$fa-var-arrows-h: "\f07e";
$fa-var-arrows-v: "\f07d";
$fa-var-asl-interpreting: "\f2a3";
$fa-var-assistive-listening-systems: "\f2a2";
$fa-var-asterisk: "\f069";
$fa-var-at: "\f1fa";
$fa-var-audio-description: "\f29e";
$fa-var-automobile: "\f1b9";
$fa-var-backward: "\f04a";
$fa-var-balance-scale: "\f24e";
$fa-var-ban: "\f05e";
$fa-var-bandcamp: "\f2d5";
$fa-var-bank: "\f19c";
$fa-var-bar-chart: "\f080";
$fa-var-bar-chart-o: "\f080";
$fa-var-barcode: "\f02a";
$fa-var-bars: "\f0c9";
$fa-var-bath: "\f2cd";
$fa-var-bathtub: "\f2cd";
$fa-var-battery: "\f240";
$fa-var-battery-0: "\f244";
$fa-var-battery-1: "\f243";
$fa-var-battery-2: "\f242";
$fa-var-battery-3: "\f241";
$fa-var-battery-4: "\f240";
$fa-var-battery-empty: "\f244";
$fa-var-battery-full: "\f240";
$fa-var-battery-half: "\f242";
$fa-var-battery-quarter: "\f243";
$fa-var-battery-three-quarters: "\f241";
$fa-var-bed: "\f236";
$fa-var-beer: "\f0fc";
$fa-var-behance: "\f1b4";
$fa-var-behance-square: "\f1b5";
$fa-var-bell: "\f0f3";
$fa-var-bell-o: "\f0a2";
$fa-var-bell-slash: "\f1f6";
$fa-var-bell-slash-o: "\f1f7";
$fa-var-bicycle: "\f206";
$fa-var-binoculars: "\f1e5";
$fa-var-birthday-cake: "\f1fd";
$fa-var-bitbucket: "\f171";
$fa-var-bitbucket-square: "\f172";
$fa-var-bitcoin: "\f15a";
$fa-var-black-tie: "\f27e";
$fa-var-blind: "\f29d";
$fa-var-bluetooth: "\f293";
$fa-var-bluetooth-b: "\f294";
$fa-var-bold: "\f032";
$fa-var-bolt: "\f0e7";
$fa-var-bomb: "\f1e2";
$fa-var-book: "\f02d";
$fa-var-bookmark: "\f02e";
$fa-var-bookmark-o: "\f097";
$fa-var-braille: "\f2a1";
$fa-var-briefcase: "\f0b1";
$fa-var-btc: "\f15a";
$fa-var-bug: "\f188";
$fa-var-building: "\f1ad";
$fa-var-building-o: "\f0f7";
$fa-var-bullhorn: "\f0a1";
$fa-var-bullseye: "\f140";
$fa-var-bus: "\f207";
$fa-var-buysellads: "\f20d";
$fa-var-cab: "\f1ba";
$fa-var-calculator: "\f1ec";
$fa-var-calendar: "\f073";
$fa-var-calendar-check-o: "\f274";
$fa-var-calendar-minus-o: "\f272";
$fa-var-calendar-o: "\f133";
$fa-var-calendar-plus-o: "\f271";
$fa-var-calendar-times-o: "\f273";
$fa-var-camera: "\f030";
$fa-var-camera-retro: "\f083";
$fa-var-car: "\f1b9";
$fa-var-caret-down: "\f0d7";
$fa-var-caret-left: "\f0d9";
$fa-var-caret-right: "\f0da";
$fa-var-caret-square-o-down: "\f150";
$fa-var-caret-square-o-left: "\f191";
$fa-var-caret-square-o-right: "\f152";
$fa-var-caret-square-o-up: "\f151";
$fa-var-caret-up: "\f0d8";
$fa-var-cart-arrow-down: "\f218";
$fa-var-cart-plus: "\f217";
$fa-var-cc: "\f20a";
$fa-var-cc-amex: "\f1f3";
$fa-var-cc-diners-club: "\f24c";
$fa-var-cc-discover: "\f1f2";
$fa-var-cc-jcb: "\f24b";
$fa-var-cc-mastercard: "\f1f1";
$fa-var-cc-paypal: "\f1f4";
$fa-var-cc-stripe: "\f1f5";
$fa-var-cc-visa: "\f1f0";
$fa-var-certificate: "\f0a3";
$fa-var-chain: "\f0c1";
$fa-var-chain-broken: "\f127";
$fa-var-check: "\f00c";
$fa-var-check-circle: "\f058";
$fa-var-check-circle-o: "\f05d";
$fa-var-check-square: "\f14a";
$fa-var-check-square-o: "\f046";
$fa-var-chevron-circle-down: "\f13a";
$fa-var-chevron-circle-left: "\f137";
$fa-var-chevron-circle-right: "\f138";
$fa-var-chevron-circle-up: "\f139";
$fa-var-chevron-down: "\f078";
$fa-var-chevron-left: "\f053";
$fa-var-chevron-right: "\f054";
$fa-var-chevron-up: "\f077";
$fa-var-child: "\f1ae";
$fa-var-chrome: "\f268";
$fa-var-circle: "\f111";
$fa-var-circle-o: "\f10c";
$fa-var-circle-o-notch: "\f1ce";
$fa-var-circle-thin: "\f1db";
$fa-var-clipboard: "\f0ea";
$fa-var-clock-o: "\f017";
$fa-var-clone: "\f24d";
$fa-var-close: "\f00d";
$fa-var-cloud: "\f0c2";
$fa-var-cloud-download: "\f0ed";
$fa-var-cloud-upload: "\f0ee";
$fa-var-cny: "\f157";
$fa-var-code: "\f121";
$fa-var-code-fork: "\f126";
$fa-var-codepen: "\f1cb";
$fa-var-codiepie: "\f284";
$fa-var-coffee: "\f0f4";
$fa-var-cog: "\f013";
$fa-var-cogs: "\f085";
$fa-var-columns: "\f0db";
$fa-var-comment: "\f075";
$fa-var-comment-o: "\f0e5";
$fa-var-commenting: "\f27a";
$fa-var-commenting-o: "\f27b";
$fa-var-comments: "\f086";
$fa-var-comments-o: "\f0e6";
$fa-var-compass: "\f14e";
$fa-var-compress: "\f066";
$fa-var-connectdevelop: "\f20e";
$fa-var-contao: "\f26d";
$fa-var-copy: "\f0c5";
$fa-var-copyright: "\f1f9";
$fa-var-creative-commons: "\f25e";
$fa-var-credit-card: "\f09d";
$fa-var-credit-card-alt: "\f283";
$fa-var-crop: "\f125";
$fa-var-crosshairs: "\f05b";
$fa-var-css3: "\f13c";
$fa-var-cube: "\f1b2";
$fa-var-cubes: "\f1b3";
$fa-var-cut: "\f0c4";
$fa-var-cutlery: "\f0f5";
$fa-var-dashboard: "\f0e4";
$fa-var-dashcube: "\f210";
$fa-var-database: "\f1c0";
$fa-var-deaf: "\f2a4";
$fa-var-deafness: "\f2a4";
$fa-var-dedent: "\f03b";
$fa-var-delicious: "\f1a5";
$fa-var-desktop: "\f108";
$fa-var-deviantart: "\f1bd";
$fa-var-diamond: "\f219";
$fa-var-digg: "\f1a6";
$fa-var-dollar: "\f155";
$fa-var-dot-circle-o: "\f192";
$fa-var-download: "\f019";
$fa-var-dribbble: "\f17d";
$fa-var-drivers-license: "\f2c2";
$fa-var-drivers-license-o: "\f2c3";
$fa-var-dropbox: "\f16b";
$fa-var-drupal: "\f1a9";
$fa-var-edge: "\f282";
$fa-var-edit: "\f044";
$fa-var-eercast: "\f2da";
$fa-var-eject: "\f052";
$fa-var-ellipsis-h: "\f141";
$fa-var-ellipsis-v: "\f142";
$fa-var-empire: "\f1d1";
$fa-var-envelope: "\f0e0";
$fa-var-envelope-o: "\f003";
$fa-var-envelope-open: "\f2b6";
$fa-var-envelope-open-o: "\f2b7";
$fa-var-envelope-square: "\f199";
$fa-var-envira: "\f299";
$fa-var-eraser: "\f12d";
$fa-var-etsy: "\f2d7";
$fa-var-eur: "\f153";
$fa-var-euro: "\f153";
$fa-var-exchange: "\f0ec";
$fa-var-exclamation: "\f12a";
$fa-var-exclamation-circle: "\f06a";
$fa-var-exclamation-triangle: "\f071";
$fa-var-expand: "\f065";
$fa-var-expeditedssl: "\f23e";
$fa-var-external-link: "\f08e";
$fa-var-external-link-square: "\f14c";
$fa-var-eye: "\f06e";
$fa-var-eye-slash: "\f070";
$fa-var-eyedropper: "\f1fb";
$fa-var-fa: "\f2b4";
$fa-var-facebook: "\f09a";
$fa-var-facebook-f: "\f09a";
$fa-var-facebook-official: "\f230";
$fa-var-facebook-square: "\f082";
$fa-var-fast-backward: "\f049";
$fa-var-fast-forward: "\f050";
$fa-var-fax: "\f1ac";
$fa-var-feed: "\f09e";
$fa-var-female: "\f182";
$fa-var-fighter-jet: "\f0fb";
$fa-var-file: "\f15b";
$fa-var-file-archive-o: "\f1c6";
$fa-var-file-audio-o: "\f1c7";
$fa-var-file-code-o: "\f1c9";
$fa-var-file-excel-o: "\f1c3";
$fa-var-file-image-o: "\f1c5";
$fa-var-file-movie-o: "\f1c8";
$fa-var-file-o: "\f016";
$fa-var-file-pdf-o: "\f1c1";
$fa-var-file-photo-o: "\f1c5";
$fa-var-file-picture-o: "\f1c5";
$fa-var-file-powerpoint-o: "\f1c4";
$fa-var-file-sound-o: "\f1c7";
$fa-var-file-text: "\f15c";
$fa-var-file-text-o: "\f0f6";
$fa-var-file-video-o: "\f1c8";
$fa-var-file-word-o: "\f1c2";
$fa-var-file-zip-o: "\f1c6";
$fa-var-files-o: "\f0c5";
$fa-var-film: "\f008";
$fa-var-filter: "\f0b0";
$fa-var-fire: "\f06d";
$fa-var-fire-extinguisher: "\f134";
$fa-var-firefox: "\f269";
$fa-var-first-order: "\f2b0";
$fa-var-flag: "\f024";
$fa-var-flag-checkered: "\f11e";
$fa-var-flag-o: "\f11d";
$fa-var-flash: "\f0e7";
$fa-var-flask: "\f0c3";
$fa-var-flickr: "\f16e";
$fa-var-floppy-o: "\f0c7";
$fa-var-folder: "\f07b";
$fa-var-folder-o: "\f114";
$fa-var-folder-open: "\f07c";
$fa-var-folder-open-o: "\f115";
$fa-var-font: "\f031";
$fa-var-font-awesome: "\f2b4";
$fa-var-fonticons: "\f280";
$fa-var-fort-awesome: "\f286";
$fa-var-forumbee: "\f211";
$fa-var-forward: "\f04e";
$fa-var-foursquare: "\f180";
$fa-var-free-code-camp: "\f2c5";
$fa-var-frown-o: "\f119";
$fa-var-futbol-o: "\f1e3";
$fa-var-gamepad: "\f11b";
$fa-var-gavel: "\f0e3";
$fa-var-gbp: "\f154";
$fa-var-ge: "\f1d1";
$fa-var-gear: "\f013";
$fa-var-gears: "\f085";
$fa-var-genderless: "\f22d";
$fa-var-get-pocket: "\f265";
$fa-var-gg: "\f260";
$fa-var-gg-circle: "\f261";
$fa-var-gift: "\f06b";
$fa-var-git: "\f1d3";
$fa-var-git-square: "\f1d2";
$fa-var-github: "\f09b";
$fa-var-github-alt: "\f113";
$fa-var-github-square: "\f092";
$fa-var-gitlab: "\f296";
$fa-var-gittip: "\f184";
$fa-var-glass: "\f000";
$fa-var-glide: "\f2a5";
$fa-var-glide-g: "\f2a6";
$fa-var-globe: "\f0ac";
$fa-var-google: "\f1a0";
$fa-var-google-plus: "\f0d5";
$fa-var-google-plus-circle: "\f2b3";
$fa-var-google-plus-official: "\f2b3";
$fa-var-google-plus-square: "\f0d4";
$fa-var-google-wallet: "\f1ee";
$fa-var-graduation-cap: "\f19d";
$fa-var-gratipay: "\f184";
$fa-var-grav: "\f2d6";
$fa-var-group: "\f0c0";
$fa-var-h-square: "\f0fd";
$fa-var-hacker-news: "\f1d4";
$fa-var-hand-grab-o: "\f255";
$fa-var-hand-lizard-o: "\f258";
$fa-var-hand-o-down: "\f0a7";
$fa-var-hand-o-left: "\f0a5";
$fa-var-hand-o-right: "\f0a4";
$fa-var-hand-o-up: "\f0a6";
$fa-var-hand-paper-o: "\f256";
$fa-var-hand-peace-o: "\f25b";
$fa-var-hand-pointer-o: "\f25a";
$fa-var-hand-rock-o: "\f255";
$fa-var-hand-scissors-o: "\f257";
$fa-var-hand-spock-o: "\f259";
$fa-var-hand-stop-o: "\f256";
$fa-var-handshake-o: "\f2b5";
$fa-var-hard-of-hearing: "\f2a4";
$fa-var-hashtag: "\f292";
$fa-var-hdd-o: "\f0a0";
$fa-var-header: "\f1dc";
$fa-var-headphones: "\f025";
$fa-var-heart: "\f004";
$fa-var-heart-o: "\f08a";
$fa-var-heartbeat: "\f21e";
$fa-var-history: "\f1da";
$fa-var-home: "\f015";
$fa-var-hospital-o: "\f0f8";
$fa-var-hotel: "\f236";
$fa-var-hourglass: "\f254";
$fa-var-hourglass-1: "\f251";
$fa-var-hourglass-2: "\f252";
$fa-var-hourglass-3: "\f253";
$fa-var-hourglass-end: "\f253";
$fa-var-hourglass-half: "\f252";
$fa-var-hourglass-o: "\f250";
$fa-var-hourglass-start: "\f251";
$fa-var-houzz: "\f27c";
$fa-var-html5: "\f13b";
$fa-var-i-cursor: "\f246";
$fa-var-id-badge: "\f2c1";
$fa-var-id-card: "\f2c2";
$fa-var-id-card-o: "\f2c3";
$fa-var-ils: "\f20b";
$fa-var-image: "\f03e";
$fa-var-imdb: "\f2d8";
$fa-var-inbox: "\f01c";
$fa-var-indent: "\f03c";
$fa-var-industry: "\f275";
$fa-var-info: "\f129";
$fa-var-info-circle: "\f05a";
$fa-var-inr: "\f156";
$fa-var-instagram: "\f16d";
$fa-var-institution: "\f19c";
$fa-var-internet-explorer: "\f26b";
$fa-var-intersex: "\f224";
$fa-var-ioxhost: "\f208";
$fa-var-italic: "\f033";
$fa-var-joomla: "\f1aa";
$fa-var-jpy: "\f157";
$fa-var-jsfiddle: "\f1cc";
$fa-var-key: "\f084";
$fa-var-keyboard-o: "\f11c";
$fa-var-krw: "\f159";
$fa-var-language: "\f1ab";
$fa-var-laptop: "\f109";
$fa-var-lastfm: "\f202";
$fa-var-lastfm-square: "\f203";
$fa-var-leaf: "\f06c";
$fa-var-leanpub: "\f212";
$fa-var-legal: "\f0e3";
$fa-var-lemon-o: "\f094";
$fa-var-level-down: "\f149";
$fa-var-level-up: "\f148";
$fa-var-life-bouy: "\f1cd";
$fa-var-life-buoy: "\f1cd";
$fa-var-life-ring: "\f1cd";
$fa-var-life-saver: "\f1cd";
$fa-var-lightbulb-o: "\f0eb";
$fa-var-line-chart: "\f201";
$fa-var-link: "\f0c1";
$fa-var-linkedin: "\f0e1";
$fa-var-linkedin-square: "\f08c";
$fa-var-linode: "\f2b8";
$fa-var-linux: "\f17c";
$fa-var-list: "\f03a";
$fa-var-list-alt: "\f022";
$fa-var-list-ol: "\f0cb";
$fa-var-list-ul: "\f0ca";
$fa-var-location-arrow: "\f124";
$fa-var-lock: "\f023";
$fa-var-long-arrow-down: "\f175";
$fa-var-long-arrow-left: "\f177";
$fa-var-long-arrow-right: "\f178";
$fa-var-long-arrow-up: "\f176";
$fa-var-low-vision: "\f2a8";
$fa-var-magic: "\f0d0";
$fa-var-magnet: "\f076";
$fa-var-mail-forward: "\f064";
$fa-var-mail-reply: "\f112";
$fa-var-mail-reply-all: "\f122";
$fa-var-male: "\f183";
$fa-var-map: "\f279";
$fa-var-map-marker: "\f041";
$fa-var-map-o: "\f278";
$fa-var-map-pin: "\f276";
$fa-var-map-signs: "\f277";
$fa-var-mars: "\f222";
$fa-var-mars-double: "\f227";
$fa-var-mars-stroke: "\f229";
$fa-var-mars-stroke-h: "\f22b";
$fa-var-mars-stroke-v: "\f22a";
$fa-var-maxcdn: "\f136";
$fa-var-meanpath: "\f20c";
$fa-var-medium: "\f23a";
$fa-var-medkit: "\f0fa";
$fa-var-meetup: "\f2e0";
$fa-var-meh-o: "\f11a";
$fa-var-mercury: "\f223";
$fa-var-microchip: "\f2db";
$fa-var-microphone: "\f130";
$fa-var-microphone-slash: "\f131";
$fa-var-minus: "\f068";
$fa-var-minus-circle: "\f056";
$fa-var-minus-square: "\f146";
$fa-var-minus-square-o: "\f147";
$fa-var-mixcloud: "\f289";
$fa-var-mobile: "\f10b";
$fa-var-mobile-phone: "\f10b";
$fa-var-modx: "\f285";
$fa-var-money: "\f0d6";
$fa-var-moon-o: "\f186";
$fa-var-mortar-board: "\f19d";
$fa-var-motorcycle: "\f21c";
$fa-var-mouse-pointer: "\f245";
$fa-var-music: "\f001";
$fa-var-navicon: "\f0c9";
$fa-var-neuter: "\f22c";
$fa-var-newspaper-o: "\f1ea";
$fa-var-object-group: "\f247";
$fa-var-object-ungroup: "\f248";
$fa-var-odnoklassniki: "\f263";
$fa-var-odnoklassniki-square: "\f264";
$fa-var-opencart: "\f23d";
$fa-var-openid: "\f19b";
$fa-var-opera: "\f26a";
$fa-var-optin-monster: "\f23c";
$fa-var-outdent: "\f03b";
$fa-var-pagelines: "\f18c";
$fa-var-paint-brush: "\f1fc";
$fa-var-paper-plane: "\f1d8";
$fa-var-paper-plane-o: "\f1d9";
$fa-var-paperclip: "\f0c6";
$fa-var-paragraph: "\f1dd";
$fa-var-paste: "\f0ea";
$fa-var-pause: "\f04c";
$fa-var-pause-circle: "\f28b";
$fa-var-pause-circle-o: "\f28c";
$fa-var-paw: "\f1b0";
$fa-var-paypal: "\f1ed";
$fa-var-pencil: "\f040";
$fa-var-pencil-square: "\f14b";
$fa-var-pencil-square-o: "\f044";
$fa-var-percent: "\f295";
$fa-var-phone: "\f095";
$fa-var-phone-square: "\f098";
$fa-var-photo: "\f03e";
$fa-var-picture-o: "\f03e";
$fa-var-pie-chart: "\f200";
$fa-var-pied-piper: "\f2ae";
$fa-var-pied-piper-alt: "\f1a8";
$fa-var-pied-piper-pp: "\f1a7";
$fa-var-pinterest: "\f0d2";
$fa-var-pinterest-p: "\f231";
$fa-var-pinterest-square: "\f0d3";
$fa-var-plane: "\f072";
$fa-var-play: "\f04b";
$fa-var-play-circle: "\f144";
$fa-var-play-circle-o: "\f01d";
$fa-var-plug: "\f1e6";
$fa-var-plus: "\f067";
$fa-var-plus-circle: "\f055";
$fa-var-plus-square: "\f0fe";
$fa-var-plus-square-o: "\f196";
$fa-var-podcast: "\f2ce";
$fa-var-power-off: "\f011";
$fa-var-print: "\f02f";
$fa-var-product-hunt: "\f288";
$fa-var-puzzle-piece: "\f12e";
$fa-var-qq: "\f1d6";
$fa-var-qrcode: "\f029";
$fa-var-question: "\f128";
$fa-var-question-circle: "\f059";
$fa-var-question-circle-o: "\f29c";
$fa-var-quora: "\f2c4";
$fa-var-quote-left: "\f10d";
$fa-var-quote-right: "\f10e";
$fa-var-ra: "\f1d0";
$fa-var-random: "\f074";
$fa-var-ravelry: "\f2d9";
$fa-var-rebel: "\f1d0";
$fa-var-recycle: "\f1b8";
$fa-var-reddit: "\f1a1";
$fa-var-reddit-alien: "\f281";
$fa-var-reddit-square: "\f1a2";
$fa-var-refresh: "\f021";
$fa-var-registered: "\f25d";
$fa-var-remove: "\f00d";
$fa-var-renren: "\f18b";
$fa-var-reorder: "\f0c9";
$fa-var-repeat: "\f01e";
$fa-var-reply: "\f112";
$fa-var-reply-all: "\f122";
$fa-var-resistance: "\f1d0";
$fa-var-retweet: "\f079";
$fa-var-rmb: "\f157";
$fa-var-road: "\f018";
$fa-var-rocket: "\f135";
$fa-var-rotate-left: "\f0e2";
$fa-var-rotate-right: "\f01e";
$fa-var-rouble: "\f158";
$fa-var-rss: "\f09e";
$fa-var-rss-square: "\f143";
$fa-var-rub: "\f158";
$fa-var-ruble: "\f158";
$fa-var-rupee: "\f156";
$fa-var-s15: "\f2cd";
$fa-var-safari: "\f267";
$fa-var-save: "\f0c7";
$fa-var-scissors: "\f0c4";
$fa-var-scribd: "\f28a";
$fa-var-search: "\f002";
$fa-var-search-minus: "\f010";
$fa-var-search-plus: "\f00e";
$fa-var-sellsy: "\f213";
$fa-var-send: "\f1d8";
$fa-var-send-o: "\f1d9";
$fa-var-server: "\f233";
$fa-var-share: "\f064";
$fa-var-share-alt: "\f1e0";
$fa-var-share-alt-square: "\f1e1";
$fa-var-share-square: "\f14d";
$fa-var-share-square-o: "\f045";
$fa-var-shekel: "\f20b";
$fa-var-sheqel: "\f20b";
$fa-var-shield: "\f132";
$fa-var-ship: "\f21a";
$fa-var-shirtsinbulk: "\f214";
$fa-var-shopping-bag: "\f290";
$fa-var-shopping-basket: "\f291";
$fa-var-shopping-cart: "\f07a";
$fa-var-shower: "\f2cc";
$fa-var-sign-in: "\f090";
$fa-var-sign-language: "\f2a7";
$fa-var-sign-out: "\f08b";
$fa-var-signal: "\f012";
$fa-var-signing: "\f2a7";
$fa-var-simplybuilt: "\f215";
$fa-var-sitemap: "\f0e8";
$fa-var-skyatlas: "\f216";
$fa-var-skype: "\f17e";
$fa-var-slack: "\f198";
$fa-var-sliders: "\f1de";
$fa-var-slideshare: "\f1e7";
$fa-var-smile-o: "\f118";
$fa-var-snapchat: "\f2ab";
$fa-var-snapchat-ghost: "\f2ac";
$fa-var-snapchat-square: "\f2ad";
$fa-var-snowflake-o: "\f2dc";
$fa-var-soccer-ball-o: "\f1e3";
$fa-var-sort: "\f0dc";
$fa-var-sort-alpha-asc: "\f15d";
$fa-var-sort-alpha-desc: "\f15e";
$fa-var-sort-amount-asc: "\f160";
$fa-var-sort-amount-desc: "\f161";
$fa-var-sort-asc: "\f0de";
$fa-var-sort-desc: "\f0dd";
$fa-var-sort-down: "\f0dd";
$fa-var-sort-numeric-asc: "\f162";
$fa-var-sort-numeric-desc: "\f163";
$fa-var-sort-up: "\f0de";
$fa-var-soundcloud: "\f1be";
$fa-var-space-shuttle: "\f197";
$fa-var-spinner: "\f110";
$fa-var-spoon: "\f1b1";
$fa-var-spotify: "\f1bc";
$fa-var-square: "\f0c8";
$fa-var-square-o: "\f096";
$fa-var-stack-exchange: "\f18d";
$fa-var-stack-overflow: "\f16c";
$fa-var-star: "\f005";
$fa-var-star-half: "\f089";
$fa-var-star-half-empty: "\f123";
$fa-var-star-half-full: "\f123";
$fa-var-star-half-o: "\f123";
$fa-var-star-o: "\f006";
$fa-var-steam: "\f1b6";
$fa-var-steam-square: "\f1b7";
$fa-var-step-backward: "\f048";
$fa-var-step-forward: "\f051";
$fa-var-stethoscope: "\f0f1";
$fa-var-sticky-note: "\f249";
$fa-var-sticky-note-o: "\f24a";
$fa-var-stop: "\f04d";
$fa-var-stop-circle: "\f28d";
$fa-var-stop-circle-o: "\f28e";
$fa-var-street-view: "\f21d";
$fa-var-strikethrough: "\f0cc";
$fa-var-stumbleupon: "\f1a4";
$fa-var-stumbleupon-circle: "\f1a3";
$fa-var-subscript: "\f12c";
$fa-var-subway: "\f239";
$fa-var-suitcase: "\f0f2";
$fa-var-sun-o: "\f185";
$fa-var-superpowers: "\f2dd";
$fa-var-superscript: "\f12b";
$fa-var-support: "\f1cd";
$fa-var-table: "\f0ce";
$fa-var-tablet: "\f10a";
$fa-var-tachometer: "\f0e4";
$fa-var-tag: "\f02b";
$fa-var-tags: "\f02c";
$fa-var-tasks: "\f0ae";
$fa-var-taxi: "\f1ba";
$fa-var-telegram: "\f2c6";
$fa-var-television: "\f26c";
$fa-var-tencent-weibo: "\f1d5";
$fa-var-terminal: "\f120";
$fa-var-text-height: "\f034";
$fa-var-text-width: "\f035";
$fa-var-th: "\f00a";
$fa-var-th-large: "\f009";
$fa-var-th-list: "\f00b";
$fa-var-themeisle: "\f2b2";
$fa-var-thermometer: "\f2c7";
$fa-var-thermometer-0: "\f2cb";
$fa-var-thermometer-1: "\f2ca";
$fa-var-thermometer-2: "\f2c9";
$fa-var-thermometer-3: "\f2c8";
$fa-var-thermometer-4: "\f2c7";
$fa-var-thermometer-empty: "\f2cb";
$fa-var-thermometer-full: "\f2c7";
$fa-var-thermometer-half: "\f2c9";
$fa-var-thermometer-quarter: "\f2ca";
$fa-var-thermometer-three-quarters: "\f2c8";
$fa-var-thumb-tack: "\f08d";
$fa-var-thumbs-down: "\f165";
$fa-var-thumbs-o-down: "\f088";
$fa-var-thumbs-o-up: "\f087";
$fa-var-thumbs-up: "\f164";
$fa-var-ticket: "\f145";
$fa-var-times: "\f00d";
$fa-var-times-circle: "\f057";
$fa-var-times-circle-o: "\f05c";
$fa-var-times-rectangle: "\f2d3";
$fa-var-times-rectangle-o: "\f2d4";
$fa-var-tint: "\f043";
$fa-var-toggle-down: "\f150";
$fa-var-toggle-left: "\f191";
$fa-var-toggle-off: "\f204";
$fa-var-toggle-on: "\f205";
$fa-var-toggle-right: "\f152";
$fa-var-toggle-up: "\f151";
$fa-var-trademark: "\f25c";
$fa-var-train: "\f238";
$fa-var-transgender: "\f224";
$fa-var-transgender-alt: "\f225";
$fa-var-trash: "\f1f8";
$fa-var-trash-o: "\f014";
$fa-var-tree: "\f1bb";
$fa-var-trello: "\f181";
$fa-var-tripadvisor: "\f262";
$fa-var-trophy: "\f091";
$fa-var-truck: "\f0d1";
$fa-var-try: "\f195";
$fa-var-tty: "\f1e4";
$fa-var-tumblr: "\f173";
$fa-var-tumblr-square: "\f174";
$fa-var-turkish-lira: "\f195";
$fa-var-tv: "\f26c";
$fa-var-twitch: "\f1e8";
$fa-var-twitter: "\f099";
$fa-var-twitter-square: "\f081";
$fa-var-umbrella: "\f0e9";
$fa-var-underline: "\f0cd";
$fa-var-undo: "\f0e2";
$fa-var-universal-access: "\f29a";
$fa-var-university: "\f19c";
$fa-var-unlink: "\f127";
$fa-var-unlock: "\f09c";
$fa-var-unlock-alt: "\f13e";
$fa-var-unsorted: "\f0dc";
$fa-var-upload: "\f093";
$fa-var-usb: "\f287";
$fa-var-usd: "\f155";
$fa-var-user: "\f007";
$fa-var-user-circle: "\f2bd";
$fa-var-user-circle-o: "\f2be";
$fa-var-user-md: "\f0f0";
$fa-var-user-o: "\f2c0";
$fa-var-user-plus: "\f234";
$fa-var-user-secret: "\f21b";
$fa-var-user-times: "\f235";
$fa-var-users: "\f0c0";
$fa-var-vcard: "\f2bb";
$fa-var-vcard-o: "\f2bc";
$fa-var-venus: "\f221";
$fa-var-venus-double: "\f226";
$fa-var-venus-mars: "\f228";
$fa-var-viacoin: "\f237";
$fa-var-viadeo: "\f2a9";
$fa-var-viadeo-square: "\f2aa";
$fa-var-video-camera: "\f03d";
$fa-var-vimeo: "\f27d";
$fa-var-vimeo-square: "\f194";
$fa-var-vine: "\f1ca";
$fa-var-vk: "\f189";
$fa-var-volume-control-phone: "\f2a0";
$fa-var-volume-down: "\f027";
$fa-var-volume-off: "\f026";
$fa-var-volume-up: "\f028";
$fa-var-warning: "\f071";
$fa-var-wechat: "\f1d7";
$fa-var-weibo: "\f18a";
$fa-var-weixin: "\f1d7";
$fa-var-whatsapp: "\f232";
$fa-var-wheelchair: "\f193";
$fa-var-wheelchair-alt: "\f29b";
$fa-var-wifi: "\f1eb";
$fa-var-wikipedia-w: "\f266";
$fa-var-window-close: "\f2d3";
$fa-var-window-close-o: "\f2d4";
$fa-var-window-maximize: "\f2d0";
$fa-var-window-minimize: "\f2d1";
$fa-var-window-restore: "\f2d2";
$fa-var-windows: "\f17a";
$fa-var-won: "\f159";
$fa-var-wordpress: "\f19a";
$fa-var-wpbeginner: "\f297";
$fa-var-wpexplorer: "\f2de";
$fa-var-wpforms: "\f298";
$fa-var-wrench: "\f0ad";
$fa-var-xing: "\f168";
$fa-var-xing-square: "\f169";
$fa-var-y-combinator: "\f23b";
$fa-var-y-combinator-square: "\f1d4";
$fa-var-yahoo: "\f19e";
$fa-var-yc: "\f23b";
$fa-var-yc-square: "\f1d4";
$fa-var-yelp: "\f1e9";
$fa-var-yen: "\f157";
$fa-var-yoast: "\f2b1";
$fa-var-youtube: "\f167";
$fa-var-youtube-play: "\f16a";
$fa-var-youtube-square: "\f166";
| public/sass/base/font-awesome/_variables.scss | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00017543784633744508,
0.00017323889187537134,
0.0001693950907792896,
0.00017344893421977758,
0.0000011283218555036
] |
{
"id": 0,
"code_window": [
"import angular from 'angular';\n",
"\n",
"export class SoloPanelCtrl {\n",
" /** @ngInject */\n",
" constructor($scope, $routeParams, $location, dashboardLoaderSrv, contextSrv) {\n",
" var panelId;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import appEvents from 'app/core/app_events';\n"
],
"file_path": "public/app/features/panel/solo_panel_ctrl.ts",
"type": "add",
"edit_start_line_idx": 1
} | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !go1.9
package http2
import (
"net/http"
)
func configureServer19(s *http.Server, conf *Server) error {
// not supported prior to go1.9
return nil
}
| vendor/golang.org/x/net/http2/not_go19.go | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.0001810458634281531,
0.00017744238721206784,
0.00017383892554789782,
0.00017744238721206784,
0.000003603468940127641
] |
{
"id": 1,
"code_window": [
" var panelId;\n",
"\n",
" $scope.init = function() {\n",
" contextSrv.sidemenu = false;\n",
"\n",
" var params = $location.search();\n",
" panelId = parseInt(params.panelId);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" appEvents.emit('toggle-sidemenu');\n"
],
"file_path": "public/app/features/panel/solo_panel_ctrl.ts",
"type": "add",
"edit_start_line_idx": 9
} | import angular from 'angular';
export class SoloPanelCtrl {
/** @ngInject */
constructor($scope, $routeParams, $location, dashboardLoaderSrv, contextSrv) {
var panelId;
$scope.init = function() {
contextSrv.sidemenu = false;
var params = $location.search();
panelId = parseInt(params.panelId);
$scope.onAppEvent('dashboard-initialized', $scope.initPanelScope);
dashboardLoaderSrv.loadDashboard($routeParams.type, $routeParams.slug).then(function(result) {
result.meta.soloMode = true;
$scope.initDashboard(result, $scope);
});
};
$scope.initPanelScope = function() {
let panelInfo = $scope.dashboard.getPanelInfoById(panelId);
// fake row ctrl scope
$scope.ctrl = {
dashboard: $scope.dashboard,
};
$scope.panel = panelInfo.panel;
$scope.panel.soloMode = true;
$scope.$index = 0;
if (!$scope.panel) {
$scope.appEvent('alert-error', ['Panel not found', '']);
return;
}
};
$scope.init();
}
}
angular.module('grafana.routes').controller('SoloPanelCtrl', SoloPanelCtrl);
| public/app/features/panel/solo_panel_ctrl.ts | 1 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.9981122016906738,
0.5988298654556274,
0.00017471917090006173,
0.9970834851264954,
0.48859599232673645
] |
{
"id": 1,
"code_window": [
" var panelId;\n",
"\n",
" $scope.init = function() {\n",
" contextSrv.sidemenu = false;\n",
"\n",
" var params = $location.search();\n",
" panelId = parseInt(params.panelId);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" appEvents.emit('toggle-sidemenu');\n"
],
"file_path": "public/app/features/panel/solo_panel_ctrl.ts",
"type": "add",
"edit_start_line_idx": 9
} | import coreModule from 'app/core/core_module';
export class LoadDashboardCtrl {
/** @ngInject */
constructor($scope, $routeParams, dashboardLoaderSrv, backendSrv, $location) {
$scope.appEvent('dashboard-fetch-start');
if (!$routeParams.slug) {
backendSrv.get('/api/dashboards/home').then(function(homeDash) {
if (homeDash.redirectUri) {
$location.path('dashboard/' + homeDash.redirectUri);
} else {
var meta = homeDash.meta;
meta.canSave = meta.canShare = meta.canStar = false;
$scope.initDashboard(homeDash, $scope);
}
});
return;
}
dashboardLoaderSrv.loadDashboard($routeParams.type, $routeParams.slug).then(function(result) {
if ($routeParams.keepRows) {
result.meta.keepRows = true;
}
$scope.initDashboard(result, $scope);
});
}
}
export class NewDashboardCtrl {
/** @ngInject */
constructor($scope, $routeParams) {
$scope.initDashboard(
{
meta: {
canStar: false,
canShare: false,
isNew: true,
folderId: Number($routeParams.folderId),
},
dashboard: {
title: 'New dashboard',
panels: [
{
type: 'add-panel',
gridPos: { x: 0, y: 0, w: 12, h: 9 },
title: 'Panel Title',
},
],
},
},
$scope
);
}
}
coreModule.controller('LoadDashboardCtrl', LoadDashboardCtrl);
coreModule.controller('NewDashboardCtrl', NewDashboardCtrl);
| public/app/routes/dashboard_loaders.ts | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.0013498212210834026,
0.00047430943232029676,
0.00016838248120620847,
0.00026622635778039694,
0.0004172820190433413
] |
{
"id": 1,
"code_window": [
" var panelId;\n",
"\n",
" $scope.init = function() {\n",
" contextSrv.sidemenu = false;\n",
"\n",
" var params = $location.search();\n",
" panelId = parseInt(params.panelId);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" appEvents.emit('toggle-sidemenu');\n"
],
"file_path": "public/app/features/panel/solo_panel_ctrl.ts",
"type": "add",
"edit_start_line_idx": 9
} | package login
import (
"crypto/subtle"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/util"
)
var validatePassword = func(providedPassword string, userPassword string, userSalt string) error {
passwordHashed := util.EncodePassword(providedPassword, userSalt)
if subtle.ConstantTimeCompare([]byte(passwordHashed), []byte(userPassword)) != 1 {
return ErrInvalidCredentials
}
return nil
}
var loginUsingGrafanaDB = func(query *LoginUserQuery) error {
userQuery := m.GetUserByLoginQuery{LoginOrEmail: query.Username}
if err := bus.Dispatch(&userQuery); err != nil {
return err
}
user := userQuery.Result
if err := validatePassword(query.Password, user.Password, user.Salt); err != nil {
return err
}
query.User = user
return nil
}
| pkg/login/grafana_login.go | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00017400659271515906,
0.0001720421714708209,
0.00016710419731680304,
0.00017352892609778792,
0.00000287538409793342
] |
{
"id": 1,
"code_window": [
" var panelId;\n",
"\n",
" $scope.init = function() {\n",
" contextSrv.sidemenu = false;\n",
"\n",
" var params = $location.search();\n",
" panelId = parseInt(params.panelId);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" appEvents.emit('toggle-sidemenu');\n"
],
"file_path": "public/app/features/panel/solo_panel_ctrl.ts",
"type": "add",
"edit_start_line_idx": 9
} | import 'vendor/flot/jquery.flot';
import $ from 'jquery';
import _ from 'lodash';
export class ThresholdManager {
plot: any;
placeholder: any;
height: any;
thresholds: any;
needsCleanup: boolean;
hasSecondYAxis: any;
constructor(private panelCtrl) {}
getHandleHtml(handleIndex, model, valueStr) {
var stateClass = model.colorMode;
if (model.colorMode === 'custom') {
stateClass = 'critical';
}
return `
<div class="alert-handle-wrapper alert-handle-wrapper--T${handleIndex}">
<div class="alert-handle-line alert-handle-line--${stateClass}">
</div>
<div class="alert-handle" data-handle-index="${handleIndex}">
<i class="icon-gf icon-gf-${stateClass} alert-state-${stateClass}"></i>
<span class="alert-handle-value">${valueStr}<i class="alert-handle-grip"></i></span>
</div>
</div>`;
}
initDragging(evt) {
var handleElem = $(evt.currentTarget).parents('.alert-handle-wrapper');
var handleIndex = $(evt.currentTarget).data('handleIndex');
var lastY = null;
var posTop;
var plot = this.plot;
var panelCtrl = this.panelCtrl;
var model = this.thresholds[handleIndex];
function dragging(evt) {
if (lastY === null) {
lastY = evt.clientY;
} else {
var diff = evt.clientY - lastY;
posTop = posTop + diff;
lastY = evt.clientY;
handleElem.css({ top: posTop + diff });
}
}
function stopped() {
// calculate graph level
var graphValue = plot.c2p({ left: 0, top: posTop }).y;
graphValue = parseInt(graphValue.toFixed(0));
model.value = graphValue;
handleElem.off('mousemove', dragging);
handleElem.off('mouseup', dragging);
handleElem.off('mouseleave', dragging);
// trigger digest and render
panelCtrl.$scope.$apply(function() {
panelCtrl.render();
panelCtrl.events.emit('threshold-changed', {
threshold: model,
handleIndex: handleIndex,
});
});
}
lastY = null;
posTop = handleElem.position().top;
handleElem.on('mousemove', dragging);
handleElem.on('mouseup', stopped);
handleElem.on('mouseleave', stopped);
}
cleanUp() {
this.placeholder.find('.alert-handle-wrapper').remove();
this.needsCleanup = false;
}
renderHandle(handleIndex, defaultHandleTopPos) {
var model = this.thresholds[handleIndex];
var value = model.value;
var valueStr = value;
var handleTopPos = 0;
// handle no value
if (!_.isNumber(value)) {
valueStr = '';
handleTopPos = defaultHandleTopPos;
} else {
var valueCanvasPos = this.plot.p2c({ x: 0, y: value });
handleTopPos = Math.round(Math.min(Math.max(valueCanvasPos.top, 0), this.height) - 6);
}
var handleElem = $(this.getHandleHtml(handleIndex, model, valueStr));
this.placeholder.append(handleElem);
handleElem.toggleClass('alert-handle-wrapper--no-value', valueStr === '');
handleElem.css({ top: handleTopPos });
}
shouldDrawHandles() {
return !this.hasSecondYAxis && this.panelCtrl.editingThresholds && this.panelCtrl.panel.thresholds.length > 0;
}
prepare(elem, data) {
this.hasSecondYAxis = false;
for (var i = 0; i < data.length; i++) {
if (data[i].yaxis > 1) {
this.hasSecondYAxis = true;
break;
}
}
if (this.shouldDrawHandles()) {
var thresholdMargin = this.panelCtrl.panel.thresholds.length > 1 ? '220px' : '110px';
elem.css('margin-right', thresholdMargin);
} else if (this.needsCleanup) {
elem.css('margin-right', '0');
}
}
draw(plot) {
this.thresholds = this.panelCtrl.panel.thresholds;
this.plot = plot;
this.placeholder = plot.getPlaceholder();
if (this.needsCleanup) {
this.cleanUp();
}
if (!this.shouldDrawHandles()) {
return;
}
this.height = plot.height();
if (this.thresholds.length > 0) {
this.renderHandle(0, 10);
}
if (this.thresholds.length > 1) {
this.renderHandle(1, this.height - 30);
}
this.placeholder.off('mousedown', '.alert-handle');
this.placeholder.on('mousedown', '.alert-handle', this.initDragging.bind(this));
this.needsCleanup = true;
}
addFlotOptions(options, panel) {
if (!panel.thresholds || panel.thresholds.length === 0) {
return;
}
var gtLimit = Infinity;
var ltLimit = -Infinity;
var i, threshold, other;
for (i = 0; i < panel.thresholds.length; i++) {
threshold = panel.thresholds[i];
if (!_.isNumber(threshold.value)) {
continue;
}
var limit;
switch (threshold.op) {
case 'gt': {
limit = gtLimit;
// if next threshold is less then op and greater value, then use that as limit
if (panel.thresholds.length > i + 1) {
other = panel.thresholds[i + 1];
if (other.value > threshold.value) {
limit = other.value;
ltLimit = limit;
}
}
break;
}
case 'lt': {
limit = ltLimit;
// if next threshold is less then op and greater value, then use that as limit
if (panel.thresholds.length > i + 1) {
other = panel.thresholds[i + 1];
if (other.value < threshold.value) {
limit = other.value;
gtLimit = limit;
}
}
break;
}
}
var fillColor, lineColor;
switch (threshold.colorMode) {
case 'critical': {
fillColor = 'rgba(234, 112, 112, 0.12)';
lineColor = 'rgba(237, 46, 24, 0.60)';
break;
}
case 'warning': {
fillColor = 'rgba(235, 138, 14, 0.12)';
lineColor = 'rgba(247, 149, 32, 0.60)';
break;
}
case 'ok': {
fillColor = 'rgba(11, 237, 50, 0.090)';
lineColor = 'rgba(6,163,69, 0.60)';
break;
}
case 'custom': {
fillColor = threshold.fillColor;
lineColor = threshold.lineColor;
break;
}
}
// fill
if (threshold.fill) {
options.grid.markings.push({
yaxis: { from: threshold.value, to: limit },
color: fillColor,
});
}
if (threshold.line) {
options.grid.markings.push({
yaxis: { from: threshold.value, to: threshold.value },
color: lineColor,
});
}
}
}
}
| public/app/plugins/panel/graph/threshold_manager.ts | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.001911924104206264,
0.00028403973556123674,
0.00016534741735085845,
0.00017617424600757658,
0.00035395659506320953
] |
{
"id": 2,
"code_window": [
"// ---------------------\n",
"\n",
"@include media-breakpoint-down(xs) {\n",
" input[type=\"text\"],\n",
" input[type=\"number\"],\n",
" textarea {\n",
" font-size: 16px;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" input[type='text'],\n",
" input[type='number'],\n"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "replace",
"edit_start_line_idx": 20
} | .navbar-buttons--zoom {
display: none;
}
.navbar-page-btn {
max-width: 200px;
}
.gf-timepicker-nav-btn {
max-width: 120px;
}
.navbar-buttons--actions {
display: none;
}
// Media queries
// ---------------------
@include media-breakpoint-down(xs) {
input[type="text"],
input[type="number"],
textarea {
font-size: 16px;
}
}
@include media-breakpoint-up(sm) {
.navbar-page-btn {
max-width: 250px;
}
.gf-timepicker-nav-btn {
max-width: 200px;
}
}
@include media-breakpoint-up(md) {
.navbar-buttons--actions {
display: flex;
}
.navbar-page-btn {
max-width: 325px;
}
.gf-timepicker-nav-btn {
max-width: 240px;
}
}
@include media-breakpoint-up(lg) {
.navbar-buttons--zoom {
display: flex;
}
.navbar-page-btn {
max-width: none;
}
.gf-timepicker-nav-btn {
max-width: none;
}
}
| public/sass/_old_responsive.scss | 1 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.03585659712553024,
0.008361178450286388,
0.00016534049063920975,
0.0009548442903906107,
0.013001454062759876
] |
{
"id": 2,
"code_window": [
"// ---------------------\n",
"\n",
"@include media-breakpoint-down(xs) {\n",
" input[type=\"text\"],\n",
" input[type=\"number\"],\n",
" textarea {\n",
" font-size: 16px;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" input[type='text'],\n",
" input[type='number'],\n"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "replace",
"edit_start_line_idx": 20
} | // Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2016 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Package ptypes contains code for interacting with well-known types.
*/
package ptypes
| vendor/github.com/golang/protobuf/ptypes/doc.go | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00017555698286741972,
0.00017306978406850249,
0.00016895584121812135,
0.00017388314881827682,
0.0000025977649329433916
] |
{
"id": 2,
"code_window": [
"// ---------------------\n",
"\n",
"@include media-breakpoint-down(xs) {\n",
" input[type=\"text\"],\n",
" input[type=\"number\"],\n",
" textarea {\n",
" font-size: 16px;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" input[type='text'],\n",
" input[type='number'],\n"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "replace",
"edit_start_line_idx": 20
} | export class AnnotationEvent {
dashboardId: number;
panelId: number;
userId: number;
time: any;
timeEnd: any;
isRegion: boolean;
text: string;
type: string;
tags: string;
}
| public/app/features/annotations/event.ts | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00017972580099012703,
0.0001717637642286718,
0.00016380172746721655,
0.0001717637642286718,
0.000007962036761455238
] |
{
"id": 2,
"code_window": [
"// ---------------------\n",
"\n",
"@include media-breakpoint-down(xs) {\n",
" input[type=\"text\"],\n",
" input[type=\"number\"],\n",
" textarea {\n",
" font-size: 16px;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" input[type='text'],\n",
" input[type='number'],\n"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "replace",
"edit_start_line_idx": 20
} | <page-header model="navModel"></page-header>
<div class="page-container page-body">
<div class="signup">
<h3 class="p-b-1">Reset password</h3>
<form name="sendResetForm" class="login-form gf-form-group" ng-show="mode === 'send'">
<div class="gf-form">
<span class="gf-form-label width-7">User</span>
<input type="text" name="username" class="gf-form-input max-width-14" required ng-model='formModel.userOrEmail' placeholder="email or username">
</div>
<div class="gf-form-button-row">
<button type="submit" class="btn btn-success" ng-click="sendResetEmail();" ng-disabled="!sendResetForm.$valid">
Reset Password
</button>
<a href="login" class="btn btn-inverse">
Back
</a>
</div>
</form>
<div ng-if="mode === 'email-sent'">
An email with a reset link as been sent to the email address. <br>
You should receive it shortly.
<div class="p-t-1">
<a href="login" class="btn btn-success p-t-1">
Login
</a>
</div>
</div>
</div>
</div>
| public/app/partials/reset_password.html | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00017719180323183537,
0.00017141099669970572,
0.0001683603331912309,
0.00017004593973979354,
0.0000035264140478830086
] |
{
"id": 3,
"code_window": [
" .navbar-buttons--zoom {\n",
" display: flex;\n",
" }\n",
" .navbar-page-btn {\n",
" max-width: none;\n",
" }\n",
" .gf-timepicker-nav-btn {\n",
" max-width: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" max-width: 450px;\n"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "replace",
"edit_start_line_idx": 53
} | .navbar-buttons--zoom {
display: none;
}
.navbar-page-btn {
max-width: 200px;
}
.gf-timepicker-nav-btn {
max-width: 120px;
}
.navbar-buttons--actions {
display: none;
}
// Media queries
// ---------------------
@include media-breakpoint-down(xs) {
input[type="text"],
input[type="number"],
textarea {
font-size: 16px;
}
}
@include media-breakpoint-up(sm) {
.navbar-page-btn {
max-width: 250px;
}
.gf-timepicker-nav-btn {
max-width: 200px;
}
}
@include media-breakpoint-up(md) {
.navbar-buttons--actions {
display: flex;
}
.navbar-page-btn {
max-width: 325px;
}
.gf-timepicker-nav-btn {
max-width: 240px;
}
}
@include media-breakpoint-up(lg) {
.navbar-buttons--zoom {
display: flex;
}
.navbar-page-btn {
max-width: none;
}
.gf-timepicker-nav-btn {
max-width: none;
}
}
| public/sass/_old_responsive.scss | 1 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.7199174761772156,
0.16700245440006256,
0.002275198232382536,
0.07094091922044754,
0.2487471103668213
] |
{
"id": 3,
"code_window": [
" .navbar-buttons--zoom {\n",
" display: flex;\n",
" }\n",
" .navbar-page-btn {\n",
" max-width: none;\n",
" }\n",
" .gf-timepicker-nav-btn {\n",
" max-width: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" max-width: 450px;\n"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "replace",
"edit_start_line_idx": 53
} | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package flate
import "fmt"
const (
// 2 bits: type 0 = literal 1=EOF 2=Match 3=Unused
// 8 bits: xlength = length - MIN_MATCH_LENGTH
// 22 bits xoffset = offset - MIN_OFFSET_SIZE, or literal
lengthShift = 22
offsetMask = 1<<lengthShift - 1
typeMask = 3 << 30
literalType = 0 << 30
matchType = 1 << 30
)
// The length code for length X (MIN_MATCH_LENGTH <= X <= MAX_MATCH_LENGTH)
// is lengthCodes[length - MIN_MATCH_LENGTH]
var lengthCodes = [...]uint32{
0, 1, 2, 3, 4, 5, 6, 7, 8, 8,
9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15,
15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18,
18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 28,
}
var offsetCodes = [...]uint32{
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,
8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
}
type token uint32
type tokens struct {
tokens [maxStoreBlockSize + 1]token
n uint16 // Must be able to contain maxStoreBlockSize
}
// Convert a literal into a literal token.
func literalToken(literal uint32) token { return token(literalType + literal) }
// Convert a < xlength, xoffset > pair into a match token.
func matchToken(xlength uint32, xoffset uint32) token {
return token(matchType + xlength<<lengthShift + xoffset)
}
func matchTokend(xlength uint32, xoffset uint32) token {
if xlength > maxMatchLength || xoffset > maxMatchOffset {
panic(fmt.Sprintf("Invalid match: len: %d, offset: %d\n", xlength, xoffset))
return token(matchType)
}
return token(matchType + xlength<<lengthShift + xoffset)
}
// Returns the type of a token
func (t token) typ() uint32 { return uint32(t) & typeMask }
// Returns the literal of a literal token
func (t token) literal() uint32 { return uint32(t - literalType) }
// Returns the extra offset of a match token
func (t token) offset() uint32 { return uint32(t) & offsetMask }
func (t token) length() uint32 { return uint32((t - matchType) >> lengthShift) }
func lengthCode(len uint32) uint32 { return lengthCodes[len] }
// Returns the offset code corresponding to a specific offset
func offsetCode(off uint32) uint32 {
if off < uint32(len(offsetCodes)) {
return offsetCodes[off]
} else if off>>7 < uint32(len(offsetCodes)) {
return offsetCodes[off>>7] + 14
} else {
return offsetCodes[off>>14] + 28
}
}
| vendor/github.com/klauspost/compress/flate/token.go | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.0001754508848534897,
0.00016959306958597153,
0.00016091701400000602,
0.00017136585665866733,
0.000005025529844715493
] |
{
"id": 3,
"code_window": [
" .navbar-buttons--zoom {\n",
" display: flex;\n",
" }\n",
" .navbar-page-btn {\n",
" max-width: none;\n",
" }\n",
" .gf-timepicker-nav-btn {\n",
" max-width: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" max-width: 450px;\n"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "replace",
"edit_start_line_idx": 53
} | page_title: Search the Grafana documentation
page_keywords: Grafana, search documentation
no_toc: true
no_version_dropdown: true
# Search
<form id="content_search" action="/jsearch/">
<span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
<input name="q" id="tipue_search_input" type="text" class="search_input search-query ui-autocomplete-input" placeholder="Search the Docs" autocomplete="off">
</form>
<div id="tipue_search_content">
Sorry, page not found.
</div>
| docs/sources/jsearch.md | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00016525363025721163,
0.00016400401364080608,
0.00016275439702440053,
0.00016400401364080608,
0.0000012496166164055467
] |
{
"id": 3,
"code_window": [
" .navbar-buttons--zoom {\n",
" display: flex;\n",
" }\n",
" .navbar-page-btn {\n",
" max-width: none;\n",
" }\n",
" .gf-timepicker-nav-btn {\n",
" max-width: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" max-width: 450px;\n"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "replace",
"edit_start_line_idx": 53
} | Mozilla Public License, version 2.0
1. Definitions
1.1. "Contributor"
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. "Incompatible With Secondary Licenses"
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the terms of
a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in a
separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible, whether
at the time of the initial grant or subsequently, any and all of the
rights conveyed by this License.
1.10. "Modifications"
means any of the following:
a. any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the License,
by the making, using, selling, offering for sale, having made, import,
or transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights to
grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter the
recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, or
limitations of liability) contained within the Source Code Form of the
Covered Software, except that You may alter any license notices to the
extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute,
judicial order, or regulation then You must: (a) comply with the terms of
this License to the maximum extent possible; and (b) describe the
limitations and the code they affect. Such description must be placed in a
text file included with all distributions of the Covered Software under
this License. Except to the extent prohibited by statute or regulation,
such description must be sufficiently detailed for a recipient of ordinary
skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing
basis, if such Contributor fails to notify You of the non-compliance by
some reasonable means prior to 60 days after You have come back into
compliance. Moreover, Your grants from a particular Contributor are
reinstated on an ongoing basis if such Contributor notifies You of the
non-compliance by some reasonable means, this is the first time You have
received notice of non-compliance with this License from such
Contributor, and You become compliant prior to 30 days after Your receipt
of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an "as is" basis,
without warranty of any kind, either expressed, implied, or statutory,
including, without limitation, warranties that the Covered Software is free
of defects, merchantable, fit for a particular purpose or non-infringing.
The entire risk as to the quality and performance of the Covered Software
is with You. Should any Covered Software prove defective in any respect,
You (not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an essential
part of this License. No use of any Covered Software is authorized under
this License except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from
such party's negligence to the extent applicable law prohibits such
limitation. Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and limitation may
not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts
of a jurisdiction where the defendant maintains its principal place of
business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions. Nothing
in this Section shall prevent a party's ability to bring cross-claims or
counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides that
the language of a contract shall be construed against the drafter shall not
be used to construe this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses If You choose to distribute Source Code Form that is
Incompatible With Secondary Licenses under the terms of this version of
the License, the notice described in Exhibit B of this License must be
attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file,
then You may include the notice in a location (such as a LICENSE file in a
relevant directory) where a recipient would be likely to look for such a
notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible
With Secondary Licenses", as defined by
the Mozilla Public License, v. 2.0. | vendor/github.com/hashicorp/yamux/LICENSE | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00017911777831614017,
0.00017547332390677184,
0.00016792841779533774,
0.00017562595894560218,
0.0000021108787677803775
] |
{
"id": 4,
"code_window": [
" .gf-timepicker-nav-btn {\n",
" max-width: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"@include media-breakpoint-up(xl) {\n",
" .navbar-page-btn {\n",
" max-width: 600px;\n",
" }\n",
"}"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "add",
"edit_start_line_idx": 59
} | .navbar-buttons--zoom {
display: none;
}
.navbar-page-btn {
max-width: 200px;
}
.gf-timepicker-nav-btn {
max-width: 120px;
}
.navbar-buttons--actions {
display: none;
}
// Media queries
// ---------------------
@include media-breakpoint-down(xs) {
input[type="text"],
input[type="number"],
textarea {
font-size: 16px;
}
}
@include media-breakpoint-up(sm) {
.navbar-page-btn {
max-width: 250px;
}
.gf-timepicker-nav-btn {
max-width: 200px;
}
}
@include media-breakpoint-up(md) {
.navbar-buttons--actions {
display: flex;
}
.navbar-page-btn {
max-width: 325px;
}
.gf-timepicker-nav-btn {
max-width: 240px;
}
}
@include media-breakpoint-up(lg) {
.navbar-buttons--zoom {
display: flex;
}
.navbar-page-btn {
max-width: none;
}
.gf-timepicker-nav-btn {
max-width: none;
}
}
| public/sass/_old_responsive.scss | 1 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.9857221841812134,
0.32171431183815,
0.0004636447411030531,
0.128444105386734,
0.36902815103530884
] |
{
"id": 4,
"code_window": [
" .gf-timepicker-nav-btn {\n",
" max-width: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"@include media-breakpoint-up(xl) {\n",
" .navbar-page-btn {\n",
" max-width: 600px;\n",
" }\n",
"}"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "add",
"edit_start_line_idx": 59
} | Listen 10081 | docker/blocks/apache_proxy/ports.conf | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00017393642337992787,
0.00017393642337992787,
0.00017393642337992787,
0.00017393642337992787,
0
] |
{
"id": 4,
"code_window": [
" .gf-timepicker-nav-btn {\n",
" max-width: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"@include media-breakpoint-up(xl) {\n",
" .navbar-page-btn {\n",
" max-width: 600px;\n",
" }\n",
"}"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "add",
"edit_start_line_idx": 59
} | -timeout=20s
| pkg/services/sqlstore/sqlstore.goconvey | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00017212422972079366,
0.00017212422972079366,
0.00017212422972079366,
0.00017212422972079366,
0
] |
{
"id": 4,
"code_window": [
" .gf-timepicker-nav-btn {\n",
" max-width: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"@include media-breakpoint-up(xl) {\n",
" .navbar-page-btn {\n",
" max-width: 600px;\n",
" }\n",
"}"
],
"file_path": "public/sass/_old_responsive.scss",
"type": "add",
"edit_start_line_idx": 59
} | Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.
| vendor/golang.org/x/sync/PATENTS | 0 | https://github.com/grafana/grafana/commit/d08a829b690a714573351e35710a21a3c4f4d6aa | [
0.00017798850603867322,
0.00017517378728371114,
0.00017331891285721213,
0.00017421394295524806,
0.000002023569550146931
] |
{
"id": 0,
"code_window": [
"from flask_jwt_extended.exceptions import NoAuthorizationError\n",
"from flask_wtf.csrf import CSRFError\n",
"from flask_wtf.form import FlaskForm\n",
"from pkg_resources import resource_filename\n",
"from sqlalchemy import or_\n",
"from sqlalchemy.orm import Query\n",
"from werkzeug.exceptions import HTTPException\n",
"from wtforms import Form\n",
"from wtforms.fields.core import Field, UnboundField\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"from sqlalchemy import exc, or_\n"
],
"file_path": "superset/views/base.py",
"type": "replace",
"edit_start_line_idx": 47
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import functools
import logging
from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type, Union
from flask import Blueprint, g, request, Response
from flask_appbuilder import AppBuilder, Model, ModelRestApi
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.filters import BaseFilter, Filters
from flask_appbuilder.models.sqla.filters import FilterStartsWith
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import lazy_gettext as _
from marshmallow import fields, Schema
from sqlalchemy import and_, distinct, func
from sqlalchemy.orm.query import Query
from superset.exceptions import InvalidPayloadFormatError
from superset.extensions import db, event_logger, security_manager
from superset.models.core import FavStar
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice
from superset.schemas import error_payload_content
from superset.sql_lab import Query as SqllabQuery
from superset.stats_logger import BaseStatsLogger
from superset.superset_typing import FlaskResponse
from superset.utils.core import time_function
logger = logging.getLogger(__name__)
get_related_schema = {
"type": "object",
"properties": {
"page_size": {"type": "integer"},
"page": {"type": "integer"},
"include_ids": {"type": "array", "items": {"type": "integer"}},
"filter": {"type": "string"},
},
}
class RelatedResultResponseSchema(Schema):
value = fields.Integer(description="The related item identifier")
text = fields.String(description="The related item string representation")
class RelatedResponseSchema(Schema):
count = fields.Integer(description="The total number of related values")
result = fields.List(fields.Nested(RelatedResultResponseSchema))
class DistinctResultResponseSchema(Schema):
text = fields.String(description="The distinct item")
class DistincResponseSchema(Schema):
count = fields.Integer(description="The total number of distinct values")
result = fields.List(fields.Nested(DistinctResultResponseSchema))
def requires_json(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require JSON-like formatted request to the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.is_json:
raise InvalidPayloadFormatError(message="Request is not JSON")
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def requires_form_data(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require 'multipart/form-data' as request MIME type
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.mimetype == "multipart/form-data":
raise InvalidPayloadFormatError(
message="Request MIME type is not 'multipart/form-data'"
)
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def statsd_metrics(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Handle sending all statsd metrics from the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
try:
duration, response = time_function(f, self, *args, **kwargs)
except Exception as ex:
self.incr_stats("error", f.__name__)
raise ex
self.send_stats_metrics(response, f.__name__, duration)
return response
return functools.update_wrapper(wraps, f)
class RelatedFieldFilter:
# data class to specify what filter to use on a /related endpoint
# pylint: disable=too-few-public-methods
def __init__(self, field_name: str, filter_class: Type[BaseFilter]):
self.field_name = field_name
self.filter_class = filter_class
class BaseFavoriteFilter(BaseFilter): # pylint: disable=too-few-public-methods
"""
Base Custom filter for the GET list that filters all dashboards, slices
that a user has favored or not
"""
name = _("Is favorite")
arg_name = ""
class_name = ""
""" The FavStar class_name to user """
model: Type[Union[Dashboard, Slice, SqllabQuery]] = Dashboard
""" The SQLAlchemy model """
def apply(self, query: Query, value: Any) -> Query:
# If anonymous user filter nothing
if security_manager.current_user is None:
return query
users_favorite_query = db.session.query(FavStar.obj_id).filter(
and_(
FavStar.user_id == g.user.get_id(),
FavStar.class_name == self.class_name,
)
)
if value:
return query.filter(and_(self.model.id.in_(users_favorite_query)))
return query.filter(and_(~self.model.id.in_(users_favorite_query)))
class BaseSupersetModelRestApi(ModelRestApi):
"""
Extends FAB's ModelResApi to implement specific superset generic functionality
"""
csrf_exempt = False
method_permission_name = {
"bulk_delete": "delete",
"data": "list",
"data_from_cache": "list",
"delete": "delete",
"distinct": "list",
"export": "mulexport",
"import_": "add",
"get": "show",
"get_list": "list",
"info": "list",
"post": "add",
"put": "edit",
"refresh": "edit",
"related": "list",
"related_objects": "list",
"schemas": "list",
"select_star": "list",
"table_metadata": "list",
"test_connection": "post",
"thumbnail": "list",
"viz_types": "list",
}
order_rel_fields: Dict[str, Tuple[str, str]] = {}
"""
Impose ordering on related fields query::
order_rel_fields = {
"<RELATED_FIELD>": ("<RELATED_FIELD_FIELD>", "<asc|desc>"),
...
}
"""
related_field_filters: Dict[str, Union[RelatedFieldFilter, str]] = {}
"""
Declare the filters for related fields::
related_fields = {
"<RELATED_FIELD>": <RelatedFieldFilter>)
}
"""
filter_rel_fields: Dict[str, BaseFilter] = {}
"""
Declare the related field base filter::
filter_rel_fields_field = {
"<RELATED_FIELD>": "<FILTER>")
}
"""
allowed_rel_fields: Set[str] = set()
# Declare a set of allowed related fields that the `related` endpoint supports.
text_field_rel_fields: Dict[str, str] = {}
"""
Declare an alternative for the human readable representation of the Model object::
text_field_rel_fields = {
"<RELATED_FIELD>": "<RELATED_OBJECT_FIELD>"
}
"""
allowed_distinct_fields: Set[str] = set()
add_columns: List[str]
edit_columns: List[str]
list_columns: List[str]
show_columns: List[str]
responses = {
"400": {"description": "Bad request", "content": error_payload_content},
"401": {"description": "Unauthorized", "content": error_payload_content},
"403": {"description": "Forbidden", "content": error_payload_content},
"404": {"description": "Not found", "content": error_payload_content},
"422": {
"description": "Could not process entity",
"content": error_payload_content,
},
"500": {"description": "Fatal error", "content": error_payload_content},
}
def __init__(self) -> None:
super().__init__()
# Setup statsd
self.stats_logger = BaseStatsLogger()
# Add base API spec base query parameter schemas
if self.apispec_parameter_schemas is None: # type: ignore
self.apispec_parameter_schemas = {}
self.apispec_parameter_schemas["get_related_schema"] = get_related_schema
self.openapi_spec_component_schemas: Tuple[
Type[Schema], ...
] = self.openapi_spec_component_schemas + (
RelatedResponseSchema,
DistincResponseSchema,
)
def create_blueprint(
self, appbuilder: AppBuilder, *args: Any, **kwargs: Any
) -> Blueprint:
self.stats_logger = self.appbuilder.get_app.config["STATS_LOGGER"]
return super().create_blueprint(appbuilder, *args, **kwargs)
def _init_properties(self) -> None:
"""
Lock down initial not configured REST API columns. We want to just expose
model ids, if something is misconfigured. By default FAB exposes all available
columns on a Model
"""
model_id = self.datamodel.get_pk_name()
if self.list_columns is None and not self.list_model_schema:
self.list_columns = [model_id]
if self.show_columns is None and not self.show_model_schema:
self.show_columns = [model_id]
if self.edit_columns is None and not self.edit_model_schema:
self.edit_columns = [model_id]
if self.add_columns is None and not self.add_model_schema:
self.add_columns = [model_id]
super()._init_properties()
def _get_related_filter(
self, datamodel: SQLAInterface, column_name: str, value: str
) -> Filters:
filter_field = self.related_field_filters.get(column_name)
if isinstance(filter_field, str):
filter_field = RelatedFieldFilter(cast(str, filter_field), FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = datamodel.get_filters(search_columns)
base_filters = self.filter_rel_fields.get(column_name)
if base_filters:
filters.add_filter_list(base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_distinct_filter(self, column_name: str, value: str) -> Filters:
filter_field = RelatedFieldFilter(column_name, FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = self.datamodel.get_filters(search_columns)
filters.add_filter_list(self.base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_text_for_model(self, model: Model, column_name: str) -> str:
if column_name in self.text_field_rel_fields:
model_column_name = self.text_field_rel_fields.get(column_name)
if model_column_name:
return getattr(model, model_column_name)
return str(model)
def _get_result_from_rows(
self, datamodel: SQLAInterface, rows: List[Model], column_name: str
) -> List[Dict[str, Any]]:
return [
{
"value": datamodel.get_pk_value(row),
"text": self._get_text_for_model(row, column_name),
}
for row in rows
]
def _add_extra_ids_to_result(
self,
datamodel: SQLAInterface,
column_name: str,
ids: List[int],
result: List[Dict[str, Any]],
) -> None:
if ids:
# Filter out already present values on the result
values = [row["value"] for row in result]
ids = [id_ for id_ in ids if id_ not in values]
pk_col = datamodel.get_pk()
# Fetch requested values from ids
extra_rows = db.session.query(datamodel.obj).filter(pk_col.in_(ids)).all()
result += self._get_result_from_rows(datamodel, extra_rows, column_name)
def incr_stats(self, action: str, func_name: str) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
"""
self.stats_logger.incr(f"{self.__class__.__name__}.{func_name}.{action}")
def timing_stats(self, action: str, func_name: str, value: float) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
:param value: A float with the time it took for the endpoint to execute
"""
self.stats_logger.timing(
f"{self.__class__.__name__}.{func_name}.{action}", value
)
def send_stats_metrics(
self, response: Response, key: str, time_delta: Optional[float] = None
) -> None:
"""
Helper function to handle sending statsd metrics
:param response: flask response object, will evaluate if it was an error
:param key: The function name
:param time_delta: Optional time it took for the endpoint to execute
"""
if 200 <= response.status_code < 400:
self.incr_stats("success", key)
else:
self.incr_stats("error", key)
if time_delta:
self.timing_stats("time", key, time_delta)
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.info",
object_ref=False,
log_to_statsd=False,
)
def info_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB _info endpoint
"""
duration, response = time_function(super().info_headless, **kwargs)
self.send_stats_metrics(response, self.info.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get",
object_ref=False,
log_to_statsd=False,
)
def get_headless(self, pk: int, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET endpoint
"""
duration, response = time_function(super().get_headless, pk, **kwargs)
self.send_stats_metrics(response, self.get.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_list",
object_ref=False,
log_to_statsd=False,
)
def get_list_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET list endpoint
"""
duration, response = time_function(super().get_list_headless, **kwargs)
self.send_stats_metrics(response, self.get_list.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
object_ref=False,
log_to_statsd=False,
)
def post_headless(self) -> Response:
"""
Add statsd metrics to builtin FAB POST endpoint
"""
duration, response = time_function(super().post_headless)
self.send_stats_metrics(response, self.post.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put",
object_ref=False,
log_to_statsd=False,
)
def put_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB PUT endpoint
"""
duration, response = time_function(super().put_headless, pk)
self.send_stats_metrics(response, self.put.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete",
object_ref=False,
log_to_statsd=False,
)
def delete_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB DELETE endpoint
"""
duration, response = time_function(super().delete_headless, pk)
self.send_stats_metrics(response, self.delete.__name__, duration)
return response
@expose("/related/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def related(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get related fields data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Related column data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/RelatedResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_rel_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._handle_page_args(args)
ids = args.get("include_ids")
if page and ids:
# pagination with forced ids is not supported
return self.response_422()
try:
datamodel = self.datamodel.get_related_interface(column_name)
except KeyError:
return self.response_404()
page, page_size = self._sanitize_page_args(page, page_size)
# handle ordering
order_field = self.order_rel_fields.get(column_name)
if order_field:
order_column, order_direction = order_field
else:
order_column, order_direction = "", ""
# handle filters
filters = self._get_related_filter(datamodel, column_name, args.get("filter"))
# Make the query
total_rows, rows = datamodel.query(
filters, order_column, order_direction, page=page, page_size=page_size
)
# produce response
result = self._get_result_from_rows(datamodel, rows, column_name)
# If ids are specified make sure we fetch and include them on the response
if ids:
self._add_extra_ids_to_result(datamodel, column_name, ids, result)
total_rows = len(result)
return self.response(200, count=total_rows, result=result)
@expose("/distinct/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get distinct values from field data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Distinct field data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/DistincResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_distinct_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._sanitize_page_args(*self._handle_page_args(args))
# Create generic base filters with added request filter
filters = self._get_distinct_filter(column_name, args.get("filter"))
# Make the query
query_count = self.appbuilder.get_session.query(
func.count(distinct(getattr(self.datamodel.obj, column_name)))
)
count = self.datamodel.apply_filters(query_count, filters).scalar()
if count == 0:
return self.response(200, count=count, result=[])
query = self.appbuilder.get_session.query(
distinct(getattr(self.datamodel.obj, column_name))
)
# Apply generic base filters with added request filter
query = self.datamodel.apply_filters(query, filters)
# Apply sort
query = self.datamodel.apply_order_by(query, column_name, "asc")
# Apply pagination
result = self.datamodel.apply_pagination(query, page, page_size).all()
# produce response
result = [
{"text": item[0], "value": item[0]}
for item in result
if item[0] is not None
]
return self.response(200, count=count, result=result)
| superset/views/base_api.py | 1 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0007966369157657027,
0.00018940614245366305,
0.00016321861767210066,
0.00017157645197585225,
0.0000852729135658592
] |
{
"id": 0,
"code_window": [
"from flask_jwt_extended.exceptions import NoAuthorizationError\n",
"from flask_wtf.csrf import CSRFError\n",
"from flask_wtf.form import FlaskForm\n",
"from pkg_resources import resource_filename\n",
"from sqlalchemy import or_\n",
"from sqlalchemy.orm import Query\n",
"from werkzeug.exceptions import HTTPException\n",
"from wtforms import Form\n",
"from wtforms.fields.core import Field, UnboundField\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"from sqlalchemy import exc, or_\n"
],
"file_path": "superset/views/base.py",
"type": "replace",
"edit_start_line_idx": 47
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
| tests/integration_tests/cachekeys/__init__.py | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0001759147271513939,
0.0001753755350364372,
0.00017483634292148054,
0.0001753755350364372,
5.39192114956677e-7
] |
{
"id": 0,
"code_window": [
"from flask_jwt_extended.exceptions import NoAuthorizationError\n",
"from flask_wtf.csrf import CSRFError\n",
"from flask_wtf.form import FlaskForm\n",
"from pkg_resources import resource_filename\n",
"from sqlalchemy import or_\n",
"from sqlalchemy.orm import Query\n",
"from werkzeug.exceptions import HTTPException\n",
"from wtforms import Form\n",
"from wtforms.fields.core import Field, UnboundField\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"from sqlalchemy import exc, or_\n"
],
"file_path": "superset/views/base.py",
"type": "replace",
"edit_start_line_idx": 47
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from textwrap import dedent
from unittest import mock
from sqlalchemy import column, literal_column
from sqlalchemy.dialects import postgresql
from superset.db_engine_specs import get_engine_specs
from superset.db_engine_specs.postgres import PostgresEngineSpec
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.models.sql_lab import Query
from superset.utils.core import GenericDataType
from tests.integration_tests.db_engine_specs.base_tests import (
assert_generic_types,
TestDbEngineSpec,
)
from tests.integration_tests.fixtures.certificates import ssl_certificate
from tests.integration_tests.fixtures.database import default_db_extra
class TestPostgresDbEngineSpec(TestDbEngineSpec):
def test_get_table_names(self):
"""
DB Eng Specs (postgres): Test get table names
"""
""" Make sure postgres doesn't try to remove schema name from table name
ie. when try_remove_schema_from_table_name == False. """
inspector = mock.Mock()
inspector.get_table_names = mock.Mock(return_value=["schema.table", "table_2"])
inspector.get_foreign_table_names = mock.Mock(return_value=["table_3"])
pg_result_expected = ["schema.table", "table_2", "table_3"]
pg_result = PostgresEngineSpec.get_table_names(
database=mock.ANY, schema="schema", inspector=inspector
)
self.assertListEqual(pg_result_expected, pg_result)
def test_time_exp_literal_no_grain(self):
"""
DB Eng Specs (postgres): Test no grain literal column
"""
col = literal_column("COALESCE(a, b)")
expr = PostgresEngineSpec.get_timestamp_expr(col, None, None)
result = str(expr.compile(None, dialect=postgresql.dialect()))
self.assertEqual(result, "COALESCE(a, b)")
def test_time_exp_literal_1y_grain(self):
"""
DB Eng Specs (postgres): Test grain literal column 1 YEAR
"""
col = literal_column("COALESCE(a, b)")
expr = PostgresEngineSpec.get_timestamp_expr(col, None, "P1Y")
result = str(expr.compile(None, dialect=postgresql.dialect()))
self.assertEqual(result, "DATE_TRUNC('year', COALESCE(a, b))")
def test_time_ex_lowr_col_no_grain(self):
"""
DB Eng Specs (postgres): Test no grain expr lower case
"""
col = column("lower_case")
expr = PostgresEngineSpec.get_timestamp_expr(col, None, None)
result = str(expr.compile(None, dialect=postgresql.dialect()))
self.assertEqual(result, "lower_case")
def test_time_exp_lowr_col_sec_1y(self):
"""
DB Eng Specs (postgres): Test grain expr lower case 1 YEAR
"""
col = column("lower_case")
expr = PostgresEngineSpec.get_timestamp_expr(col, "epoch_s", "P1Y")
result = str(expr.compile(None, dialect=postgresql.dialect()))
self.assertEqual(
result,
"DATE_TRUNC('year', "
"(timestamp 'epoch' + lower_case * interval '1 second'))",
)
def test_time_exp_mixd_case_col_1y(self):
"""
DB Eng Specs (postgres): Test grain expr mixed case 1 YEAR
"""
col = column("MixedCase")
expr = PostgresEngineSpec.get_timestamp_expr(col, None, "P1Y")
result = str(expr.compile(None, dialect=postgresql.dialect()))
self.assertEqual(result, "DATE_TRUNC('year', \"MixedCase\")")
def test_convert_dttm(self):
"""
DB Eng Specs (postgres): Test conversion to date time
"""
dttm = self.get_dttm()
self.assertEqual(
PostgresEngineSpec.convert_dttm("DATE", dttm),
"TO_DATE('2019-01-02', 'YYYY-MM-DD')",
)
self.assertEqual(
PostgresEngineSpec.convert_dttm("TIMESTAMP", dttm),
"TO_TIMESTAMP('2019-01-02 03:04:05.678900', 'YYYY-MM-DD HH24:MI:SS.US')",
)
self.assertEqual(
PostgresEngineSpec.convert_dttm("DATETIME", dttm),
"TO_TIMESTAMP('2019-01-02 03:04:05.678900', 'YYYY-MM-DD HH24:MI:SS.US')",
)
self.assertEqual(PostgresEngineSpec.convert_dttm("TIME", dttm), None)
def test_empty_dbapi_cursor_description(self):
"""
DB Eng Specs (postgres): Test empty cursor description (no columns)
"""
cursor = mock.Mock()
# empty description mean no columns, this mocks the following SQL: "SELECT"
cursor.description = []
results = PostgresEngineSpec.fetch_data(cursor, 1000)
self.assertEqual(results, [])
def test_engine_alias_name(self):
"""
DB Eng Specs (postgres): Test "postgres" in engine spec
"""
self.assertIn("postgres", get_engine_specs())
def test_extras_without_ssl(self):
db = mock.Mock()
db.extra = default_db_extra
db.server_cert = None
extras = PostgresEngineSpec.get_extra_params(db)
assert "connect_args" not in extras["engine_params"]
def test_extras_with_ssl_default(self):
db = mock.Mock()
db.extra = default_db_extra
db.server_cert = ssl_certificate
extras = PostgresEngineSpec.get_extra_params(db)
connect_args = extras["engine_params"]["connect_args"]
assert connect_args["sslmode"] == "verify-full"
assert "sslrootcert" in connect_args
def test_extras_with_ssl_custom(self):
db = mock.Mock()
db.extra = default_db_extra.replace(
'"engine_params": {}',
'"engine_params": {"connect_args": {"sslmode": "verify-ca"}}',
)
db.server_cert = ssl_certificate
extras = PostgresEngineSpec.get_extra_params(db)
connect_args = extras["engine_params"]["connect_args"]
assert connect_args["sslmode"] == "verify-ca"
assert "sslrootcert" in connect_args
def test_estimate_statement_cost_select_star(self):
"""
DB Eng Specs (postgres): Test estimate_statement_cost select star
"""
cursor = mock.Mock()
cursor.fetchone.return_value = (
"Seq Scan on birth_names (cost=0.00..1537.91 rows=75691 width=46)",
)
sql = "SELECT * FROM birth_names"
results = PostgresEngineSpec.estimate_statement_cost(sql, cursor)
self.assertEqual(
results,
{
"Start-up cost": 0.00,
"Total cost": 1537.91,
},
)
def test_estimate_statement_invalid_syntax(self):
"""
DB Eng Specs (postgres): Test estimate_statement_cost invalid syntax
"""
from psycopg2 import errors
cursor = mock.Mock()
cursor.execute.side_effect = errors.SyntaxError(
"""
syntax error at or near "EXPLAIN"
LINE 1: EXPLAIN DROP TABLE birth_names
^
"""
)
sql = "DROP TABLE birth_names"
with self.assertRaises(errors.SyntaxError):
PostgresEngineSpec.estimate_statement_cost(sql, cursor)
def test_query_cost_formatter_example_costs(self):
"""
DB Eng Specs (postgres): Test test_query_cost_formatter example costs
"""
raw_cost = [
{
"Start-up cost": 0.00,
"Total cost": 1537.91,
},
{
"Start-up cost": 10.00,
"Total cost": 1537.00,
},
]
result = PostgresEngineSpec.query_cost_formatter(raw_cost)
self.assertEqual(
result,
[
{
"Start-up cost": "0.0",
"Total cost": "1537.91",
},
{
"Start-up cost": "10.0",
"Total cost": "1537.0",
},
],
)
def test_extract_errors(self):
"""
Test that custom error messages are extracted correctly.
"""
msg = 'psql: error: FATAL: role "testuser" does not exist'
result = PostgresEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
error_type=SupersetErrorType.CONNECTION_INVALID_USERNAME_ERROR,
message='The username "testuser" does not exist.',
level=ErrorLevel.ERROR,
extra={
"engine_name": "PostgreSQL",
"issue_codes": [
{
"code": 1012,
"message": (
"Issue 1012 - The username provided when "
"connecting to a database is not valid."
),
},
],
"invalid": ["username"],
},
)
]
msg = (
'psql: error: could not translate host name "locahost" to address: '
"nodename nor servname provided, or not known"
)
result = PostgresEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
error_type=SupersetErrorType.CONNECTION_INVALID_HOSTNAME_ERROR,
message='The hostname "locahost" cannot be resolved.',
level=ErrorLevel.ERROR,
extra={
"engine_name": "PostgreSQL",
"issue_codes": [
{
"code": 1007,
"message": "Issue 1007 - The hostname provided "
"can't be resolved.",
}
],
"invalid": ["host"],
},
)
]
msg = dedent(
"""
psql: error: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 12345?
could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 12345?
"""
)
result = PostgresEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
error_type=SupersetErrorType.CONNECTION_PORT_CLOSED_ERROR,
message='Port 12345 on hostname "localhost" refused the connection.',
level=ErrorLevel.ERROR,
extra={
"engine_name": "PostgreSQL",
"issue_codes": [
{"code": 1008, "message": "Issue 1008 - The port is closed."}
],
"invalid": ["host", "port"],
},
)
]
msg = dedent(
"""
psql: error: could not connect to server: Operation timed out
Is the server running on host "example.com" (93.184.216.34) and accepting
TCP/IP connections on port 12345?
"""
)
result = PostgresEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
error_type=SupersetErrorType.CONNECTION_HOST_DOWN_ERROR,
message=(
'The host "example.com" might be down, '
"and can't be reached on port 12345."
),
level=ErrorLevel.ERROR,
extra={
"engine_name": "PostgreSQL",
"issue_codes": [
{
"code": 1009,
"message": "Issue 1009 - The host might be down, "
"and can't be reached on the provided port.",
}
],
"invalid": ["host", "port"],
},
)
]
# response with IP only
msg = dedent(
"""
psql: error: could not connect to server: Operation timed out
Is the server running on host "93.184.216.34" and accepting
TCP/IP connections on port 12345?
"""
)
result = PostgresEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
error_type=SupersetErrorType.CONNECTION_HOST_DOWN_ERROR,
message=(
'The host "93.184.216.34" might be down, '
"and can't be reached on port 12345."
),
level=ErrorLevel.ERROR,
extra={
"engine_name": "PostgreSQL",
"issue_codes": [
{
"code": 1009,
"message": "Issue 1009 - The host might be down, "
"and can't be reached on the provided port.",
}
],
"invalid": ["host", "port"],
},
)
]
msg = 'FATAL: password authentication failed for user "postgres"'
result = PostgresEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
error_type=SupersetErrorType.CONNECTION_INVALID_PASSWORD_ERROR,
message=('The password provided for username "postgres" is incorrect.'),
level=ErrorLevel.ERROR,
extra={
"engine_name": "PostgreSQL",
"issue_codes": [
{
"code": 1013,
"message": (
"Issue 1013 - The password provided when "
"connecting to a database is not valid."
),
},
],
"invalid": ["username", "password"],
},
)
]
msg = 'database "badDB" does not exist'
result = PostgresEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
message='Unable to connect to database "badDB".',
error_type=SupersetErrorType.CONNECTION_UNKNOWN_DATABASE_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "PostgreSQL",
"issue_codes": [
{
"code": 1015,
"message": (
"Issue 1015 - Either the database is spelled "
"incorrectly or does not exist.",
),
}
],
"invalid": ["database"],
},
)
]
msg = "no password supplied"
result = PostgresEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
message="Please re-enter the password.",
error_type=SupersetErrorType.CONNECTION_ACCESS_DENIED_ERROR,
level=ErrorLevel.ERROR,
extra={
"invalid": ["password"],
"engine_name": "PostgreSQL",
"issue_codes": [
{
"code": 1014,
"message": "Issue 1014 - Either the username or the password is wrong.",
},
{
"code": 1015,
"message": "Issue 1015 - Either the database is spelled incorrectly or does not exist.",
},
],
},
)
]
msg = 'syntax error at or near "fromm"'
result = PostgresEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
message='Please check your query for syntax errors at or near "fromm". Then, try running your query again.',
error_type=SupersetErrorType.SYNTAX_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "PostgreSQL",
"issue_codes": [
{
"code": 1030,
"message": "Issue 1030 - The query has a syntax error.",
}
],
},
)
]
@mock.patch("sqlalchemy.engine.Engine.connect")
def test_get_cancel_query_id(self, engine_mock):
query = Query()
cursor_mock = engine_mock.return_value.__enter__.return_value
cursor_mock.fetchone.return_value = [123]
assert PostgresEngineSpec.get_cancel_query_id(cursor_mock, query) == 123
@mock.patch("sqlalchemy.engine.Engine.connect")
def test_cancel_query(self, engine_mock):
query = Query()
cursor_mock = engine_mock.return_value.__enter__.return_value
assert PostgresEngineSpec.cancel_query(cursor_mock, query, 123) is True
@mock.patch("sqlalchemy.engine.Engine.connect")
def test_cancel_query_failed(self, engine_mock):
query = Query()
cursor_mock = engine_mock.raiseError.side_effect = Exception()
assert PostgresEngineSpec.cancel_query(cursor_mock, query, 123) is False
def test_base_parameters_mixin():
parameters = {
"username": "username",
"password": "password",
"host": "localhost",
"port": 5432,
"database": "dbname",
"query": {"foo": "bar"},
"encryption": True,
}
encrypted_extra = None
sqlalchemy_uri = PostgresEngineSpec.build_sqlalchemy_uri(
parameters, encrypted_extra
)
assert sqlalchemy_uri == (
"postgresql+psycopg2://username:password@localhost:5432/dbname?"
"foo=bar&sslmode=require"
)
parameters_from_uri = PostgresEngineSpec.get_parameters_from_uri(sqlalchemy_uri)
assert parameters_from_uri == parameters
json_schema = PostgresEngineSpec.parameters_json_schema()
assert json_schema == {
"type": "object",
"properties": {
"encryption": {
"type": "boolean",
"description": "Use an encrypted connection to the database",
},
"host": {"type": "string", "description": "Hostname or IP address"},
"database": {"type": "string", "description": "Database name"},
"port": {
"type": "integer",
"format": "int32",
"minimum": 0,
"maximum": 65536,
"description": "Database port",
},
"password": {"type": "string", "nullable": True, "description": "Password"},
"username": {"type": "string", "nullable": True, "description": "Username"},
"query": {
"type": "object",
"description": "Additional parameters",
"additionalProperties": {},
},
},
"required": ["database", "host", "port", "username"],
}
def test_generic_type():
type_expectations = (
# Numeric
("SMALLINT", GenericDataType.NUMERIC),
("INTEGER", GenericDataType.NUMERIC),
("BIGINT", GenericDataType.NUMERIC),
("DECIMAL", GenericDataType.NUMERIC),
("NUMERIC", GenericDataType.NUMERIC),
("REAL", GenericDataType.NUMERIC),
("DOUBLE PRECISION", GenericDataType.NUMERIC),
("MONEY", GenericDataType.NUMERIC),
# String
("CHAR", GenericDataType.STRING),
("VARCHAR", GenericDataType.STRING),
("TEXT", GenericDataType.STRING),
# Temporal
("DATE", GenericDataType.TEMPORAL),
("TIMESTAMP", GenericDataType.TEMPORAL),
("TIME", GenericDataType.TEMPORAL),
# Boolean
("BOOLEAN", GenericDataType.BOOLEAN),
)
assert_generic_types(PostgresEngineSpec, type_expectations)
| tests/integration_tests/db_engine_specs/postgres_tests.py | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0006164626101963222,
0.00018029041530098766,
0.00015887190238572657,
0.00017052015755325556,
0.00006034828766132705
] |
{
"id": 0,
"code_window": [
"from flask_jwt_extended.exceptions import NoAuthorizationError\n",
"from flask_wtf.csrf import CSRFError\n",
"from flask_wtf.form import FlaskForm\n",
"from pkg_resources import resource_filename\n",
"from sqlalchemy import or_\n",
"from sqlalchemy.orm import Query\n",
"from werkzeug.exceptions import HTTPException\n",
"from wtforms import Form\n",
"from wtforms.fields.core import Field, UnboundField\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"from sqlalchemy import exc, or_\n"
],
"file_path": "superset/views/base.py",
"type": "replace",
"edit_start_line_idx": 47
} | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { SuperChart } from '@superset-ui/core';
import dummyDatasource from '../../../../../shared/dummyDatasource';
export const timeFormat = () => (
<SuperChart
chartType="compare"
width={400}
height={400}
datasource={dummyDatasource}
queriesData={[
{
data: [
{
key: ['Africa and Middle East'],
values: [
{
x: 1606348800000,
y: 3985,
},
{
x: 1606435200000,
y: 5882,
},
{
x: 1606521600000,
y: 7983,
},
{
x: 1606608000000,
y: 16462,
},
{
x: 1606694400000,
y: 5542,
},
{
x: 1606780800000,
y: 2825,
},
],
},
{
key: ['Asia'],
values: [
{
x: 1606348800000,
y: 34837,
},
{
x: 1606435200000,
y: 40718,
},
{
x: 1606521600000,
y: 58507,
},
{
x: 1606608000000,
y: 110120,
},
{
x: 1606694400000,
y: 43443,
},
{
x: 1606780800000,
y: 33538,
},
],
},
{
key: ['Australia'],
values: [
{
x: 1606348800000,
y: 12975,
},
{
x: 1606435200000,
y: 18471,
},
{
x: 1606521600000,
y: 17880,
},
{
x: 1606608000000,
y: 52204,
},
{
x: 1606694400000,
y: 26690,
},
{
x: 1606780800000,
y: 16423,
},
],
},
{
key: ['Europe'],
values: [
{
x: 1606348800000,
y: 127029,
},
{
x: 1606435200000,
y: 177637,
},
{
x: 1606521600000,
y: 172653,
},
{
x: 1606608000000,
y: 203654,
},
{
x: 1606694400000,
y: 79200,
},
{
x: 1606780800000,
y: 45238,
},
],
},
{
key: ['LatAm'],
values: [
{
x: 1606348800000,
y: 22513,
},
{
x: 1606435200000,
y: 24594,
},
{
x: 1606521600000,
y: 32578,
},
{
x: 1606608000000,
y: 34733,
},
{
x: 1606694400000,
y: 71696,
},
{
x: 1606780800000,
y: 166611,
},
],
},
{
key: ['North America'],
values: [
{
x: 1606348800000,
y: 104596,
},
{
x: 1606435200000,
y: 109850,
},
{
x: 1606521600000,
y: 136873,
},
{
x: 1606608000000,
y: 133243,
},
{
x: 1606694400000,
y: 327739,
},
{
x: 1606780800000,
y: 162711,
},
],
},
],
},
]}
formData={{
datasource: '24771__table',
vizType: 'compare',
urlParams: {},
timeRangeEndpoints: ['inclusive', 'exclusive'],
granularitySqla: '__time',
timeGrainSqla: 'P1D',
timeRange: 'Last week',
metrics: ['random_metric'],
adhocFilters: [],
groupby: ['dim_origin_region'],
timeseriesLimitMetric: null,
orderDesc: true,
contribution: false,
rowLimit: 10000,
colorScheme: 'd3Category10',
labelColors: {},
xAxisLabel: '',
bottomMargin: 'auto',
xTicksLayout: 'auto',
xAxisFormat: 'smart_date',
xAxisShowminmax: false,
yAxisLabel: '',
leftMargin: 'auto',
yAxisShowminmax: false,
yLogScale: false,
yAxisFormat: 'SMART_NUMBER',
yAxisBounds: [null, null],
rollingType: 'None',
comparisonType: 'values',
resampleRule: null,
resampleMethod: null,
annotationLayers: [],
appliedTimeExtras: {},
where: '',
having: '',
havingFilters: [],
filters: [],
}}
/>
);
| superset-frontend/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/Compare/stories/timeFormat.tsx | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0001799200545065105,
0.0001734499237500131,
0.00017067980661522597,
0.00017290402320213616,
0.0000022394347070076037
] |
{
"id": 1,
"code_window": [
" logger.exception(ex)\n",
" return json_error_response(\n",
" utils.error_msg_from_exception(ex), status=cast(int, ex.code)\n",
" )\n",
" except Exception as ex: # pylint: disable=broad-except\n",
" logger.exception(ex)\n",
" return json_error_response(utils.error_msg_from_exception(ex))\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" except (exc.IntegrityError, exc.DatabaseError, exc.DataError) as ex:\n",
" logger.exception(ex)\n",
" return json_error_response(utils.error_msg_from_exception(ex), status=422)\n"
],
"file_path": "superset/views/base.py",
"type": "add",
"edit_start_line_idx": 233
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import functools
import logging
from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type, Union
from flask import Blueprint, g, request, Response
from flask_appbuilder import AppBuilder, Model, ModelRestApi
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.filters import BaseFilter, Filters
from flask_appbuilder.models.sqla.filters import FilterStartsWith
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import lazy_gettext as _
from marshmallow import fields, Schema
from sqlalchemy import and_, distinct, func
from sqlalchemy.orm.query import Query
from superset.exceptions import InvalidPayloadFormatError
from superset.extensions import db, event_logger, security_manager
from superset.models.core import FavStar
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice
from superset.schemas import error_payload_content
from superset.sql_lab import Query as SqllabQuery
from superset.stats_logger import BaseStatsLogger
from superset.superset_typing import FlaskResponse
from superset.utils.core import time_function
logger = logging.getLogger(__name__)
get_related_schema = {
"type": "object",
"properties": {
"page_size": {"type": "integer"},
"page": {"type": "integer"},
"include_ids": {"type": "array", "items": {"type": "integer"}},
"filter": {"type": "string"},
},
}
class RelatedResultResponseSchema(Schema):
value = fields.Integer(description="The related item identifier")
text = fields.String(description="The related item string representation")
class RelatedResponseSchema(Schema):
count = fields.Integer(description="The total number of related values")
result = fields.List(fields.Nested(RelatedResultResponseSchema))
class DistinctResultResponseSchema(Schema):
text = fields.String(description="The distinct item")
class DistincResponseSchema(Schema):
count = fields.Integer(description="The total number of distinct values")
result = fields.List(fields.Nested(DistinctResultResponseSchema))
def requires_json(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require JSON-like formatted request to the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.is_json:
raise InvalidPayloadFormatError(message="Request is not JSON")
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def requires_form_data(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require 'multipart/form-data' as request MIME type
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.mimetype == "multipart/form-data":
raise InvalidPayloadFormatError(
message="Request MIME type is not 'multipart/form-data'"
)
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def statsd_metrics(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Handle sending all statsd metrics from the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
try:
duration, response = time_function(f, self, *args, **kwargs)
except Exception as ex:
self.incr_stats("error", f.__name__)
raise ex
self.send_stats_metrics(response, f.__name__, duration)
return response
return functools.update_wrapper(wraps, f)
class RelatedFieldFilter:
# data class to specify what filter to use on a /related endpoint
# pylint: disable=too-few-public-methods
def __init__(self, field_name: str, filter_class: Type[BaseFilter]):
self.field_name = field_name
self.filter_class = filter_class
class BaseFavoriteFilter(BaseFilter): # pylint: disable=too-few-public-methods
"""
Base Custom filter for the GET list that filters all dashboards, slices
that a user has favored or not
"""
name = _("Is favorite")
arg_name = ""
class_name = ""
""" The FavStar class_name to user """
model: Type[Union[Dashboard, Slice, SqllabQuery]] = Dashboard
""" The SQLAlchemy model """
def apply(self, query: Query, value: Any) -> Query:
# If anonymous user filter nothing
if security_manager.current_user is None:
return query
users_favorite_query = db.session.query(FavStar.obj_id).filter(
and_(
FavStar.user_id == g.user.get_id(),
FavStar.class_name == self.class_name,
)
)
if value:
return query.filter(and_(self.model.id.in_(users_favorite_query)))
return query.filter(and_(~self.model.id.in_(users_favorite_query)))
class BaseSupersetModelRestApi(ModelRestApi):
"""
Extends FAB's ModelResApi to implement specific superset generic functionality
"""
csrf_exempt = False
method_permission_name = {
"bulk_delete": "delete",
"data": "list",
"data_from_cache": "list",
"delete": "delete",
"distinct": "list",
"export": "mulexport",
"import_": "add",
"get": "show",
"get_list": "list",
"info": "list",
"post": "add",
"put": "edit",
"refresh": "edit",
"related": "list",
"related_objects": "list",
"schemas": "list",
"select_star": "list",
"table_metadata": "list",
"test_connection": "post",
"thumbnail": "list",
"viz_types": "list",
}
order_rel_fields: Dict[str, Tuple[str, str]] = {}
"""
Impose ordering on related fields query::
order_rel_fields = {
"<RELATED_FIELD>": ("<RELATED_FIELD_FIELD>", "<asc|desc>"),
...
}
"""
related_field_filters: Dict[str, Union[RelatedFieldFilter, str]] = {}
"""
Declare the filters for related fields::
related_fields = {
"<RELATED_FIELD>": <RelatedFieldFilter>)
}
"""
filter_rel_fields: Dict[str, BaseFilter] = {}
"""
Declare the related field base filter::
filter_rel_fields_field = {
"<RELATED_FIELD>": "<FILTER>")
}
"""
allowed_rel_fields: Set[str] = set()
# Declare a set of allowed related fields that the `related` endpoint supports.
text_field_rel_fields: Dict[str, str] = {}
"""
Declare an alternative for the human readable representation of the Model object::
text_field_rel_fields = {
"<RELATED_FIELD>": "<RELATED_OBJECT_FIELD>"
}
"""
allowed_distinct_fields: Set[str] = set()
add_columns: List[str]
edit_columns: List[str]
list_columns: List[str]
show_columns: List[str]
responses = {
"400": {"description": "Bad request", "content": error_payload_content},
"401": {"description": "Unauthorized", "content": error_payload_content},
"403": {"description": "Forbidden", "content": error_payload_content},
"404": {"description": "Not found", "content": error_payload_content},
"422": {
"description": "Could not process entity",
"content": error_payload_content,
},
"500": {"description": "Fatal error", "content": error_payload_content},
}
def __init__(self) -> None:
super().__init__()
# Setup statsd
self.stats_logger = BaseStatsLogger()
# Add base API spec base query parameter schemas
if self.apispec_parameter_schemas is None: # type: ignore
self.apispec_parameter_schemas = {}
self.apispec_parameter_schemas["get_related_schema"] = get_related_schema
self.openapi_spec_component_schemas: Tuple[
Type[Schema], ...
] = self.openapi_spec_component_schemas + (
RelatedResponseSchema,
DistincResponseSchema,
)
def create_blueprint(
self, appbuilder: AppBuilder, *args: Any, **kwargs: Any
) -> Blueprint:
self.stats_logger = self.appbuilder.get_app.config["STATS_LOGGER"]
return super().create_blueprint(appbuilder, *args, **kwargs)
def _init_properties(self) -> None:
"""
Lock down initial not configured REST API columns. We want to just expose
model ids, if something is misconfigured. By default FAB exposes all available
columns on a Model
"""
model_id = self.datamodel.get_pk_name()
if self.list_columns is None and not self.list_model_schema:
self.list_columns = [model_id]
if self.show_columns is None and not self.show_model_schema:
self.show_columns = [model_id]
if self.edit_columns is None and not self.edit_model_schema:
self.edit_columns = [model_id]
if self.add_columns is None and not self.add_model_schema:
self.add_columns = [model_id]
super()._init_properties()
def _get_related_filter(
self, datamodel: SQLAInterface, column_name: str, value: str
) -> Filters:
filter_field = self.related_field_filters.get(column_name)
if isinstance(filter_field, str):
filter_field = RelatedFieldFilter(cast(str, filter_field), FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = datamodel.get_filters(search_columns)
base_filters = self.filter_rel_fields.get(column_name)
if base_filters:
filters.add_filter_list(base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_distinct_filter(self, column_name: str, value: str) -> Filters:
filter_field = RelatedFieldFilter(column_name, FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = self.datamodel.get_filters(search_columns)
filters.add_filter_list(self.base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_text_for_model(self, model: Model, column_name: str) -> str:
if column_name in self.text_field_rel_fields:
model_column_name = self.text_field_rel_fields.get(column_name)
if model_column_name:
return getattr(model, model_column_name)
return str(model)
def _get_result_from_rows(
self, datamodel: SQLAInterface, rows: List[Model], column_name: str
) -> List[Dict[str, Any]]:
return [
{
"value": datamodel.get_pk_value(row),
"text": self._get_text_for_model(row, column_name),
}
for row in rows
]
def _add_extra_ids_to_result(
self,
datamodel: SQLAInterface,
column_name: str,
ids: List[int],
result: List[Dict[str, Any]],
) -> None:
if ids:
# Filter out already present values on the result
values = [row["value"] for row in result]
ids = [id_ for id_ in ids if id_ not in values]
pk_col = datamodel.get_pk()
# Fetch requested values from ids
extra_rows = db.session.query(datamodel.obj).filter(pk_col.in_(ids)).all()
result += self._get_result_from_rows(datamodel, extra_rows, column_name)
def incr_stats(self, action: str, func_name: str) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
"""
self.stats_logger.incr(f"{self.__class__.__name__}.{func_name}.{action}")
def timing_stats(self, action: str, func_name: str, value: float) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
:param value: A float with the time it took for the endpoint to execute
"""
self.stats_logger.timing(
f"{self.__class__.__name__}.{func_name}.{action}", value
)
def send_stats_metrics(
self, response: Response, key: str, time_delta: Optional[float] = None
) -> None:
"""
Helper function to handle sending statsd metrics
:param response: flask response object, will evaluate if it was an error
:param key: The function name
:param time_delta: Optional time it took for the endpoint to execute
"""
if 200 <= response.status_code < 400:
self.incr_stats("success", key)
else:
self.incr_stats("error", key)
if time_delta:
self.timing_stats("time", key, time_delta)
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.info",
object_ref=False,
log_to_statsd=False,
)
def info_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB _info endpoint
"""
duration, response = time_function(super().info_headless, **kwargs)
self.send_stats_metrics(response, self.info.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get",
object_ref=False,
log_to_statsd=False,
)
def get_headless(self, pk: int, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET endpoint
"""
duration, response = time_function(super().get_headless, pk, **kwargs)
self.send_stats_metrics(response, self.get.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_list",
object_ref=False,
log_to_statsd=False,
)
def get_list_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET list endpoint
"""
duration, response = time_function(super().get_list_headless, **kwargs)
self.send_stats_metrics(response, self.get_list.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
object_ref=False,
log_to_statsd=False,
)
def post_headless(self) -> Response:
"""
Add statsd metrics to builtin FAB POST endpoint
"""
duration, response = time_function(super().post_headless)
self.send_stats_metrics(response, self.post.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put",
object_ref=False,
log_to_statsd=False,
)
def put_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB PUT endpoint
"""
duration, response = time_function(super().put_headless, pk)
self.send_stats_metrics(response, self.put.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete",
object_ref=False,
log_to_statsd=False,
)
def delete_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB DELETE endpoint
"""
duration, response = time_function(super().delete_headless, pk)
self.send_stats_metrics(response, self.delete.__name__, duration)
return response
@expose("/related/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def related(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get related fields data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Related column data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/RelatedResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_rel_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._handle_page_args(args)
ids = args.get("include_ids")
if page and ids:
# pagination with forced ids is not supported
return self.response_422()
try:
datamodel = self.datamodel.get_related_interface(column_name)
except KeyError:
return self.response_404()
page, page_size = self._sanitize_page_args(page, page_size)
# handle ordering
order_field = self.order_rel_fields.get(column_name)
if order_field:
order_column, order_direction = order_field
else:
order_column, order_direction = "", ""
# handle filters
filters = self._get_related_filter(datamodel, column_name, args.get("filter"))
# Make the query
total_rows, rows = datamodel.query(
filters, order_column, order_direction, page=page, page_size=page_size
)
# produce response
result = self._get_result_from_rows(datamodel, rows, column_name)
# If ids are specified make sure we fetch and include them on the response
if ids:
self._add_extra_ids_to_result(datamodel, column_name, ids, result)
total_rows = len(result)
return self.response(200, count=total_rows, result=result)
@expose("/distinct/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get distinct values from field data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Distinct field data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/DistincResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_distinct_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._sanitize_page_args(*self._handle_page_args(args))
# Create generic base filters with added request filter
filters = self._get_distinct_filter(column_name, args.get("filter"))
# Make the query
query_count = self.appbuilder.get_session.query(
func.count(distinct(getattr(self.datamodel.obj, column_name)))
)
count = self.datamodel.apply_filters(query_count, filters).scalar()
if count == 0:
return self.response(200, count=count, result=[])
query = self.appbuilder.get_session.query(
distinct(getattr(self.datamodel.obj, column_name))
)
# Apply generic base filters with added request filter
query = self.datamodel.apply_filters(query, filters)
# Apply sort
query = self.datamodel.apply_order_by(query, column_name, "asc")
# Apply pagination
result = self.datamodel.apply_pagination(query, page, page_size).all()
# produce response
result = [
{"text": item[0], "value": item[0]}
for item in result
if item[0] is not None
]
return self.response(200, count=count, result=result)
| superset/views/base_api.py | 1 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0007817749283276498,
0.00019678828539326787,
0.00016430855612270534,
0.00017112500790972263,
0.00011759596964111552
] |
{
"id": 1,
"code_window": [
" logger.exception(ex)\n",
" return json_error_response(\n",
" utils.error_msg_from_exception(ex), status=cast(int, ex.code)\n",
" )\n",
" except Exception as ex: # pylint: disable=broad-except\n",
" logger.exception(ex)\n",
" return json_error_response(utils.error_msg_from_exception(ex))\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" except (exc.IntegrityError, exc.DatabaseError, exc.DataError) as ex:\n",
" logger.exception(ex)\n",
" return json_error_response(utils.error_msg_from_exception(ex), status=422)\n"
],
"file_path": "superset/views/base.py",
"type": "add",
"edit_start_line_idx": 233
} | ---
title: Apache Solr
hide_title: true
sidebar_position: 13
version: 1
---
## Apache Solr
The [sqlalchemy-solr](https://pypi.org/project/sqlalchemy-solr/) library provides a
Python / SQLAlchemy interface to Apache Solr.
The connection string for Solr looks like this:
```
solr://{username}:{password}@{host}:{port}/{server_path}/{collection}[/?use_ssl=true|false]
```
| docs/docs/databases/solr.mdx | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00016644045535940677,
0.00016268526087515056,
0.00015893008094280958,
0.00016268526087515056,
0.0000037551872082985938
] |
{
"id": 1,
"code_window": [
" logger.exception(ex)\n",
" return json_error_response(\n",
" utils.error_msg_from_exception(ex), status=cast(int, ex.code)\n",
" )\n",
" except Exception as ex: # pylint: disable=broad-except\n",
" logger.exception(ex)\n",
" return json_error_response(utils.error_msg_from_exception(ex))\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" except (exc.IntegrityError, exc.DatabaseError, exc.DataError) as ex:\n",
" logger.exception(ex)\n",
" return json_error_response(utils.error_msg_from_exception(ex), status=422)\n"
],
"file_path": "superset/views/base.py",
"type": "add",
"edit_start_line_idx": 233
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regardin
* g copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Behavior, ChartMetadata, ChartPlugin, t } from '@superset-ui/core';
import buildQuery from './buildQuery';
import controlPanel from './controlPanel';
import transformProps from './transformProps';
import thumbnail from './images/thumbnail.png';
import example1 from './images/treemap_v2_1.png';
import example2 from './images/treemap_v2_2.jpg';
import { EchartsTreemapChartProps, EchartsTreemapFormData } from './types';
export default class EchartsTreemapChartPlugin extends ChartPlugin<
EchartsTreemapFormData,
EchartsTreemapChartProps
> {
/**
* The constructor is used to pass relevant metadata and callbacks that get
* registered in respective registries that are used throughout the library
* and application. A more thorough description of each property is given in
* the respective imported file.
*
* It is worth noting that `buildQuery` and is optional, and only needed for
* advanced visualizations that require either post processing operations
* (pivoting, rolling aggregations, sorting etc) or submitting multiple queries.
*/
constructor() {
super({
buildQuery,
controlPanel,
loadChart: () => import('./EchartsTreemap'),
metadata: new ChartMetadata({
behaviors: [Behavior.INTERACTIVE_CHART],
category: t('Part of a Whole'),
credits: ['https://echarts.apache.org'],
description: t(
'Show hierarchical relationships of data, with with the value represented by area, showing proportion and contribution to the whole.',
),
exampleGallery: [{ url: example1 }, { url: example2 }],
name: t('Treemap v2'),
tags: [
t('Aesthetic'),
t('Categorical'),
t('Comparison'),
t('ECharts'),
t('Multi-Levels'),
t('Percentages'),
t('Proportional'),
],
thumbnail,
}),
transformProps,
});
}
}
| superset-frontend/plugins/plugin-chart-echarts/src/Treemap/index.ts | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0001762690080795437,
0.00017189636128023267,
0.00016196732758544385,
0.0001735542609822005,
0.000004958322733727982
] |
{
"id": 1,
"code_window": [
" logger.exception(ex)\n",
" return json_error_response(\n",
" utils.error_msg_from_exception(ex), status=cast(int, ex.code)\n",
" )\n",
" except Exception as ex: # pylint: disable=broad-except\n",
" logger.exception(ex)\n",
" return json_error_response(utils.error_msg_from_exception(ex))\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" except (exc.IntegrityError, exc.DatabaseError, exc.DataError) as ex:\n",
" logger.exception(ex)\n",
" return json_error_response(utils.error_msg_from_exception(ex), status=422)\n"
],
"file_path": "superset/views/base.py",
"type": "add",
"edit_start_line_idx": 233
} | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import LazyFactory from './LazyFactory';
import createHiddenSvgNode from './createHiddenSvgNode';
import createTextNode from './createTextNode';
export const hiddenSvgFactory = new LazyFactory(createHiddenSvgNode);
export const textFactory = new LazyFactory(createTextNode);
| superset-frontend/packages/superset-ui-core/src/dimension/svg/factories.ts | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00017747451784089208,
0.0001760292361723259,
0.00017521817062515765,
0.000175395020050928,
0.0000010245155408483697
] |
{
"id": 2,
"code_window": [
"from superset.stats_logger import BaseStatsLogger\n",
"from superset.superset_typing import FlaskResponse\n",
"from superset.utils.core import time_function\n",
"\n",
"logger = logging.getLogger(__name__)\n",
"get_related_schema = {\n",
" \"type\": \"object\",\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"from superset.views.base import handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 41
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import functools
import logging
from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type, Union
from flask import Blueprint, g, request, Response
from flask_appbuilder import AppBuilder, Model, ModelRestApi
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.filters import BaseFilter, Filters
from flask_appbuilder.models.sqla.filters import FilterStartsWith
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import lazy_gettext as _
from marshmallow import fields, Schema
from sqlalchemy import and_, distinct, func
from sqlalchemy.orm.query import Query
from superset.exceptions import InvalidPayloadFormatError
from superset.extensions import db, event_logger, security_manager
from superset.models.core import FavStar
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice
from superset.schemas import error_payload_content
from superset.sql_lab import Query as SqllabQuery
from superset.stats_logger import BaseStatsLogger
from superset.superset_typing import FlaskResponse
from superset.utils.core import time_function
logger = logging.getLogger(__name__)
get_related_schema = {
"type": "object",
"properties": {
"page_size": {"type": "integer"},
"page": {"type": "integer"},
"include_ids": {"type": "array", "items": {"type": "integer"}},
"filter": {"type": "string"},
},
}
class RelatedResultResponseSchema(Schema):
value = fields.Integer(description="The related item identifier")
text = fields.String(description="The related item string representation")
class RelatedResponseSchema(Schema):
count = fields.Integer(description="The total number of related values")
result = fields.List(fields.Nested(RelatedResultResponseSchema))
class DistinctResultResponseSchema(Schema):
text = fields.String(description="The distinct item")
class DistincResponseSchema(Schema):
count = fields.Integer(description="The total number of distinct values")
result = fields.List(fields.Nested(DistinctResultResponseSchema))
def requires_json(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require JSON-like formatted request to the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.is_json:
raise InvalidPayloadFormatError(message="Request is not JSON")
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def requires_form_data(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require 'multipart/form-data' as request MIME type
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.mimetype == "multipart/form-data":
raise InvalidPayloadFormatError(
message="Request MIME type is not 'multipart/form-data'"
)
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def statsd_metrics(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Handle sending all statsd metrics from the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
try:
duration, response = time_function(f, self, *args, **kwargs)
except Exception as ex:
self.incr_stats("error", f.__name__)
raise ex
self.send_stats_metrics(response, f.__name__, duration)
return response
return functools.update_wrapper(wraps, f)
class RelatedFieldFilter:
# data class to specify what filter to use on a /related endpoint
# pylint: disable=too-few-public-methods
def __init__(self, field_name: str, filter_class: Type[BaseFilter]):
self.field_name = field_name
self.filter_class = filter_class
class BaseFavoriteFilter(BaseFilter): # pylint: disable=too-few-public-methods
"""
Base Custom filter for the GET list that filters all dashboards, slices
that a user has favored or not
"""
name = _("Is favorite")
arg_name = ""
class_name = ""
""" The FavStar class_name to user """
model: Type[Union[Dashboard, Slice, SqllabQuery]] = Dashboard
""" The SQLAlchemy model """
def apply(self, query: Query, value: Any) -> Query:
# If anonymous user filter nothing
if security_manager.current_user is None:
return query
users_favorite_query = db.session.query(FavStar.obj_id).filter(
and_(
FavStar.user_id == g.user.get_id(),
FavStar.class_name == self.class_name,
)
)
if value:
return query.filter(and_(self.model.id.in_(users_favorite_query)))
return query.filter(and_(~self.model.id.in_(users_favorite_query)))
class BaseSupersetModelRestApi(ModelRestApi):
"""
Extends FAB's ModelResApi to implement specific superset generic functionality
"""
csrf_exempt = False
method_permission_name = {
"bulk_delete": "delete",
"data": "list",
"data_from_cache": "list",
"delete": "delete",
"distinct": "list",
"export": "mulexport",
"import_": "add",
"get": "show",
"get_list": "list",
"info": "list",
"post": "add",
"put": "edit",
"refresh": "edit",
"related": "list",
"related_objects": "list",
"schemas": "list",
"select_star": "list",
"table_metadata": "list",
"test_connection": "post",
"thumbnail": "list",
"viz_types": "list",
}
order_rel_fields: Dict[str, Tuple[str, str]] = {}
"""
Impose ordering on related fields query::
order_rel_fields = {
"<RELATED_FIELD>": ("<RELATED_FIELD_FIELD>", "<asc|desc>"),
...
}
"""
related_field_filters: Dict[str, Union[RelatedFieldFilter, str]] = {}
"""
Declare the filters for related fields::
related_fields = {
"<RELATED_FIELD>": <RelatedFieldFilter>)
}
"""
filter_rel_fields: Dict[str, BaseFilter] = {}
"""
Declare the related field base filter::
filter_rel_fields_field = {
"<RELATED_FIELD>": "<FILTER>")
}
"""
allowed_rel_fields: Set[str] = set()
# Declare a set of allowed related fields that the `related` endpoint supports.
text_field_rel_fields: Dict[str, str] = {}
"""
Declare an alternative for the human readable representation of the Model object::
text_field_rel_fields = {
"<RELATED_FIELD>": "<RELATED_OBJECT_FIELD>"
}
"""
allowed_distinct_fields: Set[str] = set()
add_columns: List[str]
edit_columns: List[str]
list_columns: List[str]
show_columns: List[str]
responses = {
"400": {"description": "Bad request", "content": error_payload_content},
"401": {"description": "Unauthorized", "content": error_payload_content},
"403": {"description": "Forbidden", "content": error_payload_content},
"404": {"description": "Not found", "content": error_payload_content},
"422": {
"description": "Could not process entity",
"content": error_payload_content,
},
"500": {"description": "Fatal error", "content": error_payload_content},
}
def __init__(self) -> None:
super().__init__()
# Setup statsd
self.stats_logger = BaseStatsLogger()
# Add base API spec base query parameter schemas
if self.apispec_parameter_schemas is None: # type: ignore
self.apispec_parameter_schemas = {}
self.apispec_parameter_schemas["get_related_schema"] = get_related_schema
self.openapi_spec_component_schemas: Tuple[
Type[Schema], ...
] = self.openapi_spec_component_schemas + (
RelatedResponseSchema,
DistincResponseSchema,
)
def create_blueprint(
self, appbuilder: AppBuilder, *args: Any, **kwargs: Any
) -> Blueprint:
self.stats_logger = self.appbuilder.get_app.config["STATS_LOGGER"]
return super().create_blueprint(appbuilder, *args, **kwargs)
def _init_properties(self) -> None:
"""
Lock down initial not configured REST API columns. We want to just expose
model ids, if something is misconfigured. By default FAB exposes all available
columns on a Model
"""
model_id = self.datamodel.get_pk_name()
if self.list_columns is None and not self.list_model_schema:
self.list_columns = [model_id]
if self.show_columns is None and not self.show_model_schema:
self.show_columns = [model_id]
if self.edit_columns is None and not self.edit_model_schema:
self.edit_columns = [model_id]
if self.add_columns is None and not self.add_model_schema:
self.add_columns = [model_id]
super()._init_properties()
def _get_related_filter(
self, datamodel: SQLAInterface, column_name: str, value: str
) -> Filters:
filter_field = self.related_field_filters.get(column_name)
if isinstance(filter_field, str):
filter_field = RelatedFieldFilter(cast(str, filter_field), FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = datamodel.get_filters(search_columns)
base_filters = self.filter_rel_fields.get(column_name)
if base_filters:
filters.add_filter_list(base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_distinct_filter(self, column_name: str, value: str) -> Filters:
filter_field = RelatedFieldFilter(column_name, FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = self.datamodel.get_filters(search_columns)
filters.add_filter_list(self.base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_text_for_model(self, model: Model, column_name: str) -> str:
if column_name in self.text_field_rel_fields:
model_column_name = self.text_field_rel_fields.get(column_name)
if model_column_name:
return getattr(model, model_column_name)
return str(model)
def _get_result_from_rows(
self, datamodel: SQLAInterface, rows: List[Model], column_name: str
) -> List[Dict[str, Any]]:
return [
{
"value": datamodel.get_pk_value(row),
"text": self._get_text_for_model(row, column_name),
}
for row in rows
]
def _add_extra_ids_to_result(
self,
datamodel: SQLAInterface,
column_name: str,
ids: List[int],
result: List[Dict[str, Any]],
) -> None:
if ids:
# Filter out already present values on the result
values = [row["value"] for row in result]
ids = [id_ for id_ in ids if id_ not in values]
pk_col = datamodel.get_pk()
# Fetch requested values from ids
extra_rows = db.session.query(datamodel.obj).filter(pk_col.in_(ids)).all()
result += self._get_result_from_rows(datamodel, extra_rows, column_name)
def incr_stats(self, action: str, func_name: str) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
"""
self.stats_logger.incr(f"{self.__class__.__name__}.{func_name}.{action}")
def timing_stats(self, action: str, func_name: str, value: float) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
:param value: A float with the time it took for the endpoint to execute
"""
self.stats_logger.timing(
f"{self.__class__.__name__}.{func_name}.{action}", value
)
def send_stats_metrics(
self, response: Response, key: str, time_delta: Optional[float] = None
) -> None:
"""
Helper function to handle sending statsd metrics
:param response: flask response object, will evaluate if it was an error
:param key: The function name
:param time_delta: Optional time it took for the endpoint to execute
"""
if 200 <= response.status_code < 400:
self.incr_stats("success", key)
else:
self.incr_stats("error", key)
if time_delta:
self.timing_stats("time", key, time_delta)
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.info",
object_ref=False,
log_to_statsd=False,
)
def info_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB _info endpoint
"""
duration, response = time_function(super().info_headless, **kwargs)
self.send_stats_metrics(response, self.info.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get",
object_ref=False,
log_to_statsd=False,
)
def get_headless(self, pk: int, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET endpoint
"""
duration, response = time_function(super().get_headless, pk, **kwargs)
self.send_stats_metrics(response, self.get.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_list",
object_ref=False,
log_to_statsd=False,
)
def get_list_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET list endpoint
"""
duration, response = time_function(super().get_list_headless, **kwargs)
self.send_stats_metrics(response, self.get_list.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
object_ref=False,
log_to_statsd=False,
)
def post_headless(self) -> Response:
"""
Add statsd metrics to builtin FAB POST endpoint
"""
duration, response = time_function(super().post_headless)
self.send_stats_metrics(response, self.post.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put",
object_ref=False,
log_to_statsd=False,
)
def put_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB PUT endpoint
"""
duration, response = time_function(super().put_headless, pk)
self.send_stats_metrics(response, self.put.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete",
object_ref=False,
log_to_statsd=False,
)
def delete_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB DELETE endpoint
"""
duration, response = time_function(super().delete_headless, pk)
self.send_stats_metrics(response, self.delete.__name__, duration)
return response
@expose("/related/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def related(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get related fields data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Related column data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/RelatedResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_rel_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._handle_page_args(args)
ids = args.get("include_ids")
if page and ids:
# pagination with forced ids is not supported
return self.response_422()
try:
datamodel = self.datamodel.get_related_interface(column_name)
except KeyError:
return self.response_404()
page, page_size = self._sanitize_page_args(page, page_size)
# handle ordering
order_field = self.order_rel_fields.get(column_name)
if order_field:
order_column, order_direction = order_field
else:
order_column, order_direction = "", ""
# handle filters
filters = self._get_related_filter(datamodel, column_name, args.get("filter"))
# Make the query
total_rows, rows = datamodel.query(
filters, order_column, order_direction, page=page, page_size=page_size
)
# produce response
result = self._get_result_from_rows(datamodel, rows, column_name)
# If ids are specified make sure we fetch and include them on the response
if ids:
self._add_extra_ids_to_result(datamodel, column_name, ids, result)
total_rows = len(result)
return self.response(200, count=total_rows, result=result)
@expose("/distinct/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get distinct values from field data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Distinct field data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/DistincResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_distinct_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._sanitize_page_args(*self._handle_page_args(args))
# Create generic base filters with added request filter
filters = self._get_distinct_filter(column_name, args.get("filter"))
# Make the query
query_count = self.appbuilder.get_session.query(
func.count(distinct(getattr(self.datamodel.obj, column_name)))
)
count = self.datamodel.apply_filters(query_count, filters).scalar()
if count == 0:
return self.response(200, count=count, result=[])
query = self.appbuilder.get_session.query(
distinct(getattr(self.datamodel.obj, column_name))
)
# Apply generic base filters with added request filter
query = self.datamodel.apply_filters(query, filters)
# Apply sort
query = self.datamodel.apply_order_by(query, column_name, "asc")
# Apply pagination
result = self.datamodel.apply_pagination(query, page, page_size).all()
# produce response
result = [
{"text": item[0], "value": item[0]}
for item in result
if item[0] is not None
]
return self.response(200, count=count, result=result)
| superset/views/base_api.py | 1 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.9991499185562134,
0.14215774834156036,
0.00016338477144017816,
0.0001990439632209018,
0.33738842606544495
] |
{
"id": 2,
"code_window": [
"from superset.stats_logger import BaseStatsLogger\n",
"from superset.superset_typing import FlaskResponse\n",
"from superset.utils.core import time_function\n",
"\n",
"logger = logging.getLogger(__name__)\n",
"get_related_schema = {\n",
" \"type\": \"object\",\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"from superset.views.base import handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 41
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
toggleExpandSlice,
setFocusedFilterField,
unsetFocusedFilterField,
} from 'src/dashboard/actions/dashboardState';
import { updateComponents } from 'src/dashboard/actions/dashboardLayout';
import { changeFilter } from 'src/dashboard/actions/dashboardFilters';
import {
addSuccessToast,
addDangerToast,
} from 'src/components/MessageToasts/actions';
import { refreshChart } from 'src/components/Chart/chartAction';
import { logEvent } from 'src/logger/actions';
import {
getActiveFilters,
getAppliedFilterValues,
} from 'src/dashboard/util/activeDashboardFilters';
import getFormDataWithExtraFilters from 'src/dashboard/util/charts/getFormDataWithExtraFilters';
import Chart from 'src/dashboard/components/gridComponents/Chart';
import { PLACEHOLDER_DATASOURCE } from 'src/dashboard/constants';
const EMPTY_OBJECT = {};
function mapStateToProps(
{
charts: chartQueries,
dashboardInfo,
dashboardState,
dashboardLayout,
dataMask,
datasources,
sliceEntities,
nativeFilters,
common,
},
ownProps,
) {
const { id } = ownProps;
const chart = chartQueries[id] || EMPTY_OBJECT;
const datasource =
(chart && chart.form_data && datasources[chart.form_data.datasource]) ||
PLACEHOLDER_DATASOURCE;
const { colorScheme, colorNamespace, datasetsStatus } = dashboardState;
const labelColors = dashboardInfo?.metadata?.label_colors || {};
const sharedLabelColors = dashboardInfo?.metadata?.shared_label_colors || {};
// note: this method caches filters if possible to prevent render cascades
const formData = getFormDataWithExtraFilters({
layout: dashboardLayout.present,
chart,
// eslint-disable-next-line camelcase
chartConfiguration: dashboardInfo.metadata?.chart_configuration,
charts: chartQueries,
filters: getAppliedFilterValues(id),
colorScheme,
colorNamespace,
sliceId: id,
nativeFilters,
dataMask,
labelColors,
sharedLabelColors,
});
formData.dashboardId = dashboardInfo.id;
return {
chart,
datasource,
labelColors,
sharedLabelColors,
slice: sliceEntities.slices[id],
timeout: dashboardInfo.common.conf.SUPERSET_WEBSERVER_TIMEOUT,
filters: getActiveFilters() || EMPTY_OBJECT,
formData,
editMode: dashboardState.editMode,
isExpanded: !!dashboardState.expandedSlices[id],
supersetCanExplore: !!dashboardInfo.superset_can_explore,
supersetCanShare: !!dashboardInfo.superset_can_share,
supersetCanCSV: !!dashboardInfo.superset_can_csv,
sliceCanEdit: !!dashboardInfo.slice_can_edit,
ownState: dataMask[id]?.ownState,
filterState: dataMask[id]?.filterState,
maxRows: common.conf.SQL_MAX_ROW,
filterboxMigrationState: dashboardState.filterboxMigrationState,
datasetsStatus,
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
updateComponents,
addSuccessToast,
addDangerToast,
toggleExpandSlice,
changeFilter,
setFocusedFilterField,
unsetFocusedFilterField,
refreshChart,
logEvent,
},
dispatch,
);
}
export default connect(mapStateToProps, mapDispatchToProps)(Chart);
| superset-frontend/src/dashboard/containers/Chart.jsx | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0005040643736720085,
0.00019759788119699806,
0.00016762810992076993,
0.0001710648211883381,
0.0000885880072019063
] |
{
"id": 2,
"code_window": [
"from superset.stats_logger import BaseStatsLogger\n",
"from superset.superset_typing import FlaskResponse\n",
"from superset.utils.core import time_function\n",
"\n",
"logger = logging.getLogger(__name__)\n",
"get_related_schema = {\n",
" \"type\": \"object\",\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"from superset.views.base import handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 41
} | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
export { default as ChartFrame } from './ChartFrame';
export { default as WithLegend } from './legend/WithLegend';
export { default as TooltipFrame } from './tooltip/TooltipFrame';
export { default as TooltipTable } from './tooltip/TooltipTable';
| superset-frontend/packages/superset-ui-core/src/chart-composition/index.ts | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00017542764544487,
0.0001751623349264264,
0.00017481799295637757,
0.00017524139548186213,
2.5508930434625654e-7
] |
{
"id": 2,
"code_window": [
"from superset.stats_logger import BaseStatsLogger\n",
"from superset.superset_typing import FlaskResponse\n",
"from superset.utils.core import time_function\n",
"\n",
"logger = logging.getLogger(__name__)\n",
"get_related_schema = {\n",
" \"type\": \"object\",\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"from superset.views.base import handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 41
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { buildQueryContext } from '@superset-ui/core';
import { boxplotOperator } from '@superset-ui/chart-controls';
import { BoxPlotQueryFormData } from './types';
export default function buildQuery(formData: BoxPlotQueryFormData) {
const { columns = [], granularity_sqla, groupby = [] } = formData;
return buildQueryContext(formData, baseQueryObject => {
const distributionColumns: string[] = [];
// For now default to using the temporal column as distribution column.
// In the future this control should be made mandatory.
if (!columns.length && granularity_sqla) {
distributionColumns.push(granularity_sqla);
}
return [
{
...baseQueryObject,
columns: [...distributionColumns, ...columns, ...groupby],
series_columns: groupby,
post_processing: [boxplotOperator(formData, baseQueryObject)],
},
];
});
}
| superset-frontend/plugins/plugin-chart-echarts/src/BoxPlot/buildQuery.ts | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00017473982006777078,
0.00017253620899282396,
0.00016913378203753382,
0.0001734971592668444,
0.0000022816043383500073
] |
{
"id": 3,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.info\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def info_headless(self, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB _info endpoint\n",
" \"\"\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 388
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import functools
import logging
from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type, Union
from flask import Blueprint, g, request, Response
from flask_appbuilder import AppBuilder, Model, ModelRestApi
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.filters import BaseFilter, Filters
from flask_appbuilder.models.sqla.filters import FilterStartsWith
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import lazy_gettext as _
from marshmallow import fields, Schema
from sqlalchemy import and_, distinct, func
from sqlalchemy.orm.query import Query
from superset.exceptions import InvalidPayloadFormatError
from superset.extensions import db, event_logger, security_manager
from superset.models.core import FavStar
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice
from superset.schemas import error_payload_content
from superset.sql_lab import Query as SqllabQuery
from superset.stats_logger import BaseStatsLogger
from superset.superset_typing import FlaskResponse
from superset.utils.core import time_function
logger = logging.getLogger(__name__)
get_related_schema = {
"type": "object",
"properties": {
"page_size": {"type": "integer"},
"page": {"type": "integer"},
"include_ids": {"type": "array", "items": {"type": "integer"}},
"filter": {"type": "string"},
},
}
class RelatedResultResponseSchema(Schema):
value = fields.Integer(description="The related item identifier")
text = fields.String(description="The related item string representation")
class RelatedResponseSchema(Schema):
count = fields.Integer(description="The total number of related values")
result = fields.List(fields.Nested(RelatedResultResponseSchema))
class DistinctResultResponseSchema(Schema):
text = fields.String(description="The distinct item")
class DistincResponseSchema(Schema):
count = fields.Integer(description="The total number of distinct values")
result = fields.List(fields.Nested(DistinctResultResponseSchema))
def requires_json(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require JSON-like formatted request to the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.is_json:
raise InvalidPayloadFormatError(message="Request is not JSON")
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def requires_form_data(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require 'multipart/form-data' as request MIME type
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.mimetype == "multipart/form-data":
raise InvalidPayloadFormatError(
message="Request MIME type is not 'multipart/form-data'"
)
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def statsd_metrics(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Handle sending all statsd metrics from the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
try:
duration, response = time_function(f, self, *args, **kwargs)
except Exception as ex:
self.incr_stats("error", f.__name__)
raise ex
self.send_stats_metrics(response, f.__name__, duration)
return response
return functools.update_wrapper(wraps, f)
class RelatedFieldFilter:
# data class to specify what filter to use on a /related endpoint
# pylint: disable=too-few-public-methods
def __init__(self, field_name: str, filter_class: Type[BaseFilter]):
self.field_name = field_name
self.filter_class = filter_class
class BaseFavoriteFilter(BaseFilter): # pylint: disable=too-few-public-methods
"""
Base Custom filter for the GET list that filters all dashboards, slices
that a user has favored or not
"""
name = _("Is favorite")
arg_name = ""
class_name = ""
""" The FavStar class_name to user """
model: Type[Union[Dashboard, Slice, SqllabQuery]] = Dashboard
""" The SQLAlchemy model """
def apply(self, query: Query, value: Any) -> Query:
# If anonymous user filter nothing
if security_manager.current_user is None:
return query
users_favorite_query = db.session.query(FavStar.obj_id).filter(
and_(
FavStar.user_id == g.user.get_id(),
FavStar.class_name == self.class_name,
)
)
if value:
return query.filter(and_(self.model.id.in_(users_favorite_query)))
return query.filter(and_(~self.model.id.in_(users_favorite_query)))
class BaseSupersetModelRestApi(ModelRestApi):
"""
Extends FAB's ModelResApi to implement specific superset generic functionality
"""
csrf_exempt = False
method_permission_name = {
"bulk_delete": "delete",
"data": "list",
"data_from_cache": "list",
"delete": "delete",
"distinct": "list",
"export": "mulexport",
"import_": "add",
"get": "show",
"get_list": "list",
"info": "list",
"post": "add",
"put": "edit",
"refresh": "edit",
"related": "list",
"related_objects": "list",
"schemas": "list",
"select_star": "list",
"table_metadata": "list",
"test_connection": "post",
"thumbnail": "list",
"viz_types": "list",
}
order_rel_fields: Dict[str, Tuple[str, str]] = {}
"""
Impose ordering on related fields query::
order_rel_fields = {
"<RELATED_FIELD>": ("<RELATED_FIELD_FIELD>", "<asc|desc>"),
...
}
"""
related_field_filters: Dict[str, Union[RelatedFieldFilter, str]] = {}
"""
Declare the filters for related fields::
related_fields = {
"<RELATED_FIELD>": <RelatedFieldFilter>)
}
"""
filter_rel_fields: Dict[str, BaseFilter] = {}
"""
Declare the related field base filter::
filter_rel_fields_field = {
"<RELATED_FIELD>": "<FILTER>")
}
"""
allowed_rel_fields: Set[str] = set()
# Declare a set of allowed related fields that the `related` endpoint supports.
text_field_rel_fields: Dict[str, str] = {}
"""
Declare an alternative for the human readable representation of the Model object::
text_field_rel_fields = {
"<RELATED_FIELD>": "<RELATED_OBJECT_FIELD>"
}
"""
allowed_distinct_fields: Set[str] = set()
add_columns: List[str]
edit_columns: List[str]
list_columns: List[str]
show_columns: List[str]
responses = {
"400": {"description": "Bad request", "content": error_payload_content},
"401": {"description": "Unauthorized", "content": error_payload_content},
"403": {"description": "Forbidden", "content": error_payload_content},
"404": {"description": "Not found", "content": error_payload_content},
"422": {
"description": "Could not process entity",
"content": error_payload_content,
},
"500": {"description": "Fatal error", "content": error_payload_content},
}
def __init__(self) -> None:
super().__init__()
# Setup statsd
self.stats_logger = BaseStatsLogger()
# Add base API spec base query parameter schemas
if self.apispec_parameter_schemas is None: # type: ignore
self.apispec_parameter_schemas = {}
self.apispec_parameter_schemas["get_related_schema"] = get_related_schema
self.openapi_spec_component_schemas: Tuple[
Type[Schema], ...
] = self.openapi_spec_component_schemas + (
RelatedResponseSchema,
DistincResponseSchema,
)
def create_blueprint(
self, appbuilder: AppBuilder, *args: Any, **kwargs: Any
) -> Blueprint:
self.stats_logger = self.appbuilder.get_app.config["STATS_LOGGER"]
return super().create_blueprint(appbuilder, *args, **kwargs)
def _init_properties(self) -> None:
"""
Lock down initial not configured REST API columns. We want to just expose
model ids, if something is misconfigured. By default FAB exposes all available
columns on a Model
"""
model_id = self.datamodel.get_pk_name()
if self.list_columns is None and not self.list_model_schema:
self.list_columns = [model_id]
if self.show_columns is None and not self.show_model_schema:
self.show_columns = [model_id]
if self.edit_columns is None and not self.edit_model_schema:
self.edit_columns = [model_id]
if self.add_columns is None and not self.add_model_schema:
self.add_columns = [model_id]
super()._init_properties()
def _get_related_filter(
self, datamodel: SQLAInterface, column_name: str, value: str
) -> Filters:
filter_field = self.related_field_filters.get(column_name)
if isinstance(filter_field, str):
filter_field = RelatedFieldFilter(cast(str, filter_field), FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = datamodel.get_filters(search_columns)
base_filters = self.filter_rel_fields.get(column_name)
if base_filters:
filters.add_filter_list(base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_distinct_filter(self, column_name: str, value: str) -> Filters:
filter_field = RelatedFieldFilter(column_name, FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = self.datamodel.get_filters(search_columns)
filters.add_filter_list(self.base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_text_for_model(self, model: Model, column_name: str) -> str:
if column_name in self.text_field_rel_fields:
model_column_name = self.text_field_rel_fields.get(column_name)
if model_column_name:
return getattr(model, model_column_name)
return str(model)
def _get_result_from_rows(
self, datamodel: SQLAInterface, rows: List[Model], column_name: str
) -> List[Dict[str, Any]]:
return [
{
"value": datamodel.get_pk_value(row),
"text": self._get_text_for_model(row, column_name),
}
for row in rows
]
def _add_extra_ids_to_result(
self,
datamodel: SQLAInterface,
column_name: str,
ids: List[int],
result: List[Dict[str, Any]],
) -> None:
if ids:
# Filter out already present values on the result
values = [row["value"] for row in result]
ids = [id_ for id_ in ids if id_ not in values]
pk_col = datamodel.get_pk()
# Fetch requested values from ids
extra_rows = db.session.query(datamodel.obj).filter(pk_col.in_(ids)).all()
result += self._get_result_from_rows(datamodel, extra_rows, column_name)
def incr_stats(self, action: str, func_name: str) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
"""
self.stats_logger.incr(f"{self.__class__.__name__}.{func_name}.{action}")
def timing_stats(self, action: str, func_name: str, value: float) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
:param value: A float with the time it took for the endpoint to execute
"""
self.stats_logger.timing(
f"{self.__class__.__name__}.{func_name}.{action}", value
)
def send_stats_metrics(
self, response: Response, key: str, time_delta: Optional[float] = None
) -> None:
"""
Helper function to handle sending statsd metrics
:param response: flask response object, will evaluate if it was an error
:param key: The function name
:param time_delta: Optional time it took for the endpoint to execute
"""
if 200 <= response.status_code < 400:
self.incr_stats("success", key)
else:
self.incr_stats("error", key)
if time_delta:
self.timing_stats("time", key, time_delta)
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.info",
object_ref=False,
log_to_statsd=False,
)
def info_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB _info endpoint
"""
duration, response = time_function(super().info_headless, **kwargs)
self.send_stats_metrics(response, self.info.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get",
object_ref=False,
log_to_statsd=False,
)
def get_headless(self, pk: int, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET endpoint
"""
duration, response = time_function(super().get_headless, pk, **kwargs)
self.send_stats_metrics(response, self.get.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_list",
object_ref=False,
log_to_statsd=False,
)
def get_list_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET list endpoint
"""
duration, response = time_function(super().get_list_headless, **kwargs)
self.send_stats_metrics(response, self.get_list.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
object_ref=False,
log_to_statsd=False,
)
def post_headless(self) -> Response:
"""
Add statsd metrics to builtin FAB POST endpoint
"""
duration, response = time_function(super().post_headless)
self.send_stats_metrics(response, self.post.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put",
object_ref=False,
log_to_statsd=False,
)
def put_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB PUT endpoint
"""
duration, response = time_function(super().put_headless, pk)
self.send_stats_metrics(response, self.put.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete",
object_ref=False,
log_to_statsd=False,
)
def delete_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB DELETE endpoint
"""
duration, response = time_function(super().delete_headless, pk)
self.send_stats_metrics(response, self.delete.__name__, duration)
return response
@expose("/related/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def related(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get related fields data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Related column data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/RelatedResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_rel_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._handle_page_args(args)
ids = args.get("include_ids")
if page and ids:
# pagination with forced ids is not supported
return self.response_422()
try:
datamodel = self.datamodel.get_related_interface(column_name)
except KeyError:
return self.response_404()
page, page_size = self._sanitize_page_args(page, page_size)
# handle ordering
order_field = self.order_rel_fields.get(column_name)
if order_field:
order_column, order_direction = order_field
else:
order_column, order_direction = "", ""
# handle filters
filters = self._get_related_filter(datamodel, column_name, args.get("filter"))
# Make the query
total_rows, rows = datamodel.query(
filters, order_column, order_direction, page=page, page_size=page_size
)
# produce response
result = self._get_result_from_rows(datamodel, rows, column_name)
# If ids are specified make sure we fetch and include them on the response
if ids:
self._add_extra_ids_to_result(datamodel, column_name, ids, result)
total_rows = len(result)
return self.response(200, count=total_rows, result=result)
@expose("/distinct/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get distinct values from field data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Distinct field data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/DistincResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_distinct_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._sanitize_page_args(*self._handle_page_args(args))
# Create generic base filters with added request filter
filters = self._get_distinct_filter(column_name, args.get("filter"))
# Make the query
query_count = self.appbuilder.get_session.query(
func.count(distinct(getattr(self.datamodel.obj, column_name)))
)
count = self.datamodel.apply_filters(query_count, filters).scalar()
if count == 0:
return self.response(200, count=count, result=[])
query = self.appbuilder.get_session.query(
distinct(getattr(self.datamodel.obj, column_name))
)
# Apply generic base filters with added request filter
query = self.datamodel.apply_filters(query, filters)
# Apply sort
query = self.datamodel.apply_order_by(query, column_name, "asc")
# Apply pagination
result = self.datamodel.apply_pagination(query, page, page_size).all()
# produce response
result = [
{"text": item[0], "value": item[0]}
for item in result
if item[0] is not None
]
return self.response(200, count=count, result=result)
| superset/views/base_api.py | 1 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.9944157600402832,
0.01864568702876568,
0.000163940159836784,
0.0001767555804690346,
0.126167431473732
] |
{
"id": 3,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.info\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def info_headless(self, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB _info endpoint\n",
" \"\"\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 388
} | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
export type AnnotationLayerMetadata = {
name: string;
sourceType?: string;
};
| superset-frontend/packages/superset-ui-core/src/chart/types/Annotation.ts | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00017520914843771607,
0.0001731625379761681,
0.0001707447663648054,
0.00017353369912598282,
0.000001841375819822133
] |
{
"id": 3,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.info\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def info_headless(self, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB _info endpoint\n",
" \"\"\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 388
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# isort:skip_file
import re
from typing import Any, Dict, List, Optional
from unittest import mock
import pytest
from flask import g
from superset import db, security_manager
from superset.connectors.sqla.models import RowLevelSecurityFilter, SqlaTable
from superset.security.guest_token import (
GuestTokenRlsRule,
GuestTokenResourceType,
GuestUser,
)
from ..base_tests import SupersetTestCase
from tests.integration_tests.fixtures.birth_names_dashboard import (
load_birth_names_dashboard_with_slices,
load_birth_names_data,
)
from tests.integration_tests.fixtures.energy_dashboard import (
load_energy_table_with_slice,
load_energy_table_data,
)
from tests.integration_tests.fixtures.unicode_dashboard import (
load_unicode_dashboard_with_slice,
load_unicode_data,
)
class TestRowLevelSecurity(SupersetTestCase):
"""
Testing Row Level Security
"""
rls_entry = None
query_obj: Dict[str, Any] = dict(
groupby=[],
metrics=None,
filter=[],
is_timeseries=False,
columns=["value"],
granularity=None,
from_dttm=None,
to_dttm=None,
extras={},
)
NAME_AB_ROLE = "NameAB"
NAME_Q_ROLE = "NameQ"
NAMES_A_REGEX = re.compile(r"name like 'A%'")
NAMES_B_REGEX = re.compile(r"name like 'B%'")
NAMES_Q_REGEX = re.compile(r"name like 'Q%'")
BASE_FILTER_REGEX = re.compile(r"gender = 'boy'")
def setUp(self):
session = db.session
# Create roles
self.role_ab = security_manager.add_role(self.NAME_AB_ROLE)
self.role_q = security_manager.add_role(self.NAME_Q_ROLE)
gamma_user = security_manager.find_user(username="gamma")
gamma_user.roles.append(self.role_ab)
gamma_user.roles.append(self.role_q)
self.create_user_with_roles("NoRlsRoleUser", ["Gamma"])
session.commit()
# Create regular RowLevelSecurityFilter (energy_usage, unicode_test)
self.rls_entry1 = RowLevelSecurityFilter()
self.rls_entry1.tables.extend(
session.query(SqlaTable)
.filter(SqlaTable.table_name.in_(["energy_usage", "unicode_test"]))
.all()
)
self.rls_entry1.filter_type = "Regular"
self.rls_entry1.clause = "value > {{ cache_key_wrapper(1) }}"
self.rls_entry1.group_key = None
self.rls_entry1.roles.append(security_manager.find_role("Gamma"))
self.rls_entry1.roles.append(security_manager.find_role("Alpha"))
db.session.add(self.rls_entry1)
# Create regular RowLevelSecurityFilter (birth_names name starts with A or B)
self.rls_entry2 = RowLevelSecurityFilter()
self.rls_entry2.tables.extend(
session.query(SqlaTable)
.filter(SqlaTable.table_name.in_(["birth_names"]))
.all()
)
self.rls_entry2.filter_type = "Regular"
self.rls_entry2.clause = "name like 'A%' or name like 'B%'"
self.rls_entry2.group_key = "name"
self.rls_entry2.roles.append(security_manager.find_role("NameAB"))
db.session.add(self.rls_entry2)
# Create Regular RowLevelSecurityFilter (birth_names name starts with Q)
self.rls_entry3 = RowLevelSecurityFilter()
self.rls_entry3.tables.extend(
session.query(SqlaTable)
.filter(SqlaTable.table_name.in_(["birth_names"]))
.all()
)
self.rls_entry3.filter_type = "Regular"
self.rls_entry3.clause = "name like 'Q%'"
self.rls_entry3.group_key = "name"
self.rls_entry3.roles.append(security_manager.find_role("NameQ"))
db.session.add(self.rls_entry3)
# Create Base RowLevelSecurityFilter (birth_names boys)
self.rls_entry4 = RowLevelSecurityFilter()
self.rls_entry4.tables.extend(
session.query(SqlaTable)
.filter(SqlaTable.table_name.in_(["birth_names"]))
.all()
)
self.rls_entry4.filter_type = "Base"
self.rls_entry4.clause = "gender = 'boy'"
self.rls_entry4.group_key = "gender"
self.rls_entry4.roles.append(security_manager.find_role("Admin"))
db.session.add(self.rls_entry4)
db.session.commit()
def tearDown(self):
session = db.session
session.delete(self.rls_entry1)
session.delete(self.rls_entry2)
session.delete(self.rls_entry3)
session.delete(self.rls_entry4)
session.delete(security_manager.find_role("NameAB"))
session.delete(security_manager.find_role("NameQ"))
session.delete(self.get_user("NoRlsRoleUser"))
session.commit()
@pytest.mark.usefixtures("load_energy_table_with_slice")
def test_rls_filter_alters_energy_query(self):
g.user = self.get_user(username="alpha")
tbl = self.get_table(name="energy_usage")
sql = tbl.get_query_str(self.query_obj)
assert tbl.get_extra_cache_keys(self.query_obj) == [1]
assert "value > 1" in sql
@pytest.mark.usefixtures("load_energy_table_with_slice")
def test_rls_filter_doesnt_alter_energy_query(self):
g.user = self.get_user(
username="admin"
) # self.login() doesn't actually set the user
tbl = self.get_table(name="energy_usage")
sql = tbl.get_query_str(self.query_obj)
assert tbl.get_extra_cache_keys(self.query_obj) == []
assert "value > 1" not in sql
@pytest.mark.usefixtures("load_unicode_dashboard_with_slice")
def test_multiple_table_filter_alters_another_tables_query(self):
g.user = self.get_user(
username="alpha"
) # self.login() doesn't actually set the user
tbl = self.get_table(name="unicode_test")
sql = tbl.get_query_str(self.query_obj)
assert tbl.get_extra_cache_keys(self.query_obj) == [1]
assert "value > 1" in sql
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_rls_filter_alters_gamma_birth_names_query(self):
g.user = self.get_user(username="gamma")
tbl = self.get_table(name="birth_names")
sql = tbl.get_query_str(self.query_obj)
# establish that the filters are grouped together correctly with
# ANDs, ORs and parens in the correct place
assert (
"WHERE ((name like 'A%'\n or name like 'B%')\n OR (name like 'Q%'))\n AND (gender = 'boy');"
in sql
)
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_rls_filter_alters_no_role_user_birth_names_query(self):
g.user = self.get_user(username="NoRlsRoleUser")
tbl = self.get_table(name="birth_names")
sql = tbl.get_query_str(self.query_obj)
# gamma's filters should not be present query
assert not self.NAMES_A_REGEX.search(sql)
assert not self.NAMES_B_REGEX.search(sql)
assert not self.NAMES_Q_REGEX.search(sql)
# base query should be present
assert self.BASE_FILTER_REGEX.search(sql)
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_rls_filter_doesnt_alter_admin_birth_names_query(self):
g.user = self.get_user(username="admin")
tbl = self.get_table(name="birth_names")
sql = tbl.get_query_str(self.query_obj)
# no filters are applied for admin user
assert not self.NAMES_A_REGEX.search(sql)
assert not self.NAMES_B_REGEX.search(sql)
assert not self.NAMES_Q_REGEX.search(sql)
assert not self.BASE_FILTER_REGEX.search(sql)
RLS_ALICE_REGEX = re.compile(r"name = 'Alice'")
RLS_GENDER_REGEX = re.compile(r"AND \(gender = 'girl'\)")
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
EMBEDDED_SUPERSET=True,
)
class GuestTokenRowLevelSecurityTests(SupersetTestCase):
query_obj: Dict[str, Any] = dict(
groupby=[],
metrics=None,
filter=[],
is_timeseries=False,
columns=["value"],
granularity=None,
from_dttm=None,
to_dttm=None,
extras={},
)
def default_rls_rule(self):
return {
"dataset": self.get_table(name="birth_names").id,
"clause": "name = 'Alice'",
}
def guest_user_with_rls(self, rules: Optional[List[Any]] = None) -> GuestUser:
if rules is None:
rules = [self.default_rls_rule()]
return security_manager.get_guest_user_from_token(
{
"user": {},
"resources": [{"type": GuestTokenResourceType.DASHBOARD.value}],
"rls_rules": rules,
}
)
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_rls_filter_alters_query(self):
g.user = self.guest_user_with_rls()
tbl = self.get_table(name="birth_names")
sql = tbl.get_query_str(self.query_obj)
self.assertRegex(sql, RLS_ALICE_REGEX)
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_rls_filter_does_not_alter_unrelated_query(self):
g.user = self.guest_user_with_rls(
rules=[
{
"dataset": self.get_table(name="birth_names").id + 1,
"clause": "name = 'Alice'",
}
]
)
tbl = self.get_table(name="birth_names")
sql = tbl.get_query_str(self.query_obj)
self.assertNotRegex(sql, RLS_ALICE_REGEX)
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_multiple_rls_filters_are_unionized(self):
g.user = self.guest_user_with_rls(
rules=[
self.default_rls_rule(),
{
"dataset": self.get_table(name="birth_names").id,
"clause": "gender = 'girl'",
},
]
)
tbl = self.get_table(name="birth_names")
sql = tbl.get_query_str(self.query_obj)
self.assertRegex(sql, RLS_ALICE_REGEX)
self.assertRegex(sql, RLS_GENDER_REGEX)
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
@pytest.mark.usefixtures("load_energy_table_with_slice")
def test_rls_filter_for_all_datasets(self):
births = self.get_table(name="birth_names")
energy = self.get_table(name="energy_usage")
guest = self.guest_user_with_rls(rules=[{"clause": "name = 'Alice'"}])
guest.resources.append({type: "dashboard", id: energy.id})
g.user = guest
births_sql = births.get_query_str(self.query_obj)
energy_sql = energy.get_query_str(self.query_obj)
self.assertRegex(births_sql, RLS_ALICE_REGEX)
self.assertRegex(energy_sql, RLS_ALICE_REGEX)
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_dataset_id_can_be_string(self):
dataset = self.get_table(name="birth_names")
str_id = str(dataset.id)
g.user = self.guest_user_with_rls(
rules=[{"dataset": str_id, "clause": "name = 'Alice'"}]
)
sql = dataset.get_query_str(self.query_obj)
self.assertRegex(sql, RLS_ALICE_REGEX)
| tests/integration_tests/security/row_level_security_tests.py | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.02478398010134697,
0.0009423441952094436,
0.00016455423610750586,
0.00017244885384570807,
0.004282092209905386
] |
{
"id": 3,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.info\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def info_headless(self, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB _info endpoint\n",
" \"\"\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 388
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from . import models, views
| superset/connectors/sqla/__init__.py | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0001778097212081775,
0.0001772823161445558,
0.00017675489652901888,
0.0001772823161445558,
5.27412339579314e-7
] |
{
"id": 4,
"code_window": [
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.get\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def get_headless(self, pk: int, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB GET endpoint\n",
" \"\"\"\n",
" duration, response = time_function(super().get_headless, pk, **kwargs)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 401
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import dataclasses
import functools
import logging
import traceback
from datetime import datetime
from typing import Any, Callable, cast, Dict, List, Optional, TYPE_CHECKING, Union
import simplejson as json
import yaml
from flask import (
abort,
flash,
g,
get_flashed_messages,
redirect,
request,
Response,
send_file,
session,
)
from flask_appbuilder import BaseView, Model, ModelView
from flask_appbuilder.actions import action
from flask_appbuilder.forms import DynamicForm
from flask_appbuilder.models.sqla.filters import BaseFilter
from flask_appbuilder.security.sqla.models import User
from flask_appbuilder.widgets import ListWidget
from flask_babel import get_locale, gettext as __, lazy_gettext as _
from flask_jwt_extended.exceptions import NoAuthorizationError
from flask_wtf.csrf import CSRFError
from flask_wtf.form import FlaskForm
from pkg_resources import resource_filename
from sqlalchemy import or_
from sqlalchemy.orm import Query
from werkzeug.exceptions import HTTPException
from wtforms import Form
from wtforms.fields.core import Field, UnboundField
from superset import (
app as superset_app,
appbuilder,
conf,
db,
get_feature_flags,
security_manager,
)
from superset.commands.exceptions import CommandException, CommandInvalidError
from superset.connectors.sqla import models
from superset.datasets.commands.exceptions import get_dataset_exist_error_msg
from superset.db_engine_specs import get_available_engine_specs
from superset.db_engine_specs.gsheets import GSheetsEngineSpec
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.exceptions import (
SupersetErrorException,
SupersetErrorsException,
SupersetException,
SupersetSecurityException,
)
from superset.models.helpers import ImportExportMixin
from superset.models.reports import ReportRecipientType
from superset.superset_typing import FlaskResponse
from superset.translations.utils import get_language_pack
from superset.utils import core as utils
from .utils import bootstrap_user_data
if TYPE_CHECKING:
from superset.connectors.druid.views import DruidClusterModelView
FRONTEND_CONF_KEYS = (
"SUPERSET_WEBSERVER_TIMEOUT",
"SUPERSET_DASHBOARD_POSITION_DATA_LIMIT",
"SUPERSET_DASHBOARD_PERIODICAL_REFRESH_LIMIT",
"SUPERSET_DASHBOARD_PERIODICAL_REFRESH_WARNING_MESSAGE",
"DISABLE_DATASET_SOURCE_EDIT",
"DRUID_IS_ACTIVE",
"ENABLE_JAVASCRIPT_CONTROLS",
"DEFAULT_SQLLAB_LIMIT",
"DEFAULT_VIZ_TYPE",
"SQL_MAX_ROW",
"SUPERSET_WEBSERVER_DOMAINS",
"SQLLAB_SAVE_WARNING_MESSAGE",
"DISPLAY_MAX_ROW",
"GLOBAL_ASYNC_QUERIES_TRANSPORT",
"GLOBAL_ASYNC_QUERIES_POLLING_DELAY",
"SQL_VALIDATORS_BY_ENGINE",
"SQLALCHEMY_DOCS_URL",
"SQLALCHEMY_DISPLAY_TEXT",
"GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL",
"DASHBOARD_AUTO_REFRESH_MODE",
"SCHEDULED_QUERIES",
"EXCEL_EXTENSIONS",
"CSV_EXTENSIONS",
"COLUMNAR_EXTENSIONS",
"ALLOWED_EXTENSIONS",
)
logger = logging.getLogger(__name__)
config = superset_app.config
def get_error_msg() -> str:
if conf.get("SHOW_STACKTRACE"):
error_msg = traceback.format_exc()
else:
error_msg = "FATAL ERROR \n"
error_msg += (
"Stacktrace is hidden. Change the SHOW_STACKTRACE "
"configuration setting to enable it"
)
return error_msg
def json_error_response(
msg: Optional[str] = None,
status: int = 500,
payload: Optional[Dict[str, Any]] = None,
link: Optional[str] = None,
) -> FlaskResponse:
if not payload:
payload = {"error": "{}".format(msg)}
if link:
payload["link"] = link
return Response(
json.dumps(payload, default=utils.json_iso_dttm_ser, ignore_nan=True),
status=status,
mimetype="application/json",
)
def json_errors_response(
errors: List[SupersetError],
status: int = 500,
payload: Optional[Dict[str, Any]] = None,
) -> FlaskResponse:
if not payload:
payload = {}
payload["errors"] = [dataclasses.asdict(error) for error in errors]
return Response(
json.dumps(payload, default=utils.json_iso_dttm_ser, ignore_nan=True),
status=status,
mimetype="application/json; charset=utf-8",
)
def json_success(json_msg: str, status: int = 200) -> FlaskResponse:
return Response(json_msg, status=status, mimetype="application/json")
def data_payload_response(payload_json: str, has_error: bool = False) -> FlaskResponse:
status = 400 if has_error else 200
return json_success(payload_json, status=status)
def generate_download_headers(
extension: str, filename: Optional[str] = None
) -> Dict[str, Any]:
filename = filename if filename else datetime.now().strftime("%Y%m%d_%H%M%S")
content_disp = f"attachment; filename={filename}.{extension}"
headers = {"Content-Disposition": content_disp}
return headers
def api(f: Callable[..., FlaskResponse]) -> Callable[..., FlaskResponse]:
"""
A decorator to label an endpoint as an API. Catches uncaught exceptions and
return the response in the JSON format
"""
def wraps(self: "BaseSupersetView", *args: Any, **kwargs: Any) -> FlaskResponse:
try:
return f(self, *args, **kwargs)
except NoAuthorizationError as ex:
logger.warning(ex)
return json_error_response(get_error_msg(), status=401)
except Exception as ex: # pylint: disable=broad-except
logger.exception(ex)
return json_error_response(get_error_msg())
return functools.update_wrapper(wraps, f)
def handle_api_exception(
f: Callable[..., FlaskResponse]
) -> Callable[..., FlaskResponse]:
"""
A decorator to catch superset exceptions. Use it after the @api decorator above
so superset exception handler is triggered before the handler for generic
exceptions.
"""
def wraps(self: "BaseSupersetView", *args: Any, **kwargs: Any) -> FlaskResponse:
try:
return f(self, *args, **kwargs)
except SupersetSecurityException as ex:
logger.warning(ex)
return json_errors_response(
errors=[ex.error], status=ex.status, payload=ex.payload
)
except SupersetErrorsException as ex:
logger.warning(ex, exc_info=True)
return json_errors_response(errors=ex.errors, status=ex.status)
except SupersetErrorException as ex:
logger.warning(ex)
return json_errors_response(errors=[ex.error], status=ex.status)
except SupersetException as ex:
if ex.status >= 500:
logger.exception(ex)
return json_error_response(
utils.error_msg_from_exception(ex), status=ex.status
)
except HTTPException as ex:
logger.exception(ex)
return json_error_response(
utils.error_msg_from_exception(ex), status=cast(int, ex.code)
)
except Exception as ex: # pylint: disable=broad-except
logger.exception(ex)
return json_error_response(utils.error_msg_from_exception(ex))
return functools.update_wrapper(wraps, f)
def validate_sqlatable(table: models.SqlaTable) -> None:
"""Checks the table existence in the database."""
with db.session.no_autoflush:
table_query = db.session.query(models.SqlaTable).filter(
models.SqlaTable.table_name == table.table_name,
models.SqlaTable.schema == table.schema,
models.SqlaTable.database_id == table.database.id,
)
if db.session.query(table_query.exists()).scalar():
raise Exception(get_dataset_exist_error_msg(table.full_name))
# Fail before adding if the table can't be found
try:
table.get_sqla_table_object()
except Exception as ex:
logger.exception("Got an error in pre_add for %s", table.name)
raise Exception(
_(
"Table [%{table}s] could not be found, "
"please double check your "
"database connection, schema, and "
"table name, error: {}"
).format(table.name, str(ex))
) from ex
def create_table_permissions(table: models.SqlaTable) -> None:
security_manager.add_permission_view_menu("datasource_access", table.get_perm())
if table.schema:
security_manager.add_permission_view_menu("schema_access", table.schema_perm)
def is_user_admin() -> bool:
user_roles = [role.name.lower() for role in list(security_manager.get_user_roles())]
return "admin" in user_roles
class BaseSupersetView(BaseView):
@staticmethod
def json_response(obj: Any, status: int = 200) -> FlaskResponse:
return Response(
json.dumps(obj, default=utils.json_int_dttm_ser, ignore_nan=True),
status=status,
mimetype="application/json",
)
def render_app_template(self) -> FlaskResponse:
payload = {
"user": bootstrap_user_data(g.user, include_perms=True),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/spa.html",
entry="spa",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
def menu_data() -> Dict[str, Any]:
menu = appbuilder.menu.get_data()
languages = {}
for lang in appbuilder.languages:
languages[lang] = {
**appbuilder.languages[lang],
"url": appbuilder.get_url_for_locale(lang),
}
brand_text = appbuilder.app.config["LOGO_RIGHT_TEXT"]
if callable(brand_text):
brand_text = brand_text()
build_number = appbuilder.app.config["BUILD_NUMBER"]
return {
"menu": menu,
"brand": {
"path": appbuilder.app.config["LOGO_TARGET_PATH"] or "/",
"icon": appbuilder.app_icon,
"alt": appbuilder.app_name,
"tooltip": appbuilder.app.config["LOGO_TOOLTIP"],
"text": brand_text,
},
"navbar_right": {
# show the watermark if the default app icon has been overriden
"show_watermark": ("superset-logo-horiz" not in appbuilder.app_icon),
"bug_report_url": appbuilder.app.config["BUG_REPORT_URL"],
"documentation_url": appbuilder.app.config["DOCUMENTATION_URL"],
"version_string": appbuilder.app.config["VERSION_STRING"],
"version_sha": appbuilder.app.config["VERSION_SHA"],
"build_number": build_number,
"languages": languages,
"show_language_picker": len(languages.keys()) > 1,
"user_is_anonymous": g.user.is_anonymous,
"user_info_url": None
if appbuilder.app.config["MENU_HIDE_USER_INFO"]
else appbuilder.get_url_for_userinfo,
"user_logout_url": appbuilder.get_url_for_logout,
"user_login_url": appbuilder.get_url_for_login,
"user_profile_url": None
if g.user.is_anonymous or appbuilder.app.config["MENU_HIDE_USER_INFO"]
else f"/superset/profile/{g.user.username}",
"locale": session.get("locale", "en"),
},
}
def common_bootstrap_payload() -> Dict[str, Any]:
"""Common data always sent to the client"""
messages = get_flashed_messages(with_categories=True)
locale = str(get_locale())
# should not expose API TOKEN to frontend
frontend_config = {
k: (list(conf.get(k)) if isinstance(conf.get(k), set) else conf.get(k))
for k in FRONTEND_CONF_KEYS
}
if conf.get("SLACK_API_TOKEN"):
frontend_config["ALERT_REPORTS_NOTIFICATION_METHODS"] = [
ReportRecipientType.EMAIL,
ReportRecipientType.SLACK,
]
else:
frontend_config["ALERT_REPORTS_NOTIFICATION_METHODS"] = [
ReportRecipientType.EMAIL,
]
# verify client has google sheets installed
available_specs = get_available_engine_specs()
frontend_config["HAS_GSHEETS_INSTALLED"] = bool(available_specs[GSheetsEngineSpec])
bootstrap_data = {
"flash_messages": messages,
"conf": frontend_config,
"locale": locale,
"language_pack": get_language_pack(locale),
"feature_flags": get_feature_flags(),
"extra_sequential_color_schemes": conf["EXTRA_SEQUENTIAL_COLOR_SCHEMES"],
"extra_categorical_color_schemes": conf["EXTRA_CATEGORICAL_COLOR_SCHEMES"],
"theme_overrides": conf["THEME_OVERRIDES"],
"menu_data": menu_data(),
}
bootstrap_data.update(conf["COMMON_BOOTSTRAP_OVERRIDES_FUNC"](bootstrap_data))
return bootstrap_data
def get_error_level_from_status_code( # pylint: disable=invalid-name
status: int,
) -> ErrorLevel:
if status < 400:
return ErrorLevel.INFO
if status < 500:
return ErrorLevel.WARNING
return ErrorLevel.ERROR
# SIP-40 compatible error responses; make sure APIs raise
# SupersetErrorException or SupersetErrorsException
@superset_app.errorhandler(SupersetErrorException)
def show_superset_error(ex: SupersetErrorException) -> FlaskResponse:
logger.warning(ex)
return json_errors_response(errors=[ex.error], status=ex.status)
@superset_app.errorhandler(SupersetErrorsException)
def show_superset_errors(ex: SupersetErrorsException) -> FlaskResponse:
logger.warning(ex)
return json_errors_response(errors=ex.errors, status=ex.status)
# Redirect to login if the CSRF token is expired
@superset_app.errorhandler(CSRFError)
def refresh_csrf_token(ex: CSRFError) -> FlaskResponse:
logger.warning(ex)
if request.is_json:
return show_http_exception(ex)
return redirect(appbuilder.get_url_for_login)
@superset_app.errorhandler(HTTPException)
def show_http_exception(ex: HTTPException) -> FlaskResponse:
logger.warning(ex)
if (
"text/html" in request.accept_mimetypes
and not config["DEBUG"]
and ex.code in {404, 500}
):
path = resource_filename("superset", f"static/assets/{ex.code}.html")
return send_file(path, cache_timeout=0), ex.code
return json_errors_response(
errors=[
SupersetError(
message=utils.error_msg_from_exception(ex),
error_type=SupersetErrorType.GENERIC_BACKEND_ERROR,
level=ErrorLevel.ERROR,
),
],
status=ex.code or 500,
)
# Temporary handler for CommandException; if an API raises a
# CommandException it should be fixed to map it to SupersetErrorException
# or SupersetErrorsException, with a specific status code and error type
@superset_app.errorhandler(CommandException)
def show_command_errors(ex: CommandException) -> FlaskResponse:
logger.warning(ex)
if "text/html" in request.accept_mimetypes and not config["DEBUG"]:
path = resource_filename("superset", "static/assets/500.html")
return send_file(path, cache_timeout=0), 500
extra = ex.normalized_messages() if isinstance(ex, CommandInvalidError) else {}
return json_errors_response(
errors=[
SupersetError(
message=ex.message,
error_type=SupersetErrorType.GENERIC_COMMAND_ERROR,
level=get_error_level_from_status_code(ex.status),
extra=extra,
),
],
status=ex.status,
)
# Catch-all, to ensure all errors from the backend conform to SIP-40
@superset_app.errorhandler(Exception)
def show_unexpected_exception(ex: Exception) -> FlaskResponse:
logger.exception(ex)
if "text/html" in request.accept_mimetypes and not config["DEBUG"]:
path = resource_filename("superset", "static/assets/500.html")
return send_file(path, cache_timeout=0), 500
return json_errors_response(
errors=[
SupersetError(
message=utils.error_msg_from_exception(ex),
error_type=SupersetErrorType.GENERIC_BACKEND_ERROR,
level=ErrorLevel.ERROR,
),
],
)
@superset_app.context_processor
def get_common_bootstrap_data() -> Dict[str, Any]:
def serialize_bootstrap_data() -> str:
return json.dumps(
{"common": common_bootstrap_payload()},
default=utils.pessimistic_json_iso_dttm_ser,
)
return {"bootstrap_data": serialize_bootstrap_data}
class SupersetListWidget(ListWidget): # pylint: disable=too-few-public-methods
template = "superset/fab_overrides/list.html"
class SupersetModelView(ModelView):
page_size = 100
list_widget = SupersetListWidget
def render_app_template(self) -> FlaskResponse:
payload = {
"user": bootstrap_user_data(g.user, include_perms=True),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/spa.html",
entry="spa",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
class ListWidgetWithCheckboxes(ListWidget): # pylint: disable=too-few-public-methods
"""An alternative to list view that renders Boolean fields as checkboxes
Works in conjunction with the `checkbox` view."""
template = "superset/fab_overrides/list_with_checkboxes.html"
def validate_json(form: Form, field: Field) -> None: # pylint: disable=unused-argument
try:
json.loads(field.data)
except Exception as ex:
logger.exception(ex)
raise Exception(_("json isn't valid")) from ex
class YamlExportMixin: # pylint: disable=too-few-public-methods
"""
Override this if you want a dict response instead, with a certain key.
Used on DatabaseView for cli compatibility
"""
yaml_dict_key: Optional[str] = None
@action("yaml_export", __("Export to YAML"), __("Export to YAML?"), "fa-download")
def yaml_export(
self, items: Union[ImportExportMixin, List[ImportExportMixin]]
) -> FlaskResponse:
if not isinstance(items, list):
items = [items]
data = [t.export_to_dict() for t in items]
return Response(
yaml.safe_dump({self.yaml_dict_key: data} if self.yaml_dict_key else data),
headers=generate_download_headers("yaml"),
mimetype="application/text",
)
class DeleteMixin: # pylint: disable=too-few-public-methods
def _delete(self: BaseView, primary_key: int) -> None:
"""
Delete function logic, override to implement diferent logic
deletes the record with primary_key = primary_key
:param primary_key:
record primary key to delete
"""
item = self.datamodel.get(primary_key, self._base_filters)
if not item:
abort(404)
try:
self.pre_delete(item)
except Exception as ex: # pylint: disable=broad-except
flash(str(ex), "danger")
else:
view_menu = security_manager.find_view_menu(item.get_perm())
pvs = (
security_manager.get_session.query(
security_manager.permissionview_model
)
.filter_by(view_menu=view_menu)
.all()
)
if self.datamodel.delete(item):
self.post_delete(item)
for pv in pvs:
security_manager.get_session.delete(pv)
if view_menu:
security_manager.get_session.delete(view_menu)
security_manager.get_session.commit()
flash(*self.datamodel.message)
self.update_redirect()
@action(
"muldelete", __("Delete"), __("Delete all Really?"), "fa-trash", single=False
)
def muldelete(self: BaseView, items: List[Model]) -> FlaskResponse:
if not items:
abort(404)
for item in items:
try:
self.pre_delete(item)
except Exception as ex: # pylint: disable=broad-except
flash(str(ex), "danger")
else:
self._delete(item.id)
self.update_redirect()
return redirect(self.get_redirect())
class DatasourceFilter(BaseFilter): # pylint: disable=too-few-public-methods
def apply(self, query: Query, value: Any) -> Query:
if security_manager.can_access_all_datasources():
return query
datasource_perms = security_manager.user_view_menu_names("datasource_access")
schema_perms = security_manager.user_view_menu_names("schema_access")
return query.filter(
or_(
self.model.perm.in_(datasource_perms),
self.model.schema_perm.in_(schema_perms),
)
)
class CsvResponse(Response):
"""
Override Response to take into account csv encoding from config.py
"""
charset = conf["CSV_EXPORT"].get("encoding", "utf-8")
default_mimetype = "text/csv"
def check_ownership(obj: Any, raise_if_false: bool = True) -> bool:
"""Meant to be used in `pre_update` hooks on models to enforce ownership
Admin have all access, and other users need to be referenced on either
the created_by field that comes with the ``AuditMixin``, or in a field
named ``owners`` which is expected to be a one-to-many with the User
model. It is meant to be used in the ModelView's pre_update hook in
which raising will abort the update.
"""
if not obj:
return False
security_exception = SupersetSecurityException(
SupersetError(
error_type=SupersetErrorType.MISSING_OWNERSHIP_ERROR,
message="You don't have the rights to alter [{}]".format(obj),
level=ErrorLevel.ERROR,
)
)
if g.user.is_anonymous:
if raise_if_false:
raise security_exception
return False
if is_user_admin():
return True
scoped_session = db.create_scoped_session()
orig_obj = scoped_session.query(obj.__class__).filter_by(id=obj.id).first()
# Making a list of owners that works across ORM models
owners: List[User] = []
if hasattr(orig_obj, "owners"):
owners += orig_obj.owners
if hasattr(orig_obj, "owner"):
owners += [orig_obj.owner]
if hasattr(orig_obj, "created_by"):
owners += [orig_obj.created_by]
owner_names = [o.username for o in owners if o]
if g.user and hasattr(g.user, "username") and g.user.username in owner_names:
return True
if raise_if_false:
raise security_exception
return False
def bind_field(
_: Any, form: DynamicForm, unbound_field: UnboundField, options: Dict[Any, Any]
) -> Field:
"""
Customize how fields are bound by stripping all whitespace.
:param form: The form
:param unbound_field: The unbound field
:param options: The field options
:returns: The bound field
"""
filters = unbound_field.kwargs.get("filters", [])
filters.append(lambda x: x.strip() if isinstance(x, str) else x)
return unbound_field.bind(form=form, filters=filters, **options)
FlaskForm.Meta.bind_field = bind_field
@superset_app.after_request
def apply_http_headers(response: Response) -> Response:
"""Applies the configuration's http headers to all responses"""
# HTTP_HEADERS is deprecated, this provides backwards compatibility
response.headers.extend( # type: ignore
{**config["OVERRIDE_HTTP_HEADERS"], **config["HTTP_HEADERS"]}
)
for k, v in config["DEFAULT_HTTP_HEADERS"].items():
if k not in response.headers:
response.headers[k] = v
return response
| superset/views/base.py | 1 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.010259809903800488,
0.00036687037209048867,
0.00016272430366370827,
0.00017008699069265276,
0.0012327088043093681
] |
{
"id": 4,
"code_window": [
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.get\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def get_headless(self, pk: int, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB GET endpoint\n",
" \"\"\"\n",
" duration, response = time_function(super().get_headless, pk, **kwargs)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 401
} | v16.9.1
| superset-frontend/.nvmrc | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0001685914903646335,
0.0001685914903646335,
0.0001685914903646335,
0.0001685914903646335,
0
] |
{
"id": 4,
"code_window": [
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.get\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def get_headless(self, pk: int, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB GET endpoint\n",
" \"\"\"\n",
" duration, response = time_function(super().get_headless, pk, **kwargs)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 401
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
from datetime import datetime, timedelta, timezone as dt_timezone
from typing import Iterator
from croniter import croniter
from pytz import timezone as pytz_timezone, UnknownTimeZoneError
from superset import app
logger = logging.getLogger(__name__)
def cron_schedule_window(cron: str, timezone: str) -> Iterator[datetime]:
window_size = app.config["ALERT_REPORTS_CRON_WINDOW_SIZE"]
# create a time-aware datetime in utc
time_now = datetime.now(tz=dt_timezone.utc)
try:
tz = pytz_timezone(timezone)
except UnknownTimeZoneError:
# fallback to default timezone
tz = pytz_timezone("UTC")
logger.warning("Timezone %s was invalid. Falling back to 'UTC'", timezone)
utc = pytz_timezone("UTC")
# convert the current time to the user's local time for comparison
time_now = time_now.astimezone(tz)
start_at = time_now - timedelta(seconds=1)
stop_at = time_now + timedelta(seconds=window_size)
crons = croniter(cron, start_at)
for schedule in crons.all_next(datetime):
if schedule >= stop_at:
break
# convert schedule back to utc
yield schedule.astimezone(utc).replace(tzinfo=None)
| superset/tasks/cron_util.py | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00017727747035678476,
0.00017462909454479814,
0.00017200021829921752,
0.00017488159937784076,
0.0000018712390783548472
] |
{
"id": 4,
"code_window": [
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.get\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def get_headless(self, pk: int, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB GET endpoint\n",
" \"\"\"\n",
" duration, response = time_function(super().get_headless, pk, **kwargs)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 401
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from superset.exceptions import InvalidPostProcessingError
from superset.utils.pandas_postprocessing.select import select
from tests.unit_tests.fixtures.dataframes import timeseries_df
def test_select():
# reorder columns
post_df = select(df=timeseries_df, columns=["y", "label"])
assert post_df.columns.tolist() == ["y", "label"]
# one column
post_df = select(df=timeseries_df, columns=["label"])
assert post_df.columns.tolist() == ["label"]
# rename and select one column
post_df = select(df=timeseries_df, columns=["y"], rename={"y": "y1"})
assert post_df.columns.tolist() == ["y1"]
# rename one and leave one unchanged
post_df = select(df=timeseries_df, rename={"y": "y1"})
assert post_df.columns.tolist() == ["label", "y1"]
# drop one column
post_df = select(df=timeseries_df, exclude=["label"])
assert post_df.columns.tolist() == ["y"]
# rename and drop one column
post_df = select(df=timeseries_df, rename={"y": "y1"}, exclude=["label"])
assert post_df.columns.tolist() == ["y1"]
# invalid columns
with pytest.raises(InvalidPostProcessingError):
select(df=timeseries_df, columns=["abc"], rename={"abc": "qwerty"})
# select renamed column by new name
with pytest.raises(InvalidPostProcessingError):
select(df=timeseries_df, columns=["label_new"], rename={"label": "label_new"})
| tests/unit_tests/pandas_postprocessing/test_select.py | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00017727747035678476,
0.00017286698857787997,
0.00016638428496662527,
0.00017337632016278803,
0.00000330108650814509
] |
{
"id": 5,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.get_list\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def get_list_headless(self, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB GET list endpoint\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 414
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import functools
import logging
from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type, Union
from flask import Blueprint, g, request, Response
from flask_appbuilder import AppBuilder, Model, ModelRestApi
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.filters import BaseFilter, Filters
from flask_appbuilder.models.sqla.filters import FilterStartsWith
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import lazy_gettext as _
from marshmallow import fields, Schema
from sqlalchemy import and_, distinct, func
from sqlalchemy.orm.query import Query
from superset.exceptions import InvalidPayloadFormatError
from superset.extensions import db, event_logger, security_manager
from superset.models.core import FavStar
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice
from superset.schemas import error_payload_content
from superset.sql_lab import Query as SqllabQuery
from superset.stats_logger import BaseStatsLogger
from superset.superset_typing import FlaskResponse
from superset.utils.core import time_function
logger = logging.getLogger(__name__)
get_related_schema = {
"type": "object",
"properties": {
"page_size": {"type": "integer"},
"page": {"type": "integer"},
"include_ids": {"type": "array", "items": {"type": "integer"}},
"filter": {"type": "string"},
},
}
class RelatedResultResponseSchema(Schema):
value = fields.Integer(description="The related item identifier")
text = fields.String(description="The related item string representation")
class RelatedResponseSchema(Schema):
count = fields.Integer(description="The total number of related values")
result = fields.List(fields.Nested(RelatedResultResponseSchema))
class DistinctResultResponseSchema(Schema):
text = fields.String(description="The distinct item")
class DistincResponseSchema(Schema):
count = fields.Integer(description="The total number of distinct values")
result = fields.List(fields.Nested(DistinctResultResponseSchema))
def requires_json(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require JSON-like formatted request to the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.is_json:
raise InvalidPayloadFormatError(message="Request is not JSON")
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def requires_form_data(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Require 'multipart/form-data' as request MIME type
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
if not request.mimetype == "multipart/form-data":
raise InvalidPayloadFormatError(
message="Request MIME type is not 'multipart/form-data'"
)
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
def statsd_metrics(f: Callable[..., Any]) -> Callable[..., Any]:
"""
Handle sending all statsd metrics from the REST API
"""
def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response:
try:
duration, response = time_function(f, self, *args, **kwargs)
except Exception as ex:
self.incr_stats("error", f.__name__)
raise ex
self.send_stats_metrics(response, f.__name__, duration)
return response
return functools.update_wrapper(wraps, f)
class RelatedFieldFilter:
# data class to specify what filter to use on a /related endpoint
# pylint: disable=too-few-public-methods
def __init__(self, field_name: str, filter_class: Type[BaseFilter]):
self.field_name = field_name
self.filter_class = filter_class
class BaseFavoriteFilter(BaseFilter): # pylint: disable=too-few-public-methods
"""
Base Custom filter for the GET list that filters all dashboards, slices
that a user has favored or not
"""
name = _("Is favorite")
arg_name = ""
class_name = ""
""" The FavStar class_name to user """
model: Type[Union[Dashboard, Slice, SqllabQuery]] = Dashboard
""" The SQLAlchemy model """
def apply(self, query: Query, value: Any) -> Query:
# If anonymous user filter nothing
if security_manager.current_user is None:
return query
users_favorite_query = db.session.query(FavStar.obj_id).filter(
and_(
FavStar.user_id == g.user.get_id(),
FavStar.class_name == self.class_name,
)
)
if value:
return query.filter(and_(self.model.id.in_(users_favorite_query)))
return query.filter(and_(~self.model.id.in_(users_favorite_query)))
class BaseSupersetModelRestApi(ModelRestApi):
"""
Extends FAB's ModelResApi to implement specific superset generic functionality
"""
csrf_exempt = False
method_permission_name = {
"bulk_delete": "delete",
"data": "list",
"data_from_cache": "list",
"delete": "delete",
"distinct": "list",
"export": "mulexport",
"import_": "add",
"get": "show",
"get_list": "list",
"info": "list",
"post": "add",
"put": "edit",
"refresh": "edit",
"related": "list",
"related_objects": "list",
"schemas": "list",
"select_star": "list",
"table_metadata": "list",
"test_connection": "post",
"thumbnail": "list",
"viz_types": "list",
}
order_rel_fields: Dict[str, Tuple[str, str]] = {}
"""
Impose ordering on related fields query::
order_rel_fields = {
"<RELATED_FIELD>": ("<RELATED_FIELD_FIELD>", "<asc|desc>"),
...
}
"""
related_field_filters: Dict[str, Union[RelatedFieldFilter, str]] = {}
"""
Declare the filters for related fields::
related_fields = {
"<RELATED_FIELD>": <RelatedFieldFilter>)
}
"""
filter_rel_fields: Dict[str, BaseFilter] = {}
"""
Declare the related field base filter::
filter_rel_fields_field = {
"<RELATED_FIELD>": "<FILTER>")
}
"""
allowed_rel_fields: Set[str] = set()
# Declare a set of allowed related fields that the `related` endpoint supports.
text_field_rel_fields: Dict[str, str] = {}
"""
Declare an alternative for the human readable representation of the Model object::
text_field_rel_fields = {
"<RELATED_FIELD>": "<RELATED_OBJECT_FIELD>"
}
"""
allowed_distinct_fields: Set[str] = set()
add_columns: List[str]
edit_columns: List[str]
list_columns: List[str]
show_columns: List[str]
responses = {
"400": {"description": "Bad request", "content": error_payload_content},
"401": {"description": "Unauthorized", "content": error_payload_content},
"403": {"description": "Forbidden", "content": error_payload_content},
"404": {"description": "Not found", "content": error_payload_content},
"422": {
"description": "Could not process entity",
"content": error_payload_content,
},
"500": {"description": "Fatal error", "content": error_payload_content},
}
def __init__(self) -> None:
super().__init__()
# Setup statsd
self.stats_logger = BaseStatsLogger()
# Add base API spec base query parameter schemas
if self.apispec_parameter_schemas is None: # type: ignore
self.apispec_parameter_schemas = {}
self.apispec_parameter_schemas["get_related_schema"] = get_related_schema
self.openapi_spec_component_schemas: Tuple[
Type[Schema], ...
] = self.openapi_spec_component_schemas + (
RelatedResponseSchema,
DistincResponseSchema,
)
def create_blueprint(
self, appbuilder: AppBuilder, *args: Any, **kwargs: Any
) -> Blueprint:
self.stats_logger = self.appbuilder.get_app.config["STATS_LOGGER"]
return super().create_blueprint(appbuilder, *args, **kwargs)
def _init_properties(self) -> None:
"""
Lock down initial not configured REST API columns. We want to just expose
model ids, if something is misconfigured. By default FAB exposes all available
columns on a Model
"""
model_id = self.datamodel.get_pk_name()
if self.list_columns is None and not self.list_model_schema:
self.list_columns = [model_id]
if self.show_columns is None and not self.show_model_schema:
self.show_columns = [model_id]
if self.edit_columns is None and not self.edit_model_schema:
self.edit_columns = [model_id]
if self.add_columns is None and not self.add_model_schema:
self.add_columns = [model_id]
super()._init_properties()
def _get_related_filter(
self, datamodel: SQLAInterface, column_name: str, value: str
) -> Filters:
filter_field = self.related_field_filters.get(column_name)
if isinstance(filter_field, str):
filter_field = RelatedFieldFilter(cast(str, filter_field), FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = datamodel.get_filters(search_columns)
base_filters = self.filter_rel_fields.get(column_name)
if base_filters:
filters.add_filter_list(base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_distinct_filter(self, column_name: str, value: str) -> Filters:
filter_field = RelatedFieldFilter(column_name, FilterStartsWith)
filter_field = cast(RelatedFieldFilter, filter_field)
search_columns = [filter_field.field_name] if filter_field else None
filters = self.datamodel.get_filters(search_columns)
filters.add_filter_list(self.base_filters)
if value and filter_field:
filters.add_filter(
filter_field.field_name, filter_field.filter_class, value
)
return filters
def _get_text_for_model(self, model: Model, column_name: str) -> str:
if column_name in self.text_field_rel_fields:
model_column_name = self.text_field_rel_fields.get(column_name)
if model_column_name:
return getattr(model, model_column_name)
return str(model)
def _get_result_from_rows(
self, datamodel: SQLAInterface, rows: List[Model], column_name: str
) -> List[Dict[str, Any]]:
return [
{
"value": datamodel.get_pk_value(row),
"text": self._get_text_for_model(row, column_name),
}
for row in rows
]
def _add_extra_ids_to_result(
self,
datamodel: SQLAInterface,
column_name: str,
ids: List[int],
result: List[Dict[str, Any]],
) -> None:
if ids:
# Filter out already present values on the result
values = [row["value"] for row in result]
ids = [id_ for id_ in ids if id_ not in values]
pk_col = datamodel.get_pk()
# Fetch requested values from ids
extra_rows = db.session.query(datamodel.obj).filter(pk_col.in_(ids)).all()
result += self._get_result_from_rows(datamodel, extra_rows, column_name)
def incr_stats(self, action: str, func_name: str) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
"""
self.stats_logger.incr(f"{self.__class__.__name__}.{func_name}.{action}")
def timing_stats(self, action: str, func_name: str, value: float) -> None:
"""
Proxy function for statsd.incr to impose a key structure for REST API's
:param action: String with an action name eg: error, success
:param func_name: The function name
:param value: A float with the time it took for the endpoint to execute
"""
self.stats_logger.timing(
f"{self.__class__.__name__}.{func_name}.{action}", value
)
def send_stats_metrics(
self, response: Response, key: str, time_delta: Optional[float] = None
) -> None:
"""
Helper function to handle sending statsd metrics
:param response: flask response object, will evaluate if it was an error
:param key: The function name
:param time_delta: Optional time it took for the endpoint to execute
"""
if 200 <= response.status_code < 400:
self.incr_stats("success", key)
else:
self.incr_stats("error", key)
if time_delta:
self.timing_stats("time", key, time_delta)
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.info",
object_ref=False,
log_to_statsd=False,
)
def info_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB _info endpoint
"""
duration, response = time_function(super().info_headless, **kwargs)
self.send_stats_metrics(response, self.info.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get",
object_ref=False,
log_to_statsd=False,
)
def get_headless(self, pk: int, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET endpoint
"""
duration, response = time_function(super().get_headless, pk, **kwargs)
self.send_stats_metrics(response, self.get.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_list",
object_ref=False,
log_to_statsd=False,
)
def get_list_headless(self, **kwargs: Any) -> Response:
"""
Add statsd metrics to builtin FAB GET list endpoint
"""
duration, response = time_function(super().get_list_headless, **kwargs)
self.send_stats_metrics(response, self.get_list.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
object_ref=False,
log_to_statsd=False,
)
def post_headless(self) -> Response:
"""
Add statsd metrics to builtin FAB POST endpoint
"""
duration, response = time_function(super().post_headless)
self.send_stats_metrics(response, self.post.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put",
object_ref=False,
log_to_statsd=False,
)
def put_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB PUT endpoint
"""
duration, response = time_function(super().put_headless, pk)
self.send_stats_metrics(response, self.put.__name__, duration)
return response
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete",
object_ref=False,
log_to_statsd=False,
)
def delete_headless(self, pk: int) -> Response:
"""
Add statsd metrics to builtin FAB DELETE endpoint
"""
duration, response = time_function(super().delete_headless, pk)
self.send_stats_metrics(response, self.delete.__name__, duration)
return response
@expose("/related/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def related(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get related fields data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Related column data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/RelatedResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_rel_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._handle_page_args(args)
ids = args.get("include_ids")
if page and ids:
# pagination with forced ids is not supported
return self.response_422()
try:
datamodel = self.datamodel.get_related_interface(column_name)
except KeyError:
return self.response_404()
page, page_size = self._sanitize_page_args(page, page_size)
# handle ordering
order_field = self.order_rel_fields.get(column_name)
if order_field:
order_column, order_direction = order_field
else:
order_column, order_direction = "", ""
# handle filters
filters = self._get_related_filter(datamodel, column_name, args.get("filter"))
# Make the query
total_rows, rows = datamodel.query(
filters, order_column, order_direction, page=page, page_size=page_size
)
# produce response
result = self._get_result_from_rows(datamodel, rows, column_name)
# If ids are specified make sure we fetch and include them on the response
if ids:
self._add_extra_ids_to_result(datamodel, column_name, ids, result)
total_rows = len(result)
return self.response(200, count=total_rows, result=result)
@expose("/distinct/<column_name>", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_related_schema)
def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse:
"""Get distinct values from field data
---
get:
parameters:
- in: path
schema:
type: string
name: column_name
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_related_schema'
responses:
200:
description: Distinct field data
content:
application/json:
schema:
schema:
$ref: "#/components/schemas/DistincResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if column_name not in self.allowed_distinct_fields:
self.incr_stats("error", self.related.__name__)
return self.response_404()
args = kwargs.get("rison", {})
# handle pagination
page, page_size = self._sanitize_page_args(*self._handle_page_args(args))
# Create generic base filters with added request filter
filters = self._get_distinct_filter(column_name, args.get("filter"))
# Make the query
query_count = self.appbuilder.get_session.query(
func.count(distinct(getattr(self.datamodel.obj, column_name)))
)
count = self.datamodel.apply_filters(query_count, filters).scalar()
if count == 0:
return self.response(200, count=count, result=[])
query = self.appbuilder.get_session.query(
distinct(getattr(self.datamodel.obj, column_name))
)
# Apply generic base filters with added request filter
query = self.datamodel.apply_filters(query, filters)
# Apply sort
query = self.datamodel.apply_order_by(query, column_name, "asc")
# Apply pagination
result = self.datamodel.apply_pagination(query, page, page_size).all()
# produce response
result = [
{"text": item[0], "value": item[0]}
for item in result
if item[0] is not None
]
return self.response(200, count=count, result=result)
| superset/views/base_api.py | 1 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.9416714310646057,
0.018231894820928574,
0.00016242620768025517,
0.000177428315510042,
0.11950692534446716
] |
{
"id": 5,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.get_list\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def get_list_headless(self, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB GET list endpoint\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 414
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import configureStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
import { shallow } from 'enzyme';
import { render, screen } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { Provider } from 'react-redux';
import '@testing-library/jest-dom/extend-expect';
import thunk from 'redux-thunk';
import SqlEditorLeftBar from 'src/SqlLab/components/SqlEditorLeftBar';
import TableElement from 'src/SqlLab/components/TableElement';
import { supersetTheme, ThemeProvider } from '@superset-ui/core';
import {
table,
initialState,
databases,
defaultQueryEditor,
mockedActions,
} from 'src/SqlLab/fixtures';
const mockedProps = {
actions: mockedActions,
tables: [table],
queryEditor: defaultQueryEditor,
database: databases,
height: 0,
};
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
const store = mockStore(initialState);
fetchMock.get('glob:*/api/v1/database/*/schemas/?*', { result: [] });
describe('SqlEditorLeftBar', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<SqlEditorLeftBar {...mockedProps} />, {
context: { store },
});
});
afterEach(() => {
wrapper.unmount();
});
it('is valid', () => {
expect(React.isValidElement(<SqlEditorLeftBar {...mockedProps} />)).toBe(
true,
);
});
it('renders a TableElement', () => {
expect(wrapper.find(TableElement)).toExist();
});
});
describe('Left Panel Expansion', () => {
it('table should be visible when expanded is true', () => {
const { container } = render(
<ThemeProvider theme={supersetTheme}>
<Provider store={store}>
<SqlEditorLeftBar {...mockedProps} />
</Provider>
</ThemeProvider>,
);
const dbSelect = screen.getByRole('combobox', {
name: 'Select database or type database name',
});
const schemaSelect = screen.getByRole('combobox', {
name: 'Select schema or type schema name',
});
const dropdown = screen.getByText(/Select table or type table name/i);
const abUser = screen.getByText(/ab_user/i);
expect(dbSelect).toBeInTheDocument();
expect(schemaSelect).toBeInTheDocument();
expect(dropdown).toBeInTheDocument();
expect(abUser).toBeInTheDocument();
expect(
container.querySelector('.ant-collapse-content-active'),
).toBeInTheDocument();
});
it('should toggle the table when the header is clicked', async () => {
const collapseMock = jest.fn();
render(
<ThemeProvider theme={supersetTheme}>
<Provider store={store}>
<SqlEditorLeftBar
actions={{ ...mockedActions, collapseTable: collapseMock }}
tables={[table]}
queryEditor={defaultQueryEditor}
database={databases}
height={0}
/>
</Provider>
</ThemeProvider>,
);
const header = screen.getByText(/ab_user/);
userEvent.click(header);
expect(collapseMock).toHaveBeenCalled();
});
});
| superset-frontend/src/SqlLab/components/SqlEditorLeftBar/SqlEditorLeftBar.test.jsx | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00017738535825628787,
0.00017473359184805304,
0.00017063358973246068,
0.0001747192582115531,
0.00000194805693354283
] |
{
"id": 5,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.get_list\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def get_list_headless(self, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB GET list endpoint\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 414
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from collections import namedtuple
from unittest import mock, skipUnless
import pandas as pd
from sqlalchemy import types
from sqlalchemy.engine.result import RowProxy
from sqlalchemy.sql import select
from superset.db_engine_specs.presto import PrestoEngineSpec
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.sql_parse import ParsedQuery
from superset.utils.core import DatasourceName, GenericDataType
from tests.integration_tests.db_engine_specs.base_tests import TestDbEngineSpec
class TestPrestoDbEngineSpec(TestDbEngineSpec):
@skipUnless(TestDbEngineSpec.is_module_installed("pyhive"), "pyhive not installed")
def test_get_datatype_presto(self):
self.assertEqual("STRING", PrestoEngineSpec.get_datatype("string"))
def test_presto_get_view_names_return_empty_list(
self,
): # pylint: disable=invalid-name
self.assertEqual(
[], PrestoEngineSpec.get_view_names(mock.ANY, mock.ANY, mock.ANY)
)
@mock.patch("superset.db_engine_specs.presto.is_feature_enabled")
def test_get_view_names(self, mock_is_feature_enabled):
mock_is_feature_enabled.return_value = True
mock_execute = mock.MagicMock()
mock_fetchall = mock.MagicMock(return_value=[["a", "b,", "c"], ["d", "e"]])
database = mock.MagicMock()
database.get_sqla_engine.return_value.raw_connection.return_value.cursor.return_value.execute = (
mock_execute
)
database.get_sqla_engine.return_value.raw_connection.return_value.cursor.return_value.fetchall = (
mock_fetchall
)
result = PrestoEngineSpec.get_view_names(database, mock.Mock(), None)
mock_execute.assert_called_once_with(
"SELECT table_name FROM information_schema.views", {}
)
assert result == ["a", "d"]
@mock.patch("superset.db_engine_specs.presto.is_feature_enabled")
def test_get_view_names_with_schema(self, mock_is_feature_enabled):
mock_is_feature_enabled.return_value = True
mock_execute = mock.MagicMock()
mock_fetchall = mock.MagicMock(return_value=[["a", "b,", "c"], ["d", "e"]])
database = mock.MagicMock()
database.get_sqla_engine.return_value.raw_connection.return_value.cursor.return_value.execute = (
mock_execute
)
database.get_sqla_engine.return_value.raw_connection.return_value.cursor.return_value.fetchall = (
mock_fetchall
)
schema = "schema"
result = PrestoEngineSpec.get_view_names(database, mock.Mock(), schema)
mock_execute.assert_called_once_with(
"SELECT table_name FROM information_schema.views "
"WHERE table_schema=%(schema)s",
{"schema": schema},
)
assert result == ["a", "d"]
def verify_presto_column(self, column, expected_results):
inspector = mock.Mock()
inspector.engine.dialect.identifier_preparer.quote_identifier = mock.Mock()
keymap = {
"Column": (None, None, 0),
"Type": (None, None, 1),
"Null": (None, None, 2),
}
row = RowProxy(mock.Mock(), column, [None, None, None, None], keymap)
inspector.bind.execute = mock.Mock(return_value=[row])
results = PrestoEngineSpec.get_columns(inspector, "", "")
self.assertEqual(len(expected_results), len(results))
for expected_result, result in zip(expected_results, results):
self.assertEqual(expected_result[0], result["name"])
self.assertEqual(expected_result[1], str(result["type"]))
def test_presto_get_column(self):
presto_column = ("column_name", "boolean", "")
expected_results = [("column_name", "BOOLEAN")]
self.verify_presto_column(presto_column, expected_results)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_get_simple_row_column(self):
presto_column = ("column_name", "row(nested_obj double)", "")
expected_results = [("column_name", "ROW"), ("column_name.nested_obj", "FLOAT")]
self.verify_presto_column(presto_column, expected_results)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_get_simple_row_column_with_name_containing_whitespace(self):
presto_column = ("column name", "row(nested_obj double)", "")
expected_results = [("column name", "ROW"), ("column name.nested_obj", "FLOAT")]
self.verify_presto_column(presto_column, expected_results)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_get_simple_row_column_with_tricky_nested_field_name(self):
presto_column = ("column_name", 'row("Field Name(Tricky, Name)" double)', "")
expected_results = [
("column_name", "ROW"),
('column_name."Field Name(Tricky, Name)"', "FLOAT"),
]
self.verify_presto_column(presto_column, expected_results)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_get_simple_array_column(self):
presto_column = ("column_name", "array(double)", "")
expected_results = [("column_name", "ARRAY")]
self.verify_presto_column(presto_column, expected_results)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_get_row_within_array_within_row_column(self):
presto_column = (
"column_name",
"row(nested_array array(row(nested_row double)), nested_obj double)",
"",
)
expected_results = [
("column_name", "ROW"),
("column_name.nested_array", "ARRAY"),
("column_name.nested_array.nested_row", "FLOAT"),
("column_name.nested_obj", "FLOAT"),
]
self.verify_presto_column(presto_column, expected_results)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_get_array_within_row_within_array_column(self):
presto_column = (
"column_name",
"array(row(nested_array array(double), nested_obj double))",
"",
)
expected_results = [
("column_name", "ARRAY"),
("column_name.nested_array", "ARRAY"),
("column_name.nested_obj", "FLOAT"),
]
self.verify_presto_column(presto_column, expected_results)
def test_presto_get_fields(self):
cols = [
{"name": "column"},
{"name": "column.nested_obj"},
{"name": 'column."quoted.nested obj"'},
]
actual_results = PrestoEngineSpec._get_fields(cols)
expected_results = [
{"name": '"column"', "label": "column"},
{"name": '"column"."nested_obj"', "label": "column.nested_obj"},
{
"name": '"column"."quoted.nested obj"',
"label": 'column."quoted.nested obj"',
},
]
for actual_result, expected_result in zip(actual_results, expected_results):
self.assertEqual(actual_result.element.name, expected_result["name"])
self.assertEqual(actual_result.name, expected_result["label"])
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_expand_data_with_simple_structural_columns(self):
cols = [
{"name": "row_column", "type": "ROW(NESTED_OBJ VARCHAR)", "is_dttm": False},
{"name": "array_column", "type": "ARRAY(BIGINT)", "is_dttm": False},
]
data = [
{"row_column": ["a"], "array_column": [1, 2, 3]},
{"row_column": ["b"], "array_column": [4, 5, 6]},
]
actual_cols, actual_data, actual_expanded_cols = PrestoEngineSpec.expand_data(
cols, data
)
expected_cols = [
{"name": "row_column", "type": "ROW(NESTED_OBJ VARCHAR)", "is_dttm": False},
{"name": "row_column.nested_obj", "type": "VARCHAR", "is_dttm": False},
{"name": "array_column", "type": "ARRAY(BIGINT)", "is_dttm": False},
]
expected_data = [
{"array_column": 1, "row_column": ["a"], "row_column.nested_obj": "a"},
{"array_column": 2, "row_column": "", "row_column.nested_obj": ""},
{"array_column": 3, "row_column": "", "row_column.nested_obj": ""},
{"array_column": 4, "row_column": ["b"], "row_column.nested_obj": "b"},
{"array_column": 5, "row_column": "", "row_column.nested_obj": ""},
{"array_column": 6, "row_column": "", "row_column.nested_obj": ""},
]
expected_expanded_cols = [
{"name": "row_column.nested_obj", "type": "VARCHAR", "is_dttm": False}
]
self.assertEqual(actual_cols, expected_cols)
self.assertEqual(actual_data, expected_data)
self.assertEqual(actual_expanded_cols, expected_expanded_cols)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_expand_data_with_complex_row_columns(self):
cols = [
{
"name": "row_column",
"type": "ROW(NESTED_OBJ1 VARCHAR, NESTED_ROW ROW(NESTED_OBJ2 VARCHAR))",
"is_dttm": False,
}
]
data = [{"row_column": ["a1", ["a2"]]}, {"row_column": ["b1", ["b2"]]}]
actual_cols, actual_data, actual_expanded_cols = PrestoEngineSpec.expand_data(
cols, data
)
expected_cols = [
{
"name": "row_column",
"type": "ROW(NESTED_OBJ1 VARCHAR, NESTED_ROW ROW(NESTED_OBJ2 VARCHAR))",
"is_dttm": False,
},
{"name": "row_column.nested_obj1", "type": "VARCHAR", "is_dttm": False},
{
"name": "row_column.nested_row",
"type": "ROW(NESTED_OBJ2 VARCHAR)",
"is_dttm": False,
},
{
"name": "row_column.nested_row.nested_obj2",
"type": "VARCHAR",
"is_dttm": False,
},
]
expected_data = [
{
"row_column": ["a1", ["a2"]],
"row_column.nested_obj1": "a1",
"row_column.nested_row": ["a2"],
"row_column.nested_row.nested_obj2": "a2",
},
{
"row_column": ["b1", ["b2"]],
"row_column.nested_obj1": "b1",
"row_column.nested_row": ["b2"],
"row_column.nested_row.nested_obj2": "b2",
},
]
expected_expanded_cols = [
{"name": "row_column.nested_obj1", "type": "VARCHAR", "is_dttm": False},
{
"name": "row_column.nested_row",
"type": "ROW(NESTED_OBJ2 VARCHAR)",
"is_dttm": False,
},
{
"name": "row_column.nested_row.nested_obj2",
"type": "VARCHAR",
"is_dttm": False,
},
]
self.assertEqual(actual_cols, expected_cols)
self.assertEqual(actual_data, expected_data)
self.assertEqual(actual_expanded_cols, expected_expanded_cols)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_expand_data_with_complex_row_columns_and_null_values(self):
cols = [
{
"name": "row_column",
"type": "ROW(NESTED_ROW ROW(NESTED_OBJ VARCHAR))",
"is_dttm": False,
}
]
data = [
{"row_column": '[["a"]]'},
{"row_column": "[[null]]"},
{"row_column": "[null]"},
{"row_column": "null"},
]
actual_cols, actual_data, actual_expanded_cols = PrestoEngineSpec.expand_data(
cols, data
)
expected_cols = [
{
"name": "row_column",
"type": "ROW(NESTED_ROW ROW(NESTED_OBJ VARCHAR))",
"is_dttm": False,
},
{
"name": "row_column.nested_row",
"type": "ROW(NESTED_OBJ VARCHAR)",
"is_dttm": False,
},
{
"name": "row_column.nested_row.nested_obj",
"type": "VARCHAR",
"is_dttm": False,
},
]
expected_data = [
{
"row_column": [["a"]],
"row_column.nested_row": ["a"],
"row_column.nested_row.nested_obj": "a",
},
{
"row_column": [[None]],
"row_column.nested_row": [None],
"row_column.nested_row.nested_obj": None,
},
{
"row_column": [None],
"row_column.nested_row": None,
"row_column.nested_row.nested_obj": "",
},
{
"row_column": None,
"row_column.nested_row": "",
"row_column.nested_row.nested_obj": "",
},
]
expected_expanded_cols = [
{
"name": "row_column.nested_row",
"type": "ROW(NESTED_OBJ VARCHAR)",
"is_dttm": False,
},
{
"name": "row_column.nested_row.nested_obj",
"type": "VARCHAR",
"is_dttm": False,
},
]
self.assertEqual(actual_cols, expected_cols)
self.assertEqual(actual_data, expected_data)
self.assertEqual(actual_expanded_cols, expected_expanded_cols)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_expand_data_with_complex_array_columns(self):
cols = [
{"name": "int_column", "type": "BIGINT", "is_dttm": False},
{
"name": "array_column",
"type": "ARRAY(ROW(NESTED_ARRAY ARRAY(ROW(NESTED_OBJ VARCHAR))))",
"is_dttm": False,
},
]
data = [
{"int_column": 1, "array_column": [[[["a"], ["b"]]], [[["c"], ["d"]]]]},
{"int_column": 2, "array_column": [[[["e"], ["f"]]], [[["g"], ["h"]]]]},
]
actual_cols, actual_data, actual_expanded_cols = PrestoEngineSpec.expand_data(
cols, data
)
expected_cols = [
{"name": "int_column", "type": "BIGINT", "is_dttm": False},
{
"name": "array_column",
"type": "ARRAY(ROW(NESTED_ARRAY ARRAY(ROW(NESTED_OBJ VARCHAR))))",
"is_dttm": False,
},
{
"name": "array_column.nested_array",
"type": "ARRAY(ROW(NESTED_OBJ VARCHAR))",
"is_dttm": False,
},
{
"name": "array_column.nested_array.nested_obj",
"type": "VARCHAR",
"is_dttm": False,
},
]
expected_data = [
{
"array_column": [[["a"], ["b"]]],
"array_column.nested_array": ["a"],
"array_column.nested_array.nested_obj": "a",
"int_column": 1,
},
{
"array_column": "",
"array_column.nested_array": ["b"],
"array_column.nested_array.nested_obj": "b",
"int_column": "",
},
{
"array_column": [[["c"], ["d"]]],
"array_column.nested_array": ["c"],
"array_column.nested_array.nested_obj": "c",
"int_column": "",
},
{
"array_column": "",
"array_column.nested_array": ["d"],
"array_column.nested_array.nested_obj": "d",
"int_column": "",
},
{
"array_column": [[["e"], ["f"]]],
"array_column.nested_array": ["e"],
"array_column.nested_array.nested_obj": "e",
"int_column": 2,
},
{
"array_column": "",
"array_column.nested_array": ["f"],
"array_column.nested_array.nested_obj": "f",
"int_column": "",
},
{
"array_column": [[["g"], ["h"]]],
"array_column.nested_array": ["g"],
"array_column.nested_array.nested_obj": "g",
"int_column": "",
},
{
"array_column": "",
"array_column.nested_array": ["h"],
"array_column.nested_array.nested_obj": "h",
"int_column": "",
},
]
expected_expanded_cols = [
{
"name": "array_column.nested_array",
"type": "ARRAY(ROW(NESTED_OBJ VARCHAR))",
"is_dttm": False,
},
{
"name": "array_column.nested_array.nested_obj",
"type": "VARCHAR",
"is_dttm": False,
},
]
self.assertEqual(actual_cols, expected_cols)
self.assertEqual(actual_data, expected_data)
self.assertEqual(actual_expanded_cols, expected_expanded_cols)
def test_presto_extra_table_metadata(self):
db = mock.Mock()
db.get_indexes = mock.Mock(return_value=[{"column_names": ["ds", "hour"]}])
db.get_extra = mock.Mock(return_value={})
df = pd.DataFrame({"ds": ["01-01-19"], "hour": [1]})
db.get_df = mock.Mock(return_value=df)
PrestoEngineSpec.get_create_view = mock.Mock(return_value=None)
result = PrestoEngineSpec.extra_table_metadata(db, "test_table", "test_schema")
self.assertEqual({"ds": "01-01-19", "hour": 1}, result["partitions"]["latest"])
def test_presto_where_latest_partition(self):
db = mock.Mock()
db.get_indexes = mock.Mock(return_value=[{"column_names": ["ds", "hour"]}])
db.get_extra = mock.Mock(return_value={})
df = pd.DataFrame({"ds": ["01-01-19"], "hour": [1]})
db.get_df = mock.Mock(return_value=df)
columns = [{"name": "ds"}, {"name": "hour"}]
result = PrestoEngineSpec.where_latest_partition(
"test_table", "test_schema", db, select(), columns
)
query_result = str(result.compile(compile_kwargs={"literal_binds": True}))
self.assertEqual("SELECT \nWHERE ds = '01-01-19' AND hour = 1", query_result)
def test_convert_dttm(self):
dttm = self.get_dttm()
self.assertEqual(
PrestoEngineSpec.convert_dttm("DATE", dttm),
"from_iso8601_date('2019-01-02')",
)
self.assertEqual(
PrestoEngineSpec.convert_dttm("TIMESTAMP", dttm),
"from_iso8601_timestamp('2019-01-02T03:04:05.678900')",
)
def test_query_cost_formatter(self):
raw_cost = [
{
"inputTableColumnInfos": [
{
"table": {
"catalog": "hive",
"schemaTable": {
"schema": "default",
"table": "fact_passenger_state",
},
},
"columnConstraints": [
{
"columnName": "ds",
"typeSignature": "varchar",
"domain": {
"nullsAllowed": False,
"ranges": [
{
"low": {
"value": "2019-07-10",
"bound": "EXACTLY",
},
"high": {
"value": "2019-07-10",
"bound": "EXACTLY",
},
}
],
},
}
],
"estimate": {
"outputRowCount": 9.04969899e8,
"outputSizeInBytes": 3.54143678301e11,
"cpuCost": 3.54143678301e11,
"maxMemory": 0.0,
"networkCost": 0.0,
},
}
],
"estimate": {
"outputRowCount": 9.04969899e8,
"outputSizeInBytes": 3.54143678301e11,
"cpuCost": 3.54143678301e11,
"maxMemory": 0.0,
"networkCost": 3.54143678301e11,
},
}
]
formatted_cost = PrestoEngineSpec.query_cost_formatter(raw_cost)
expected = [
{
"Output count": "904 M rows",
"Output size": "354 GB",
"CPU cost": "354 G",
"Max memory": "0 B",
"Network cost": "354 G",
}
]
self.assertEqual(formatted_cost, expected)
@mock.patch.dict(
"superset.extensions.feature_flag_manager._feature_flags",
{"PRESTO_EXPAND_DATA": True},
clear=True,
)
def test_presto_expand_data_array(self):
cols = [
{"name": "event_id", "type": "VARCHAR", "is_dttm": False},
{"name": "timestamp", "type": "BIGINT", "is_dttm": False},
{
"name": "user",
"type": "ROW(ID BIGINT, FIRST_NAME VARCHAR, LAST_NAME VARCHAR)",
"is_dttm": False,
},
]
data = [
{
"event_id": "abcdef01-2345-6789-abcd-ef0123456789",
"timestamp": "1595895506219",
"user": '[1, "JOHN", "DOE"]',
}
]
actual_cols, actual_data, actual_expanded_cols = PrestoEngineSpec.expand_data(
cols, data
)
expected_cols = [
{"name": "event_id", "type": "VARCHAR", "is_dttm": False},
{"name": "timestamp", "type": "BIGINT", "is_dttm": False},
{
"name": "user",
"type": "ROW(ID BIGINT, FIRST_NAME VARCHAR, LAST_NAME VARCHAR)",
"is_dttm": False,
},
{"name": "user.id", "type": "BIGINT", "is_dttm": False},
{"name": "user.first_name", "type": "VARCHAR", "is_dttm": False},
{"name": "user.last_name", "type": "VARCHAR", "is_dttm": False},
]
expected_data = [
{
"event_id": "abcdef01-2345-6789-abcd-ef0123456789",
"timestamp": "1595895506219",
"user": [1, "JOHN", "DOE"],
"user.id": 1,
"user.first_name": "JOHN",
"user.last_name": "DOE",
}
]
expected_expanded_cols = [
{"name": "user.id", "type": "BIGINT", "is_dttm": False},
{"name": "user.first_name", "type": "VARCHAR", "is_dttm": False},
{"name": "user.last_name", "type": "VARCHAR", "is_dttm": False},
]
self.assertEqual(actual_cols, expected_cols)
self.assertEqual(actual_data, expected_data)
self.assertEqual(actual_expanded_cols, expected_expanded_cols)
def test_get_sqla_column_type(self):
column_spec = PrestoEngineSpec.get_column_spec("varchar(255)")
assert isinstance(column_spec.sqla_type, types.VARCHAR)
assert column_spec.sqla_type.length == 255
self.assertEqual(column_spec.generic_type, GenericDataType.STRING)
column_spec = PrestoEngineSpec.get_column_spec("varchar")
assert isinstance(column_spec.sqla_type, types.String)
assert column_spec.sqla_type.length is None
self.assertEqual(column_spec.generic_type, GenericDataType.STRING)
column_spec = PrestoEngineSpec.get_column_spec("char(10)")
assert isinstance(column_spec.sqla_type, types.CHAR)
assert column_spec.sqla_type.length == 10
self.assertEqual(column_spec.generic_type, GenericDataType.STRING)
column_spec = PrestoEngineSpec.get_column_spec("char")
assert isinstance(column_spec.sqla_type, types.CHAR)
assert column_spec.sqla_type.length is None
self.assertEqual(column_spec.generic_type, GenericDataType.STRING)
column_spec = PrestoEngineSpec.get_column_spec("integer")
assert isinstance(column_spec.sqla_type, types.Integer)
self.assertEqual(column_spec.generic_type, GenericDataType.NUMERIC)
column_spec = PrestoEngineSpec.get_column_spec("time")
assert isinstance(column_spec.sqla_type, types.Time)
assert type(column_spec.sqla_type).__name__ == "TemporalWrapperType"
self.assertEqual(column_spec.generic_type, GenericDataType.TEMPORAL)
column_spec = PrestoEngineSpec.get_column_spec("timestamp")
assert isinstance(column_spec.sqla_type, types.TIMESTAMP)
assert type(column_spec.sqla_type).__name__ == "TemporalWrapperType"
self.assertEqual(column_spec.generic_type, GenericDataType.TEMPORAL)
sqla_type = PrestoEngineSpec.get_sqla_column_type(None)
assert sqla_type is None
@mock.patch(
"superset.utils.feature_flag_manager.FeatureFlagManager.is_feature_enabled"
)
@mock.patch("superset.db_engine_specs.base.BaseEngineSpec.get_table_names")
@mock.patch("superset.db_engine_specs.presto.PrestoEngineSpec.get_view_names")
def test_get_table_names_no_split_views_from_tables(
self, mock_get_view_names, mock_get_table_names, mock_is_feature_enabled
):
mock_get_view_names.return_value = ["view1", "view2"]
table_names = ["table1", "table2", "view1", "view2"]
mock_get_table_names.return_value = table_names
mock_is_feature_enabled.return_value = False
tables = PrestoEngineSpec.get_table_names(mock.Mock(), mock.Mock(), None)
assert tables == table_names
@mock.patch(
"superset.utils.feature_flag_manager.FeatureFlagManager.is_feature_enabled"
)
@mock.patch("superset.db_engine_specs.base.BaseEngineSpec.get_table_names")
@mock.patch("superset.db_engine_specs.presto.PrestoEngineSpec.get_view_names")
def test_get_table_names_split_views_from_tables(
self, mock_get_view_names, mock_get_table_names, mock_is_feature_enabled
):
mock_get_view_names.return_value = ["view1", "view2"]
table_names = ["table1", "table2", "view1", "view2"]
mock_get_table_names.return_value = table_names
mock_is_feature_enabled.return_value = True
tables = PrestoEngineSpec.get_table_names(mock.Mock(), mock.Mock(), None)
assert sorted(tables) == sorted(table_names)
@mock.patch(
"superset.utils.feature_flag_manager.FeatureFlagManager.is_feature_enabled"
)
@mock.patch("superset.db_engine_specs.base.BaseEngineSpec.get_table_names")
@mock.patch("superset.db_engine_specs.presto.PrestoEngineSpec.get_view_names")
def test_get_table_names_split_views_from_tables_no_tables(
self, mock_get_view_names, mock_get_table_names, mock_is_feature_enabled
):
mock_get_view_names.return_value = []
table_names = []
mock_get_table_names.return_value = table_names
mock_is_feature_enabled.return_value = True
tables = PrestoEngineSpec.get_table_names(mock.Mock(), mock.Mock(), None)
assert tables == []
def test_get_full_name(self):
names = [
("part1", "part2"),
("part11", "part22"),
]
result = PrestoEngineSpec._get_full_name(names)
assert result == "part1.part11"
def test_get_full_name_empty_tuple(self):
names = [
("part1", "part2"),
("", "part3"),
("part4", "part5"),
("", "part6"),
]
result = PrestoEngineSpec._get_full_name(names)
assert result == "part1.part4"
def test_split_data_type(self):
data_type = "value1 value2"
result = PrestoEngineSpec._split_data_type(data_type, " ")
assert result == ["value1", "value2"]
data_type = "value1,value2"
result = PrestoEngineSpec._split_data_type(data_type, ",")
assert result == ["value1", "value2"]
data_type = '"value,1",value2'
result = PrestoEngineSpec._split_data_type(data_type, ",")
assert result == ['"value,1"', "value2"]
def test_show_columns(self):
inspector = mock.MagicMock()
inspector.engine.dialect.identifier_preparer.quote_identifier = (
lambda x: f'"{x}"'
)
mock_execute = mock.MagicMock(return_value=["a", "b"])
inspector.bind.execute = mock_execute
table_name = "table_name"
result = PrestoEngineSpec._show_columns(inspector, table_name, None)
assert result == ["a", "b"]
mock_execute.assert_called_once_with(f'SHOW COLUMNS FROM "{table_name}"')
def test_show_columns_with_schema(self):
inspector = mock.MagicMock()
inspector.engine.dialect.identifier_preparer.quote_identifier = (
lambda x: f'"{x}"'
)
mock_execute = mock.MagicMock(return_value=["a", "b"])
inspector.bind.execute = mock_execute
table_name = "table_name"
schema = "schema"
result = PrestoEngineSpec._show_columns(inspector, table_name, schema)
assert result == ["a", "b"]
mock_execute.assert_called_once_with(
f'SHOW COLUMNS FROM "{schema}"."{table_name}"'
)
def test_is_column_name_quoted(self):
column_name = "mock"
assert PrestoEngineSpec._is_column_name_quoted(column_name) is False
column_name = '"mock'
assert PrestoEngineSpec._is_column_name_quoted(column_name) is False
column_name = '"moc"k'
assert PrestoEngineSpec._is_column_name_quoted(column_name) is False
column_name = '"moc"k"'
assert PrestoEngineSpec._is_column_name_quoted(column_name) is True
@mock.patch("superset.db_engine_specs.base.BaseEngineSpec.select_star")
def test_select_star_no_presto_expand_data(self, mock_select_star):
database = mock.Mock()
table_name = "table_name"
engine = mock.Mock()
cols = [
{"col1": "val1"},
{"col2": "val2"},
]
PrestoEngineSpec.select_star(database, table_name, engine, cols=cols)
mock_select_star.assert_called_once_with(
database, table_name, engine, None, 100, False, True, True, cols
)
@mock.patch("superset.db_engine_specs.presto.is_feature_enabled")
@mock.patch("superset.db_engine_specs.base.BaseEngineSpec.select_star")
def test_select_star_presto_expand_data(
self, mock_select_star, mock_is_feature_enabled
):
mock_is_feature_enabled.return_value = True
database = mock.Mock()
table_name = "table_name"
engine = mock.Mock()
cols = [
{"name": "val1"},
{"name": "val2<?!@#$312,/'][p098"},
{"name": ".val2"},
{"name": "val2."},
{"name": "val.2"},
{"name": ".val2."},
]
PrestoEngineSpec.select_star(
database, table_name, engine, show_cols=True, cols=cols
)
mock_select_star.assert_called_once_with(
database,
table_name,
engine,
None,
100,
True,
True,
True,
[
{"name": "val1"},
{"name": "val2<?!@#$312,/'][p098"},
],
)
def test_estimate_statement_cost(self):
mock_cursor = mock.MagicMock()
estimate_json = {"a": "b"}
mock_cursor.fetchone.return_value = [
'{"a": "b"}',
]
result = PrestoEngineSpec.estimate_statement_cost(
"SELECT * FROM brth_names", mock_cursor
)
assert result == estimate_json
def test_estimate_statement_cost_invalid_syntax(self):
mock_cursor = mock.MagicMock()
mock_cursor.execute.side_effect = Exception()
with self.assertRaises(Exception):
PrestoEngineSpec.estimate_statement_cost(
"DROP TABLE brth_names", mock_cursor
)
def test_get_all_datasource_names(self):
df = pd.DataFrame.from_dict(
{"table_schema": ["schema1", "schema2"], "table_name": ["name1", "name2"]}
)
database = mock.MagicMock()
database.get_df.return_value = df
result = PrestoEngineSpec.get_all_datasource_names(database, "table")
expected_result = [
DatasourceName(schema="schema1", table="name1"),
DatasourceName(schema="schema2", table="name2"),
]
assert result == expected_result
def test_get_create_view(self):
mock_execute = mock.MagicMock()
mock_fetchall = mock.MagicMock(return_value=[["a", "b,", "c"], ["d", "e"]])
database = mock.MagicMock()
database.get_sqla_engine.return_value.raw_connection.return_value.cursor.return_value.execute = (
mock_execute
)
database.get_sqla_engine.return_value.raw_connection.return_value.cursor.return_value.fetchall = (
mock_fetchall
)
database.get_sqla_engine.return_value.raw_connection.return_value.cursor.return_value.poll.return_value = (
False
)
schema = "schema"
table = "table"
result = PrestoEngineSpec.get_create_view(database, schema=schema, table=table)
assert result == "a"
mock_execute.assert_called_once_with(f"SHOW CREATE VIEW {schema}.{table}")
def test_get_create_view_exception(self):
mock_execute = mock.MagicMock(side_effect=Exception())
database = mock.MagicMock()
database.get_sqla_engine.return_value.raw_connection.return_value.cursor.return_value.execute = (
mock_execute
)
schema = "schema"
table = "table"
with self.assertRaises(Exception):
PrestoEngineSpec.get_create_view(database, schema=schema, table=table)
def test_get_create_view_database_error(self):
from pyhive.exc import DatabaseError
mock_execute = mock.MagicMock(side_effect=DatabaseError())
database = mock.MagicMock()
database.get_sqla_engine.return_value.raw_connection.return_value.cursor.return_value.execute = (
mock_execute
)
schema = "schema"
table = "table"
result = PrestoEngineSpec.get_create_view(database, schema=schema, table=table)
assert result is None
def test_extract_error_message_orig(self):
DatabaseError = namedtuple("DatabaseError", ["error_dict"])
db_err = DatabaseError(
{"errorName": "name", "errorLocation": "location", "message": "msg"}
)
exception = Exception()
exception.orig = db_err
result = PrestoEngineSpec._extract_error_message(exception)
assert result == "name at location: msg"
def test_extract_error_message_db_errr(self):
from pyhive.exc import DatabaseError
exception = DatabaseError({"message": "Err message"})
result = PrestoEngineSpec._extract_error_message(exception)
assert result == "Err message"
def test_extract_error_message_general_exception(self):
exception = Exception("Err message")
result = PrestoEngineSpec._extract_error_message(exception)
assert result == "Err message"
def test_extract_errors(self):
msg = "Generic Error"
result = PrestoEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
message="Generic Error",
error_type=SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "Presto",
"issue_codes": [
{
"code": 1002,
"message": "Issue 1002 - The database returned an unexpected error.",
}
],
},
)
]
msg = "line 1:8: Column 'bogus' cannot be resolved"
result = PrestoEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
message='We can\'t seem to resolve the column "bogus" at line 1:8.',
error_type=SupersetErrorType.COLUMN_DOES_NOT_EXIST_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "Presto",
"issue_codes": [
{
"code": 1003,
"message": "Issue 1003 - There is a syntax error in the SQL query. Perhaps there was a misspelling or a typo.",
},
{
"code": 1004,
"message": "Issue 1004 - The column was deleted or renamed in the database.",
},
],
},
)
]
msg = "line 1:15: Table 'tpch.tiny.region2' does not exist"
result = PrestoEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
message="The table \"'tpch.tiny.region2'\" does not exist. A valid table must be used to run this query.",
error_type=SupersetErrorType.TABLE_DOES_NOT_EXIST_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "Presto",
"issue_codes": [
{
"code": 1003,
"message": "Issue 1003 - There is a syntax error in the SQL query. Perhaps there was a misspelling or a typo.",
},
{
"code": 1005,
"message": "Issue 1005 - The table was deleted or renamed in the database.",
},
],
},
)
]
msg = "line 1:15: Schema 'tin' does not exist"
result = PrestoEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
message='The schema "tin" does not exist. A valid schema must be used to run this query.',
error_type=SupersetErrorType.SCHEMA_DOES_NOT_EXIST_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "Presto",
"issue_codes": [
{
"code": 1003,
"message": "Issue 1003 - There is a syntax error in the SQL query. Perhaps there was a misspelling or a typo.",
},
{
"code": 1016,
"message": "Issue 1005 - The schema was deleted or renamed in the database.",
},
],
},
)
]
msg = b"Access Denied: Invalid credentials"
result = PrestoEngineSpec.extract_errors(Exception(msg), {"username": "alice"})
assert result == [
SupersetError(
message='Either the username "alice" or the password is incorrect.',
error_type=SupersetErrorType.CONNECTION_ACCESS_DENIED_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "Presto",
"issue_codes": [
{
"code": 1014,
"message": "Issue 1014 - Either the username or the password is wrong.",
}
],
},
)
]
msg = "Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known"
result = PrestoEngineSpec.extract_errors(
Exception(msg), {"hostname": "badhost"}
)
assert result == [
SupersetError(
message='The hostname "badhost" cannot be resolved.',
error_type=SupersetErrorType.CONNECTION_INVALID_HOSTNAME_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "Presto",
"issue_codes": [
{
"code": 1007,
"message": "Issue 1007 - The hostname provided can't be resolved.",
}
],
},
)
]
msg = "Failed to establish a new connection: [Errno 60] Operation timed out"
result = PrestoEngineSpec.extract_errors(
Exception(msg), {"hostname": "badhost", "port": 12345}
)
assert result == [
SupersetError(
message='The host "badhost" might be down, and can\'t be reached on port 12345.',
error_type=SupersetErrorType.CONNECTION_HOST_DOWN_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "Presto",
"issue_codes": [
{
"code": 1009,
"message": "Issue 1009 - The host might be down, and can't be reached on the provided port.",
}
],
},
)
]
msg = "Failed to establish a new connection: [Errno 61] Connection refused"
result = PrestoEngineSpec.extract_errors(
Exception(msg), {"hostname": "badhost", "port": 12345}
)
assert result == [
SupersetError(
message='Port 12345 on hostname "badhost" refused the connection.',
error_type=SupersetErrorType.CONNECTION_PORT_CLOSED_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "Presto",
"issue_codes": [
{"code": 1008, "message": "Issue 1008 - The port is closed."}
],
},
)
]
msg = "line 1:15: Catalog 'wrong' does not exist"
result = PrestoEngineSpec.extract_errors(Exception(msg))
assert result == [
SupersetError(
message='Unable to connect to catalog named "wrong".',
error_type=SupersetErrorType.CONNECTION_UNKNOWN_DATABASE_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "Presto",
"issue_codes": [
{
"code": 1015,
"message": "Issue 1015 - Either the database is spelled incorrectly or does not exist.",
}
],
},
)
]
def test_is_readonly():
def is_readonly(sql: str) -> bool:
return PrestoEngineSpec.is_readonly_query(ParsedQuery(sql))
assert not is_readonly("SET hivevar:desc='Legislators'")
assert not is_readonly("UPDATE t1 SET col1 = NULL")
assert not is_readonly("INSERT OVERWRITE TABLE tabB SELECT a.Age FROM TableA")
assert is_readonly("SHOW LOCKS test EXTENDED")
assert is_readonly("EXPLAIN SELECT 1")
assert is_readonly("SELECT 1")
assert is_readonly("WITH (SELECT 1) bla SELECT * from bla")
| tests/integration_tests/db_engine_specs/presto_tests.py | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0001779647427611053,
0.00017262295295950025,
0.00016572148888371885,
0.00017307283997070044,
0.0000025372289655933855
] |
{
"id": 5,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.get_list\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def get_list_headless(self, **kwargs: Any) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB GET list endpoint\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 414
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useCallback, useMemo, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { css, t, useTheme } from '@superset-ui/core';
import { setDirectPathToChild } from 'src/dashboard/actions/dashboardState';
import Icons from 'src/components/Icons';
import {
DependencyItem,
Row,
RowLabel,
RowTruncationCount,
RowValue,
TooltipList,
} from './Styles';
import { useFilterDependencies } from './useFilterDependencies';
import { useTruncation } from './useTruncation';
import { DependencyValueProps, FilterCardRowProps } from './types';
import { TooltipWithTruncation } from './TooltipWithTruncation';
const DependencyValue = ({
dependency,
hasSeparator,
}: DependencyValueProps) => {
const dispatch = useDispatch();
const handleClick = useCallback(() => {
dispatch(setDirectPathToChild([dependency.id]));
}, [dependency.id, dispatch]);
return (
<span>
{hasSeparator && <span>, </span>}
<DependencyItem role="button" onClick={handleClick} tabIndex={0}>
{dependency.name}
</DependencyItem>
</span>
);
};
export const DependenciesRow = React.memo(({ filter }: FilterCardRowProps) => {
const dependencies = useFilterDependencies(filter);
const dependenciesRef = useRef<HTMLDivElement>(null);
const [elementsTruncated, hasHiddenElements] = useTruncation(dependenciesRef);
const theme = useTheme();
const tooltipText = useMemo(
() =>
elementsTruncated > 0 && dependencies ? (
<TooltipList>
{dependencies.map(dependency => (
<li>
<DependencyValue dependency={dependency} />
</li>
))}
</TooltipList>
) : null,
[elementsTruncated, dependencies],
);
if (!Array.isArray(dependencies) || dependencies.length === 0) {
return null;
}
return (
<Row>
<RowLabel
css={css`
display: inline-flex;
align-items: center;
`}
>
{t('Dependent on')}{' '}
<TooltipWithTruncation
title={t(
'Filter only displays values relevant to selections made in other filters.',
)}
>
<Icons.Info
iconSize="m"
iconColor={theme.colors.grayscale.light1}
css={css`
margin-left: ${theme.gridUnit}px;
`}
/>
</TooltipWithTruncation>
</RowLabel>
<TooltipWithTruncation title={tooltipText}>
<RowValue ref={dependenciesRef}>
{dependencies.map((dependency, index) => (
<DependencyValue
dependency={dependency}
hasSeparator={index !== 0}
/>
))}
</RowValue>
{hasHiddenElements && (
<RowTruncationCount>+{elementsTruncated}</RowTruncationCount>
)}
</TooltipWithTruncation>
</Row>
);
});
| superset-frontend/src/dashboard/components/nativeFilters/FilterCard/DependenciesRow.tsx | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0001770360831869766,
0.00017408262647222728,
0.00017205154290422797,
0.00017368412227369845,
0.00000169848601672129
] |
{
"id": 6,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.post\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def post_headless(self) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB POST endpoint\n",
" \"\"\"\n",
" duration, response = time_function(super().post_headless)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 427
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import dataclasses
import functools
import logging
import traceback
from datetime import datetime
from typing import Any, Callable, cast, Dict, List, Optional, TYPE_CHECKING, Union
import simplejson as json
import yaml
from flask import (
abort,
flash,
g,
get_flashed_messages,
redirect,
request,
Response,
send_file,
session,
)
from flask_appbuilder import BaseView, Model, ModelView
from flask_appbuilder.actions import action
from flask_appbuilder.forms import DynamicForm
from flask_appbuilder.models.sqla.filters import BaseFilter
from flask_appbuilder.security.sqla.models import User
from flask_appbuilder.widgets import ListWidget
from flask_babel import get_locale, gettext as __, lazy_gettext as _
from flask_jwt_extended.exceptions import NoAuthorizationError
from flask_wtf.csrf import CSRFError
from flask_wtf.form import FlaskForm
from pkg_resources import resource_filename
from sqlalchemy import or_
from sqlalchemy.orm import Query
from werkzeug.exceptions import HTTPException
from wtforms import Form
from wtforms.fields.core import Field, UnboundField
from superset import (
app as superset_app,
appbuilder,
conf,
db,
get_feature_flags,
security_manager,
)
from superset.commands.exceptions import CommandException, CommandInvalidError
from superset.connectors.sqla import models
from superset.datasets.commands.exceptions import get_dataset_exist_error_msg
from superset.db_engine_specs import get_available_engine_specs
from superset.db_engine_specs.gsheets import GSheetsEngineSpec
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.exceptions import (
SupersetErrorException,
SupersetErrorsException,
SupersetException,
SupersetSecurityException,
)
from superset.models.helpers import ImportExportMixin
from superset.models.reports import ReportRecipientType
from superset.superset_typing import FlaskResponse
from superset.translations.utils import get_language_pack
from superset.utils import core as utils
from .utils import bootstrap_user_data
if TYPE_CHECKING:
from superset.connectors.druid.views import DruidClusterModelView
FRONTEND_CONF_KEYS = (
"SUPERSET_WEBSERVER_TIMEOUT",
"SUPERSET_DASHBOARD_POSITION_DATA_LIMIT",
"SUPERSET_DASHBOARD_PERIODICAL_REFRESH_LIMIT",
"SUPERSET_DASHBOARD_PERIODICAL_REFRESH_WARNING_MESSAGE",
"DISABLE_DATASET_SOURCE_EDIT",
"DRUID_IS_ACTIVE",
"ENABLE_JAVASCRIPT_CONTROLS",
"DEFAULT_SQLLAB_LIMIT",
"DEFAULT_VIZ_TYPE",
"SQL_MAX_ROW",
"SUPERSET_WEBSERVER_DOMAINS",
"SQLLAB_SAVE_WARNING_MESSAGE",
"DISPLAY_MAX_ROW",
"GLOBAL_ASYNC_QUERIES_TRANSPORT",
"GLOBAL_ASYNC_QUERIES_POLLING_DELAY",
"SQL_VALIDATORS_BY_ENGINE",
"SQLALCHEMY_DOCS_URL",
"SQLALCHEMY_DISPLAY_TEXT",
"GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL",
"DASHBOARD_AUTO_REFRESH_MODE",
"SCHEDULED_QUERIES",
"EXCEL_EXTENSIONS",
"CSV_EXTENSIONS",
"COLUMNAR_EXTENSIONS",
"ALLOWED_EXTENSIONS",
)
logger = logging.getLogger(__name__)
config = superset_app.config
def get_error_msg() -> str:
if conf.get("SHOW_STACKTRACE"):
error_msg = traceback.format_exc()
else:
error_msg = "FATAL ERROR \n"
error_msg += (
"Stacktrace is hidden. Change the SHOW_STACKTRACE "
"configuration setting to enable it"
)
return error_msg
def json_error_response(
msg: Optional[str] = None,
status: int = 500,
payload: Optional[Dict[str, Any]] = None,
link: Optional[str] = None,
) -> FlaskResponse:
if not payload:
payload = {"error": "{}".format(msg)}
if link:
payload["link"] = link
return Response(
json.dumps(payload, default=utils.json_iso_dttm_ser, ignore_nan=True),
status=status,
mimetype="application/json",
)
def json_errors_response(
errors: List[SupersetError],
status: int = 500,
payload: Optional[Dict[str, Any]] = None,
) -> FlaskResponse:
if not payload:
payload = {}
payload["errors"] = [dataclasses.asdict(error) for error in errors]
return Response(
json.dumps(payload, default=utils.json_iso_dttm_ser, ignore_nan=True),
status=status,
mimetype="application/json; charset=utf-8",
)
def json_success(json_msg: str, status: int = 200) -> FlaskResponse:
return Response(json_msg, status=status, mimetype="application/json")
def data_payload_response(payload_json: str, has_error: bool = False) -> FlaskResponse:
status = 400 if has_error else 200
return json_success(payload_json, status=status)
def generate_download_headers(
extension: str, filename: Optional[str] = None
) -> Dict[str, Any]:
filename = filename if filename else datetime.now().strftime("%Y%m%d_%H%M%S")
content_disp = f"attachment; filename={filename}.{extension}"
headers = {"Content-Disposition": content_disp}
return headers
def api(f: Callable[..., FlaskResponse]) -> Callable[..., FlaskResponse]:
"""
A decorator to label an endpoint as an API. Catches uncaught exceptions and
return the response in the JSON format
"""
def wraps(self: "BaseSupersetView", *args: Any, **kwargs: Any) -> FlaskResponse:
try:
return f(self, *args, **kwargs)
except NoAuthorizationError as ex:
logger.warning(ex)
return json_error_response(get_error_msg(), status=401)
except Exception as ex: # pylint: disable=broad-except
logger.exception(ex)
return json_error_response(get_error_msg())
return functools.update_wrapper(wraps, f)
def handle_api_exception(
f: Callable[..., FlaskResponse]
) -> Callable[..., FlaskResponse]:
"""
A decorator to catch superset exceptions. Use it after the @api decorator above
so superset exception handler is triggered before the handler for generic
exceptions.
"""
def wraps(self: "BaseSupersetView", *args: Any, **kwargs: Any) -> FlaskResponse:
try:
return f(self, *args, **kwargs)
except SupersetSecurityException as ex:
logger.warning(ex)
return json_errors_response(
errors=[ex.error], status=ex.status, payload=ex.payload
)
except SupersetErrorsException as ex:
logger.warning(ex, exc_info=True)
return json_errors_response(errors=ex.errors, status=ex.status)
except SupersetErrorException as ex:
logger.warning(ex)
return json_errors_response(errors=[ex.error], status=ex.status)
except SupersetException as ex:
if ex.status >= 500:
logger.exception(ex)
return json_error_response(
utils.error_msg_from_exception(ex), status=ex.status
)
except HTTPException as ex:
logger.exception(ex)
return json_error_response(
utils.error_msg_from_exception(ex), status=cast(int, ex.code)
)
except Exception as ex: # pylint: disable=broad-except
logger.exception(ex)
return json_error_response(utils.error_msg_from_exception(ex))
return functools.update_wrapper(wraps, f)
def validate_sqlatable(table: models.SqlaTable) -> None:
"""Checks the table existence in the database."""
with db.session.no_autoflush:
table_query = db.session.query(models.SqlaTable).filter(
models.SqlaTable.table_name == table.table_name,
models.SqlaTable.schema == table.schema,
models.SqlaTable.database_id == table.database.id,
)
if db.session.query(table_query.exists()).scalar():
raise Exception(get_dataset_exist_error_msg(table.full_name))
# Fail before adding if the table can't be found
try:
table.get_sqla_table_object()
except Exception as ex:
logger.exception("Got an error in pre_add for %s", table.name)
raise Exception(
_(
"Table [%{table}s] could not be found, "
"please double check your "
"database connection, schema, and "
"table name, error: {}"
).format(table.name, str(ex))
) from ex
def create_table_permissions(table: models.SqlaTable) -> None:
security_manager.add_permission_view_menu("datasource_access", table.get_perm())
if table.schema:
security_manager.add_permission_view_menu("schema_access", table.schema_perm)
def is_user_admin() -> bool:
user_roles = [role.name.lower() for role in list(security_manager.get_user_roles())]
return "admin" in user_roles
class BaseSupersetView(BaseView):
@staticmethod
def json_response(obj: Any, status: int = 200) -> FlaskResponse:
return Response(
json.dumps(obj, default=utils.json_int_dttm_ser, ignore_nan=True),
status=status,
mimetype="application/json",
)
def render_app_template(self) -> FlaskResponse:
payload = {
"user": bootstrap_user_data(g.user, include_perms=True),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/spa.html",
entry="spa",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
def menu_data() -> Dict[str, Any]:
menu = appbuilder.menu.get_data()
languages = {}
for lang in appbuilder.languages:
languages[lang] = {
**appbuilder.languages[lang],
"url": appbuilder.get_url_for_locale(lang),
}
brand_text = appbuilder.app.config["LOGO_RIGHT_TEXT"]
if callable(brand_text):
brand_text = brand_text()
build_number = appbuilder.app.config["BUILD_NUMBER"]
return {
"menu": menu,
"brand": {
"path": appbuilder.app.config["LOGO_TARGET_PATH"] or "/",
"icon": appbuilder.app_icon,
"alt": appbuilder.app_name,
"tooltip": appbuilder.app.config["LOGO_TOOLTIP"],
"text": brand_text,
},
"navbar_right": {
# show the watermark if the default app icon has been overriden
"show_watermark": ("superset-logo-horiz" not in appbuilder.app_icon),
"bug_report_url": appbuilder.app.config["BUG_REPORT_URL"],
"documentation_url": appbuilder.app.config["DOCUMENTATION_URL"],
"version_string": appbuilder.app.config["VERSION_STRING"],
"version_sha": appbuilder.app.config["VERSION_SHA"],
"build_number": build_number,
"languages": languages,
"show_language_picker": len(languages.keys()) > 1,
"user_is_anonymous": g.user.is_anonymous,
"user_info_url": None
if appbuilder.app.config["MENU_HIDE_USER_INFO"]
else appbuilder.get_url_for_userinfo,
"user_logout_url": appbuilder.get_url_for_logout,
"user_login_url": appbuilder.get_url_for_login,
"user_profile_url": None
if g.user.is_anonymous or appbuilder.app.config["MENU_HIDE_USER_INFO"]
else f"/superset/profile/{g.user.username}",
"locale": session.get("locale", "en"),
},
}
def common_bootstrap_payload() -> Dict[str, Any]:
"""Common data always sent to the client"""
messages = get_flashed_messages(with_categories=True)
locale = str(get_locale())
# should not expose API TOKEN to frontend
frontend_config = {
k: (list(conf.get(k)) if isinstance(conf.get(k), set) else conf.get(k))
for k in FRONTEND_CONF_KEYS
}
if conf.get("SLACK_API_TOKEN"):
frontend_config["ALERT_REPORTS_NOTIFICATION_METHODS"] = [
ReportRecipientType.EMAIL,
ReportRecipientType.SLACK,
]
else:
frontend_config["ALERT_REPORTS_NOTIFICATION_METHODS"] = [
ReportRecipientType.EMAIL,
]
# verify client has google sheets installed
available_specs = get_available_engine_specs()
frontend_config["HAS_GSHEETS_INSTALLED"] = bool(available_specs[GSheetsEngineSpec])
bootstrap_data = {
"flash_messages": messages,
"conf": frontend_config,
"locale": locale,
"language_pack": get_language_pack(locale),
"feature_flags": get_feature_flags(),
"extra_sequential_color_schemes": conf["EXTRA_SEQUENTIAL_COLOR_SCHEMES"],
"extra_categorical_color_schemes": conf["EXTRA_CATEGORICAL_COLOR_SCHEMES"],
"theme_overrides": conf["THEME_OVERRIDES"],
"menu_data": menu_data(),
}
bootstrap_data.update(conf["COMMON_BOOTSTRAP_OVERRIDES_FUNC"](bootstrap_data))
return bootstrap_data
def get_error_level_from_status_code( # pylint: disable=invalid-name
status: int,
) -> ErrorLevel:
if status < 400:
return ErrorLevel.INFO
if status < 500:
return ErrorLevel.WARNING
return ErrorLevel.ERROR
# SIP-40 compatible error responses; make sure APIs raise
# SupersetErrorException or SupersetErrorsException
@superset_app.errorhandler(SupersetErrorException)
def show_superset_error(ex: SupersetErrorException) -> FlaskResponse:
logger.warning(ex)
return json_errors_response(errors=[ex.error], status=ex.status)
@superset_app.errorhandler(SupersetErrorsException)
def show_superset_errors(ex: SupersetErrorsException) -> FlaskResponse:
logger.warning(ex)
return json_errors_response(errors=ex.errors, status=ex.status)
# Redirect to login if the CSRF token is expired
@superset_app.errorhandler(CSRFError)
def refresh_csrf_token(ex: CSRFError) -> FlaskResponse:
logger.warning(ex)
if request.is_json:
return show_http_exception(ex)
return redirect(appbuilder.get_url_for_login)
@superset_app.errorhandler(HTTPException)
def show_http_exception(ex: HTTPException) -> FlaskResponse:
logger.warning(ex)
if (
"text/html" in request.accept_mimetypes
and not config["DEBUG"]
and ex.code in {404, 500}
):
path = resource_filename("superset", f"static/assets/{ex.code}.html")
return send_file(path, cache_timeout=0), ex.code
return json_errors_response(
errors=[
SupersetError(
message=utils.error_msg_from_exception(ex),
error_type=SupersetErrorType.GENERIC_BACKEND_ERROR,
level=ErrorLevel.ERROR,
),
],
status=ex.code or 500,
)
# Temporary handler for CommandException; if an API raises a
# CommandException it should be fixed to map it to SupersetErrorException
# or SupersetErrorsException, with a specific status code and error type
@superset_app.errorhandler(CommandException)
def show_command_errors(ex: CommandException) -> FlaskResponse:
logger.warning(ex)
if "text/html" in request.accept_mimetypes and not config["DEBUG"]:
path = resource_filename("superset", "static/assets/500.html")
return send_file(path, cache_timeout=0), 500
extra = ex.normalized_messages() if isinstance(ex, CommandInvalidError) else {}
return json_errors_response(
errors=[
SupersetError(
message=ex.message,
error_type=SupersetErrorType.GENERIC_COMMAND_ERROR,
level=get_error_level_from_status_code(ex.status),
extra=extra,
),
],
status=ex.status,
)
# Catch-all, to ensure all errors from the backend conform to SIP-40
@superset_app.errorhandler(Exception)
def show_unexpected_exception(ex: Exception) -> FlaskResponse:
logger.exception(ex)
if "text/html" in request.accept_mimetypes and not config["DEBUG"]:
path = resource_filename("superset", "static/assets/500.html")
return send_file(path, cache_timeout=0), 500
return json_errors_response(
errors=[
SupersetError(
message=utils.error_msg_from_exception(ex),
error_type=SupersetErrorType.GENERIC_BACKEND_ERROR,
level=ErrorLevel.ERROR,
),
],
)
@superset_app.context_processor
def get_common_bootstrap_data() -> Dict[str, Any]:
def serialize_bootstrap_data() -> str:
return json.dumps(
{"common": common_bootstrap_payload()},
default=utils.pessimistic_json_iso_dttm_ser,
)
return {"bootstrap_data": serialize_bootstrap_data}
class SupersetListWidget(ListWidget): # pylint: disable=too-few-public-methods
template = "superset/fab_overrides/list.html"
class SupersetModelView(ModelView):
page_size = 100
list_widget = SupersetListWidget
def render_app_template(self) -> FlaskResponse:
payload = {
"user": bootstrap_user_data(g.user, include_perms=True),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/spa.html",
entry="spa",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
class ListWidgetWithCheckboxes(ListWidget): # pylint: disable=too-few-public-methods
"""An alternative to list view that renders Boolean fields as checkboxes
Works in conjunction with the `checkbox` view."""
template = "superset/fab_overrides/list_with_checkboxes.html"
def validate_json(form: Form, field: Field) -> None: # pylint: disable=unused-argument
try:
json.loads(field.data)
except Exception as ex:
logger.exception(ex)
raise Exception(_("json isn't valid")) from ex
class YamlExportMixin: # pylint: disable=too-few-public-methods
"""
Override this if you want a dict response instead, with a certain key.
Used on DatabaseView for cli compatibility
"""
yaml_dict_key: Optional[str] = None
@action("yaml_export", __("Export to YAML"), __("Export to YAML?"), "fa-download")
def yaml_export(
self, items: Union[ImportExportMixin, List[ImportExportMixin]]
) -> FlaskResponse:
if not isinstance(items, list):
items = [items]
data = [t.export_to_dict() for t in items]
return Response(
yaml.safe_dump({self.yaml_dict_key: data} if self.yaml_dict_key else data),
headers=generate_download_headers("yaml"),
mimetype="application/text",
)
class DeleteMixin: # pylint: disable=too-few-public-methods
def _delete(self: BaseView, primary_key: int) -> None:
"""
Delete function logic, override to implement diferent logic
deletes the record with primary_key = primary_key
:param primary_key:
record primary key to delete
"""
item = self.datamodel.get(primary_key, self._base_filters)
if not item:
abort(404)
try:
self.pre_delete(item)
except Exception as ex: # pylint: disable=broad-except
flash(str(ex), "danger")
else:
view_menu = security_manager.find_view_menu(item.get_perm())
pvs = (
security_manager.get_session.query(
security_manager.permissionview_model
)
.filter_by(view_menu=view_menu)
.all()
)
if self.datamodel.delete(item):
self.post_delete(item)
for pv in pvs:
security_manager.get_session.delete(pv)
if view_menu:
security_manager.get_session.delete(view_menu)
security_manager.get_session.commit()
flash(*self.datamodel.message)
self.update_redirect()
@action(
"muldelete", __("Delete"), __("Delete all Really?"), "fa-trash", single=False
)
def muldelete(self: BaseView, items: List[Model]) -> FlaskResponse:
if not items:
abort(404)
for item in items:
try:
self.pre_delete(item)
except Exception as ex: # pylint: disable=broad-except
flash(str(ex), "danger")
else:
self._delete(item.id)
self.update_redirect()
return redirect(self.get_redirect())
class DatasourceFilter(BaseFilter): # pylint: disable=too-few-public-methods
def apply(self, query: Query, value: Any) -> Query:
if security_manager.can_access_all_datasources():
return query
datasource_perms = security_manager.user_view_menu_names("datasource_access")
schema_perms = security_manager.user_view_menu_names("schema_access")
return query.filter(
or_(
self.model.perm.in_(datasource_perms),
self.model.schema_perm.in_(schema_perms),
)
)
class CsvResponse(Response):
"""
Override Response to take into account csv encoding from config.py
"""
charset = conf["CSV_EXPORT"].get("encoding", "utf-8")
default_mimetype = "text/csv"
def check_ownership(obj: Any, raise_if_false: bool = True) -> bool:
"""Meant to be used in `pre_update` hooks on models to enforce ownership
Admin have all access, and other users need to be referenced on either
the created_by field that comes with the ``AuditMixin``, or in a field
named ``owners`` which is expected to be a one-to-many with the User
model. It is meant to be used in the ModelView's pre_update hook in
which raising will abort the update.
"""
if not obj:
return False
security_exception = SupersetSecurityException(
SupersetError(
error_type=SupersetErrorType.MISSING_OWNERSHIP_ERROR,
message="You don't have the rights to alter [{}]".format(obj),
level=ErrorLevel.ERROR,
)
)
if g.user.is_anonymous:
if raise_if_false:
raise security_exception
return False
if is_user_admin():
return True
scoped_session = db.create_scoped_session()
orig_obj = scoped_session.query(obj.__class__).filter_by(id=obj.id).first()
# Making a list of owners that works across ORM models
owners: List[User] = []
if hasattr(orig_obj, "owners"):
owners += orig_obj.owners
if hasattr(orig_obj, "owner"):
owners += [orig_obj.owner]
if hasattr(orig_obj, "created_by"):
owners += [orig_obj.created_by]
owner_names = [o.username for o in owners if o]
if g.user and hasattr(g.user, "username") and g.user.username in owner_names:
return True
if raise_if_false:
raise security_exception
return False
def bind_field(
_: Any, form: DynamicForm, unbound_field: UnboundField, options: Dict[Any, Any]
) -> Field:
"""
Customize how fields are bound by stripping all whitespace.
:param form: The form
:param unbound_field: The unbound field
:param options: The field options
:returns: The bound field
"""
filters = unbound_field.kwargs.get("filters", [])
filters.append(lambda x: x.strip() if isinstance(x, str) else x)
return unbound_field.bind(form=form, filters=filters, **options)
FlaskForm.Meta.bind_field = bind_field
@superset_app.after_request
def apply_http_headers(response: Response) -> Response:
"""Applies the configuration's http headers to all responses"""
# HTTP_HEADERS is deprecated, this provides backwards compatibility
response.headers.extend( # type: ignore
{**config["OVERRIDE_HTTP_HEADERS"], **config["HTTP_HEADERS"]}
)
for k, v in config["DEFAULT_HTTP_HEADERS"].items():
if k not in response.headers:
response.headers[k] = v
return response
| superset/views/base.py | 1 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.006794142536818981,
0.00033402704866603017,
0.00016322842566296458,
0.00016993621829897165,
0.0008564606541767716
] |
{
"id": 6,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.post\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def post_headless(self) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB POST endpoint\n",
" \"\"\"\n",
" duration, response = time_function(super().post_headless)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 427
} | {#
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
#}
{% import 'appbuilder/general/lib.html' as lib %}
{% set can_add = "can_add" | is_item_visible(modelview_name) %}
{% set can_show = "can_show" | is_item_visible(modelview_name) %}
{% set can_edit = "can_edit" | is_item_visible(modelview_name) %}
{% set can_delete = "can_delete" | is_item_visible(modelview_name) %}
{% set actions = actions | get_actions_on_list(modelview_name) %}
{% if can_add %}
<span class="list-add-action">
{% set path = url_for(modelview_name + '.add') %}
{% set path = path | set_link_filters(filters) %}
{{ lib.lnk_add(path) }}
</span>
{% endif %}
{% if count > 0 %}
{% block begin_content scoped %}
{% endblock %}
{% block begin_loop_header scoped %}
{% endblock %}
{% block begin_loop_values %}
{% endblock %}
{% block end_content scoped %}
{% endblock %}
<div class="form-actions-container">
{{ lib.render_actions(actions, modelview_name) }}
</div>
{{ lib.action_form(actions,modelview_name) }}
<div class="pagination-container pull-right">
<strong>{{ _('Record Count') }}:</strong> {{ count }}
{{ lib.render_pagination(page, page_size, count, modelview_name) }}
{{ lib.render_set_page_size(page, page_size, count, modelview_name) }}
</div>
<script language="javascript">
var modelActions = new AdminActions();
</script>
{% else %}
<b>{{_("No records found")}}</b>
{% endif %}
| superset/templates/appbuilder/general/widgets/base_list.html | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00017844102694652975,
0.00017273965931963176,
0.00016995469923131168,
0.00017114769434556365,
0.0000032729321901570074
] |
{
"id": 6,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.post\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def post_headless(self) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB POST endpoint\n",
" \"\"\"\n",
" duration, response = time_function(super().post_headless)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 427
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import moment, { Moment } from 'moment';
import {
CustomRangeDecodeType,
CustomRangeType,
DateTimeGrainType,
DateTimeModeType,
} from 'src/explore/components/controls/DateFilterControl/types';
import { SEPARATOR } from './dateFilterUtils';
import { SEVEN_DAYS_AGO, MIDNIGHT, MOMENT_FORMAT } from './constants';
/**
* RegExp to test a string for a full ISO 8601 Date
* Does not do any sort of date validation, only checks if the string is according to the ISO 8601 spec.
* YYYY-MM-DDThh:mm:ss
* YYYY-MM-DDThh:mm:ssTZD
* YYYY-MM-DDThh:mm:ss.sTZD
* @see: https://www.w3.org/TR/NOTE-datetime
*/
const iso8601 = String.raw`\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:(?:[+-]\d\d:\d\d)|Z)?`;
const datetimeConstant = String.raw`TODAY|NOW`;
const grainValue = String.raw`[+-]?[1-9][0-9]*`;
const grain = String.raw`YEAR|QUARTER|MONTH|WEEK|DAY|HOUR|MINUTE|SECOND`;
const CUSTOM_RANGE_EXPRESSION = RegExp(
String.raw`^DATEADD\(DATETIME\("(${iso8601}|${datetimeConstant})"\),\s(${grainValue}),\s(${grain})\)$`,
'i',
);
export const ISO8601_AND_CONSTANT = RegExp(
String.raw`^${iso8601}$|^${datetimeConstant}$`,
'i',
);
const DATETIME_CONSTANT = ['now', 'today'];
const defaultCustomRange: CustomRangeType = {
sinceDatetime: SEVEN_DAYS_AGO,
sinceMode: 'relative',
sinceGrain: 'day',
sinceGrainValue: -7,
untilDatetime: MIDNIGHT,
untilMode: 'specific',
untilGrain: 'day',
untilGrainValue: 7,
anchorMode: 'now',
anchorValue: 'now',
};
const SPECIFIC_MODE = ['specific', 'today', 'now'];
export const dttmToMoment = (dttm: string): Moment => {
if (dttm === 'now') {
return moment().utc().startOf('second');
}
if (dttm === 'today') {
return moment().utc().startOf('day');
}
return moment(dttm);
};
export const dttmToString = (dttm: string): string =>
dttmToMoment(dttm).format(MOMENT_FORMAT);
export const customTimeRangeDecode = (
timeRange: string,
): CustomRangeDecodeType => {
const splitDateRange = timeRange.split(SEPARATOR);
if (splitDateRange.length === 2) {
const [since, until] = splitDateRange;
// specific : specific
if (ISO8601_AND_CONSTANT.test(since) && ISO8601_AND_CONSTANT.test(until)) {
const sinceMode = (
DATETIME_CONSTANT.includes(since) ? since : 'specific'
) as DateTimeModeType;
const untilMode = (
DATETIME_CONSTANT.includes(until) ? until : 'specific'
) as DateTimeModeType;
return {
customRange: {
...defaultCustomRange,
sinceDatetime: since,
untilDatetime: until,
sinceMode,
untilMode,
},
matchedFlag: true,
};
}
// relative : specific
const sinceCapturedGroup = since.match(CUSTOM_RANGE_EXPRESSION);
if (
sinceCapturedGroup &&
ISO8601_AND_CONSTANT.test(until) &&
since.includes(until)
) {
const [dttm, grainValue, grain] = sinceCapturedGroup.slice(1);
const untilMode = (
DATETIME_CONSTANT.includes(until) ? until : 'specific'
) as DateTimeModeType;
return {
customRange: {
...defaultCustomRange,
sinceGrain: grain as DateTimeGrainType,
sinceGrainValue: parseInt(grainValue, 10),
sinceDatetime: dttm,
untilDatetime: dttm,
sinceMode: 'relative',
untilMode,
},
matchedFlag: true,
};
}
// specific : relative
const untilCapturedGroup = until.match(CUSTOM_RANGE_EXPRESSION);
if (
ISO8601_AND_CONSTANT.test(since) &&
untilCapturedGroup &&
until.includes(since)
) {
const [dttm, grainValue, grain] = [...untilCapturedGroup.slice(1)];
const sinceMode = (
DATETIME_CONSTANT.includes(since) ? since : 'specific'
) as DateTimeModeType;
return {
customRange: {
...defaultCustomRange,
untilGrain: grain as DateTimeGrainType,
untilGrainValue: parseInt(grainValue, 10),
sinceDatetime: dttm,
untilDatetime: dttm,
untilMode: 'relative',
sinceMode,
},
matchedFlag: true,
};
}
// relative : relative
if (sinceCapturedGroup && untilCapturedGroup) {
const [sinceDttm, sinceGrainValue, sinceGrain] = [
...sinceCapturedGroup.slice(1),
];
const [untileDttm, untilGrainValue, untilGrain] = [
...untilCapturedGroup.slice(1),
];
if (sinceDttm === untileDttm) {
return {
customRange: {
...defaultCustomRange,
sinceGrain: sinceGrain as DateTimeGrainType,
sinceGrainValue: parseInt(sinceGrainValue, 10),
sinceDatetime: sinceDttm,
untilGrain: untilGrain as DateTimeGrainType,
untilGrainValue: parseInt(untilGrainValue, 10),
untilDatetime: untileDttm,
anchorValue: sinceDttm,
sinceMode: 'relative',
untilMode: 'relative',
anchorMode: sinceDttm === 'now' ? 'now' : 'specific',
},
matchedFlag: true,
};
}
}
}
return {
customRange: defaultCustomRange,
matchedFlag: false,
};
};
export const customTimeRangeEncode = (customRange: CustomRangeType): string => {
const {
sinceDatetime,
sinceMode,
sinceGrain,
sinceGrainValue,
untilDatetime,
untilMode,
untilGrain,
untilGrainValue,
anchorValue,
} = { ...customRange };
// specific : specific
if (SPECIFIC_MODE.includes(sinceMode) && SPECIFIC_MODE.includes(untilMode)) {
const since =
sinceMode === 'specific' ? dttmToString(sinceDatetime) : sinceMode;
const until =
untilMode === 'specific' ? dttmToString(untilDatetime) : untilMode;
return `${since} : ${until}`;
}
// specific : relative
if (SPECIFIC_MODE.includes(sinceMode) && untilMode === 'relative') {
const since =
sinceMode === 'specific' ? dttmToString(sinceDatetime) : sinceMode;
const until = `DATEADD(DATETIME("${since}"), ${untilGrainValue}, ${untilGrain})`;
return `${since} : ${until}`;
}
// relative : specific
if (sinceMode === 'relative' && SPECIFIC_MODE.includes(untilMode)) {
const until =
untilMode === 'specific' ? dttmToString(untilDatetime) : untilMode;
const since = `DATEADD(DATETIME("${until}"), ${-Math.abs(
sinceGrainValue,
)}, ${sinceGrain})`;
return `${since} : ${until}`;
}
// relative : relative
const since = `DATEADD(DATETIME("${anchorValue}"), ${-Math.abs(
sinceGrainValue,
)}, ${sinceGrain})`;
const until = `DATEADD(DATETIME("${anchorValue}"), ${untilGrainValue}, ${untilGrain})`;
return `${since} : ${until}`;
};
| superset-frontend/src/explore/components/controls/DateFilterControl/utils/dateParser.ts | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0001902481890283525,
0.00017298692546319216,
0.00016510352725163102,
0.00017221753660123795,
0.000004689014076575404
] |
{
"id": 6,
"code_window": [
" @event_logger.log_this_with_context(\n",
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.post\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def post_headless(self) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB POST endpoint\n",
" \"\"\"\n",
" duration, response = time_function(super().post_headless)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 427
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { hot } from 'react-hot-loader/root';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { ThemeProvider } from '@superset-ui/core';
import { GlobalStyles } from 'src/GlobalStyles';
import App from 'src/profile/components/App';
import messageToastReducer from 'src/components/MessageToasts/reducers';
import { initEnhancer } from 'src/reduxUtils';
import setupApp from 'src/setup/setupApp';
import { theme } from 'src/preamble';
import ToastContainer from 'src/components/MessageToasts/ToastContainer';
setupApp();
const profileViewContainer = document.getElementById('app');
const bootstrap = JSON.parse(
profileViewContainer?.getAttribute('data-bootstrap') ?? '{}',
);
const store = createStore(
combineReducers({
messageToasts: messageToastReducer,
}),
{},
compose(applyMiddleware(thunk), initEnhancer(false)),
);
const Application = () => (
<Provider store={store}>
<ThemeProvider theme={theme}>
<GlobalStyles />
<App user={bootstrap.user} />
<ToastContainer />
</ThemeProvider>
</Provider>
);
export default hot(Application);
| superset-frontend/src/profile/App.tsx | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.0001766654459061101,
0.00017427217971999198,
0.00017076870426535606,
0.00017445316188968718,
0.000002061379063889035
] |
{
"id": 7,
"code_window": [
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.put\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def put_headless(self, pk: int) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB PUT endpoint\n",
" \"\"\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 440
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import dataclasses
import functools
import logging
import traceback
from datetime import datetime
from typing import Any, Callable, cast, Dict, List, Optional, TYPE_CHECKING, Union
import simplejson as json
import yaml
from flask import (
abort,
flash,
g,
get_flashed_messages,
redirect,
request,
Response,
send_file,
session,
)
from flask_appbuilder import BaseView, Model, ModelView
from flask_appbuilder.actions import action
from flask_appbuilder.forms import DynamicForm
from flask_appbuilder.models.sqla.filters import BaseFilter
from flask_appbuilder.security.sqla.models import User
from flask_appbuilder.widgets import ListWidget
from flask_babel import get_locale, gettext as __, lazy_gettext as _
from flask_jwt_extended.exceptions import NoAuthorizationError
from flask_wtf.csrf import CSRFError
from flask_wtf.form import FlaskForm
from pkg_resources import resource_filename
from sqlalchemy import or_
from sqlalchemy.orm import Query
from werkzeug.exceptions import HTTPException
from wtforms import Form
from wtforms.fields.core import Field, UnboundField
from superset import (
app as superset_app,
appbuilder,
conf,
db,
get_feature_flags,
security_manager,
)
from superset.commands.exceptions import CommandException, CommandInvalidError
from superset.connectors.sqla import models
from superset.datasets.commands.exceptions import get_dataset_exist_error_msg
from superset.db_engine_specs import get_available_engine_specs
from superset.db_engine_specs.gsheets import GSheetsEngineSpec
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.exceptions import (
SupersetErrorException,
SupersetErrorsException,
SupersetException,
SupersetSecurityException,
)
from superset.models.helpers import ImportExportMixin
from superset.models.reports import ReportRecipientType
from superset.superset_typing import FlaskResponse
from superset.translations.utils import get_language_pack
from superset.utils import core as utils
from .utils import bootstrap_user_data
if TYPE_CHECKING:
from superset.connectors.druid.views import DruidClusterModelView
FRONTEND_CONF_KEYS = (
"SUPERSET_WEBSERVER_TIMEOUT",
"SUPERSET_DASHBOARD_POSITION_DATA_LIMIT",
"SUPERSET_DASHBOARD_PERIODICAL_REFRESH_LIMIT",
"SUPERSET_DASHBOARD_PERIODICAL_REFRESH_WARNING_MESSAGE",
"DISABLE_DATASET_SOURCE_EDIT",
"DRUID_IS_ACTIVE",
"ENABLE_JAVASCRIPT_CONTROLS",
"DEFAULT_SQLLAB_LIMIT",
"DEFAULT_VIZ_TYPE",
"SQL_MAX_ROW",
"SUPERSET_WEBSERVER_DOMAINS",
"SQLLAB_SAVE_WARNING_MESSAGE",
"DISPLAY_MAX_ROW",
"GLOBAL_ASYNC_QUERIES_TRANSPORT",
"GLOBAL_ASYNC_QUERIES_POLLING_DELAY",
"SQL_VALIDATORS_BY_ENGINE",
"SQLALCHEMY_DOCS_URL",
"SQLALCHEMY_DISPLAY_TEXT",
"GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL",
"DASHBOARD_AUTO_REFRESH_MODE",
"SCHEDULED_QUERIES",
"EXCEL_EXTENSIONS",
"CSV_EXTENSIONS",
"COLUMNAR_EXTENSIONS",
"ALLOWED_EXTENSIONS",
)
logger = logging.getLogger(__name__)
config = superset_app.config
def get_error_msg() -> str:
if conf.get("SHOW_STACKTRACE"):
error_msg = traceback.format_exc()
else:
error_msg = "FATAL ERROR \n"
error_msg += (
"Stacktrace is hidden. Change the SHOW_STACKTRACE "
"configuration setting to enable it"
)
return error_msg
def json_error_response(
msg: Optional[str] = None,
status: int = 500,
payload: Optional[Dict[str, Any]] = None,
link: Optional[str] = None,
) -> FlaskResponse:
if not payload:
payload = {"error": "{}".format(msg)}
if link:
payload["link"] = link
return Response(
json.dumps(payload, default=utils.json_iso_dttm_ser, ignore_nan=True),
status=status,
mimetype="application/json",
)
def json_errors_response(
errors: List[SupersetError],
status: int = 500,
payload: Optional[Dict[str, Any]] = None,
) -> FlaskResponse:
if not payload:
payload = {}
payload["errors"] = [dataclasses.asdict(error) for error in errors]
return Response(
json.dumps(payload, default=utils.json_iso_dttm_ser, ignore_nan=True),
status=status,
mimetype="application/json; charset=utf-8",
)
def json_success(json_msg: str, status: int = 200) -> FlaskResponse:
return Response(json_msg, status=status, mimetype="application/json")
def data_payload_response(payload_json: str, has_error: bool = False) -> FlaskResponse:
status = 400 if has_error else 200
return json_success(payload_json, status=status)
def generate_download_headers(
extension: str, filename: Optional[str] = None
) -> Dict[str, Any]:
filename = filename if filename else datetime.now().strftime("%Y%m%d_%H%M%S")
content_disp = f"attachment; filename={filename}.{extension}"
headers = {"Content-Disposition": content_disp}
return headers
def api(f: Callable[..., FlaskResponse]) -> Callable[..., FlaskResponse]:
"""
A decorator to label an endpoint as an API. Catches uncaught exceptions and
return the response in the JSON format
"""
def wraps(self: "BaseSupersetView", *args: Any, **kwargs: Any) -> FlaskResponse:
try:
return f(self, *args, **kwargs)
except NoAuthorizationError as ex:
logger.warning(ex)
return json_error_response(get_error_msg(), status=401)
except Exception as ex: # pylint: disable=broad-except
logger.exception(ex)
return json_error_response(get_error_msg())
return functools.update_wrapper(wraps, f)
def handle_api_exception(
f: Callable[..., FlaskResponse]
) -> Callable[..., FlaskResponse]:
"""
A decorator to catch superset exceptions. Use it after the @api decorator above
so superset exception handler is triggered before the handler for generic
exceptions.
"""
def wraps(self: "BaseSupersetView", *args: Any, **kwargs: Any) -> FlaskResponse:
try:
return f(self, *args, **kwargs)
except SupersetSecurityException as ex:
logger.warning(ex)
return json_errors_response(
errors=[ex.error], status=ex.status, payload=ex.payload
)
except SupersetErrorsException as ex:
logger.warning(ex, exc_info=True)
return json_errors_response(errors=ex.errors, status=ex.status)
except SupersetErrorException as ex:
logger.warning(ex)
return json_errors_response(errors=[ex.error], status=ex.status)
except SupersetException as ex:
if ex.status >= 500:
logger.exception(ex)
return json_error_response(
utils.error_msg_from_exception(ex), status=ex.status
)
except HTTPException as ex:
logger.exception(ex)
return json_error_response(
utils.error_msg_from_exception(ex), status=cast(int, ex.code)
)
except Exception as ex: # pylint: disable=broad-except
logger.exception(ex)
return json_error_response(utils.error_msg_from_exception(ex))
return functools.update_wrapper(wraps, f)
def validate_sqlatable(table: models.SqlaTable) -> None:
"""Checks the table existence in the database."""
with db.session.no_autoflush:
table_query = db.session.query(models.SqlaTable).filter(
models.SqlaTable.table_name == table.table_name,
models.SqlaTable.schema == table.schema,
models.SqlaTable.database_id == table.database.id,
)
if db.session.query(table_query.exists()).scalar():
raise Exception(get_dataset_exist_error_msg(table.full_name))
# Fail before adding if the table can't be found
try:
table.get_sqla_table_object()
except Exception as ex:
logger.exception("Got an error in pre_add for %s", table.name)
raise Exception(
_(
"Table [%{table}s] could not be found, "
"please double check your "
"database connection, schema, and "
"table name, error: {}"
).format(table.name, str(ex))
) from ex
def create_table_permissions(table: models.SqlaTable) -> None:
security_manager.add_permission_view_menu("datasource_access", table.get_perm())
if table.schema:
security_manager.add_permission_view_menu("schema_access", table.schema_perm)
def is_user_admin() -> bool:
user_roles = [role.name.lower() for role in list(security_manager.get_user_roles())]
return "admin" in user_roles
class BaseSupersetView(BaseView):
@staticmethod
def json_response(obj: Any, status: int = 200) -> FlaskResponse:
return Response(
json.dumps(obj, default=utils.json_int_dttm_ser, ignore_nan=True),
status=status,
mimetype="application/json",
)
def render_app_template(self) -> FlaskResponse:
payload = {
"user": bootstrap_user_data(g.user, include_perms=True),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/spa.html",
entry="spa",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
def menu_data() -> Dict[str, Any]:
menu = appbuilder.menu.get_data()
languages = {}
for lang in appbuilder.languages:
languages[lang] = {
**appbuilder.languages[lang],
"url": appbuilder.get_url_for_locale(lang),
}
brand_text = appbuilder.app.config["LOGO_RIGHT_TEXT"]
if callable(brand_text):
brand_text = brand_text()
build_number = appbuilder.app.config["BUILD_NUMBER"]
return {
"menu": menu,
"brand": {
"path": appbuilder.app.config["LOGO_TARGET_PATH"] or "/",
"icon": appbuilder.app_icon,
"alt": appbuilder.app_name,
"tooltip": appbuilder.app.config["LOGO_TOOLTIP"],
"text": brand_text,
},
"navbar_right": {
# show the watermark if the default app icon has been overriden
"show_watermark": ("superset-logo-horiz" not in appbuilder.app_icon),
"bug_report_url": appbuilder.app.config["BUG_REPORT_URL"],
"documentation_url": appbuilder.app.config["DOCUMENTATION_URL"],
"version_string": appbuilder.app.config["VERSION_STRING"],
"version_sha": appbuilder.app.config["VERSION_SHA"],
"build_number": build_number,
"languages": languages,
"show_language_picker": len(languages.keys()) > 1,
"user_is_anonymous": g.user.is_anonymous,
"user_info_url": None
if appbuilder.app.config["MENU_HIDE_USER_INFO"]
else appbuilder.get_url_for_userinfo,
"user_logout_url": appbuilder.get_url_for_logout,
"user_login_url": appbuilder.get_url_for_login,
"user_profile_url": None
if g.user.is_anonymous or appbuilder.app.config["MENU_HIDE_USER_INFO"]
else f"/superset/profile/{g.user.username}",
"locale": session.get("locale", "en"),
},
}
def common_bootstrap_payload() -> Dict[str, Any]:
"""Common data always sent to the client"""
messages = get_flashed_messages(with_categories=True)
locale = str(get_locale())
# should not expose API TOKEN to frontend
frontend_config = {
k: (list(conf.get(k)) if isinstance(conf.get(k), set) else conf.get(k))
for k in FRONTEND_CONF_KEYS
}
if conf.get("SLACK_API_TOKEN"):
frontend_config["ALERT_REPORTS_NOTIFICATION_METHODS"] = [
ReportRecipientType.EMAIL,
ReportRecipientType.SLACK,
]
else:
frontend_config["ALERT_REPORTS_NOTIFICATION_METHODS"] = [
ReportRecipientType.EMAIL,
]
# verify client has google sheets installed
available_specs = get_available_engine_specs()
frontend_config["HAS_GSHEETS_INSTALLED"] = bool(available_specs[GSheetsEngineSpec])
bootstrap_data = {
"flash_messages": messages,
"conf": frontend_config,
"locale": locale,
"language_pack": get_language_pack(locale),
"feature_flags": get_feature_flags(),
"extra_sequential_color_schemes": conf["EXTRA_SEQUENTIAL_COLOR_SCHEMES"],
"extra_categorical_color_schemes": conf["EXTRA_CATEGORICAL_COLOR_SCHEMES"],
"theme_overrides": conf["THEME_OVERRIDES"],
"menu_data": menu_data(),
}
bootstrap_data.update(conf["COMMON_BOOTSTRAP_OVERRIDES_FUNC"](bootstrap_data))
return bootstrap_data
def get_error_level_from_status_code( # pylint: disable=invalid-name
status: int,
) -> ErrorLevel:
if status < 400:
return ErrorLevel.INFO
if status < 500:
return ErrorLevel.WARNING
return ErrorLevel.ERROR
# SIP-40 compatible error responses; make sure APIs raise
# SupersetErrorException or SupersetErrorsException
@superset_app.errorhandler(SupersetErrorException)
def show_superset_error(ex: SupersetErrorException) -> FlaskResponse:
logger.warning(ex)
return json_errors_response(errors=[ex.error], status=ex.status)
@superset_app.errorhandler(SupersetErrorsException)
def show_superset_errors(ex: SupersetErrorsException) -> FlaskResponse:
logger.warning(ex)
return json_errors_response(errors=ex.errors, status=ex.status)
# Redirect to login if the CSRF token is expired
@superset_app.errorhandler(CSRFError)
def refresh_csrf_token(ex: CSRFError) -> FlaskResponse:
logger.warning(ex)
if request.is_json:
return show_http_exception(ex)
return redirect(appbuilder.get_url_for_login)
@superset_app.errorhandler(HTTPException)
def show_http_exception(ex: HTTPException) -> FlaskResponse:
logger.warning(ex)
if (
"text/html" in request.accept_mimetypes
and not config["DEBUG"]
and ex.code in {404, 500}
):
path = resource_filename("superset", f"static/assets/{ex.code}.html")
return send_file(path, cache_timeout=0), ex.code
return json_errors_response(
errors=[
SupersetError(
message=utils.error_msg_from_exception(ex),
error_type=SupersetErrorType.GENERIC_BACKEND_ERROR,
level=ErrorLevel.ERROR,
),
],
status=ex.code or 500,
)
# Temporary handler for CommandException; if an API raises a
# CommandException it should be fixed to map it to SupersetErrorException
# or SupersetErrorsException, with a specific status code and error type
@superset_app.errorhandler(CommandException)
def show_command_errors(ex: CommandException) -> FlaskResponse:
logger.warning(ex)
if "text/html" in request.accept_mimetypes and not config["DEBUG"]:
path = resource_filename("superset", "static/assets/500.html")
return send_file(path, cache_timeout=0), 500
extra = ex.normalized_messages() if isinstance(ex, CommandInvalidError) else {}
return json_errors_response(
errors=[
SupersetError(
message=ex.message,
error_type=SupersetErrorType.GENERIC_COMMAND_ERROR,
level=get_error_level_from_status_code(ex.status),
extra=extra,
),
],
status=ex.status,
)
# Catch-all, to ensure all errors from the backend conform to SIP-40
@superset_app.errorhandler(Exception)
def show_unexpected_exception(ex: Exception) -> FlaskResponse:
logger.exception(ex)
if "text/html" in request.accept_mimetypes and not config["DEBUG"]:
path = resource_filename("superset", "static/assets/500.html")
return send_file(path, cache_timeout=0), 500
return json_errors_response(
errors=[
SupersetError(
message=utils.error_msg_from_exception(ex),
error_type=SupersetErrorType.GENERIC_BACKEND_ERROR,
level=ErrorLevel.ERROR,
),
],
)
@superset_app.context_processor
def get_common_bootstrap_data() -> Dict[str, Any]:
def serialize_bootstrap_data() -> str:
return json.dumps(
{"common": common_bootstrap_payload()},
default=utils.pessimistic_json_iso_dttm_ser,
)
return {"bootstrap_data": serialize_bootstrap_data}
class SupersetListWidget(ListWidget): # pylint: disable=too-few-public-methods
template = "superset/fab_overrides/list.html"
class SupersetModelView(ModelView):
page_size = 100
list_widget = SupersetListWidget
def render_app_template(self) -> FlaskResponse:
payload = {
"user": bootstrap_user_data(g.user, include_perms=True),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/spa.html",
entry="spa",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
class ListWidgetWithCheckboxes(ListWidget): # pylint: disable=too-few-public-methods
"""An alternative to list view that renders Boolean fields as checkboxes
Works in conjunction with the `checkbox` view."""
template = "superset/fab_overrides/list_with_checkboxes.html"
def validate_json(form: Form, field: Field) -> None: # pylint: disable=unused-argument
try:
json.loads(field.data)
except Exception as ex:
logger.exception(ex)
raise Exception(_("json isn't valid")) from ex
class YamlExportMixin: # pylint: disable=too-few-public-methods
"""
Override this if you want a dict response instead, with a certain key.
Used on DatabaseView for cli compatibility
"""
yaml_dict_key: Optional[str] = None
@action("yaml_export", __("Export to YAML"), __("Export to YAML?"), "fa-download")
def yaml_export(
self, items: Union[ImportExportMixin, List[ImportExportMixin]]
) -> FlaskResponse:
if not isinstance(items, list):
items = [items]
data = [t.export_to_dict() for t in items]
return Response(
yaml.safe_dump({self.yaml_dict_key: data} if self.yaml_dict_key else data),
headers=generate_download_headers("yaml"),
mimetype="application/text",
)
class DeleteMixin: # pylint: disable=too-few-public-methods
def _delete(self: BaseView, primary_key: int) -> None:
"""
Delete function logic, override to implement diferent logic
deletes the record with primary_key = primary_key
:param primary_key:
record primary key to delete
"""
item = self.datamodel.get(primary_key, self._base_filters)
if not item:
abort(404)
try:
self.pre_delete(item)
except Exception as ex: # pylint: disable=broad-except
flash(str(ex), "danger")
else:
view_menu = security_manager.find_view_menu(item.get_perm())
pvs = (
security_manager.get_session.query(
security_manager.permissionview_model
)
.filter_by(view_menu=view_menu)
.all()
)
if self.datamodel.delete(item):
self.post_delete(item)
for pv in pvs:
security_manager.get_session.delete(pv)
if view_menu:
security_manager.get_session.delete(view_menu)
security_manager.get_session.commit()
flash(*self.datamodel.message)
self.update_redirect()
@action(
"muldelete", __("Delete"), __("Delete all Really?"), "fa-trash", single=False
)
def muldelete(self: BaseView, items: List[Model]) -> FlaskResponse:
if not items:
abort(404)
for item in items:
try:
self.pre_delete(item)
except Exception as ex: # pylint: disable=broad-except
flash(str(ex), "danger")
else:
self._delete(item.id)
self.update_redirect()
return redirect(self.get_redirect())
class DatasourceFilter(BaseFilter): # pylint: disable=too-few-public-methods
def apply(self, query: Query, value: Any) -> Query:
if security_manager.can_access_all_datasources():
return query
datasource_perms = security_manager.user_view_menu_names("datasource_access")
schema_perms = security_manager.user_view_menu_names("schema_access")
return query.filter(
or_(
self.model.perm.in_(datasource_perms),
self.model.schema_perm.in_(schema_perms),
)
)
class CsvResponse(Response):
"""
Override Response to take into account csv encoding from config.py
"""
charset = conf["CSV_EXPORT"].get("encoding", "utf-8")
default_mimetype = "text/csv"
def check_ownership(obj: Any, raise_if_false: bool = True) -> bool:
"""Meant to be used in `pre_update` hooks on models to enforce ownership
Admin have all access, and other users need to be referenced on either
the created_by field that comes with the ``AuditMixin``, or in a field
named ``owners`` which is expected to be a one-to-many with the User
model. It is meant to be used in the ModelView's pre_update hook in
which raising will abort the update.
"""
if not obj:
return False
security_exception = SupersetSecurityException(
SupersetError(
error_type=SupersetErrorType.MISSING_OWNERSHIP_ERROR,
message="You don't have the rights to alter [{}]".format(obj),
level=ErrorLevel.ERROR,
)
)
if g.user.is_anonymous:
if raise_if_false:
raise security_exception
return False
if is_user_admin():
return True
scoped_session = db.create_scoped_session()
orig_obj = scoped_session.query(obj.__class__).filter_by(id=obj.id).first()
# Making a list of owners that works across ORM models
owners: List[User] = []
if hasattr(orig_obj, "owners"):
owners += orig_obj.owners
if hasattr(orig_obj, "owner"):
owners += [orig_obj.owner]
if hasattr(orig_obj, "created_by"):
owners += [orig_obj.created_by]
owner_names = [o.username for o in owners if o]
if g.user and hasattr(g.user, "username") and g.user.username in owner_names:
return True
if raise_if_false:
raise security_exception
return False
def bind_field(
_: Any, form: DynamicForm, unbound_field: UnboundField, options: Dict[Any, Any]
) -> Field:
"""
Customize how fields are bound by stripping all whitespace.
:param form: The form
:param unbound_field: The unbound field
:param options: The field options
:returns: The bound field
"""
filters = unbound_field.kwargs.get("filters", [])
filters.append(lambda x: x.strip() if isinstance(x, str) else x)
return unbound_field.bind(form=form, filters=filters, **options)
FlaskForm.Meta.bind_field = bind_field
@superset_app.after_request
def apply_http_headers(response: Response) -> Response:
"""Applies the configuration's http headers to all responses"""
# HTTP_HEADERS is deprecated, this provides backwards compatibility
response.headers.extend( # type: ignore
{**config["OVERRIDE_HTTP_HEADERS"], **config["HTTP_HEADERS"]}
)
for k, v in config["DEFAULT_HTTP_HEADERS"].items():
if k not in response.headers:
response.headers[k] = v
return response
| superset/views/base.py | 1 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.015165600925683975,
0.0005751581047661602,
0.00016227495507337153,
0.00017063863924704492,
0.0018975787097588181
] |
{
"id": 7,
"code_window": [
" action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.put\",\n",
" object_ref=False,\n",
" log_to_statsd=False,\n",
" )\n",
" def put_headless(self, pk: int) -> Response:\n",
" \"\"\"\n",
" Add statsd metrics to builtin FAB PUT endpoint\n",
" \"\"\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @handle_api_exception\n"
],
"file_path": "superset/views/base_api.py",
"type": "add",
"edit_start_line_idx": 440
} | {
"name": "@superset-ui/legacy-plugin-chart-sankey",
"version": "0.18.25",
"description": "Superset Legacy Chart - Sankey Diagram",
"sideEffects": [
"*.css"
],
"main": "lib/index.js",
"module": "esm/index.js",
"files": [
"esm",
"lib"
],
"repository": {
"type": "git",
"url": "git+https://github.com/apache-superset/superset-ui.git"
},
"keywords": [
"superset"
],
"author": "Superset",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/apache-superset/superset-ui/issues"
},
"homepage": "https://github.com/apache-superset/superset-ui#readme",
"publishConfig": {
"access": "public"
},
"dependencies": {
"d3": "^3.5.17",
"d3-sankey": "^0.4.2",
"prop-types": "^15.6.2"
},
"peerDependencies": {
"@superset-ui/chart-controls": "*",
"@superset-ui/core": "*",
"react": "^16.13.1"
}
}
| superset-frontend/plugins/legacy-plugin-chart-sankey/package.json | 0 | https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f | [
0.00017337875033263117,
0.0001720028230920434,
0.00016903915093280375,
0.00017314811702817678,
0.0000017121025166488835
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.