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": 3,
"code_window": [
"\t\t\t\t\tmarker = [];\n",
"\t\t\t\t\tconst sorted = diagnostics.slice(0).sort(Diagnostic.compare);\n",
"\t\t\t\t\tfor (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) {\n",
"\t\t\t\t\t\tmarker.push(DiagnosticCollection._toMarkerData(sorted[i]));\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst order = [DiagnosticSeverity.Error, DiagnosticSeverity.Warning, DiagnosticSeverity.Information, DiagnosticSeverity.Hint];\n",
"\t\t\t\t\torderLoop: for (let i = 0; i < 4; i++) {\n",
"\t\t\t\t\t\tfor (const diagnostic of diagnostics) {\n",
"\t\t\t\t\t\t\tif (diagnostic.severity === order[i]) {\n",
"\t\t\t\t\t\t\t\tconst len = marker.push(DiagnosticCollection._toMarkerData(diagnostic));\n",
"\t\t\t\t\t\t\t\tif (len === DiagnosticCollection._maxDiagnosticsPerFile) {\n",
"\t\t\t\t\t\t\t\t\tbreak orderLoop;\n",
"\t\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts",
"type": "replace",
"edit_start_line_idx": 102
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"toggle.wordwrap": "Visualizza: Attiva/Disattiva ritorno a capo automatico"
} | i18n/ita/src/vs/editor/contrib/toggleWordWrap/common/toggleWordWrap.i18n.json | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.0001764418848324567,
0.0001764418848324567,
0.0001764418848324567,
0.0001764418848324567,
0
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\tmarker = [];\n",
"\t\t\t\t\tconst sorted = diagnostics.slice(0).sort(Diagnostic.compare);\n",
"\t\t\t\t\tfor (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) {\n",
"\t\t\t\t\t\tmarker.push(DiagnosticCollection._toMarkerData(sorted[i]));\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst order = [DiagnosticSeverity.Error, DiagnosticSeverity.Warning, DiagnosticSeverity.Information, DiagnosticSeverity.Hint];\n",
"\t\t\t\t\torderLoop: for (let i = 0; i < 4; i++) {\n",
"\t\t\t\t\t\tfor (const diagnostic of diagnostics) {\n",
"\t\t\t\t\t\t\tif (diagnostic.severity === order[i]) {\n",
"\t\t\t\t\t\t\t\tconst len = marker.push(DiagnosticCollection._toMarkerData(diagnostic));\n",
"\t\t\t\t\t\t\t\tif (len === DiagnosticCollection._maxDiagnosticsPerFile) {\n",
"\t\t\t\t\t\t\t\t\tbreak orderLoop;\n",
"\t\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts",
"type": "replace",
"edit_start_line_idx": 102
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as editorCommon from 'vs/editor/common/editorCommon';
export class TokenIterator implements editorCommon.ITokenIterator {
private _model:editorCommon.ITokenizedModel;
private _currentLineNumber:number;
private _currentTokenIndex:number;
private _currentLineTokens:editorCommon.ILineTokens;
private _next:editorCommon.ITokenInfo;
private _prev:editorCommon.ITokenInfo;
constructor(model:editorCommon.ITokenizedModel, position:editorCommon.IPosition) {
this._model = model;
this._currentLineNumber = position.lineNumber;
this._currentTokenIndex = 0;
this._readLineTokens(this._currentLineNumber);
this._next = null;
this._prev = null;
// start with a position to next/prev run
var columnIndex = position.column - 1, tokenEndIndex = Number.MAX_VALUE;
for (var i = this._currentLineTokens.getTokenCount() - 1; i >= 0; i--) {
let tokenStartIndex = this._currentLineTokens.getTokenStartIndex(i);
if (tokenStartIndex <= columnIndex && columnIndex <= tokenEndIndex) {
this._currentTokenIndex = i;
this._next = this._current();
this._prev = this._current();
break;
}
tokenEndIndex = tokenStartIndex;
}
}
private _readLineTokens(lineNumber:number): void {
this._currentLineTokens = this._model.getLineTokens(lineNumber, false);
}
private _advanceNext() {
this._prev = this._next;
this._next = null;
if (this._currentTokenIndex + 1 < this._currentLineTokens.getTokenCount()) {
// There are still tokens on current line
this._currentTokenIndex++;
this._next = this._current();
} else {
// find the next line with tokens
while (this._currentLineNumber + 1 <= this._model.getLineCount()) {
this._currentLineNumber++;
this._readLineTokens(this._currentLineNumber);
if (this._currentLineTokens.getTokenCount() > 0) {
this._currentTokenIndex = 0;
this._next = this._current();
break;
}
}
if (this._next === null) {
// prepare of a previous run
this._readLineTokens(this._currentLineNumber);
this._currentTokenIndex = this._currentLineTokens.getTokenCount();
this._advancePrev();
this._next = null;
}
}
}
private _advancePrev() {
this._next = this._prev;
this._prev = null;
if (this._currentTokenIndex > 0) {
// There are still tokens on current line
this._currentTokenIndex--;
this._prev = this._current();
} else {
// find previous line with tokens
while (this._currentLineNumber > 1) {
this._currentLineNumber--;
this._readLineTokens(this._currentLineNumber);
if (this._currentLineTokens.getTokenCount() > 0) {
this._currentTokenIndex = this._currentLineTokens.getTokenCount() - 1;
this._prev = this._current();
break;
}
}
}
}
private _current(): editorCommon.ITokenInfo {
let startIndex = this._currentLineTokens.getTokenStartIndex(this._currentTokenIndex);
let type = this._currentLineTokens.getTokenType(this._currentTokenIndex);
let endIndex = this._currentLineTokens.getTokenEndIndex(this._currentTokenIndex, this._model.getLineContent(this._currentLineNumber).length);
return {
token: {
startIndex: startIndex,
type: type
},
lineNumber: this._currentLineNumber,
startColumn: startIndex + 1,
endColumn: endIndex + 1
};
}
public hasNext(): boolean {
return this._next !== null;
}
public next(): editorCommon.ITokenInfo {
var result = this._next;
this._advanceNext();
return result;
}
public hasPrev(): boolean {
return this._prev !== null;
}
public prev(): editorCommon.ITokenInfo {
var result = this._prev;
this._advancePrev();
return result;
}
public _invalidate() {
// replace all public functions with errors
var errorFn = function(): any {
throw new Error('iteration isn\'t valid anymore');
};
this.hasNext = errorFn;
this.next = errorFn;
this.hasPrev = errorFn;
this.prev = errorFn;
}
}
| src/vs/editor/common/model/tokenIterator.ts | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.9346143007278442,
0.06246964633464813,
0.000169715189258568,
0.00017344886146020144,
0.23309046030044556
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tmarker = diagnostics.map(DiagnosticCollection._toMarkerData);\n",
"\t\t\t\t}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\t\t// add 'signal' marker for showing omitted errors/warnings\n",
"\t\t\t\t\tmarker.push({\n",
"\t\t\t\t\t\tseverity: Severity.Error,\n",
"\t\t\t\t\t\tmessage: localize('limitHit', \"Not showing {0} further errors and warnings.\", diagnostics.length - DiagnosticCollection._maxDiagnosticsPerFile),\n",
"\t\t\t\t\t\tstartLineNumber: marker[marker.length - 1].startLineNumber,\n",
"\t\t\t\t\t\tstartColumn: marker[marker.length - 1].startColumn,\n",
"\t\t\t\t\t\tendLineNumber: marker[marker.length - 1].endLineNumber,\n",
"\t\t\t\t\t\tendColumn: marker[marker.length - 1].endColumn\n",
"\t\t\t\t\t});\n"
],
"file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts",
"type": "add",
"edit_start_line_idx": 106
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {IThreadService} from 'vs/workbench/services/thread/common/threadService';
import {IMarkerData} from 'vs/platform/markers/common/markers';
import URI from 'vs/base/common/uri';
import Severity from 'vs/base/common/severity';
import * as vscode from 'vscode';
import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol';
import {Diagnostic} from './extHostTypes';
export class DiagnosticCollection implements vscode.DiagnosticCollection {
private static _maxDiagnosticsPerFile: number = 250;
private _name: string;
private _proxy: MainThreadDiagnosticsShape;
private _isDisposed = false;
private _data: {[uri:string]: vscode.Diagnostic[]} = Object.create(null);
constructor(name: string, proxy: MainThreadDiagnosticsShape) {
this._name = name;
this._proxy = proxy;
}
dispose(): void {
if (!this._isDisposed) {
this._proxy.$clear(this.name);
this._proxy = undefined;
this._data = undefined;
this._isDisposed = true;
}
}
get name(): string {
this._checkDisposed();
return this._name;
}
set(uri: vscode.Uri, diagnostics: vscode.Diagnostic[]): void;
set(entries: [vscode.Uri, vscode.Diagnostic[]][]): void;
set(first: vscode.Uri | [vscode.Uri, vscode.Diagnostic[]][], diagnostics?: vscode.Diagnostic[]) {
if (!first) {
// this set-call is a clear-call
this.clear();
return;
}
// the actual implementation for #set
this._checkDisposed();
let toSync: vscode.Uri[];
if (first instanceof URI) {
if (!diagnostics) {
// remove this entry
this.delete(first);
return;
}
// update single row
this._data[first.toString()] = diagnostics;
toSync = [first];
} else if (Array.isArray(first)) {
// update many rows
toSync = [];
for (let entry of first) {
let [uri, diagnostics] = entry;
toSync.push(uri);
if (!diagnostics) {
// [Uri, undefined] means clear this
delete this._data[uri.toString()];
} else {
// set or merge diagnostics
let existing = this._data[uri.toString()];
if (existing) {
existing.push(...diagnostics);
} else {
this._data[uri.toString()] = diagnostics;
}
}
}
}
// compute change and send to main side
const entries: [URI, IMarkerData[]][] = [];
for (let uri of toSync) {
let marker: IMarkerData[];
let diagnostics = this._data[uri.toString()];
if (diagnostics) {
// no more than 250 diagnostics per file
if (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) {
console.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length);
marker = [];
const sorted = diagnostics.slice(0).sort(Diagnostic.compare);
for (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) {
marker.push(DiagnosticCollection._toMarkerData(sorted[i]));
}
} else {
marker = diagnostics.map(DiagnosticCollection._toMarkerData);
}
}
entries.push([<URI> uri, marker]);
}
this._proxy.$changeMany(this.name, entries);
}
delete(uri: vscode.Uri): void {
this._checkDisposed();
delete this._data[uri.toString()];
this._proxy.$changeMany(this.name, [[<URI> uri, undefined]]);
}
clear(): void {
this._checkDisposed();
this._data = Object.create(null);
this._proxy.$clear(this.name);
}
forEach(callback: (uri: URI, diagnostics: vscode.Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void {
this._checkDisposed();
for (let key in this._data) {
let uri = URI.parse(key);
callback.apply(thisArg, [uri, this.get(uri), this]);
}
}
get(uri: URI): vscode.Diagnostic[] {
this._checkDisposed();
let result = this._data[uri.toString()];
if (Array.isArray(result)) {
return Object.freeze(result.slice(0));
}
}
has(uri: URI): boolean {
this._checkDisposed();
return Array.isArray(this._data[uri.toString()]);
}
private _checkDisposed() {
if (this._isDisposed) {
throw new Error('illegal state - object is disposed');
}
}
private static _toMarkerData(diagnostic: vscode.Diagnostic): IMarkerData {
let range = diagnostic.range;
return <IMarkerData>{
startLineNumber: range.start.line + 1,
startColumn: range.start.character + 1,
endLineNumber: range.end.line + 1,
endColumn: range.end.character + 1,
message: diagnostic.message,
source: diagnostic.source,
severity: DiagnosticCollection._convertDiagnosticsSeverity(diagnostic.severity),
code: String(diagnostic.code)
};
}
private static _convertDiagnosticsSeverity(severity: number): Severity {
switch (severity) {
case 0: return Severity.Error;
case 1: return Severity.Warning;
case 2: return Severity.Info;
case 3: return Severity.Ignore;
default: return Severity.Error;
}
}
}
export class ExtHostDiagnostics extends ExtHostDiagnosticsShape {
private static _idPool: number = 0;
private _proxy: MainThreadDiagnosticsShape;
private _collections: DiagnosticCollection[];
constructor(threadService: IThreadService) {
super();
this._proxy = threadService.get(MainContext.MainThreadDiagnostics);
this._collections = [];
}
createDiagnosticCollection(name: string): vscode.DiagnosticCollection {
if (!name) {
name = '_generated_diagnostic_collection_name_#' + ExtHostDiagnostics._idPool++;
}
const {_collections, _proxy} = this;
const result = new class extends DiagnosticCollection {
constructor() {
super(name, _proxy);
_collections.push(this);
}
dispose() {
super.dispose();
let idx = _collections.indexOf(this);
if (idx !== -1) {
_collections.splice(idx, 1);
}
}
};
return result;
}
forEach(callback: (collection: DiagnosticCollection) => any): void {
this._collections.forEach(callback);
}
}
| src/vs/workbench/api/node/extHostDiagnostics.ts | 1 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.994963526725769,
0.04595307633280754,
0.00016357353888452053,
0.0013307171175256371,
0.202373206615448
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tmarker = diagnostics.map(DiagnosticCollection._toMarkerData);\n",
"\t\t\t\t}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\t\t// add 'signal' marker for showing omitted errors/warnings\n",
"\t\t\t\t\tmarker.push({\n",
"\t\t\t\t\t\tseverity: Severity.Error,\n",
"\t\t\t\t\t\tmessage: localize('limitHit', \"Not showing {0} further errors and warnings.\", diagnostics.length - DiagnosticCollection._maxDiagnosticsPerFile),\n",
"\t\t\t\t\t\tstartLineNumber: marker[marker.length - 1].startLineNumber,\n",
"\t\t\t\t\t\tstartColumn: marker[marker.length - 1].startColumn,\n",
"\t\t\t\t\t\tendLineNumber: marker[marker.length - 1].endLineNumber,\n",
"\t\t\t\t\t\tendColumn: marker[marker.length - 1].endColumn\n",
"\t\t\t\t\t});\n"
],
"file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts",
"type": "add",
"edit_start_line_idx": 106
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"mutlicursor.insertAbove": "カーソルを上に挿入",
"mutlicursor.insertAtEndOfEachLineSelected": "選択した行から複数のカーソルを作成",
"mutlicursor.insertBelow": "カーソルを下に挿入"
} | i18n/jpn/src/vs/editor/contrib/multicursor/common/multicursor.i18n.json | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.00018093835387844592,
0.00017711830150801688,
0.00017329824913758785,
0.00017711830150801688,
0.000003820052370429039
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tmarker = diagnostics.map(DiagnosticCollection._toMarkerData);\n",
"\t\t\t\t}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\t\t// add 'signal' marker for showing omitted errors/warnings\n",
"\t\t\t\t\tmarker.push({\n",
"\t\t\t\t\t\tseverity: Severity.Error,\n",
"\t\t\t\t\t\tmessage: localize('limitHit', \"Not showing {0} further errors and warnings.\", diagnostics.length - DiagnosticCollection._maxDiagnosticsPerFile),\n",
"\t\t\t\t\t\tstartLineNumber: marker[marker.length - 1].startLineNumber,\n",
"\t\t\t\t\t\tstartColumn: marker[marker.length - 1].startColumn,\n",
"\t\t\t\t\t\tendLineNumber: marker[marker.length - 1].endLineNumber,\n",
"\t\t\t\t\t\tendColumn: marker[marker.length - 1].endColumn\n",
"\t\t\t\t\t});\n"
],
"file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts",
"type": "add",
"edit_start_line_idx": 106
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"activateBreakpoints": "Активировать точки останова",
"addConditionalBreakpoint": "Добавить условную точку останова",
"addFunctionBreakpoint": "Добавить точку останова в функции",
"addToWatchExpressions": "Добавить контрольное значение",
"addWatchExpression": "Добавить выражение",
"clearRepl": "Очистить консоль",
"continueDebug": "Продолжить",
"copy": "Копировать",
"copyValue": "Копировать значение",
"deactivateBreakpoints": "Отключить точки останова",
"debugActionLabelAndKeybinding": "{0} ({1})",
"debugConsoleAction": "Консоль отладки",
"disableAllBreakpoints": "Отключить все точки останова",
"disconnectDebug": "Отключить",
"editConditionalBreakpoint": "Изменить точку останова",
"enableAllBreakpoints": "Включить все точки останова",
"openLaunchJson": "Открыть {0}",
"pauseDebug": "Приостановить",
"reapplyAllBreakpoints": "Повторно применить все точки останова",
"reconnectDebug": "Повторно подключить",
"removeAllBreakpoints": "Удалить все точки останова",
"removeAllWatchExpressions": "Удалить все выражения",
"removeBreakpoint": "Удалить точку останова",
"removeWatchExpression": "Удалить выражение",
"renameFunctionBreakpoint": "Переименовать точку останова в функции",
"renameWatchExpression": "Переименовать выражение",
"restartDebug": "Перезапустить",
"selectConfig": "Выбрать конфигурацию",
"startDebug": "Начать отладку",
"startWithoutDebugging": "Начать без отладки",
"stepIntoDebug": "Шаг с заходом",
"stepOutDebug": "Шаг с выходом",
"stepOverDebug": "Шаг с обходом",
"stopDebug": "Остановить",
"toggleEnablement": "Включить или отключить точку останова"
} | i18n/rus/src/vs/workbench/parts/debug/electron-browser/debugActions.i18n.json | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.0001692507357802242,
0.0001673156803008169,
0.00016507378313690424,
0.00016739763668738306,
0.0000017090848132284009
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tmarker = diagnostics.map(DiagnosticCollection._toMarkerData);\n",
"\t\t\t\t}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\t\t// add 'signal' marker for showing omitted errors/warnings\n",
"\t\t\t\t\tmarker.push({\n",
"\t\t\t\t\t\tseverity: Severity.Error,\n",
"\t\t\t\t\t\tmessage: localize('limitHit', \"Not showing {0} further errors and warnings.\", diagnostics.length - DiagnosticCollection._maxDiagnosticsPerFile),\n",
"\t\t\t\t\t\tstartLineNumber: marker[marker.length - 1].startLineNumber,\n",
"\t\t\t\t\t\tstartColumn: marker[marker.length - 1].startColumn,\n",
"\t\t\t\t\t\tendLineNumber: marker[marker.length - 1].endLineNumber,\n",
"\t\t\t\t\t\tendColumn: marker[marker.length - 1].endColumn\n",
"\t\t\t\t\t});\n"
],
"file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts",
"type": "add",
"edit_start_line_idx": 106
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {TPromise} from 'vs/base/common/winjs.base';
export namespace Schemas {
/**
* A schema that is used for models that exist in memory
* only and that have no correspondence on a server or such.
*/
export var inMemory:string = 'inmemory';
/**
* A schema that is used for setting files
*/
export var vscode:string = 'vscode';
/**
* A schema that is used for internal private files
*/
export var internal:string = 'private';
export var http:string = 'http';
export var https:string = 'https';
export var file:string = 'file';
}
export interface IXHROptions {
type?:string;
url?:string;
user?:string;
password?:string;
responseType?:string;
headers?:any;
customRequestInitializer?:(req:any)=>void;
data?:any;
}
export function xhr(options:IXHROptions): TPromise<XMLHttpRequest> {
let req:XMLHttpRequest = null;
let canceled = false;
return new TPromise<XMLHttpRequest>((c, e, p) => {
req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (canceled) {
return;
}
if (req.readyState === 4) {
// Handle 1223: http://bugs.jquery.com/ticket/1450
if ((req.status >= 200 && req.status < 300) || req.status === 1223) {
c(req);
} else {
e(req);
}
req.onreadystatechange = () => { };
} else {
p(req);
}
};
req.open(
options.type || 'GET',
options.url,
// Promise based XHR does not support sync.
//
true,
options.user,
options.password
);
req.responseType = options.responseType || '';
Object.keys(options.headers || {}).forEach((k) => {
req.setRequestHeader(k, options.headers[k]);
});
if (options.customRequestInitializer) {
options.customRequestInitializer(req);
}
req.send(options.data);
}, () => {
canceled = true;
req.abort();
});
}
| src/vs/base/common/network.ts | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.00017689350352156907,
0.00017094599024858326,
0.0001659224508330226,
0.00017089844914153218,
0.0000027743592454498867
] |
{
"id": 5,
"code_window": [
"\t\t\tcode: this.code,\n",
"\t\t};\n",
"\t}\n",
"\n",
"\tstatic compare(a: vscode.Diagnostic, b: vscode.Diagnostic): number{\n",
"\t\tlet ret = a.severity - b.severity;\n",
"\t\tif (ret === 0) {\n",
"\t\t\tret = a.range.start.compareTo(b.range.start);\n",
"\t\t}\n",
"\t\tif (ret === 0) {\n",
"\t\t\tret = a.message.localeCompare(b.message);\n",
"\t\t}\n",
"\t\treturn ret;\n",
"\t}\n",
"}\n",
"\n",
"export class Hover {\n",
"\n",
"\tpublic contents: vscode.MarkedString[];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/api/node/extHostTypes.ts",
"type": "replace",
"edit_start_line_idx": 554
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {IThreadService} from 'vs/workbench/services/thread/common/threadService';
import {IMarkerData} from 'vs/platform/markers/common/markers';
import URI from 'vs/base/common/uri';
import Severity from 'vs/base/common/severity';
import * as vscode from 'vscode';
import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol';
import {Diagnostic} from './extHostTypes';
export class DiagnosticCollection implements vscode.DiagnosticCollection {
private static _maxDiagnosticsPerFile: number = 250;
private _name: string;
private _proxy: MainThreadDiagnosticsShape;
private _isDisposed = false;
private _data: {[uri:string]: vscode.Diagnostic[]} = Object.create(null);
constructor(name: string, proxy: MainThreadDiagnosticsShape) {
this._name = name;
this._proxy = proxy;
}
dispose(): void {
if (!this._isDisposed) {
this._proxy.$clear(this.name);
this._proxy = undefined;
this._data = undefined;
this._isDisposed = true;
}
}
get name(): string {
this._checkDisposed();
return this._name;
}
set(uri: vscode.Uri, diagnostics: vscode.Diagnostic[]): void;
set(entries: [vscode.Uri, vscode.Diagnostic[]][]): void;
set(first: vscode.Uri | [vscode.Uri, vscode.Diagnostic[]][], diagnostics?: vscode.Diagnostic[]) {
if (!first) {
// this set-call is a clear-call
this.clear();
return;
}
// the actual implementation for #set
this._checkDisposed();
let toSync: vscode.Uri[];
if (first instanceof URI) {
if (!diagnostics) {
// remove this entry
this.delete(first);
return;
}
// update single row
this._data[first.toString()] = diagnostics;
toSync = [first];
} else if (Array.isArray(first)) {
// update many rows
toSync = [];
for (let entry of first) {
let [uri, diagnostics] = entry;
toSync.push(uri);
if (!diagnostics) {
// [Uri, undefined] means clear this
delete this._data[uri.toString()];
} else {
// set or merge diagnostics
let existing = this._data[uri.toString()];
if (existing) {
existing.push(...diagnostics);
} else {
this._data[uri.toString()] = diagnostics;
}
}
}
}
// compute change and send to main side
const entries: [URI, IMarkerData[]][] = [];
for (let uri of toSync) {
let marker: IMarkerData[];
let diagnostics = this._data[uri.toString()];
if (diagnostics) {
// no more than 250 diagnostics per file
if (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) {
console.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length);
marker = [];
const sorted = diagnostics.slice(0).sort(Diagnostic.compare);
for (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) {
marker.push(DiagnosticCollection._toMarkerData(sorted[i]));
}
} else {
marker = diagnostics.map(DiagnosticCollection._toMarkerData);
}
}
entries.push([<URI> uri, marker]);
}
this._proxy.$changeMany(this.name, entries);
}
delete(uri: vscode.Uri): void {
this._checkDisposed();
delete this._data[uri.toString()];
this._proxy.$changeMany(this.name, [[<URI> uri, undefined]]);
}
clear(): void {
this._checkDisposed();
this._data = Object.create(null);
this._proxy.$clear(this.name);
}
forEach(callback: (uri: URI, diagnostics: vscode.Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void {
this._checkDisposed();
for (let key in this._data) {
let uri = URI.parse(key);
callback.apply(thisArg, [uri, this.get(uri), this]);
}
}
get(uri: URI): vscode.Diagnostic[] {
this._checkDisposed();
let result = this._data[uri.toString()];
if (Array.isArray(result)) {
return Object.freeze(result.slice(0));
}
}
has(uri: URI): boolean {
this._checkDisposed();
return Array.isArray(this._data[uri.toString()]);
}
private _checkDisposed() {
if (this._isDisposed) {
throw new Error('illegal state - object is disposed');
}
}
private static _toMarkerData(diagnostic: vscode.Diagnostic): IMarkerData {
let range = diagnostic.range;
return <IMarkerData>{
startLineNumber: range.start.line + 1,
startColumn: range.start.character + 1,
endLineNumber: range.end.line + 1,
endColumn: range.end.character + 1,
message: diagnostic.message,
source: diagnostic.source,
severity: DiagnosticCollection._convertDiagnosticsSeverity(diagnostic.severity),
code: String(diagnostic.code)
};
}
private static _convertDiagnosticsSeverity(severity: number): Severity {
switch (severity) {
case 0: return Severity.Error;
case 1: return Severity.Warning;
case 2: return Severity.Info;
case 3: return Severity.Ignore;
default: return Severity.Error;
}
}
}
export class ExtHostDiagnostics extends ExtHostDiagnosticsShape {
private static _idPool: number = 0;
private _proxy: MainThreadDiagnosticsShape;
private _collections: DiagnosticCollection[];
constructor(threadService: IThreadService) {
super();
this._proxy = threadService.get(MainContext.MainThreadDiagnostics);
this._collections = [];
}
createDiagnosticCollection(name: string): vscode.DiagnosticCollection {
if (!name) {
name = '_generated_diagnostic_collection_name_#' + ExtHostDiagnostics._idPool++;
}
const {_collections, _proxy} = this;
const result = new class extends DiagnosticCollection {
constructor() {
super(name, _proxy);
_collections.push(this);
}
dispose() {
super.dispose();
let idx = _collections.indexOf(this);
if (idx !== -1) {
_collections.splice(idx, 1);
}
}
};
return result;
}
forEach(callback: (collection: DiagnosticCollection) => any): void {
this._collections.forEach(callback);
}
}
| src/vs/workbench/api/node/extHostDiagnostics.ts | 1 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.005298340227454901,
0.0007078191847540438,
0.00016243178106378764,
0.0001724764733808115,
0.0013470349367707968
] |
{
"id": 5,
"code_window": [
"\t\t\tcode: this.code,\n",
"\t\t};\n",
"\t}\n",
"\n",
"\tstatic compare(a: vscode.Diagnostic, b: vscode.Diagnostic): number{\n",
"\t\tlet ret = a.severity - b.severity;\n",
"\t\tif (ret === 0) {\n",
"\t\t\tret = a.range.start.compareTo(b.range.start);\n",
"\t\t}\n",
"\t\tif (ret === 0) {\n",
"\t\t\tret = a.message.localeCompare(b.message);\n",
"\t\t}\n",
"\t\treturn ret;\n",
"\t}\n",
"}\n",
"\n",
"export class Hover {\n",
"\n",
"\tpublic contents: vscode.MarkedString[];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/api/node/extHostTypes.ts",
"type": "replace",
"edit_start_line_idx": 554
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as strings from 'vs/base/common/strings';
import {Arrays} from 'vs/editor/common/core/arrays';
import {Range} from 'vs/editor/common/core/range';
import {ViewLineToken, ViewLineTokens} from 'vs/editor/common/core/viewLineToken';
import {InlineDecoration} from 'vs/editor/common/viewModel/viewModel';
function cmpLineDecorations(a:InlineDecoration, b:InlineDecoration): number {
return Range.compareRangesUsingStarts(a.range, b.range);
}
export function createLineParts(lineNumber:number, minLineColumn:number, lineContent:string, tabSize:number, lineTokens:ViewLineTokens, rawLineDecorations:InlineDecoration[], renderWhitespace:boolean): LineParts {
if (renderWhitespace) {
let oldLength = rawLineDecorations.length;
rawLineDecorations = insertWhitespaceLineDecorations(lineNumber, lineContent, tabSize, lineTokens.getFauxIndentLength(), rawLineDecorations);
if (rawLineDecorations.length !== oldLength) {
rawLineDecorations.sort(cmpLineDecorations);
}
}
if (rawLineDecorations.length > 0) {
return createViewLineParts(lineNumber, minLineColumn, lineTokens, lineContent, rawLineDecorations);
} else {
return createFastViewLineParts(lineTokens, lineContent);
}
}
export function getColumnOfLinePartOffset(stopRenderingLineAfter:number, lineParts:ViewLineToken[], lineMaxColumn:number, charOffsetInPart:number[], partIndex:number, partLength:number, offset:number): number {
if (partIndex >= lineParts.length) {
return stopRenderingLineAfter;
}
if (offset === 0) {
return lineParts[partIndex].startIndex + 1;
}
if (offset === partLength) {
return (partIndex + 1 < lineParts.length ? lineParts[partIndex + 1].startIndex + 1 : lineMaxColumn);
}
let originalMin = lineParts[partIndex].startIndex;
let originalMax = (partIndex + 1 < lineParts.length ? lineParts[partIndex + 1].startIndex : lineMaxColumn - 1);
let min = originalMin;
let max = originalMax;
// invariant: offsetOf(min) <= offset <= offsetOf(max)
while (min + 1 < max) {
let mid = Math.floor( (min + max) / 2 );
let midOffset = charOffsetInPart[mid];
if (midOffset === offset) {
return mid + 1;
} else if (midOffset > offset) {
max = mid;
} else {
min = mid;
}
}
if (min === max) {
return min + 1;
}
let minOffset = charOffsetInPart[min];
let maxOffset = (max < originalMax ? charOffsetInPart[max] : partLength);
let distanceToMin = offset - minOffset;
let distanceToMax = maxOffset - offset;
if (distanceToMin <= distanceToMax) {
return min + 1;
} else {
return max + 1;
}
}
function trimEmptyTrailingPart(parts: ViewLineToken[], lineContent: string): ViewLineToken[] {
if (parts.length <= 1) {
return parts;
}
var lastPartStartIndex = parts[parts.length - 1].startIndex;
if (lastPartStartIndex < lineContent.length) {
// All is good
return parts;
}
// Remove last line part
return parts.slice(0, parts.length - 1);
}
const _tab = '\t'.charCodeAt(0);
const _space = ' '.charCodeAt(0);
function insertOneCustomLineDecoration(dest:InlineDecoration[], lineNumber:number, startColumn:number, endColumn:number, className:string): void {
dest.push(new InlineDecoration(new Range(lineNumber, startColumn, lineNumber, endColumn), className));
}
function insertWhitespaceLineDecorations(lineNumber:number, lineContent: string, tabSize:number, fauxIndentLength: number, rawLineDecorations: InlineDecoration[]): InlineDecoration[] {
let lineLength = lineContent.length;
if (lineLength === fauxIndentLength) {
return rawLineDecorations;
}
let firstChar = lineContent.charCodeAt(fauxIndentLength);
let lastChar = lineContent.charCodeAt(lineLength - 1);
if (firstChar !== _tab && firstChar !== _space && lastChar !== _tab && lastChar !== _space) {
// This line contains no leading nor trailing whitespace => fast path
return rawLineDecorations;
}
let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
let lastNonWhitespaceIndex: number;
if (firstNonWhitespaceIndex === -1) {
// The entire line is whitespace
firstNonWhitespaceIndex = lineLength;
lastNonWhitespaceIndex = lineLength;
} else {
lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent);
}
let sm_endIndex: number[] = [];
let sm_decoration: string[] = [];
if (fauxIndentLength > 0) {
// add faux indent state
sm_endIndex.push(fauxIndentLength - 1);
sm_decoration.push(null);
}
if (firstNonWhitespaceIndex > fauxIndentLength) {
// add leading whitespace state
sm_endIndex.push(firstNonWhitespaceIndex - 1);
sm_decoration.push('leading whitespace');
}
// add content state
sm_endIndex.push(lastNonWhitespaceIndex);
sm_decoration.push(null);
// add trailing whitespace state
sm_endIndex.push(lineLength - 1);
sm_decoration.push('trailing whitespace');
// add dummy state to avoid array length checks
sm_endIndex.push(lineLength);
sm_decoration.push(null);
return insertCustomLineDecorationsWithStateMachine(lineNumber, lineContent, tabSize, rawLineDecorations, sm_endIndex, sm_decoration);
}
function insertCustomLineDecorationsWithStateMachine(lineNumber:number, lineContent: string, tabSize:number, rawLineDecorations: InlineDecoration[], sm_endIndex: number[], sm_decoration: string[]): InlineDecoration[] {
let lineLength = lineContent.length;
let currentStateIndex = 0;
let stateEndIndex = sm_endIndex[currentStateIndex];
let stateDecoration = sm_decoration[currentStateIndex];
let result = rawLineDecorations.slice(0);
let tmpIndent = 0;
let whitespaceStartColumn = 1;
for (let index = 0; index < lineLength; index++) {
let chCode = lineContent.charCodeAt(index);
if (chCode === _tab) {
tmpIndent = tabSize;
} else {
tmpIndent++;
}
if (index === stateEndIndex) {
if (stateDecoration !== null) {
insertOneCustomLineDecoration(result, lineNumber, whitespaceStartColumn, index + 2, stateDecoration);
}
whitespaceStartColumn = index + 2;
tmpIndent = tmpIndent % tabSize;
currentStateIndex++;
stateEndIndex = sm_endIndex[currentStateIndex];
stateDecoration = sm_decoration[currentStateIndex];
} else {
if (stateDecoration !== null && tmpIndent >= tabSize) {
insertOneCustomLineDecoration(result, lineNumber, whitespaceStartColumn, index + 2, stateDecoration);
whitespaceStartColumn = index + 2;
tmpIndent = tmpIndent % tabSize;
}
}
}
return result;
}
export class LineParts {
_linePartsBrand: void;
private _parts: ViewLineToken[];
constructor(parts: ViewLineToken[]) {
this._parts = parts;
}
public getParts(): ViewLineToken[] {
return this._parts;
}
public equals(other:LineParts): boolean {
return ViewLineToken.equalsArray(this._parts, other._parts);
}
public findIndexOfOffset(offset:number): number {
return Arrays.findIndexInSegmentsArray(this._parts, offset);
}
}
function createFastViewLineParts(lineTokens:ViewLineTokens, lineContent:string): LineParts {
let parts = lineTokens.getTokens();
parts = trimEmptyTrailingPart(parts, lineContent);
return new LineParts(parts);
}
function createViewLineParts(lineNumber:number, minLineColumn:number, lineTokens:ViewLineTokens, lineContent:string, rawLineDecorations:InlineDecoration[]): LineParts {
// lineDecorations might overlap on top of each other, so they need to be normalized
var lineDecorations = LineDecorationsNormalizer.normalize(lineNumber, minLineColumn, rawLineDecorations),
lineDecorationsIndex = 0,
lineDecorationsLength = lineDecorations.length;
var actualLineTokens = lineTokens.getTokens(),
nextStartOffset:number,
currentTokenEndOffset:number,
currentTokenClassName:string;
var parts:ViewLineToken[] = [];
for (var i = 0, len = actualLineTokens.length; i < len; i++) {
nextStartOffset = actualLineTokens[i].startIndex;
currentTokenEndOffset = (i + 1 < len ? actualLineTokens[i + 1].startIndex : lineTokens.getTextLength());
currentTokenClassName = actualLineTokens[i].type;
while (lineDecorationsIndex < lineDecorationsLength && lineDecorations[lineDecorationsIndex].startOffset < currentTokenEndOffset) {
if (lineDecorations[lineDecorationsIndex].startOffset > nextStartOffset) {
// the first decorations starts after the token
parts.push(new ViewLineToken(nextStartOffset, currentTokenClassName));
nextStartOffset = lineDecorations[lineDecorationsIndex].startOffset;
}
parts.push(new ViewLineToken(nextStartOffset, currentTokenClassName + ' ' + lineDecorations[lineDecorationsIndex].className));
if (lineDecorations[lineDecorationsIndex].endOffset >= currentTokenEndOffset) {
// this decoration goes on to the next token
nextStartOffset = currentTokenEndOffset;
break;
} else {
// this decorations stops inside this token
nextStartOffset = lineDecorations[lineDecorationsIndex].endOffset + 1;
lineDecorationsIndex++;
}
}
if (nextStartOffset < currentTokenEndOffset) {
parts.push(new ViewLineToken(nextStartOffset, currentTokenClassName));
}
}
return new LineParts(parts);
}
export class DecorationSegment {
startOffset:number;
endOffset:number;
className:string;
constructor(startOffset:number, endOffset:number, className:string) {
this.startOffset = startOffset;
this.endOffset = endOffset;
this.className = className;
}
}
class Stack {
public count:number;
private stopOffsets:number[];
private classNames:string[];
constructor() {
this.stopOffsets = [];
this.classNames = [];
this.count = 0;
}
public consumeLowerThan(maxStopOffset:number, nextStartOffset:number, result:DecorationSegment[]): number {
while (this.count > 0 && this.stopOffsets[0] < maxStopOffset) {
var i = 0;
// Take all equal stopping offsets
while(i + 1 < this.count && this.stopOffsets[i] === this.stopOffsets[i + 1]) {
i++;
}
// Basically we are consuming the first i + 1 elements of the stack
result.push(new DecorationSegment(nextStartOffset, this.stopOffsets[i], this.classNames.join(' ')));
nextStartOffset = this.stopOffsets[i] + 1;
// Consume them
this.stopOffsets.splice(0, i + 1);
this.classNames.splice(0, i + 1);
this.count -= (i + 1);
}
if (this.count > 0 && nextStartOffset < maxStopOffset) {
result.push(new DecorationSegment(nextStartOffset, maxStopOffset - 1, this.classNames.join(' ')));
nextStartOffset = maxStopOffset;
}
return nextStartOffset;
}
public insert(stopOffset:number, className:string): void {
if (this.count === 0 || this.stopOffsets[this.count - 1] <= stopOffset) {
// Insert at the end
this.stopOffsets.push(stopOffset);
this.classNames.push(className);
} else {
// Find the insertion position for `stopOffset`
for (var i = 0; i < this.count; i++) {
if (this.stopOffsets[i] >= stopOffset) {
this.stopOffsets.splice(i, 0, stopOffset);
this.classNames.splice(i, 0, className);
break;
}
}
}
this.count++;
return;
}
}
export class LineDecorationsNormalizer {
/**
* A number that is guaranteed to be larger than the maximum line column
*/
private static MAX_LINE_LENGTH = 10000000;
/**
* Normalize line decorations. Overlapping decorations will generate multiple segments
*/
public static normalize(lineNumber:number, minLineColumn:number, lineDecorations:InlineDecoration[]): DecorationSegment[] {
var result:DecorationSegment[] = [];
if (lineDecorations.length === 0) {
return result;
}
var stack = new Stack(),
nextStartOffset = 0,
d:InlineDecoration,
currentStartOffset:number,
currentEndOffset:number,
i:number,
len:number;
for (i = 0, len = lineDecorations.length; i < len; i++) {
d = lineDecorations[i];
if (d.range.endLineNumber < lineNumber || d.range.startLineNumber > lineNumber) {
// Ignore decorations that sit outside this line
continue;
}
if (d.range.startLineNumber === d.range.endLineNumber && d.range.startColumn === d.range.endColumn) {
// Ignore empty range decorations
continue;
}
currentStartOffset = (d.range.startLineNumber === lineNumber ? d.range.startColumn - 1 : minLineColumn - 1);
currentEndOffset = (d.range.endLineNumber === lineNumber ? d.range.endColumn - 2 : LineDecorationsNormalizer.MAX_LINE_LENGTH - 1);
if (currentEndOffset < 0) {
// An empty decoration (endColumn === 1)
continue;
}
nextStartOffset = stack.consumeLowerThan(currentStartOffset, nextStartOffset, result);
if (stack.count === 0) {
nextStartOffset = currentStartOffset;
}
stack.insert(currentEndOffset, d.inlineClassName);
}
stack.consumeLowerThan(LineDecorationsNormalizer.MAX_LINE_LENGTH, nextStartOffset, result);
return result;
}
}
| src/vs/editor/common/viewLayout/viewLineParts.ts | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.0005060955882072449,
0.0001792160328477621,
0.00016095723549369723,
0.00017158707487396896,
0.00005181368760531768
] |
{
"id": 5,
"code_window": [
"\t\t\tcode: this.code,\n",
"\t\t};\n",
"\t}\n",
"\n",
"\tstatic compare(a: vscode.Diagnostic, b: vscode.Diagnostic): number{\n",
"\t\tlet ret = a.severity - b.severity;\n",
"\t\tif (ret === 0) {\n",
"\t\t\tret = a.range.start.compareTo(b.range.start);\n",
"\t\t}\n",
"\t\tif (ret === 0) {\n",
"\t\t\tret = a.message.localeCompare(b.message);\n",
"\t\t}\n",
"\t\treturn ret;\n",
"\t}\n",
"}\n",
"\n",
"export class Hover {\n",
"\n",
"\tpublic contents: vscode.MarkedString[];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/api/node/extHostTypes.ts",
"type": "replace",
"edit_start_line_idx": 554
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"addBreakpoint": "加入中斷點"
} | i18n/cht/src/vs/workbench/parts/debug/browser/debugEditorContribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.00017559900879859924,
0.00017559900879859924,
0.00017559900879859924,
0.00017559900879859924,
0
] |
{
"id": 5,
"code_window": [
"\t\t\tcode: this.code,\n",
"\t\t};\n",
"\t}\n",
"\n",
"\tstatic compare(a: vscode.Diagnostic, b: vscode.Diagnostic): number{\n",
"\t\tlet ret = a.severity - b.severity;\n",
"\t\tif (ret === 0) {\n",
"\t\t\tret = a.range.start.compareTo(b.range.start);\n",
"\t\t}\n",
"\t\tif (ret === 0) {\n",
"\t\t\tret = a.message.localeCompare(b.message);\n",
"\t\t}\n",
"\t\treturn ret;\n",
"\t}\n",
"}\n",
"\n",
"export class Hover {\n",
"\n",
"\tpublic contents: vscode.MarkedString[];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/api/node/extHostTypes.ts",
"type": "replace",
"edit_start_line_idx": 554
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"clearExtensionsInput": "Cancella input estensioni",
"deleteSure": "Disinstallare '{0}'?",
"enableAction": "Abilita",
"installAction": "Installa",
"installExtensions": "Installa estensioni",
"installing": "Installazione",
"postUninstallMessage": "{0} è stato disinstallato. Riavviare per disattivarlo.",
"restartNow": "Riavvia ora",
"showExtensionRecommendations": "Mostra suggerimenti per estensioni",
"showInstalledExtensions": "Mostra estensioni installate",
"showOutdatedExtensions": "Mostra estensioni obsolete",
"showPopularExtensions": "Mostra estensioni più richieste",
"uninstall": "Disinstalla",
"updateAction": "Aggiorna"
} | i18n/ita/src/vs/workbench/parts/extensions/electron-browser/extensionsActions.i18n.json | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.0001756872661644593,
0.0001749331277096644,
0.00017413456225767732,
0.00017497756925877184,
6.346670033963164e-7
] |
{
"id": 6,
"code_window": [
"\n",
"\t\tcollection.set(uri, diagnostics);\n",
"\t\tassert.equal(collection.get(uri).length, 500);\n",
"\t\tassert.equal(lastEntries.length, 1);\n",
"\t\tassert.equal(lastEntries[0][1].length, 250);\n",
"\t\tassert.equal(lastEntries[0][1][0].severity, Severity.Error);\n",
"\t\tassert.equal(lastEntries[0][1][200].severity, Severity.Warning);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.equal(lastEntries[0][1].length, 251);\n"
],
"file_path": "src/vs/workbench/test/node/api/extHostDiagnostics.test.ts",
"type": "replace",
"edit_start_line_idx": 183
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {IThreadService} from 'vs/workbench/services/thread/common/threadService';
import {IMarkerData} from 'vs/platform/markers/common/markers';
import URI from 'vs/base/common/uri';
import Severity from 'vs/base/common/severity';
import * as vscode from 'vscode';
import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol';
import {Diagnostic} from './extHostTypes';
export class DiagnosticCollection implements vscode.DiagnosticCollection {
private static _maxDiagnosticsPerFile: number = 250;
private _name: string;
private _proxy: MainThreadDiagnosticsShape;
private _isDisposed = false;
private _data: {[uri:string]: vscode.Diagnostic[]} = Object.create(null);
constructor(name: string, proxy: MainThreadDiagnosticsShape) {
this._name = name;
this._proxy = proxy;
}
dispose(): void {
if (!this._isDisposed) {
this._proxy.$clear(this.name);
this._proxy = undefined;
this._data = undefined;
this._isDisposed = true;
}
}
get name(): string {
this._checkDisposed();
return this._name;
}
set(uri: vscode.Uri, diagnostics: vscode.Diagnostic[]): void;
set(entries: [vscode.Uri, vscode.Diagnostic[]][]): void;
set(first: vscode.Uri | [vscode.Uri, vscode.Diagnostic[]][], diagnostics?: vscode.Diagnostic[]) {
if (!first) {
// this set-call is a clear-call
this.clear();
return;
}
// the actual implementation for #set
this._checkDisposed();
let toSync: vscode.Uri[];
if (first instanceof URI) {
if (!diagnostics) {
// remove this entry
this.delete(first);
return;
}
// update single row
this._data[first.toString()] = diagnostics;
toSync = [first];
} else if (Array.isArray(first)) {
// update many rows
toSync = [];
for (let entry of first) {
let [uri, diagnostics] = entry;
toSync.push(uri);
if (!diagnostics) {
// [Uri, undefined] means clear this
delete this._data[uri.toString()];
} else {
// set or merge diagnostics
let existing = this._data[uri.toString()];
if (existing) {
existing.push(...diagnostics);
} else {
this._data[uri.toString()] = diagnostics;
}
}
}
}
// compute change and send to main side
const entries: [URI, IMarkerData[]][] = [];
for (let uri of toSync) {
let marker: IMarkerData[];
let diagnostics = this._data[uri.toString()];
if (diagnostics) {
// no more than 250 diagnostics per file
if (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) {
console.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length);
marker = [];
const sorted = diagnostics.slice(0).sort(Diagnostic.compare);
for (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) {
marker.push(DiagnosticCollection._toMarkerData(sorted[i]));
}
} else {
marker = diagnostics.map(DiagnosticCollection._toMarkerData);
}
}
entries.push([<URI> uri, marker]);
}
this._proxy.$changeMany(this.name, entries);
}
delete(uri: vscode.Uri): void {
this._checkDisposed();
delete this._data[uri.toString()];
this._proxy.$changeMany(this.name, [[<URI> uri, undefined]]);
}
clear(): void {
this._checkDisposed();
this._data = Object.create(null);
this._proxy.$clear(this.name);
}
forEach(callback: (uri: URI, diagnostics: vscode.Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void {
this._checkDisposed();
for (let key in this._data) {
let uri = URI.parse(key);
callback.apply(thisArg, [uri, this.get(uri), this]);
}
}
get(uri: URI): vscode.Diagnostic[] {
this._checkDisposed();
let result = this._data[uri.toString()];
if (Array.isArray(result)) {
return Object.freeze(result.slice(0));
}
}
has(uri: URI): boolean {
this._checkDisposed();
return Array.isArray(this._data[uri.toString()]);
}
private _checkDisposed() {
if (this._isDisposed) {
throw new Error('illegal state - object is disposed');
}
}
private static _toMarkerData(diagnostic: vscode.Diagnostic): IMarkerData {
let range = diagnostic.range;
return <IMarkerData>{
startLineNumber: range.start.line + 1,
startColumn: range.start.character + 1,
endLineNumber: range.end.line + 1,
endColumn: range.end.character + 1,
message: diagnostic.message,
source: diagnostic.source,
severity: DiagnosticCollection._convertDiagnosticsSeverity(diagnostic.severity),
code: String(diagnostic.code)
};
}
private static _convertDiagnosticsSeverity(severity: number): Severity {
switch (severity) {
case 0: return Severity.Error;
case 1: return Severity.Warning;
case 2: return Severity.Info;
case 3: return Severity.Ignore;
default: return Severity.Error;
}
}
}
export class ExtHostDiagnostics extends ExtHostDiagnosticsShape {
private static _idPool: number = 0;
private _proxy: MainThreadDiagnosticsShape;
private _collections: DiagnosticCollection[];
constructor(threadService: IThreadService) {
super();
this._proxy = threadService.get(MainContext.MainThreadDiagnostics);
this._collections = [];
}
createDiagnosticCollection(name: string): vscode.DiagnosticCollection {
if (!name) {
name = '_generated_diagnostic_collection_name_#' + ExtHostDiagnostics._idPool++;
}
const {_collections, _proxy} = this;
const result = new class extends DiagnosticCollection {
constructor() {
super(name, _proxy);
_collections.push(this);
}
dispose() {
super.dispose();
let idx = _collections.indexOf(this);
if (idx !== -1) {
_collections.splice(idx, 1);
}
}
};
return result;
}
forEach(callback: (collection: DiagnosticCollection) => any): void {
this._collections.forEach(callback);
}
}
| src/vs/workbench/api/node/extHostDiagnostics.ts | 1 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.004278720822185278,
0.0008110749186016619,
0.00016476887685712427,
0.00046734249917790294,
0.0009356733062304556
] |
{
"id": 6,
"code_window": [
"\n",
"\t\tcollection.set(uri, diagnostics);\n",
"\t\tassert.equal(collection.get(uri).length, 500);\n",
"\t\tassert.equal(lastEntries.length, 1);\n",
"\t\tassert.equal(lastEntries[0][1].length, 250);\n",
"\t\tassert.equal(lastEntries[0][1][0].severity, Severity.Error);\n",
"\t\tassert.equal(lastEntries[0][1][200].severity, Severity.Warning);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.equal(lastEntries[0][1].length, 251);\n"
],
"file_path": "src/vs/workbench/test/node/api/extHostDiagnostics.test.ts",
"type": "replace",
"edit_start_line_idx": 183
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"QuickFixSelectionWidget.loading": "Cargando...",
"QuickFixSelectionWidget.noSuggestions": "No hay sugerencias de correcciones.",
"ariaCurrentFix": "{0}, sugerencia de corrección rápida",
"quickFixAriaAccepted": "{0}, aceptada",
"treeAriaLabel": "Corrección rápida"
} | i18n/esn/src/vs/editor/contrib/quickFix/browser/quickFixSelectionWidget.i18n.json | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.0001737618731567636,
0.00017309229588136077,
0.0001724227040540427,
0.00017309229588136077,
6.695845513604581e-7
] |
{
"id": 6,
"code_window": [
"\n",
"\t\tcollection.set(uri, diagnostics);\n",
"\t\tassert.equal(collection.get(uri).length, 500);\n",
"\t\tassert.equal(lastEntries.length, 1);\n",
"\t\tassert.equal(lastEntries[0][1].length, 250);\n",
"\t\tassert.equal(lastEntries[0][1][0].severity, Severity.Error);\n",
"\t\tassert.equal(lastEntries[0][1][200].severity, Severity.Warning);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.equal(lastEntries[0][1].length, 251);\n"
],
"file_path": "src/vs/workbench/test/node/api/extHostDiagnostics.test.ts",
"type": "replace",
"edit_start_line_idx": 183
} | <svg width="16" height="16" xmlns="http://www.w3.org/2000/svg"><title>Layer 1</title><rect height="11" width="3" y="3" x="7" fill="#C5C5C5"/><rect height="3" width="11" y="7" x="3" fill="#C5C5C5"/></svg> | src/vs/workbench/parts/debug/browser/media/add-inverse.svg | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.00017446762649342418,
0.00017446762649342418,
0.00017446762649342418,
0.00017446762649342418,
0
] |
{
"id": 6,
"code_window": [
"\n",
"\t\tcollection.set(uri, diagnostics);\n",
"\t\tassert.equal(collection.get(uri).length, 500);\n",
"\t\tassert.equal(lastEntries.length, 1);\n",
"\t\tassert.equal(lastEntries[0][1].length, 250);\n",
"\t\tassert.equal(lastEntries[0][1][0].severity, Severity.Error);\n",
"\t\tassert.equal(lastEntries[0][1][200].severity, Severity.Warning);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.equal(lastEntries[0][1].length, 251);\n"
],
"file_path": "src/vs/workbench/test/node/api/extHostDiagnostics.test.ts",
"type": "replace",
"edit_start_line_idx": 183
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"binaryDiffEditor": "Средство просмотра двоичных различий",
"cannotDiffTextToBinary": "Сравнение двоичных файлов с недвоичными в настоящее время не поддерживается"
} | i18n/rus/src/vs/workbench/browser/parts/editor/binaryDiffEditor.i18n.json | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.00017203841707669199,
0.00017203841707669199,
0.00017203841707669199,
0.00017203841707669199,
0
] |
{
"id": 7,
"code_window": [
"\t\tassert.equal(lastEntries[0][1][0].severity, Severity.Error);\n",
"\t\tassert.equal(lastEntries[0][1][200].severity, Severity.Warning);\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.equal(lastEntries[0][1][250].severity, Severity.Error);\n"
],
"file_path": "src/vs/workbench/test/node/api/extHostDiagnostics.test.ts",
"type": "add",
"edit_start_line_idx": 186
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import URI from 'vs/base/common/uri';
import {illegalArgument} from 'vs/base/common/errors';
export class Disposable {
static from(...disposables: { dispose(): any }[]): Disposable {
return new Disposable(function () {
if (disposables) {
for (let disposable of disposables) {
if (disposable && typeof disposable.dispose === 'function') {
disposable.dispose();
}
}
disposables = undefined;
}
});
}
private _callOnDispose: Function;
constructor(callOnDispose: Function) {
this._callOnDispose = callOnDispose;
}
dispose(): any {
if (typeof this._callOnDispose === 'function') {
this._callOnDispose();
this._callOnDispose = undefined;
}
}
}
export interface EditorOptions {
tabSize: number | string;
insertSpaces: boolean | string;
}
export class Position {
static Min(...positions: Position[]): Position {
let result = positions.pop();
for (let p of positions) {
if (p.isBefore(result)) {
result = p;
}
}
return result;
}
static Max(...positions: Position[]): Position {
let result = positions.pop();
for (let p of positions) {
if (p.isAfter(result)) {
result = p;
}
}
return result;
}
static is(other: any): other is Position {
if (!other) {
return false;
}
if (other instanceof Position) {
return true;
}
let {line, character} = <Position>other;
if (typeof line === 'number' && typeof character === 'number') {
return true;
}
return false;
}
private _line: number;
private _character: number;
get line(): number {
return this._line;
}
get character(): number {
return this._character;
}
constructor(line: number, character: number) {
if (line < 0) {
throw illegalArgument('line must be positive');
}
if (character < 0) {
throw illegalArgument('character must be positive');
}
this._line = line;
this._character = character;
}
isBefore(other: Position): boolean {
if (this._line < other._line) {
return true;
}
if (other._line < this._line) {
return false;
}
return this._character < other._character;
}
isBeforeOrEqual(other: Position): boolean {
if (this._line < other._line) {
return true;
}
if (other._line < this._line) {
return false;
}
return this._character <= other._character;
}
isAfter(other: Position): boolean {
return !this.isBeforeOrEqual(other);
}
isAfterOrEqual(other: Position): boolean {
return !this.isBefore(other);
}
isEqual(other: Position): boolean {
return this._line === other._line && this._character === other._character;
}
compareTo(other: Position): number {
if (this._line < other._line) {
return -1;
} else if (this._line > other.line) {
return 1;
} else {
// equal line
if (this._character < other._character) {
return -1;
} else if (this._character > other._character) {
return 1;
} else {
// equal line and character
return 0;
}
}
}
translate(change: { lineDelta?: number; characterDelta?: number;}): Position;
translate(lineDelta?: number, characterDelta?: number): Position;
translate(lineDeltaOrChange: number | { lineDelta?: number; characterDelta?: number; }, characterDelta: number = 0): Position {
if (lineDeltaOrChange === null || characterDelta === null) {
throw illegalArgument();
}
let lineDelta: number;
if (typeof lineDeltaOrChange === 'undefined') {
lineDelta = 0;
} else if (typeof lineDeltaOrChange === 'number') {
lineDelta = lineDeltaOrChange;
} else {
lineDelta = typeof lineDeltaOrChange.lineDelta === 'number' ? lineDeltaOrChange.lineDelta : 0;
characterDelta = typeof lineDeltaOrChange.characterDelta === 'number' ? lineDeltaOrChange.characterDelta : 0;
}
if (lineDelta === 0 && characterDelta === 0) {
return this;
}
return new Position(this.line + lineDelta, this.character + characterDelta);
}
with(change: { line?: number; character?: number; }): Position;
with(line?: number, character?: number): Position;
with(lineOrChange: number | { line?: number; character?: number; }, character: number = this.character): Position {
if (lineOrChange === null || character === null) {
throw illegalArgument();
}
let line: number;
if (typeof lineOrChange === 'undefined') {
line = this.line;
} else if (typeof lineOrChange === 'number') {
line = lineOrChange;
} else {
line = typeof lineOrChange.line === 'number' ? lineOrChange.line : this.line;
character = typeof lineOrChange.character === 'number' ? lineOrChange.character : this.character;
}
if (line === this.line && character === this.character) {
return this;
}
return new Position(line, character);
}
toJSON(): any {
return { line: this.line, character: this.character };
}
}
export class Range {
static is(thing: any): thing is Range {
if (thing instanceof Range) {
return true;
}
if (!thing) {
return false;
}
return Position.is((<Range>thing).start)
&& Position.is((<Range>thing.end));
}
protected _start: Position;
protected _end: Position;
get start(): Position {
return this._start;
}
get end(): Position {
return this._end;
}
constructor(start: Position, end: Position);
constructor(startLine: number, startColumn: number, endLine: number, endColumn: number);
constructor(startLineOrStart: number|Position, startColumnOrEnd: number|Position, endLine?: number, endColumn?: number) {
let start: Position;
let end: Position;
if (typeof startLineOrStart === 'number' && typeof startColumnOrEnd === 'number' && typeof endLine === 'number' && typeof endColumn === 'number') {
start = new Position(startLineOrStart, startColumnOrEnd);
end = new Position(endLine, endColumn);
} else if (startLineOrStart instanceof Position && startColumnOrEnd instanceof Position) {
start = startLineOrStart;
end = startColumnOrEnd;
}
if (!start || !end) {
throw new Error('Invalid arguments');
}
if (start.isBefore(end)) {
this._start = start;
this._end = end;
} else {
this._start = end;
this._end = start;
}
}
contains(positionOrRange: Position | Range): boolean {
if (positionOrRange instanceof Range) {
return this.contains(positionOrRange._start)
&& this.contains(positionOrRange._end);
} else if (positionOrRange instanceof Position) {
if (positionOrRange.isBefore(this._start)) {
return false;
}
if (this._end.isBefore(positionOrRange)) {
return false;
}
return true;
}
return false;
}
isEqual(other: Range): boolean {
return this._start.isEqual(other._start) && this._end.isEqual(other._end);
}
intersection(other: Range): Range {
let start = Position.Max(other.start, this._start);
let end = Position.Min(other.end, this._end);
if (start.isAfter(end)) {
// this happens when there is no overlap:
// |-----|
// |----|
return;
}
return new Range(start, end);
}
union(other: Range): Range {
if (this.contains(other)) {
return this;
} else if (other.contains(this)) {
return other;
}
let start = Position.Min(other.start, this._start);
let end = Position.Max(other.end, this.end);
return new Range(start, end);
}
get isEmpty(): boolean {
return this._start.isEqual(this._end);
}
get isSingleLine(): boolean {
return this._start.line === this._end.line;
}
with(change: { start?: Position, end?: Position }): Range;
with(start?: Position, end?: Position): Range;
with(startOrChange: Position | { start?: Position, end?: Position }, end: Position = this.end): Range {
if (startOrChange === null || end === null) {
throw illegalArgument();
}
let start: Position;
if (!startOrChange) {
start = this.start;
} else if (Position.is(startOrChange)) {
start = startOrChange;
} else {
start = startOrChange.start || this.start;
end = startOrChange.end || this.end;
}
if (start.isEqual(this._start) && end.isEqual(this.end)) {
return this;
}
return new Range(start, end);
}
toJSON(): any {
return [this.start, this.end];
}
}
export class Selection extends Range {
private _anchor: Position;
public get anchor(): Position {
return this._anchor;
}
private _active: Position;
public get active(): Position {
return this._active;
}
constructor(anchor: Position, active: Position);
constructor(anchorLine: number, anchorColumn: number, activeLine: number, activeColumn: number);
constructor(anchorLineOrAnchor: number|Position, anchorColumnOrActive: number|Position, activeLine?: number, activeColumn?: number) {
let anchor: Position;
let active: Position;
if (typeof anchorLineOrAnchor === 'number' && typeof anchorColumnOrActive === 'number' && typeof activeLine === 'number' && typeof activeColumn === 'number') {
anchor = new Position(anchorLineOrAnchor, anchorColumnOrActive);
active = new Position(activeLine, activeColumn);
} else if (anchorLineOrAnchor instanceof Position && anchorColumnOrActive instanceof Position) {
anchor = anchorLineOrAnchor;
active = anchorColumnOrActive;
}
if (!anchor || !active) {
throw new Error('Invalid arguments');
}
super(anchor, active);
this._anchor = anchor;
this._active = active;
}
get isReversed(): boolean {
return this._anchor === this._end;
}
toJSON() {
return {
start: this.start,
end: this.end,
active: this.active,
anchor: this.anchor
};
}
}
export class TextEdit {
static replace(range: Range, newText: string): TextEdit {
return new TextEdit(range, newText);
}
static insert(position: Position, newText: string): TextEdit {
return TextEdit.replace(new Range(position, position), newText);
}
static delete(range: Range): TextEdit {
return TextEdit.replace(range, '');
}
protected _range: Range;
protected _newText: string;
get range(): Range {
return this._range;
}
set range(value: Range) {
if (!value) {
throw illegalArgument('range');
}
this._range = value;
}
get newText(): string {
return this._newText || '';
}
set newText(value) {
this._newText = value;
}
constructor(range: Range, newText: string) {
this.range = range;
this.newText = newText;
}
toJSON(): any {
return {
range: this.range,
newText: this.newText
};
}
}
export class Uri extends URI { }
export class WorkspaceEdit {
private _values: [Uri, TextEdit[]][] = [];
private _index: { [uri: string]: number } = Object.create(null);
replace(uri: Uri, range: Range, newText: string): void {
let edit = new TextEdit(range, newText);
let array = this.get(uri);
if (array) {
array.push(edit);
} else {
this.set(uri, [edit]);
}
}
insert(resource: Uri, position: Position, newText: string): void {
this.replace(resource, new Range(position, position), newText);
}
delete(resource: Uri, range: Range): void {
this.replace(resource, range, '');
}
has(uri: Uri): boolean {
return typeof this._index[uri.toString()] !== 'undefined';
}
set(uri: Uri, edits: TextEdit[]): void {
let idx = this._index[uri.toString()];
if (typeof idx === 'undefined') {
let newLen = this._values.push([uri, edits]);
this._index[uri.toString()] = newLen - 1;
} else {
this._values[idx][1] = edits;
}
}
get(uri: Uri): TextEdit[] {
let idx = this._index[uri.toString()];
return typeof idx !== 'undefined' && this._values[idx][1];
}
entries(): [Uri, TextEdit[]][] {
return this._values;
}
get size(): number {
return this._values.length;
}
toJSON(): any {
return this._values;
}
}
export enum DiagnosticSeverity {
Hint = 3,
Information = 2,
Warning = 1,
Error = 0
}
export class Location {
uri: URI;
range: Range;
constructor(uri: URI, range: Range | Position) {
this.uri = uri;
if (range instanceof Range) {
this.range = range;
} else if (range instanceof Position) {
this.range = new Range(range, range);
} else {
throw new Error('Illegal argument');
}
}
toJSON(): any {
return {
uri: this.uri,
range: this.range
};
}
}
export class Diagnostic {
range: Range;
message: string;
source: string;
code: string | number;
severity: DiagnosticSeverity;
constructor(range: Range, message: string, severity: DiagnosticSeverity = DiagnosticSeverity.Error) {
this.range = range;
this.message = message;
this.severity = severity;
}
toJSON(): any {
return {
severity: DiagnosticSeverity[this.severity],
message: this.message,
range: this.range,
source: this.source,
code: this.code,
};
}
static compare(a: vscode.Diagnostic, b: vscode.Diagnostic): number{
let ret = a.severity - b.severity;
if (ret === 0) {
ret = a.range.start.compareTo(b.range.start);
}
if (ret === 0) {
ret = a.message.localeCompare(b.message);
}
return ret;
}
}
export class Hover {
public contents: vscode.MarkedString[];
public range: Range;
constructor(contents: vscode.MarkedString | vscode.MarkedString[], range?: Range) {
if (!contents) {
throw new Error('Illegal argument');
}
if (Array.isArray(contents)) {
this.contents = contents;
} else {
this.contents = [contents];
}
this.range = range;
}
}
export enum DocumentHighlightKind {
Text,
Read,
Write
}
export class DocumentHighlight {
range: Range;
kind: DocumentHighlightKind;
constructor(range: Range, kind: DocumentHighlightKind = DocumentHighlightKind.Text) {
this.range = range;
this.kind = kind;
}
toJSON(): any {
return {
range: this.range,
kind: DocumentHighlightKind[this.kind]
};
}
}
export enum SymbolKind {
File,
Module,
Namespace,
Package,
Class,
Method,
Property,
Field,
Constructor,
Enum,
Interface,
Function,
Variable,
Constant,
String,
Number,
Boolean,
Array,
Object,
Key,
Null
}
export class SymbolInformation {
name: string;
location: Location;
kind: SymbolKind;
containerName: string;
constructor(name: string, kind: SymbolKind, range: Range, uri?: URI, containerName?: string) {
this.name = name;
this.kind = kind;
this.location = new Location(uri, range);
this.containerName = containerName;
}
toJSON(): any {
return {
name: this.name,
kind: SymbolKind[this.kind],
location: this.location,
containerName: this.containerName
};
}
}
export class CodeLens {
range: Range;
command: vscode.Command;
constructor(range: Range, command?: vscode.Command) {
this.range = range;
this.command = command;
}
get isResolved(): boolean {
return !!this.command;
}
}
export class ParameterInformation {
label: string;
documentation: string;
constructor(label: string, documentation?: string) {
this.label = label;
this.documentation = documentation;
}
}
export class SignatureInformation {
label: string;
documentation: string;
parameters: ParameterInformation[];
constructor(label: string, documentation?: string) {
this.label = label;
this.documentation = documentation;
this.parameters = [];
}
}
export class SignatureHelp {
signatures: SignatureInformation[];
activeSignature: number;
activeParameter: number;
constructor() {
this.signatures = [];
}
}
export enum CompletionItemKind {
Text,
Method,
Function,
Constructor,
Field,
Variable,
Class,
Interface,
Module,
Property,
Unit,
Value,
Enum,
Keyword,
Snippet,
Color,
File,
Reference
}
export class CompletionItem {
label: string;
kind: CompletionItemKind;
detail: string;
documentation: string;
sortText: string;
filterText: string;
insertText: string;
textEdit: TextEdit;
constructor(label: string, kind?: CompletionItemKind) {
this.label = label;
this.kind = kind;
}
toJSON(): any {
return {
label: this.label,
kind: CompletionItemKind[this.kind],
detail: this.detail,
documentation: this.documentation,
sortText: this.sortText,
filterText: this.filterText,
insertText: this.insertText,
textEdit: this.textEdit
};
}
}
export class CompletionList {
isIncomplete: boolean;
items: vscode.CompletionItem[];
constructor(items: vscode.CompletionItem[] = [], isIncomplete: boolean = false) {
this.items = items;
this.isIncomplete = isIncomplete;
}
}
export enum ViewColumn {
One = 1,
Two = 2,
Three = 3
}
export enum StatusBarAlignment {
Left = 1,
Right = 2
}
export enum EndOfLine {
LF = 1,
CRLF = 2
}
export enum TextEditorRevealType {
Default = 0,
InCenter = 1,
InCenterIfOutsideViewport = 2
}
export class DocumentLink {
range: Range;
target: URI;
constructor(range: Range, target: URI) {
if (!(target instanceof URI)) {
throw illegalArgument('target');
}
if (!Range.is(range) || range.isEmpty) {
throw illegalArgument('range');
}
this.range = range;
this.target = target;
}
} | src/vs/workbench/api/node/extHostTypes.ts | 1 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.0008457545773126185,
0.00018950121011584997,
0.00016365808551199734,
0.0001731190859572962,
0.00010338144056731835
] |
{
"id": 7,
"code_window": [
"\t\tassert.equal(lastEntries[0][1][0].severity, Severity.Error);\n",
"\t\tassert.equal(lastEntries[0][1][200].severity, Severity.Warning);\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.equal(lastEntries[0][1][250].severity, Severity.Error);\n"
],
"file_path": "src/vs/workbench/test/node/api/extHostDiagnostics.test.ts",
"type": "add",
"edit_start_line_idx": 186
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"noResults": "결과 없음",
"peekView.alternateTitle": "참조",
"referenceCount": "참조 {0}개",
"referencesCount": "참조 {0}개",
"referencesFailre": "파일을 확인하지 못했습니다.",
"treeAriaLabel": "참조"
} | i18n/kor/src/vs/editor/contrib/referenceSearch/browser/referencesWidget.i18n.json | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.00017546011076774448,
0.00017335654410999268,
0.00017125297745224088,
0.00017335654410999268,
0.0000021035666577517986
] |
{
"id": 7,
"code_window": [
"\t\tassert.equal(lastEntries[0][1][0].severity, Severity.Error);\n",
"\t\tassert.equal(lastEntries[0][1][200].severity, Severity.Warning);\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.equal(lastEntries[0][1][250].severity, Severity.Error);\n"
],
"file_path": "src/vs/workbench/test/node/api/extHostDiagnostics.test.ts",
"type": "add",
"edit_start_line_idx": 186
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-editor .lines-decorations {
position: absolute;
top: 0;
background: white;
}
/*
Keeping name short for faster parsing.
cldr = core lines decorations rendering (div)
*/
.monaco-editor .margin-view-overlays .cldr {
position: absolute;
} | src/vs/editor/browser/viewParts/linesDecorations/linesDecorations.css | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.00017698798910714686,
0.00017376404139213264,
0.0001705400791252032,
0.00017376404139213264,
0.0000032239549909718335
] |
{
"id": 7,
"code_window": [
"\t\tassert.equal(lastEntries[0][1][0].severity, Severity.Error);\n",
"\t\tassert.equal(lastEntries[0][1][200].severity, Severity.Warning);\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.equal(lastEntries[0][1][250].severity, Severity.Error);\n"
],
"file_path": "src/vs/workbench/test/node/api/extHostDiagnostics.test.ts",
"type": "add",
"edit_start_line_idx": 186
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"dirtyDisplay": "Geändert",
"dirtyMeta": "An der Datei wurden Änderungen vorgenommen...",
"pendingSaveMeeta": "Änderungen werden zurzeit gespeichert...",
"saveConflictDisplay": "Konflikt",
"saveConflictMeta": "Die Änderungen können nicht gespeichert werden, weil sie einen Konflikt mit der Version auf dem Datenträger verursachen.",
"saveErorDisplay": "Speicherfehler",
"saveErrorMeta": "Leider gibt es Probleme beim Speichern Ihrer Änderungen.",
"savedDisplay": "Gespeichert",
"savedMeta": "Alle Änderungen wurden gespeichert.",
"savingDisplay": "Speichern..."
} | i18n/deu/src/vs/workbench/parts/files/browser/editors/fileEditorInput.i18n.json | 0 | https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82 | [
0.00017487183504272252,
0.00017176606343127787,
0.00016866030637174845,
0.00017176606343127787,
0.000003105764335487038
] |
{
"id": 0,
"code_window": [
" },\n",
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('Azure Monitor', dependencies);\n",
"\n",
" return dispatchedActions;\n",
"};\n",
"\n",
"describe('loadDataSource()', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('Azure Monitor', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 74
} | import { thunkTester } from 'test/core/thunk/thunkTester';
import { AppPluginMeta, DataSourceSettings, PluginMetaInfo, PluginType } from '@grafana/data';
import { FetchError } from '@grafana/runtime';
import { ThunkResult, ThunkDispatch } from 'app/types';
import { getMockDataSource } from '../__mocks__';
import * as api from '../api';
import { DATASOURCES_ROUTES } from '../constants';
import { trackDataSourceCreated, trackDataSourceTested } from '../tracking';
import { GenericDataSourcePlugin } from '../types';
import {
InitDataSourceSettingDependencies,
testDataSource,
TestDataSourceDependencies,
initDataSourceSettings,
loadDataSource,
addDataSource,
} from './actions';
import {
initDataSourceSettingsSucceeded,
initDataSourceSettingsFailed,
testDataSourceStarting,
testDataSourceSucceeded,
testDataSourceFailed,
dataSourceLoaded,
dataSourcesLoaded,
} from './reducers';
jest.mock('../api');
jest.mock('app/core/services/backend_srv');
jest.mock('app/core/core');
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as unknown as object),
getDataSourceSrv: jest.fn().mockReturnValue({ reload: jest.fn() }),
getBackendSrv: jest.fn().mockReturnValue({ get: jest.fn() }),
}));
jest.mock('../tracking', () => ({
trackDataSourceCreated: jest.fn(),
trackDataSourceTested: jest.fn(),
}));
const getBackendSrvMock = () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
}),
withNoBackendCache: jest.fn().mockImplementationOnce((cb) => cb()),
} as any);
const failDataSourceTest = async (error: object) => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw error;
}),
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
return dispatchedActions;
};
describe('loadDataSource()', () => {
it('should resolve to a data-source if a UID was used for fetching', async () => {
const dataSourceMock = getMockDataSource();
const dispatch = jest.fn();
const getState = jest.fn();
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
const dataSource = await loadDataSource(dataSourceMock.uid)(dispatch, getState, undefined);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded(dataSource));
expect(dataSource).toBe(dataSourceMock);
});
it('should resolve to an empty data-source if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
const dataSource = await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(dataSource).toEqual({});
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded({} as DataSourceSettings));
});
it('should redirect to a URL which uses the UID if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(window.location.href).toBe(`/datasources/edit/${uid}`);
});
});
describe('initDataSourceSettings', () => {
describe('when pageId is missing', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dispatchedActions = await thunkTester({}).givenThunk(initDataSourceSettings).whenThunkIsDispatched('');
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Invalid UID'))]);
});
});
describe('when pageId is a valid', () => {
it('then initDataSourceSettingsSucceeded should be dispatched', async () => {
const dataSource = { type: 'app' };
const dataSourceMeta = { id: 'some id' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => {}),
getDataSource: jest.fn().mockReturnValue(dataSource),
getDataSourceMeta: jest.fn().mockReturnValue(dataSourceMeta),
importDataSourcePlugin: jest.fn().mockReturnValue({} as GenericDataSourcePlugin),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(256, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsSucceeded({} as GenericDataSourcePlugin)]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(256);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
expect(dependencies.getDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSource).toHaveBeenCalledWith({}, 256);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledWith({}, 'app');
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledTimes(1);
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledWith(dataSourceMeta);
});
});
describe('when plugin loading fails', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dataSource = { type: 'app' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn().mockImplementation(() => {
throw new Error('Error loading plugin');
}),
getDataSource: jest.fn(),
getDataSourceMeta: jest.fn(),
importDataSourcePlugin: jest.fn(),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(301, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Error loading plugin'))]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(301);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
});
});
});
describe('testDataSource', () => {
describe('when a datasource is tested', () => {
it('then testDataSourceStarting and testDataSourceSucceeded should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
type: 'cloudwatch',
uid: 'CW1234',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
status: '',
message: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('CloudWatch', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'cloudwatch',
datasource_uid: 'CW1234',
grafana_version: '1.0',
success: true,
});
});
it('then testDataSourceFailed should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw new Error('Error testing datasource');
}),
type: 'azure-monitor',
uid: 'azM0nit0R',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const result = {
message: 'Error testing datasource',
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
datasource_uid: 'azM0nit0R',
grafana_version: '1.0',
success: false,
});
});
it('then testDataSourceFailed should be dispatched with response error message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response data message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response statusText', async () => {
const result = {
message: 'HTTP error Bad Request',
};
const error: FetchError = {
config: {
url: '',
},
data: {},
statusText: 'Bad Request',
status: 400,
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
});
});
describe('addDataSource', () => {
it('it creates a datasource and calls trackDataSourceCreated ', async () => {
const meta: AppPluginMeta = {
id: 'azure-monitor',
module: '',
baseUrl: 'xxx',
info: { version: '1.2.3' } as PluginMetaInfo,
type: PluginType.datasource,
name: 'test DS',
};
const state = {
dataSources: {
dataSources: [],
},
};
const dataSourceMock = { datasource: { uid: 'azure23' }, meta };
(api.createDataSource as jest.Mock).mockResolvedValueOnce(dataSourceMock);
(api.getDataSources as jest.Mock).mockResolvedValueOnce([]);
const dispatchedActions = await thunkTester(state).givenThunk(addDataSource).whenThunkIsDispatched(meta);
expect(dispatchedActions).toEqual([dataSourcesLoaded([])]);
expect(trackDataSourceCreated).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
plugin_version: '1.2.3',
datasource_uid: 'azure23',
grafana_version: '1.0',
editLink: DATASOURCES_ROUTES.Edit.replace(':uid', 'azure23'),
});
});
});
| public/app/features/datasources/state/actions.test.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.9986764788627625,
0.1424523890018463,
0.00016020602197386324,
0.0023886736016720533,
0.33115440607070923
] |
{
"id": 0,
"code_window": [
" },\n",
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('Azure Monitor', dependencies);\n",
"\n",
" return dispatchedActions;\n",
"};\n",
"\n",
"describe('loadDataSource()', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('Azure Monitor', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 74
} | import { map, Observable, ReplaySubject, Subject, Subscriber, Subscription } from 'rxjs';
import {
DataFrameJSON,
DataQueryError,
Field,
isLiveChannelMessageEvent,
isLiveChannelStatusEvent,
LiveChannelConnectionState,
LiveChannelEvent,
LiveChannelId,
LoadingState,
} from '@grafana/data';
import { LiveDataStreamOptions, StreamingFrameAction, StreamingFrameOptions } from '@grafana/runtime/src/services/live';
import { toDataQueryError } from '@grafana/runtime/src/utils/toDataQueryError';
import { getStreamingFrameOptions, StreamingDataFrame } from '../data/StreamingDataFrame';
import { StreamingResponseDataType } from '../data/utils';
import { DataStreamSubscriptionKey, StreamingDataQueryResponse } from './service';
const bufferIfNot =
(canEmitObservable: Observable<boolean>) =>
<T>(source: Observable<T>): Observable<T[]> => {
return new Observable((subscriber: Subscriber<T[]>) => {
let buffer: T[] = [];
let canEmit = true;
const emitBuffer = () => {
subscriber.next(buffer);
buffer = [];
};
const canEmitSub = canEmitObservable.subscribe({
next: (val) => {
canEmit = val;
if (canEmit && buffer.length) {
emitBuffer();
}
},
});
const sourceSub = source.subscribe({
next(value) {
if (canEmit) {
if (!buffer.length) {
subscriber.next([value]);
} else {
emitBuffer();
}
} else {
buffer.push(value);
}
},
error(error) {
subscriber.error(error);
},
complete() {
subscriber.complete();
},
});
return () => {
sourceSub.unsubscribe();
canEmitSub.unsubscribe();
};
});
};
export type DataStreamHandlerDeps<T> = {
channelId: LiveChannelId;
liveEventsObservable: Observable<LiveChannelEvent<T>>;
onShutdown: () => void;
subscriberReadiness: Observable<boolean>;
defaultStreamingFrameOptions: Readonly<StreamingFrameOptions>;
shutdownDelayInMs: number;
};
enum InternalStreamMessageType {
Error,
NewValuesSameSchema,
ChangedSchema,
}
type InternalStreamMessageTypeToData = {
[InternalStreamMessageType.Error]: {
error: DataQueryError;
};
[InternalStreamMessageType.ChangedSchema]: {};
[InternalStreamMessageType.NewValuesSameSchema]: {
values: unknown[][];
};
};
type InternalStreamMessage<T = InternalStreamMessageType> = T extends InternalStreamMessageType
? {
type: T;
} & InternalStreamMessageTypeToData[T]
: never;
const reduceNewValuesSameSchemaMessages = (
packets: Array<InternalStreamMessage<InternalStreamMessageType.NewValuesSameSchema>>
) => ({
values: packets.reduce((acc, { values }) => {
for (let i = 0; i < values.length; i++) {
if (!acc[i]) {
acc[i] = [];
}
for (let j = 0; j < values[i].length; j++) {
acc[i].push(values[i][j]);
}
}
return acc;
}, [] as unknown[][]),
type: InternalStreamMessageType.NewValuesSameSchema,
});
const filterMessages = <T extends InternalStreamMessageType>(
packets: InternalStreamMessage[],
type: T
): Array<InternalStreamMessage<T>> => packets.filter((p) => p.type === type) as Array<InternalStreamMessage<T>>;
export class LiveDataStream<T = unknown> {
private frameBuffer: StreamingDataFrame;
private liveEventsSubscription: Subscription;
private stream: Subject<InternalStreamMessage> = new ReplaySubject(1);
private shutdownTimeoutId: ReturnType<typeof setTimeout> | undefined;
constructor(private deps: DataStreamHandlerDeps<T>) {
this.frameBuffer = StreamingDataFrame.empty(deps.defaultStreamingFrameOptions);
this.liveEventsSubscription = deps.liveEventsObservable.subscribe({
error: this.onError,
complete: this.onComplete,
next: this.onNext,
});
}
private shutdown = () => {
this.stream.complete();
this.liveEventsSubscription.unsubscribe();
this.deps.onShutdown();
};
private shutdownIfNoSubscribers = () => {
if (!this.stream.observed) {
this.shutdown();
}
};
private onError = (err: any) => {
console.log('LiveQuery [error]', { err }, this.deps.channelId);
this.stream.next({
type: InternalStreamMessageType.Error,
error: toDataQueryError(err),
});
this.shutdown();
};
private onComplete = () => {
console.log('LiveQuery [complete]', this.deps.channelId);
this.shutdown();
};
private onNext = (evt: LiveChannelEvent) => {
if (isLiveChannelMessageEvent(evt)) {
this.process(evt.message);
return;
}
const liveChannelStatusEvent = isLiveChannelStatusEvent(evt);
if (liveChannelStatusEvent && evt.error) {
this.stream.next({
type: InternalStreamMessageType.Error,
error: {
...toDataQueryError(evt.error),
message: `Streaming channel error: ${evt.error.message}`,
},
});
return;
}
if (
liveChannelStatusEvent &&
(evt.state === LiveChannelConnectionState.Connected || evt.state === LiveChannelConnectionState.Pending) &&
evt.message
) {
this.process(evt.message);
}
};
private process = (msg: DataFrameJSON) => {
const packetInfo = this.frameBuffer.push(msg);
if (packetInfo.schemaChanged) {
this.stream.next({
type: InternalStreamMessageType.ChangedSchema,
});
} else {
this.stream.next({
type: InternalStreamMessageType.NewValuesSameSchema,
values: this.frameBuffer.getValuesFromLastPacket(),
});
}
};
private resizeBuffer = (bufferOptions: StreamingFrameOptions) => {
if (bufferOptions && this.frameBuffer.needsResizing(bufferOptions)) {
this.frameBuffer.resize(bufferOptions);
}
};
private prepareInternalStreamForNewSubscription = (options: LiveDataStreamOptions): void => {
if (!this.frameBuffer.hasAtLeastOnePacket() && options.frame) {
// will skip initial frames from subsequent subscribers
this.process(options.frame);
}
};
private clearShutdownTimeout = () => {
if (this.shutdownTimeoutId) {
clearTimeout(this.shutdownTimeoutId);
this.shutdownTimeoutId = undefined;
}
};
get = (options: LiveDataStreamOptions, subKey: DataStreamSubscriptionKey): Observable<StreamingDataQueryResponse> => {
this.clearShutdownTimeout();
const buffer = getStreamingFrameOptions(options.buffer);
this.resizeBuffer(buffer);
this.prepareInternalStreamForNewSubscription(options);
const shouldSendLastPacketOnly = options?.buffer?.action === StreamingFrameAction.Replace;
const fieldsNamesFilter = options.filter?.fields;
const dataNeedsFiltering = fieldsNamesFilter?.length;
const fieldFilterPredicate = dataNeedsFiltering ? ({ name }: Field) => fieldsNamesFilter.includes(name) : undefined;
let matchingFieldIndexes: number[] | undefined = undefined;
const getFullFrameResponseData = <T>(
messages: InternalStreamMessage[],
error?: DataQueryError
): StreamingDataQueryResponse => {
matchingFieldIndexes = fieldFilterPredicate
? this.frameBuffer.getMatchingFieldIndexes(fieldFilterPredicate)
: undefined;
if (!shouldSendLastPacketOnly) {
return {
key: subKey,
state: error ? LoadingState.Error : LoadingState.Streaming,
data: [
{
type: StreamingResponseDataType.FullFrame,
frame: this.frameBuffer.serialize(fieldFilterPredicate, buffer),
},
],
error,
};
}
if (error) {
// send empty frame with error
return {
key: subKey,
state: LoadingState.Error,
data: [
{
type: StreamingResponseDataType.FullFrame,
frame: this.frameBuffer.serialize(fieldFilterPredicate, buffer, { maxLength: 0 }),
},
],
error,
};
}
if (!messages.length) {
console.warn(`expected to find at least one non error message ${messages.map(({ type }) => type)}`);
// send empty frame
return {
key: subKey,
state: LoadingState.Streaming,
data: [
{
type: StreamingResponseDataType.FullFrame,
frame: this.frameBuffer.serialize(fieldFilterPredicate, buffer, { maxLength: 0 }),
},
],
error,
};
}
return {
key: subKey,
state: LoadingState.Streaming,
data: [
{
type: StreamingResponseDataType.FullFrame,
frame: this.frameBuffer.serialize(fieldFilterPredicate, buffer, {
maxLength: this.frameBuffer.packetInfo.length,
}),
},
],
error,
};
};
const getNewValuesSameSchemaResponseData = (
messages: Array<InternalStreamMessage<InternalStreamMessageType.NewValuesSameSchema>>
): StreamingDataQueryResponse => {
const lastMessage = messages.length ? messages[messages.length - 1] : undefined;
const values =
shouldSendLastPacketOnly && lastMessage
? lastMessage.values
: reduceNewValuesSameSchemaMessages(messages).values;
const filteredValues = matchingFieldIndexes
? values.filter((v, i) => (matchingFieldIndexes as number[]).includes(i))
: values;
return {
key: subKey,
state: LoadingState.Streaming,
data: [
{
type: StreamingResponseDataType.NewValuesSameSchema,
values: filteredValues,
},
],
};
};
let shouldSendFullFrame = true;
const transformedInternalStream = this.stream.pipe(
bufferIfNot(this.deps.subscriberReadiness),
map((messages, i) => {
const errors = filterMessages(messages, InternalStreamMessageType.Error);
const lastError = errors.length ? errors[errors.length - 1].error : undefined;
if (shouldSendFullFrame) {
shouldSendFullFrame = false;
return getFullFrameResponseData(messages, lastError);
}
if (errors.length) {
// send the latest frame with the last error, discard everything else
return getFullFrameResponseData(messages, lastError);
}
const schemaChanged = messages.some((n) => n.type === InternalStreamMessageType.ChangedSchema);
if (schemaChanged) {
// send the latest frame, discard intermediate appends
return getFullFrameResponseData(messages, undefined);
}
const newValueSameSchemaMessages = filterMessages(messages, InternalStreamMessageType.NewValuesSameSchema);
if (newValueSameSchemaMessages.length !== messages.length) {
console.warn(`unsupported message type ${messages.map(({ type }) => type)}`);
}
return getNewValuesSameSchemaResponseData(newValueSameSchemaMessages);
})
);
return new Observable<StreamingDataQueryResponse>((subscriber) => {
const sub = transformedInternalStream.subscribe({
next: (n) => {
subscriber.next(n);
},
error: (err) => {
subscriber.error(err);
},
complete: () => {
subscriber.complete();
},
});
return () => {
// TODO: potentially resize (downsize) the buffer on unsubscribe
sub.unsubscribe();
if (!this.stream.observed) {
this.clearShutdownTimeout();
this.shutdownTimeoutId = setTimeout(this.shutdownIfNoSubscribers, this.deps.shutdownDelayInMs);
}
};
});
};
}
| public/app/features/live/centrifuge/LiveDataStream.ts | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00018090143566951156,
0.00016985530965030193,
0.00016489948029629886,
0.00016895003500394523,
0.0000033079736567742657
] |
{
"id": 0,
"code_window": [
" },\n",
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('Azure Monitor', dependencies);\n",
"\n",
" return dispatchedActions;\n",
"};\n",
"\n",
"describe('loadDataSource()', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('Azure Monitor', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 74
} | // Code generated - EDITING IS FUTILE. DO NOT EDIT.
//
// Generated by:
// kinds/gen.go
// Using jennies:
// GoTypesJenny
// LatestJenny
//
// Run 'make gen-cue' from repository root to regenerate.
package librarypanel
// LibraryElementDTOMeta defines model for LibraryElementDTOMeta.
type LibraryElementDTOMeta struct {
ConnectedDashboards int64 `json:"connectedDashboards"`
Created string `json:"created"`
CreatedBy LibraryElementDTOMetaUser `json:"createdBy"`
FolderName string `json:"folderName"`
FolderUid string `json:"folderUid"`
Updated string `json:"updated"`
UpdatedBy LibraryElementDTOMetaUser `json:"updatedBy"`
}
// LibraryElementDTOMetaUser defines model for LibraryElementDTOMetaUser.
type LibraryElementDTOMetaUser struct {
AvatarUrl string `json:"avatarUrl"`
Id int64 `json:"id"`
Name string `json:"name"`
}
// LibraryPanel defines model for LibraryPanel.
type LibraryPanel struct {
// Panel description
Description *string `json:"description,omitempty"`
// Folder UID
FolderUid *string `json:"folderUid,omitempty"`
Meta *LibraryElementDTOMeta `json:"meta,omitempty"`
// TODO: should be the same panel schema defined in dashboard
// Typescript: Omit<Panel, 'gridPos' | 'id' | 'libraryPanel'>;
Model map[string]interface{} `json:"model"`
// Panel name (also saved in the model)
Name string `json:"name"`
// Dashboard version when this was saved (zero if unknown)
SchemaVersion *int `json:"schemaVersion,omitempty"`
// The panel type (from inside the model)
Type string `json:"type"`
// Library element UID
Uid string `json:"uid"`
// panel version, incremented each time the dashboard is updated.
Version int64 `json:"version"`
}
| pkg/kinds/librarypanel/librarypanel_types_gen.go | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0001753145916154608,
0.00016985250113066286,
0.0001654631778365001,
0.00016947690164670348,
0.000003052158490390866
] |
{
"id": 0,
"code_window": [
" },\n",
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('Azure Monitor', dependencies);\n",
"\n",
" return dispatchedActions;\n",
"};\n",
"\n",
"describe('loadDataSource()', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('Azure Monitor', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 74
} | package codegen
import (
"fmt"
"path/filepath"
"sort"
"strings"
"cuelang.org/go/cue"
"cuelang.org/go/cue/errors"
"github.com/grafana/codejen"
"github.com/grafana/cuetsy/ts"
"github.com/grafana/cuetsy/ts/ast"
"github.com/grafana/grafana/pkg/kindsys"
"github.com/grafana/thema"
"github.com/grafana/thema/encoding/typescript"
)
// TSVeneerIndexJenny generates an index.gen.ts file with references to all
// generated TS types. Elements with the attribute @grafana(TSVeneer="type") are
// exported from a handwritten file, rather than the raw generated types.
//
// The provided dir is the path, relative to the grafana root, to the directory
// that should contain the generated index.
//
// Implicitly depends on output patterns in TSTypesJenny.
// TODO this is wasteful; share-nothing generator model entails re-running the cuetsy gen that TSTypesJenny already did
func TSVeneerIndexJenny(dir string) ManyToOne {
return &genTSVeneerIndex{
dir: dir,
}
}
type genTSVeneerIndex struct {
dir string
}
func (gen *genTSVeneerIndex) JennyName() string {
return "TSVeneerIndexJenny"
}
func (gen *genTSVeneerIndex) Generate(decls ...*DeclForGen) (*codejen.File, error) {
tsf := new(ast.File)
for _, decl := range decls {
sch := decl.Lineage().Latest()
f, err := typescript.GenerateTypes(sch, &typescript.TypeConfig{
RootName: decl.Properties.Common().Name,
Group: decl.Properties.Common().LineageIsGroup,
})
if err != nil {
return nil, fmt.Errorf("%s: %w", decl.Properties.Common().Name, err)
}
elems, err := gen.extractTSIndexVeneerElements(decl, f)
if err != nil {
return nil, fmt.Errorf("%s: %w", decl.Properties.Common().Name, err)
}
tsf.Nodes = append(tsf.Nodes, elems...)
}
return codejen.NewFile(filepath.Join(gen.dir, "index.gen.ts"), []byte(tsf.String()), gen), nil
}
func (gen *genTSVeneerIndex) extractTSIndexVeneerElements(decl *DeclForGen, tf *ast.File) ([]ast.Decl, error) {
lin := decl.Lineage()
comm := decl.Properties.Common()
// Check the root, then walk the tree
rootv := lin.Latest().Underlying()
var raw, custom, rawD, customD ast.Idents
var terr errors.Error
visit := func(p cue.Path, wv cue.Value) bool {
var name string
sels := p.Selectors()
switch len(sels) {
case 0:
name = comm.Name
fallthrough
case 1:
// Only deal with subpaths that are definitions, for now
// TODO incorporate smarts about grouped lineages here
if name == "" {
if !sels[0].IsDefinition() {
return false
}
// It might seem to make sense that we'd strip replaceout the leading # here for
// definitions. However, cuetsy's tsast actually has the # still present in its
// Ident types, stripping it replaceout on the fly when stringifying.
name = sels[0].String()
}
// Search the generated TS AST for the type and default decl nodes
pair := findDeclNode(name, tf)
if pair.T == nil {
// No generated type for this item, skip it
return false
}
cust, perr := getCustomVeneerAttr(wv)
if perr != nil {
terr = errors.Append(terr, errors.Promote(perr, fmt.Sprintf("%s: ", p.String())))
}
var has bool
for _, tgt := range cust {
has = has || tgt.target == "type"
}
if has {
// enums can't use 'export type'
if pair.isEnum {
customD = append(customD, *pair.T)
} else {
custom = append(custom, *pair.T)
}
if pair.D != nil {
customD = append(customD, *pair.D)
}
} else {
// enums can't use 'export type'
if pair.isEnum {
rawD = append(rawD, *pair.T)
} else {
raw = append(raw, *pair.T)
}
if pair.D != nil {
rawD = append(rawD, *pair.D)
}
}
}
return true
}
walk(rootv, visit, nil)
if len(errors.Errors(terr)) != 0 {
return nil, terr
}
vpath := fmt.Sprintf("v%v", thema.LatestVersion(lin)[0])
if decl.Properties.Common().Maturity.Less(kindsys.MaturityStable) {
vpath = "x"
}
ret := make([]ast.Decl, 0)
if len(raw) > 0 {
ret = append(ret, ast.ExportSet{
CommentList: []ast.Comment{ts.CommentFromString(fmt.Sprintf("Raw generated types from %s kind.", comm.Name), 80, false)},
TypeOnly: true,
Exports: raw,
From: ast.Str{Value: fmt.Sprintf("./raw/%s/%s/%s_types.gen", comm.MachineName, vpath, comm.MachineName)},
})
}
if len(rawD) > 0 {
ret = append(ret, ast.ExportSet{
CommentList: []ast.Comment{ts.CommentFromString(fmt.Sprintf("Raw generated enums and default consts from %s kind.", lin.Name()), 80, false)},
TypeOnly: false,
Exports: rawD,
From: ast.Str{Value: fmt.Sprintf("./raw/%s/%s/%s_types.gen", comm.MachineName, vpath, comm.MachineName)},
})
}
vtfile := fmt.Sprintf("./veneer/%s.types", lin.Name())
customstr := fmt.Sprintf(`// The following exported declarations correspond to types in the %s@%s kind's
// schema with attribute @grafana(TSVeneer="type").
//
// The handwritten file for these type and default veneers is expected to be at
// %s.ts.
// This re-export declaration enforces that the handwritten veneer file exists,
// and exports all the symbols in the list.
//
// TODO generate code such that tsc enforces type compatibility between raw and veneer decls`,
lin.Name(), thema.LatestVersion(lin), filepath.ToSlash(filepath.Join(gen.dir, vtfile)))
customComments := []ast.Comment{{Text: customstr}}
if len(custom) > 0 {
ret = append(ret, ast.ExportSet{
CommentList: customComments,
TypeOnly: true,
Exports: custom,
From: ast.Str{Value: vtfile},
})
}
if len(customD) > 0 {
ret = append(ret, ast.ExportSet{
CommentList: customComments,
TypeOnly: false,
Exports: customD,
From: ast.Str{Value: vtfile},
})
}
// TODO emit a decl in the index.gen.ts that ensures any custom veneer types are "compatible" with current version raw types
return ret, nil
}
type declPair struct {
T, D *ast.Ident
isEnum bool
}
type tsVeneerAttr struct {
target string
}
func findDeclNode(name string, tf *ast.File) declPair {
var p declPair
for _, decl := range tf.Nodes {
// Peer through export keywords
if ex, is := decl.(ast.ExportKeyword); is {
decl = ex.Decl
}
switch x := decl.(type) {
case ast.TypeDecl:
if x.Name.Name == name {
p.T = &x.Name
_, p.isEnum = x.Type.(ast.EnumType)
}
case ast.VarDecl:
if x.Names.Idents[0].Name == "default"+name {
p.D = &x.Names.Idents[0]
}
}
}
return p
}
func walk(v cue.Value, before func(cue.Path, cue.Value) bool, after func(cue.Path, cue.Value)) {
innerWalk(cue.MakePath(), v, before, after)
}
func innerWalk(p cue.Path, v cue.Value, before func(cue.Path, cue.Value) bool, after func(cue.Path, cue.Value)) {
switch v.Kind() {
default:
if before != nil && !before(p, v) {
return
}
case cue.StructKind:
if before != nil && !before(p, v) {
return
}
iter, err := v.Fields(cue.All())
if err != nil {
panic(err)
}
for iter.Next() {
innerWalk(appendPath(p, iter.Selector()), iter.Value(), before, after)
}
if lv := v.LookupPath(cue.MakePath(cue.AnyString)); lv.Exists() {
innerWalk(appendPath(p, cue.AnyString), lv, before, after)
}
case cue.ListKind:
if before != nil && !before(p, v) {
return
}
list, err := v.List()
if err != nil {
panic(err)
}
for i := 0; list.Next(); i++ {
innerWalk(appendPath(p, cue.Index(i)), list.Value(), before, after)
}
if lv := v.LookupPath(cue.MakePath(cue.AnyIndex)); lv.Exists() {
innerWalk(appendPath(p, cue.AnyString), lv, before, after)
}
}
if after != nil {
after(p, v)
}
}
func appendPath(p cue.Path, sel cue.Selector) cue.Path {
return cue.MakePath(append(p.Selectors(), sel)...)
}
func getCustomVeneerAttr(v cue.Value) ([]tsVeneerAttr, error) {
var attrs []tsVeneerAttr
for _, a := range v.Attributes(cue.ValueAttr) {
if a.Name() != "grafana" {
continue
}
for i := 0; i < a.NumArgs(); i++ {
key, av := a.Arg(i)
if key != "TSVeneer" {
return nil, valError(v, "attribute 'grafana' only allows the arg 'TSVeneer'")
}
aterr := valError(v, "@grafana(TSVeneer=\"x\") requires one or more of the following separated veneer types for x: %s", allowedTSVeneersString())
var some bool
for _, tgt := range strings.Split(av, "|") {
some = true
if !allowedTSVeneers[tgt] {
return nil, aterr
}
attrs = append(attrs, tsVeneerAttr{
target: tgt,
})
}
if !some {
return nil, aterr
}
}
}
sort.Slice(attrs, func(i, j int) bool {
return attrs[i].target < attrs[j].target
})
return attrs, nil
}
var allowedTSVeneers = map[string]bool{
"type": true,
}
func allowedTSVeneersString() string {
list := make([]string, 0, len(allowedTSVeneers))
for tgt := range allowedTSVeneers {
list = append(list, tgt)
}
sort.Strings(list)
return strings.Join(list, "|")
}
func valError(v cue.Value, format string, args ...interface{}) error {
s := v.Source()
if s == nil {
return fmt.Errorf(format, args...)
}
return errors.Newf(s.Pos(), format, args...)
}
| pkg/codegen/jenny_tsveneerindex.go | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0001789586676750332,
0.00017379166092723608,
0.00016847433289512992,
0.00017386116087436676,
0.0000025780116175155854
] |
{
"id": 1,
"code_window": [
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('CloudWatch', dependencies);\n",
"\n",
" expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);\n",
" expect(trackDataSourceTested).toHaveBeenCalledWith({\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('CloudWatch', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | import { useContext, useEffect } from 'react';
import { DataSourcePluginMeta, DataSourceSettings, NavModelItem } from '@grafana/data';
import { cleanUpAction } from 'app/core/actions/cleanUp';
import appEvents from 'app/core/app_events';
import { contextSrv } from 'app/core/core';
import { getNavModel } from 'app/core/selectors/navModel';
import { AccessControlAction, useDispatch, useSelector } from 'app/types';
import { ShowConfirmModalEvent } from 'app/types/events';
import { DataSourceRights } from '../types';
import { constructDataSourceExploreUrl } from '../utils';
import {
initDataSourceSettings,
testDataSource,
loadDataSource,
loadDataSources,
loadDataSourcePlugins,
addDataSource,
updateDataSource,
deleteLoadedDataSource,
} from './actions';
import { DataSourcesRoutesContext } from './contexts';
import { getDataSourceLoadingNav, buildNavModel, getDataSourceNav } from './navModel';
import { getDataSource, getDataSourceMeta } from './selectors';
export const useInitDataSourceSettings = (uid: string) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(initDataSourceSettings(uid));
return function cleanUp() {
dispatch(
cleanUpAction({
cleanupAction: (state) => state.dataSourceSettings,
})
);
};
}, [uid, dispatch]);
};
export const useTestDataSource = (uid: string) => {
const dispatch = useDispatch();
return () => dispatch(testDataSource(uid));
};
export const useLoadDataSources = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadDataSources());
}, [dispatch]);
};
export const useLoadDataSource = (uid: string) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadDataSource(uid));
}, [dispatch, uid]);
};
export const useLoadDataSourcePlugins = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadDataSourcePlugins());
}, [dispatch]);
};
export const useAddDatasource = () => {
const dispatch = useDispatch();
const dataSourcesRoutes = useDataSourcesRoutes();
return (plugin: DataSourcePluginMeta) => {
dispatch(addDataSource(plugin, dataSourcesRoutes.Edit));
};
};
export const useUpdateDatasource = () => {
const dispatch = useDispatch();
return async (dataSource: DataSourceSettings) => dispatch(updateDataSource(dataSource));
};
export const useDeleteLoadedDataSource = () => {
const dispatch = useDispatch();
const { name } = useSelector((state) => state.dataSources.dataSource);
return () => {
appEvents.publish(
new ShowConfirmModalEvent({
title: 'Delete',
text: `Are you sure you want to delete the "${name}" data source?`,
yesText: 'Delete',
icon: 'trash-alt',
onConfirm: () => dispatch(deleteLoadedDataSource()),
})
);
};
};
export const useDataSource = (uid: string) => {
return useSelector((state) => getDataSource(state.dataSources, uid));
};
export const useDataSourceExploreUrl = (uid: string) => {
const dataSource = useDataSource(uid);
return constructDataSourceExploreUrl(dataSource);
};
export const useDataSourceMeta = (pluginType: string): DataSourcePluginMeta => {
return useSelector((state) => getDataSourceMeta(state.dataSources, pluginType));
};
export const useDataSourceSettings = () => {
return useSelector((state) => state.dataSourceSettings);
};
export const useDataSourceSettingsNav = (dataSourceId: string, pageId: string | null) => {
const dataSource = useDataSource(dataSourceId);
const { plugin, loadError, loading } = useDataSourceSettings();
const navIndex = useSelector((state) => state.navIndex);
const navIndexId = pageId ? `datasource-${pageId}-${dataSourceId}` : `datasource-settings-${dataSourceId}`;
if (loadError) {
const node: NavModelItem = {
text: loadError,
subTitle: 'Data Source Error',
icon: 'exclamation-triangle',
};
return {
node: node,
main: node,
};
}
if (loading || !plugin) {
return getNavModel(navIndex, navIndexId, getDataSourceLoadingNav('settings'));
}
return getNavModel(navIndex, navIndexId, getDataSourceNav(buildNavModel(dataSource, plugin), pageId || 'settings'));
};
export const useDataSourceRights = (uid: string): DataSourceRights => {
const dataSource = useDataSource(uid);
const readOnly = dataSource.readOnly === true;
const hasWriteRights = contextSrv.hasPermissionInMetadata(AccessControlAction.DataSourcesWrite, dataSource);
const hasDeleteRights = contextSrv.hasPermissionInMetadata(AccessControlAction.DataSourcesDelete, dataSource);
return {
readOnly,
hasWriteRights,
hasDeleteRights,
};
};
export const useDataSourcesRoutes = () => {
return useContext(DataSourcesRoutesContext);
};
| public/app/features/datasources/state/hooks.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.003409389406442642,
0.0006577243329957128,
0.00016497826436534524,
0.000194737731362693,
0.0009745210409164429
] |
{
"id": 1,
"code_window": [
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('CloudWatch', dependencies);\n",
"\n",
" expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);\n",
" expect(trackDataSourceTested).toHaveBeenCalledWith({\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('CloudWatch', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | import { DataQuery, DataSourceJsonData } from '@grafana/data';
export interface OpenTsdbQuery extends DataQuery {
// migrating to react
// metrics section
metric?: string;
aggregator?: string;
alias?: string;
//downsample section
downsampleInterval?: string;
downsampleAggregator?: string;
downsampleFillPolicy?: string;
disableDownsampling?: boolean;
//filters
filters?: OpenTsdbFilter[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
tags?: any;
// annotation attrs
fromAnnotations?: boolean;
isGlobal?: boolean;
target?: string;
name?: string;
// rate
shouldComputeRate?: boolean;
isCounter?: boolean;
counterMax?: string;
counterResetValue?: string;
explicitTags?: boolean;
}
export interface OpenTsdbOptions extends DataSourceJsonData {
tsdbVersion: number;
tsdbResolution: number;
lookupLimit: number;
}
export type LegacyAnnotation = {
fromAnnotations?: boolean;
isGlobal?: boolean;
target?: string;
name?: string;
};
export type OpenTsdbFilter = {
type: string;
tagk: string;
filter: string;
groupBy: boolean;
};
| public/app/plugins/datasource/opentsdb/types.ts | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017719516472425312,
0.0001750316732795909,
0.00017237108841072768,
0.00017512269550934434,
0.0000015836791362744407
] |
{
"id": 1,
"code_window": [
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('CloudWatch', dependencies);\n",
"\n",
" expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);\n",
" expect(trackDataSourceTested).toHaveBeenCalledWith({\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('CloudWatch', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | import { debounce } from 'lodash';
import React, { useCallback, useMemo } from 'react';
import { Segment, SegmentAsync } from '@grafana/ui';
import { actions } from '../state/actions';
import { useDispatch } from '../state/context';
import { getTagOperatorsSelectables, getTagsSelectables, getTagValuesSelectables } from '../state/providers';
import { GraphiteQueryEditorState } from '../state/store';
import { GraphiteTag, GraphiteTagOperator } from '../types';
type Props = {
tag: GraphiteTag;
tagIndex: number;
state: GraphiteQueryEditorState;
};
/**
* Editor for a tag at given index. Allows changing the name of the tag, operator or value. Tag names are provided with
* getTagsSelectables and contain only valid tags (it may depend on currently used tags). The dropdown for tag names is
* also used for removing tag (with a special "--remove tag--" option provided by getTagsSelectables).
*
* Options for tag names and values are reloaded while user is typing with backend taking care of auto-complete
* (auto-complete cannot be implemented in front-end because backend returns only limited number of entries)
*/
export function TagEditor({ tag, tagIndex, state }: Props) {
const dispatch = useDispatch();
const getTagsOptions = useCallback(
(inputValue: string | undefined) => {
return getTagsSelectables(state, tagIndex, inputValue || '');
},
[state, tagIndex]
);
const debouncedGetTagsOptions = useMemo(() => debounce(getTagsOptions, 200, { leading: true }), [getTagsOptions]);
const getTagValueOptions = useCallback(
(inputValue: string | undefined) => {
return getTagValuesSelectables(state, tag, tagIndex, inputValue || '');
},
[state, tagIndex, tag]
);
const debouncedGetTagValueOptions = useMemo(
() => debounce(getTagValueOptions, 200, { leading: true }),
[getTagValueOptions]
);
return (
<>
<SegmentAsync
inputMinWidth={150}
value={tag.key}
loadOptions={debouncedGetTagsOptions}
reloadOptionsOnChange={true}
onChange={(value) => {
dispatch(
actions.tagChanged({
tag: { ...tag, key: value.value! },
index: tagIndex,
})
);
}}
allowCustomValue={true}
/>
<Segment<GraphiteTagOperator>
inputMinWidth={50}
value={tag.operator}
options={getTagOperatorsSelectables()}
onChange={(value) => {
dispatch(
actions.tagChanged({
tag: { ...tag, operator: value.value! },
index: tagIndex,
})
);
}}
/>
<SegmentAsync
inputMinWidth={150}
value={tag.value}
loadOptions={debouncedGetTagValueOptions}
reloadOptionsOnChange={true}
onChange={(value) => {
dispatch(
actions.tagChanged({
tag: { ...tag, value: value.value! },
index: tagIndex,
})
);
}}
allowCustomValue={true}
/>
</>
);
}
| public/app/plugins/datasource/graphite/components/TagEditor.tsx | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0001755181438056752,
0.00017056960496120155,
0.000164307770319283,
0.00017091786139644682,
0.000003887274033331778
] |
{
"id": 1,
"code_window": [
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('CloudWatch', dependencies);\n",
"\n",
" expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);\n",
" expect(trackDataSourceTested).toHaveBeenCalledWith({\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('CloudWatch', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | package dashboards
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestPermissionType_String(t *testing.T) {
testCases := []struct {
permissionType PermissionType
expected string
}{
{PERMISSION_ADMIN, "Admin"},
{PERMISSION_EDIT, "Edit"},
{PERMISSION_VIEW, "View"},
}
for _, tc := range testCases {
t.Run(tc.expected, func(t *testing.T) {
assert.Equal(t, tc.expected, fmt.Sprint(tc.permissionType))
assert.Equal(t, tc.expected, tc.permissionType.String())
})
}
}
| pkg/services/dashboards/dashboard_acl_test.go | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0001736509002512321,
0.0001727837516227737,
0.00017199217109009624,
0.00017270819807890803,
6.792777753616974e-7
] |
{
"id": 2,
"code_window": [
" datasource_uid: 'CW1234',\n",
" grafana_version: '1.0',\n",
" success: true,\n",
" });\n",
" });\n",
"\n",
" it('then testDataSourceFailed should be dispatched', async () => {\n",
" const dependencies: TestDataSourceDependencies = {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink: '/datasources/edit/CloudWatch',\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "add",
"edit_start_line_idx": 244
} | import { thunkTester } from 'test/core/thunk/thunkTester';
import { AppPluginMeta, DataSourceSettings, PluginMetaInfo, PluginType } from '@grafana/data';
import { FetchError } from '@grafana/runtime';
import { ThunkResult, ThunkDispatch } from 'app/types';
import { getMockDataSource } from '../__mocks__';
import * as api from '../api';
import { DATASOURCES_ROUTES } from '../constants';
import { trackDataSourceCreated, trackDataSourceTested } from '../tracking';
import { GenericDataSourcePlugin } from '../types';
import {
InitDataSourceSettingDependencies,
testDataSource,
TestDataSourceDependencies,
initDataSourceSettings,
loadDataSource,
addDataSource,
} from './actions';
import {
initDataSourceSettingsSucceeded,
initDataSourceSettingsFailed,
testDataSourceStarting,
testDataSourceSucceeded,
testDataSourceFailed,
dataSourceLoaded,
dataSourcesLoaded,
} from './reducers';
jest.mock('../api');
jest.mock('app/core/services/backend_srv');
jest.mock('app/core/core');
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as unknown as object),
getDataSourceSrv: jest.fn().mockReturnValue({ reload: jest.fn() }),
getBackendSrv: jest.fn().mockReturnValue({ get: jest.fn() }),
}));
jest.mock('../tracking', () => ({
trackDataSourceCreated: jest.fn(),
trackDataSourceTested: jest.fn(),
}));
const getBackendSrvMock = () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
}),
withNoBackendCache: jest.fn().mockImplementationOnce((cb) => cb()),
} as any);
const failDataSourceTest = async (error: object) => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw error;
}),
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
return dispatchedActions;
};
describe('loadDataSource()', () => {
it('should resolve to a data-source if a UID was used for fetching', async () => {
const dataSourceMock = getMockDataSource();
const dispatch = jest.fn();
const getState = jest.fn();
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
const dataSource = await loadDataSource(dataSourceMock.uid)(dispatch, getState, undefined);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded(dataSource));
expect(dataSource).toBe(dataSourceMock);
});
it('should resolve to an empty data-source if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
const dataSource = await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(dataSource).toEqual({});
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded({} as DataSourceSettings));
});
it('should redirect to a URL which uses the UID if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(window.location.href).toBe(`/datasources/edit/${uid}`);
});
});
describe('initDataSourceSettings', () => {
describe('when pageId is missing', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dispatchedActions = await thunkTester({}).givenThunk(initDataSourceSettings).whenThunkIsDispatched('');
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Invalid UID'))]);
});
});
describe('when pageId is a valid', () => {
it('then initDataSourceSettingsSucceeded should be dispatched', async () => {
const dataSource = { type: 'app' };
const dataSourceMeta = { id: 'some id' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => {}),
getDataSource: jest.fn().mockReturnValue(dataSource),
getDataSourceMeta: jest.fn().mockReturnValue(dataSourceMeta),
importDataSourcePlugin: jest.fn().mockReturnValue({} as GenericDataSourcePlugin),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(256, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsSucceeded({} as GenericDataSourcePlugin)]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(256);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
expect(dependencies.getDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSource).toHaveBeenCalledWith({}, 256);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledWith({}, 'app');
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledTimes(1);
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledWith(dataSourceMeta);
});
});
describe('when plugin loading fails', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dataSource = { type: 'app' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn().mockImplementation(() => {
throw new Error('Error loading plugin');
}),
getDataSource: jest.fn(),
getDataSourceMeta: jest.fn(),
importDataSourcePlugin: jest.fn(),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(301, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Error loading plugin'))]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(301);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
});
});
});
describe('testDataSource', () => {
describe('when a datasource is tested', () => {
it('then testDataSourceStarting and testDataSourceSucceeded should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
type: 'cloudwatch',
uid: 'CW1234',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
status: '',
message: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('CloudWatch', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'cloudwatch',
datasource_uid: 'CW1234',
grafana_version: '1.0',
success: true,
});
});
it('then testDataSourceFailed should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw new Error('Error testing datasource');
}),
type: 'azure-monitor',
uid: 'azM0nit0R',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const result = {
message: 'Error testing datasource',
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
datasource_uid: 'azM0nit0R',
grafana_version: '1.0',
success: false,
});
});
it('then testDataSourceFailed should be dispatched with response error message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response data message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response statusText', async () => {
const result = {
message: 'HTTP error Bad Request',
};
const error: FetchError = {
config: {
url: '',
},
data: {},
statusText: 'Bad Request',
status: 400,
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
});
});
describe('addDataSource', () => {
it('it creates a datasource and calls trackDataSourceCreated ', async () => {
const meta: AppPluginMeta = {
id: 'azure-monitor',
module: '',
baseUrl: 'xxx',
info: { version: '1.2.3' } as PluginMetaInfo,
type: PluginType.datasource,
name: 'test DS',
};
const state = {
dataSources: {
dataSources: [],
},
};
const dataSourceMock = { datasource: { uid: 'azure23' }, meta };
(api.createDataSource as jest.Mock).mockResolvedValueOnce(dataSourceMock);
(api.getDataSources as jest.Mock).mockResolvedValueOnce([]);
const dispatchedActions = await thunkTester(state).givenThunk(addDataSource).whenThunkIsDispatched(meta);
expect(dispatchedActions).toEqual([dataSourcesLoaded([])]);
expect(trackDataSourceCreated).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
plugin_version: '1.2.3',
datasource_uid: 'azure23',
grafana_version: '1.0',
editLink: DATASOURCES_ROUTES.Edit.replace(':uid', 'azure23'),
});
});
});
| public/app/features/datasources/state/actions.test.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.9976603984832764,
0.1757432222366333,
0.00016499354387633502,
0.001022422220557928,
0.3587588667869568
] |
{
"id": 2,
"code_window": [
" datasource_uid: 'CW1234',\n",
" grafana_version: '1.0',\n",
" success: true,\n",
" });\n",
" });\n",
"\n",
" it('then testDataSourceFailed should be dispatched', async () => {\n",
" const dependencies: TestDataSourceDependencies = {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink: '/datasources/edit/CloudWatch',\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "add",
"edit_start_line_idx": 244
} | import { css } from '@emotion/css';
import React, { useMemo } from 'react';
interface XYCanvasProps {
top: number; // css pxls
left: number; // css pxls
}
/**
* Renders absolutely positioned element on top of the uPlot's plotting area (axes are not included!).
* Useful when you want to render some overlay with canvas-independent elements on top of the plot.
*/
export const XYCanvas = ({ children, left, top }: React.PropsWithChildren<XYCanvasProps>) => {
const className = useMemo(() => {
return css`
position: absolute;
overflow: visible;
left: ${left}px;
top: ${top}px;
`;
}, [left, top]);
return <div className={className}>{children}</div>;
};
| packages/grafana-ui/src/components/uPlot/geometries/XYCanvas.tsx | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0001722178130876273,
0.00017022155225276947,
0.0001667866308707744,
0.00017166022735182196,
0.0000024395033051405335
] |
{
"id": 2,
"code_window": [
" datasource_uid: 'CW1234',\n",
" grafana_version: '1.0',\n",
" success: true,\n",
" });\n",
" });\n",
"\n",
" it('then testDataSourceFailed should be dispatched', async () => {\n",
" const dependencies: TestDataSourceDependencies = {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink: '/datasources/edit/CloudWatch',\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "add",
"edit_start_line_idx": 244
} | import React, { FC, useMemo } from 'react';
import { dateTime } from '@grafana/data';
import { Alert, PaginationProps } from 'app/types/unified-alerting';
import { alertInstanceKey } from '../../utils/rules';
import { AlertLabels } from '../AlertLabels';
import { DynamicTable, DynamicTableColumnProps, DynamicTableItemProps } from '../DynamicTable';
import { AlertInstanceDetails } from './AlertInstanceDetails';
import { AlertStateTag } from './AlertStateTag';
interface Props {
instances: Alert[];
pagination?: PaginationProps;
footerRow?: JSX.Element;
}
type AlertTableColumnProps = DynamicTableColumnProps<Alert>;
type AlertTableItemProps = DynamicTableItemProps<Alert>;
export const AlertInstancesTable: FC<Props> = ({ instances, pagination, footerRow }) => {
const items = useMemo(
(): AlertTableItemProps[] =>
instances.map((instance) => ({
data: instance,
id: alertInstanceKey(instance),
})),
[instances]
);
return (
<DynamicTable
cols={columns}
isExpandable={true}
items={items}
renderExpandedContent={({ data }) => <AlertInstanceDetails instance={data} />}
pagination={pagination}
footerRow={footerRow}
/>
);
};
const columns: AlertTableColumnProps[] = [
{
id: 'state',
label: 'State',
// eslint-disable-next-line react/display-name
renderCell: ({ data: { state } }) => <AlertStateTag state={state} />,
size: '80px',
},
{
id: 'labels',
label: 'Labels',
// eslint-disable-next-line react/display-name
renderCell: ({ data: { labels } }) => <AlertLabels labels={labels} />,
},
{
id: 'created',
label: 'Created',
// eslint-disable-next-line react/display-name
renderCell: ({ data: { activeAt } }) => (
<>{activeAt.startsWith('0001') ? '-' : dateTime(activeAt).format('YYYY-MM-DD HH:mm:ss')}</>
),
size: '150px',
},
];
| public/app/features/alerting/unified/components/rules/AlertInstancesTable.tsx | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017604210006538779,
0.00017228024080395699,
0.0001687494368525222,
0.00017307796224486083,
0.000002622668262119987
] |
{
"id": 2,
"code_window": [
" datasource_uid: 'CW1234',\n",
" grafana_version: '1.0',\n",
" success: true,\n",
" });\n",
" });\n",
"\n",
" it('then testDataSourceFailed should be dispatched', async () => {\n",
" const dependencies: TestDataSourceDependencies = {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink: '/datasources/edit/CloudWatch',\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "add",
"edit_start_line_idx": 244
} | <svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M19.06934,5.93555a9.94468,9.94468,0,0,0-9.38868-2.6709.99992.99992,0,0,0,.43848,1.95117A8.0193,8.0193,0,0,1,20,13h-.33984a1,1,0,0,0,0,2H20v.33984a1,1,0,1,0,2,0V13A9.88842,9.88842,0,0,0,19.06934,5.93555ZM3.707,2.293A.99989.99989,0,0,0,2.293,3.707L4.72833,6.1424A9.96176,9.96176,0,0,0,2,13v7a1,1,0,0,0,1,1H6a3.00328,3.00328,0,0,0,3-3V16a3.00328,3.00328,0,0,0-3-3H4A7.96344,7.96344,0,0,1,6.14453,7.55859L15,16.41406V18a3.00328,3.00328,0,0,0,3,3h1.58594l.707.707A.99989.99989,0,0,0,21.707,20.293ZM6,15a1.0013,1.0013,0,0,1,1,1v2a1.0013,1.0013,0,0,1-1,1H4V15Z"/></svg> | public/img/icons/unicons/headphone-slash.svg | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00035141565604135394,
0.00035141565604135394,
0.00035141565604135394,
0.00035141565604135394,
0
] |
{
"id": 3,
"code_window": [
" },\n",
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('Azure Monitor', dependencies);\n",
"\n",
" expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);\n",
" expect(trackDataSourceTested).toHaveBeenCalledWith({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('Azure Monitor', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 272
} | import { thunkTester } from 'test/core/thunk/thunkTester';
import { AppPluginMeta, DataSourceSettings, PluginMetaInfo, PluginType } from '@grafana/data';
import { FetchError } from '@grafana/runtime';
import { ThunkResult, ThunkDispatch } from 'app/types';
import { getMockDataSource } from '../__mocks__';
import * as api from '../api';
import { DATASOURCES_ROUTES } from '../constants';
import { trackDataSourceCreated, trackDataSourceTested } from '../tracking';
import { GenericDataSourcePlugin } from '../types';
import {
InitDataSourceSettingDependencies,
testDataSource,
TestDataSourceDependencies,
initDataSourceSettings,
loadDataSource,
addDataSource,
} from './actions';
import {
initDataSourceSettingsSucceeded,
initDataSourceSettingsFailed,
testDataSourceStarting,
testDataSourceSucceeded,
testDataSourceFailed,
dataSourceLoaded,
dataSourcesLoaded,
} from './reducers';
jest.mock('../api');
jest.mock('app/core/services/backend_srv');
jest.mock('app/core/core');
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as unknown as object),
getDataSourceSrv: jest.fn().mockReturnValue({ reload: jest.fn() }),
getBackendSrv: jest.fn().mockReturnValue({ get: jest.fn() }),
}));
jest.mock('../tracking', () => ({
trackDataSourceCreated: jest.fn(),
trackDataSourceTested: jest.fn(),
}));
const getBackendSrvMock = () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
}),
withNoBackendCache: jest.fn().mockImplementationOnce((cb) => cb()),
} as any);
const failDataSourceTest = async (error: object) => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw error;
}),
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
return dispatchedActions;
};
describe('loadDataSource()', () => {
it('should resolve to a data-source if a UID was used for fetching', async () => {
const dataSourceMock = getMockDataSource();
const dispatch = jest.fn();
const getState = jest.fn();
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
const dataSource = await loadDataSource(dataSourceMock.uid)(dispatch, getState, undefined);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded(dataSource));
expect(dataSource).toBe(dataSourceMock);
});
it('should resolve to an empty data-source if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
const dataSource = await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(dataSource).toEqual({});
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded({} as DataSourceSettings));
});
it('should redirect to a URL which uses the UID if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(window.location.href).toBe(`/datasources/edit/${uid}`);
});
});
describe('initDataSourceSettings', () => {
describe('when pageId is missing', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dispatchedActions = await thunkTester({}).givenThunk(initDataSourceSettings).whenThunkIsDispatched('');
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Invalid UID'))]);
});
});
describe('when pageId is a valid', () => {
it('then initDataSourceSettingsSucceeded should be dispatched', async () => {
const dataSource = { type: 'app' };
const dataSourceMeta = { id: 'some id' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => {}),
getDataSource: jest.fn().mockReturnValue(dataSource),
getDataSourceMeta: jest.fn().mockReturnValue(dataSourceMeta),
importDataSourcePlugin: jest.fn().mockReturnValue({} as GenericDataSourcePlugin),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(256, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsSucceeded({} as GenericDataSourcePlugin)]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(256);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
expect(dependencies.getDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSource).toHaveBeenCalledWith({}, 256);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledWith({}, 'app');
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledTimes(1);
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledWith(dataSourceMeta);
});
});
describe('when plugin loading fails', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dataSource = { type: 'app' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn().mockImplementation(() => {
throw new Error('Error loading plugin');
}),
getDataSource: jest.fn(),
getDataSourceMeta: jest.fn(),
importDataSourcePlugin: jest.fn(),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(301, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Error loading plugin'))]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(301);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
});
});
});
describe('testDataSource', () => {
describe('when a datasource is tested', () => {
it('then testDataSourceStarting and testDataSourceSucceeded should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
type: 'cloudwatch',
uid: 'CW1234',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
status: '',
message: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('CloudWatch', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'cloudwatch',
datasource_uid: 'CW1234',
grafana_version: '1.0',
success: true,
});
});
it('then testDataSourceFailed should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw new Error('Error testing datasource');
}),
type: 'azure-monitor',
uid: 'azM0nit0R',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const result = {
message: 'Error testing datasource',
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
datasource_uid: 'azM0nit0R',
grafana_version: '1.0',
success: false,
});
});
it('then testDataSourceFailed should be dispatched with response error message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response data message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response statusText', async () => {
const result = {
message: 'HTTP error Bad Request',
};
const error: FetchError = {
config: {
url: '',
},
data: {},
statusText: 'Bad Request',
status: 400,
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
});
});
describe('addDataSource', () => {
it('it creates a datasource and calls trackDataSourceCreated ', async () => {
const meta: AppPluginMeta = {
id: 'azure-monitor',
module: '',
baseUrl: 'xxx',
info: { version: '1.2.3' } as PluginMetaInfo,
type: PluginType.datasource,
name: 'test DS',
};
const state = {
dataSources: {
dataSources: [],
},
};
const dataSourceMock = { datasource: { uid: 'azure23' }, meta };
(api.createDataSource as jest.Mock).mockResolvedValueOnce(dataSourceMock);
(api.getDataSources as jest.Mock).mockResolvedValueOnce([]);
const dispatchedActions = await thunkTester(state).givenThunk(addDataSource).whenThunkIsDispatched(meta);
expect(dispatchedActions).toEqual([dataSourcesLoaded([])]);
expect(trackDataSourceCreated).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
plugin_version: '1.2.3',
datasource_uid: 'azure23',
grafana_version: '1.0',
editLink: DATASOURCES_ROUTES.Edit.replace(':uid', 'azure23'),
});
});
});
| public/app/features/datasources/state/actions.test.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.9985156655311584,
0.16567105054855347,
0.00016622254042886198,
0.002421744167804718,
0.35711777210235596
] |
{
"id": 3,
"code_window": [
" },\n",
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('Azure Monitor', dependencies);\n",
"\n",
" expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);\n",
" expect(trackDataSourceTested).toHaveBeenCalledWith({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('Azure Monitor', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 272
} | notifiers:
- name: second-default
type: email
uid: notifier2
is_default: true
settings:
addresses: [email protected] | pkg/services/provisioning/notifiers/testdata/test-configs/double-default/default-2.yaml | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017323480278719217,
0.00017323480278719217,
0.00017323480278719217,
0.00017323480278719217,
0
] |
{
"id": 3,
"code_window": [
" },\n",
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('Azure Monitor', dependencies);\n",
"\n",
" expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);\n",
" expect(trackDataSourceTested).toHaveBeenCalledWith({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('Azure Monitor', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 272
} | #!/bin/bash
_files=$*
if [ -z "$_files" ]; then
echo "_files (arg 1) has to be set"
exit 1
fi
mkdir -p ~/.rpmdb/pubkeys
curl -s https://packages.grafana.com/gpg.key > ~/.rpmdb/pubkeys/grafana.key
ALL_SIGNED=0
for file in $_files; do
if rpm -K "$file" | grep "digests signatures OK" -q ; then
echo "$file" OK
else
ALL_SIGNED=1
echo "$file" NOT SIGNED
fi
done
exit $ALL_SIGNED
| scripts/build/verify_signed_packages.sh | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017235317500308156,
0.000169321327120997,
0.00016706899623386562,
0.00016854182467795908,
0.0000022265610368776834
] |
{
"id": 3,
"code_window": [
" },\n",
" };\n",
" const dispatchedActions = await thunkTester(state)\n",
" .givenThunk(testDataSource)\n",
" .whenThunkIsDispatched('Azure Monitor', dependencies);\n",
"\n",
" expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);\n",
" expect(trackDataSourceTested).toHaveBeenCalledWith({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" .whenThunkIsDispatched('Azure Monitor', DATASOURCES_ROUTES.Edit, dependencies);\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "replace",
"edit_start_line_idx": 272
} | import { dateTime } from '@grafana/data';
import { reduxTester } from '../../../../test/core/redux/reduxTester';
import { silenceConsoleOutput } from '../../../../test/core/utils/silenceConsoleOutput';
import { notifyApp } from '../../../core/actions';
import { getTimeSrv, setTimeSrv, TimeSrv } from '../../dashboard/services/TimeSrv';
import { TemplateSrv } from '../../templating/template_srv';
import { variableAdapters } from '../adapters';
import { intervalBuilder } from '../shared/testing/builders';
import { updateOptions } from '../state/actions';
import { getRootReducer, RootReducerType } from '../state/helpers';
import { toKeyedAction } from '../state/keyedVariablesReducer';
import {
addVariable,
setCurrentVariableValue,
variableStateFailed,
variableStateFetching,
} from '../state/sharedReducer';
import { variablesInitTransaction } from '../state/transactionReducer';
import { toKeyedVariableIdentifier, toVariablePayload } from '../utils';
import { updateAutoValue, UpdateAutoValueDependencies, updateIntervalVariableOptions } from './actions';
import { createIntervalVariableAdapter } from './adapter';
import { createIntervalOptions } from './reducer';
describe('interval actions', () => {
variableAdapters.setInit(() => [createIntervalVariableAdapter()]);
describe('when updateIntervalVariableOptions is dispatched', () => {
it('then correct actions are dispatched', async () => {
const interval = intervalBuilder()
.withId('0')
.withRootStateKey('key')
.withQuery('1s,1m,1h,1d')
.withAuto(false)
.build();
const tester = await reduxTester<RootReducerType>()
.givenRootReducer(getRootReducer())
.whenActionIsDispatched(
toKeyedAction('key', addVariable(toVariablePayload(interval, { global: false, index: 0, model: interval })))
)
.whenAsyncActionIsDispatched(updateIntervalVariableOptions(toKeyedVariableIdentifier(interval)), true);
tester.thenDispatchedActionsShouldEqual(
toKeyedAction('key', createIntervalOptions({ type: 'interval', id: '0', data: undefined })),
toKeyedAction(
'key',
setCurrentVariableValue({
type: 'interval',
id: '0',
data: { option: { text: '1s', value: '1s', selected: false } },
})
)
);
});
});
describe('when updateOptions is dispatched but something throws', () => {
silenceConsoleOutput();
const originalTimeSrv = getTimeSrv();
beforeEach(() => {
const timeSrvMock = {
timeRange: jest.fn().mockReturnValue({
from: dateTime(new Date()).subtract(1, 'days').toDate(),
to: new Date(),
raw: {
from: 'now-1d',
to: 'now',
},
}),
} as unknown as TimeSrv;
setTimeSrv(timeSrvMock);
});
afterEach(() => {
setTimeSrv(originalTimeSrv);
});
it('then an notifyApp action should be dispatched', async () => {
const interval = intervalBuilder()
.withId('0')
.withRootStateKey('key')
.withQuery('1s,1m,1h,1d')
.withAuto(true)
.withAutoMin('1xyz') // illegal interval string
.build();
const tester = await reduxTester<RootReducerType>()
.givenRootReducer(getRootReducer())
.whenActionIsDispatched(
toKeyedAction('key', addVariable(toVariablePayload(interval, { global: false, index: 0, model: interval })))
)
.whenActionIsDispatched(toKeyedAction('key', variablesInitTransaction({ uid: 'key' })))
.whenAsyncActionIsDispatched(updateOptions(toKeyedVariableIdentifier(interval)), true);
tester.thenDispatchedActionsPredicateShouldEqual((dispatchedActions) => {
const expectedNumberOfActions = 4;
expect(dispatchedActions[0]).toEqual(toKeyedAction('key', variableStateFetching(toVariablePayload(interval))));
expect(dispatchedActions[1]).toEqual(toKeyedAction('key', createIntervalOptions(toVariablePayload(interval))));
expect(dispatchedActions[2]).toEqual(
toKeyedAction(
'key',
variableStateFailed(
toVariablePayload(interval, {
error: new Error(
'Invalid interval string, has to be either unit-less or end with one of the following units: "y, M, w, d, h, m, s, ms"'
),
})
)
)
);
expect(dispatchedActions[3].type).toEqual(notifyApp.type);
expect(dispatchedActions[3].payload.title).toEqual('Templating [0]');
expect(dispatchedActions[3].payload.text).toEqual(
'Error updating options: Invalid interval string, has to be either unit-less or end with one of the following units: "y, M, w, d, h, m, s, ms"'
);
expect(dispatchedActions[3].payload.severity).toEqual('error');
return dispatchedActions.length === expectedNumberOfActions;
});
});
describe('but there is no ongoing transaction', () => {
it('then no actions are dispatched', async () => {
const interval = intervalBuilder()
.withId('0')
.withRootStateKey('key')
.withQuery('1s,1m,1h,1d')
.withAuto(true)
.withAutoMin('1xyz') // illegal interval string
.build();
const tester = await reduxTester<RootReducerType>()
.givenRootReducer(getRootReducer())
.whenActionIsDispatched(
toKeyedAction('key', addVariable(toVariablePayload(interval, { global: false, index: 0, model: interval })))
)
.whenAsyncActionIsDispatched(updateOptions(toKeyedVariableIdentifier(interval)), true);
tester.thenNoActionsWhereDispatched();
});
});
});
describe('when updateAutoValue is dispatched', () => {
describe('and auto is false', () => {
it('then no dependencies are called', async () => {
const interval = intervalBuilder().withId('0').withRootStateKey('key').withAuto(false).build();
const dependencies: UpdateAutoValueDependencies = {
calculateInterval: jest.fn(),
getTimeSrv: () => {
return {
timeRange: jest.fn().mockReturnValue({
from: '2001-01-01',
to: '2001-01-02',
raw: {
from: '2001-01-01',
to: '2001-01-02',
},
}),
} as unknown as TimeSrv;
},
templateSrv: {
setGrafanaVariable: jest.fn(),
} as unknown as TemplateSrv,
};
await reduxTester<RootReducerType>()
.givenRootReducer(getRootReducer())
.whenActionIsDispatched(
toKeyedAction('key', addVariable(toVariablePayload(interval, { global: false, index: 0, model: interval })))
)
.whenAsyncActionIsDispatched(updateAutoValue(toKeyedVariableIdentifier(interval), dependencies), true);
expect(dependencies.calculateInterval).toHaveBeenCalledTimes(0);
expect(dependencies.getTimeSrv().timeRange).toHaveBeenCalledTimes(0);
expect(dependencies.templateSrv.setGrafanaVariable).toHaveBeenCalledTimes(0);
});
});
describe('and auto is true', () => {
it('then correct dependencies are called', async () => {
const interval = intervalBuilder()
.withId('0')
.withRootStateKey('key')
.withName('intervalName')
.withAuto(true)
.withAutoCount(33)
.withAutoMin('13s')
.build();
const timeRangeMock = jest.fn().mockReturnValue({
from: '2001-01-01',
to: '2001-01-02',
raw: {
from: '2001-01-01',
to: '2001-01-02',
},
});
const setGrafanaVariableMock = jest.fn();
const dependencies: UpdateAutoValueDependencies = {
calculateInterval: jest.fn().mockReturnValue({ interval: '10s' }),
getTimeSrv: () => {
return {
timeRange: timeRangeMock,
} as unknown as TimeSrv;
},
templateSrv: {
setGrafanaVariable: setGrafanaVariableMock,
} as unknown as TemplateSrv,
};
await reduxTester<RootReducerType>()
.givenRootReducer(getRootReducer())
.whenActionIsDispatched(
toKeyedAction('key', addVariable(toVariablePayload(interval, { global: false, index: 0, model: interval })))
)
.whenAsyncActionIsDispatched(updateAutoValue(toKeyedVariableIdentifier(interval), dependencies), true);
expect(dependencies.calculateInterval).toHaveBeenCalledTimes(1);
expect(dependencies.calculateInterval).toHaveBeenCalledWith(
{
from: '2001-01-01',
to: '2001-01-02',
raw: {
from: '2001-01-01',
to: '2001-01-02',
},
},
33,
'13s'
);
expect(timeRangeMock).toHaveBeenCalledTimes(1);
expect(setGrafanaVariableMock).toHaveBeenCalledTimes(2);
expect(setGrafanaVariableMock.mock.calls[0][0]).toBe('$__auto_interval_intervalName');
expect(setGrafanaVariableMock.mock.calls[0][1]).toBe('10s');
expect(setGrafanaVariableMock.mock.calls[1][0]).toBe('$__auto_interval');
expect(setGrafanaVariableMock.mock.calls[1][1]).toBe('10s');
});
});
});
});
| public/app/features/variables/interval/actions.test.ts | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.9909442663192749,
0.04147940129041672,
0.00016450826660729945,
0.00017463606491219252,
0.19390256702899933
] |
{
"id": 4,
"code_window": [
" datasource_uid: 'azM0nit0R',\n",
" grafana_version: '1.0',\n",
" success: false,\n",
" });\n",
" });\n",
"\n",
" it('then testDataSourceFailed should be dispatched with response error message', async () => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink: '/datasources/edit/Azure Monitor',\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "add",
"edit_start_line_idx": 280
} | import { thunkTester } from 'test/core/thunk/thunkTester';
import { AppPluginMeta, DataSourceSettings, PluginMetaInfo, PluginType } from '@grafana/data';
import { FetchError } from '@grafana/runtime';
import { ThunkResult, ThunkDispatch } from 'app/types';
import { getMockDataSource } from '../__mocks__';
import * as api from '../api';
import { DATASOURCES_ROUTES } from '../constants';
import { trackDataSourceCreated, trackDataSourceTested } from '../tracking';
import { GenericDataSourcePlugin } from '../types';
import {
InitDataSourceSettingDependencies,
testDataSource,
TestDataSourceDependencies,
initDataSourceSettings,
loadDataSource,
addDataSource,
} from './actions';
import {
initDataSourceSettingsSucceeded,
initDataSourceSettingsFailed,
testDataSourceStarting,
testDataSourceSucceeded,
testDataSourceFailed,
dataSourceLoaded,
dataSourcesLoaded,
} from './reducers';
jest.mock('../api');
jest.mock('app/core/services/backend_srv');
jest.mock('app/core/core');
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as unknown as object),
getDataSourceSrv: jest.fn().mockReturnValue({ reload: jest.fn() }),
getBackendSrv: jest.fn().mockReturnValue({ get: jest.fn() }),
}));
jest.mock('../tracking', () => ({
trackDataSourceCreated: jest.fn(),
trackDataSourceTested: jest.fn(),
}));
const getBackendSrvMock = () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
}),
withNoBackendCache: jest.fn().mockImplementationOnce((cb) => cb()),
} as any);
const failDataSourceTest = async (error: object) => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw error;
}),
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
return dispatchedActions;
};
describe('loadDataSource()', () => {
it('should resolve to a data-source if a UID was used for fetching', async () => {
const dataSourceMock = getMockDataSource();
const dispatch = jest.fn();
const getState = jest.fn();
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
const dataSource = await loadDataSource(dataSourceMock.uid)(dispatch, getState, undefined);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded(dataSource));
expect(dataSource).toBe(dataSourceMock);
});
it('should resolve to an empty data-source if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
const dataSource = await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(dataSource).toEqual({});
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded({} as DataSourceSettings));
});
it('should redirect to a URL which uses the UID if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(window.location.href).toBe(`/datasources/edit/${uid}`);
});
});
describe('initDataSourceSettings', () => {
describe('when pageId is missing', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dispatchedActions = await thunkTester({}).givenThunk(initDataSourceSettings).whenThunkIsDispatched('');
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Invalid UID'))]);
});
});
describe('when pageId is a valid', () => {
it('then initDataSourceSettingsSucceeded should be dispatched', async () => {
const dataSource = { type: 'app' };
const dataSourceMeta = { id: 'some id' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => {}),
getDataSource: jest.fn().mockReturnValue(dataSource),
getDataSourceMeta: jest.fn().mockReturnValue(dataSourceMeta),
importDataSourcePlugin: jest.fn().mockReturnValue({} as GenericDataSourcePlugin),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(256, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsSucceeded({} as GenericDataSourcePlugin)]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(256);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
expect(dependencies.getDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSource).toHaveBeenCalledWith({}, 256);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledWith({}, 'app');
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledTimes(1);
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledWith(dataSourceMeta);
});
});
describe('when plugin loading fails', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dataSource = { type: 'app' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn().mockImplementation(() => {
throw new Error('Error loading plugin');
}),
getDataSource: jest.fn(),
getDataSourceMeta: jest.fn(),
importDataSourcePlugin: jest.fn(),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(301, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Error loading plugin'))]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(301);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
});
});
});
describe('testDataSource', () => {
describe('when a datasource is tested', () => {
it('then testDataSourceStarting and testDataSourceSucceeded should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
type: 'cloudwatch',
uid: 'CW1234',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
status: '',
message: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('CloudWatch', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'cloudwatch',
datasource_uid: 'CW1234',
grafana_version: '1.0',
success: true,
});
});
it('then testDataSourceFailed should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw new Error('Error testing datasource');
}),
type: 'azure-monitor',
uid: 'azM0nit0R',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const result = {
message: 'Error testing datasource',
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
datasource_uid: 'azM0nit0R',
grafana_version: '1.0',
success: false,
});
});
it('then testDataSourceFailed should be dispatched with response error message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response data message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response statusText', async () => {
const result = {
message: 'HTTP error Bad Request',
};
const error: FetchError = {
config: {
url: '',
},
data: {},
statusText: 'Bad Request',
status: 400,
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
});
});
describe('addDataSource', () => {
it('it creates a datasource and calls trackDataSourceCreated ', async () => {
const meta: AppPluginMeta = {
id: 'azure-monitor',
module: '',
baseUrl: 'xxx',
info: { version: '1.2.3' } as PluginMetaInfo,
type: PluginType.datasource,
name: 'test DS',
};
const state = {
dataSources: {
dataSources: [],
},
};
const dataSourceMock = { datasource: { uid: 'azure23' }, meta };
(api.createDataSource as jest.Mock).mockResolvedValueOnce(dataSourceMock);
(api.getDataSources as jest.Mock).mockResolvedValueOnce([]);
const dispatchedActions = await thunkTester(state).givenThunk(addDataSource).whenThunkIsDispatched(meta);
expect(dispatchedActions).toEqual([dataSourcesLoaded([])]);
expect(trackDataSourceCreated).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
plugin_version: '1.2.3',
datasource_uid: 'azure23',
grafana_version: '1.0',
editLink: DATASOURCES_ROUTES.Edit.replace(':uid', 'azure23'),
});
});
});
| public/app/features/datasources/state/actions.test.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.15066982805728912,
0.010261396877467632,
0.0001656349195400253,
0.0004701236612163484,
0.02941414900124073
] |
{
"id": 4,
"code_window": [
" datasource_uid: 'azM0nit0R',\n",
" grafana_version: '1.0',\n",
" success: false,\n",
" });\n",
" });\n",
"\n",
" it('then testDataSourceFailed should be dispatched with response error message', async () => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink: '/datasources/edit/Azure Monitor',\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "add",
"edit_start_line_idx": 280
} | import { css, cx } from '@emotion/css';
import React, { useCallback } from 'react';
import { useAsync, useLocalStorage } from 'react-use';
import { GrafanaTheme2 } from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { Card, Checkbox, CollapsableSection, Icon, IconName, Spinner, useStyles2 } from '@grafana/ui';
import { getSectionStorageKey } from 'app/features/search/utils';
import { useUniqueId } from 'app/plugins/datasource/influxdb/components/useUniqueId';
import { SearchItem } from '../..';
import { getGrafanaSearcher, SearchQuery } from '../../service';
import { DashboardSearchItemType, DashboardSectionItem } from '../../types';
import { SelectionChecker, SelectionToggle } from '../selection';
export interface DashboardSection {
kind: string; // folder | query!
uid: string;
title: string;
selected?: boolean; // not used ? keyboard
url?: string;
icon?: IconName;
itemsUIDs?: string[]; // for pseudo folders
}
interface SectionHeaderProps {
selection?: SelectionChecker;
selectionToggle?: SelectionToggle;
onClickItem?: (e: React.MouseEvent<HTMLElement>) => void;
onTagSelected: (tag: string) => void;
section: DashboardSection;
renderStandaloneBody?: boolean; // render the body on its own
tags?: string[];
}
export const FolderSection = ({
section,
selectionToggle,
onClickItem,
onTagSelected,
selection,
renderStandaloneBody,
tags,
}: SectionHeaderProps) => {
const editable = selectionToggle != null;
const styles = useStyles2(
useCallback(
(theme: GrafanaTheme2) => getSectionHeaderStyles(theme, section.selected, editable),
[section.selected, editable]
)
);
const [sectionExpanded, setSectionExpanded] = useLocalStorage(getSectionStorageKey(section.title), false);
const results = useAsync(async () => {
if (!sectionExpanded && !renderStandaloneBody) {
return Promise.resolve([]);
}
let folderUid: string | undefined = section.uid;
let folderTitle: string | undefined = section.title;
let query: SearchQuery = {
query: '*',
kind: ['dashboard'],
location: section.uid,
sort: 'name_sort',
limit: 1000, // this component does not have infinate scroll, so we need to load everything upfront
};
if (section.itemsUIDs) {
query = {
uid: section.itemsUIDs, // array of UIDs
};
folderUid = undefined;
folderTitle = undefined;
}
const raw = await getGrafanaSearcher().search({ ...query, tags });
const v = raw.view.map<DashboardSectionItem>((item) => ({
uid: item.uid,
title: item.name,
url: item.url,
uri: item.url,
type: item.kind === 'folder' ? DashboardSearchItemType.DashFolder : DashboardSearchItemType.DashDB,
id: 666, // do not use me!
isStarred: false,
tags: item.tags ?? [],
folderUid: folderUid || item.location,
folderTitle: folderTitle || raw.view.dataFrame.meta?.custom?.locationInfo[item.location].name,
}));
return v;
}, [sectionExpanded, tags]);
const onSectionExpand = () => {
setSectionExpanded(!sectionExpanded);
};
const onToggleFolder = (evt: React.FormEvent) => {
evt.preventDefault();
evt.stopPropagation();
if (selectionToggle && selection) {
const checked = !selection(section.kind, section.uid);
selectionToggle(section.kind, section.uid);
const sub = results.value ?? [];
for (const item of sub) {
if (selection('dashboard', item.uid!) !== checked) {
selectionToggle('dashboard', item.uid!);
}
}
}
};
const id = useUniqueId();
const labelId = `section-header-label-${id}`;
let icon = section.icon;
if (!icon) {
icon = sectionExpanded ? 'folder-open' : 'folder';
}
const renderResults = () => {
if (!results.value) {
return null;
} else if (results.value.length === 0 && !results.loading) {
return (
<Card>
<Card.Heading>No results found</Card.Heading>
</Card>
);
}
return results.value.map((v) => {
if (selection && selectionToggle) {
const type = v.type === DashboardSearchItemType.DashFolder ? 'folder' : 'dashboard';
v = {
...v,
checked: selection(type, v.uid!),
};
}
return (
<SearchItem
key={v.uid}
item={v}
onTagSelected={onTagSelected}
onToggleChecked={(item) => {
if (selectionToggle) {
selectionToggle('dashboard', item.uid!);
}
}}
editable={Boolean(selection != null)}
onClickItem={onClickItem}
/>
);
});
};
// Skip the folder wrapper
if (renderStandaloneBody) {
return (
<div className={styles.folderViewResults}>
{!results.value?.length && results.loading ? <Spinner className={styles.spinner} /> : renderResults()}
</div>
);
}
return (
<CollapsableSection
headerDataTestId={selectors.components.Search.folderHeader(section.title)}
contentDataTestId={selectors.components.Search.folderContent(section.title)}
isOpen={sectionExpanded ?? false}
onToggle={onSectionExpand}
className={styles.wrapper}
contentClassName={styles.content}
loading={results.loading}
labelId={labelId}
label={
<>
{selectionToggle && selection && (
<div className={styles.checkbox} onClick={onToggleFolder}>
<Checkbox value={selection(section.kind, section.uid)} aria-label="Select folder" />
</div>
)}
<div className={styles.icon}>
<Icon name={icon} />
</div>
<div className={styles.text}>
<span id={labelId}>{section.title}</span>
{section.url && section.uid !== 'general' && (
<a href={section.url} className={styles.link}>
<span className={styles.separator}>|</span> <Icon name="folder-upload" /> Go to folder
</a>
)}
</div>
</>
}
>
{results.value && <ul className={styles.sectionItems}>{renderResults()}</ul>}
</CollapsableSection>
);
};
const getSectionHeaderStyles = (theme: GrafanaTheme2, selected = false, editable: boolean) => {
const sm = theme.spacing(1);
return {
wrapper: cx(
css`
align-items: center;
font-size: ${theme.typography.size.base};
padding: 12px;
border-bottom: none;
color: ${theme.colors.text.secondary};
z-index: 1;
&:hover,
&.selected {
color: ${theme.colors.text};
}
&:hover,
&:focus-visible,
&:focus-within {
a {
opacity: 1;
}
}
`,
'pointer',
{ selected }
),
sectionItems: css`
margin: 0 24px 0 32px;
`,
checkbox: css`
padding: 0 ${sm} 0 0;
`,
icon: css`
padding: 0 ${sm} 0 ${editable ? 0 : sm};
`,
folderViewResults: css`
overflow: auto;
`,
text: css`
flex-grow: 1;
line-height: 24px;
`,
link: css`
padding: 2px 10px 0;
color: ${theme.colors.text.secondary};
opacity: 0;
transition: opacity 150ms ease-in-out;
`,
separator: css`
margin-right: 6px;
`,
content: css`
padding-top: 0px;
padding-bottom: 0px;
`,
spinner: css`
display: grid;
place-content: center;
padding-bottom: 1rem;
`,
};
};
| public/app/features/search/page/components/FolderSection.tsx | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00025694616488181055,
0.00017795547319110483,
0.0001638807589188218,
0.0001739865110721439,
0.00001928481287905015
] |
{
"id": 4,
"code_window": [
" datasource_uid: 'azM0nit0R',\n",
" grafana_version: '1.0',\n",
" success: false,\n",
" });\n",
" });\n",
"\n",
" it('then testDataSourceFailed should be dispatched with response error message', async () => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink: '/datasources/edit/Azure Monitor',\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "add",
"edit_start_line_idx": 280
} | import { useState, useCallback, useMemo } from 'react';
import { AzureMonitorErrorish } from '../types';
import { messageFromElement } from './messageFromError';
type SourcedError = [string, AzureMonitorErrorish];
export default function useLastError() {
const [errors, setErrors] = useState<SourcedError[]>([]);
// Handles errors from any child components that request data to display their options
const addError = useCallback((errorSource: string, error: AzureMonitorErrorish | undefined) => {
setErrors((errors) => {
const errorsCopy = [...errors];
const index = errors.findIndex(([vSource]) => vSource === errorSource);
// If there's already an error, remove it. If we're setting a new error
// below, we'll move it to the front
if (index > -1) {
errorsCopy.splice(index, 1);
}
// And then add the new error to the top of the array. If error is defined, it was already
// removed above.
if (error) {
errorsCopy.unshift([errorSource, error]);
}
return errorsCopy;
});
}, []);
const errorMessage = useMemo(() => {
const recentError = errors[0];
return recentError && messageFromElement(recentError[1]);
}, [errors]);
return [errorMessage, addError] as const;
}
| public/app/plugins/datasource/grafana-azure-monitor-datasource/utils/useLastError.ts | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017595819372218102,
0.00016897302703000605,
0.00016546160622965544,
0.00016762301675044,
0.0000036630833619710756
] |
{
"id": 4,
"code_window": [
" datasource_uid: 'azM0nit0R',\n",
" grafana_version: '1.0',\n",
" success: false,\n",
" });\n",
" });\n",
"\n",
" it('then testDataSourceFailed should be dispatched with response error message', async () => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink: '/datasources/edit/Azure Monitor',\n"
],
"file_path": "public/app/features/datasources/state/actions.test.ts",
"type": "add",
"edit_start_line_idx": 280
} | ---
aliases:
- ../../data-sources/loki/template-variables/
description: Guide for using template variables when querying the Loki data source
keywords:
- grafana
- loki
- logs
- queries
- template
- variable
menuTitle: Template variables
title: Loki template variables
weight: 300
---
# Loki template variables
Instead of hard-coding details such as server, application, and sensor names in metric queries, you can use variables.
Grafana lists these variables in dropdown select boxes at the top of the dashboard to help you change the data displayed in your dashboard.
Grafana refers to such variables as template variables.
For an introduction to templating and template variables, refer to the [Templating]({{< relref "../../../dashboards/variables" >}}) and [Add and manage variables]({{< relref "../../../dashboards/variables/add-template-variables" >}}) documentation.
## Use query variables
Variables of the type _Query_ help you query Loki for lists of labels or label values.
The Loki data source provides a form to select the type of values expected for a given variable.
The form has these options:
| Query type | Example label | Example stream selector | List returned |
| ------------ | ------------- | ----------------------- | ---------------------------------------------------------------- |
| Label names | Not required | Not required | Label names. |
| Label values | `label` | | Label values for `label`. |
| Label values | `label` | `log stream selector` | Label values for `label` in the specified `log stream selector`. |
## Use ad hoc filters
Loki supports the special **Ad hoc filters** variable type.
You can use this variable type to specify any number of key/value filters, and Grafana applies them automatically to all of your Loki queries.
For more information, refer to [Add ad hoc filters]({{< relref "../../../dashboards/variables/add-template-variables#add-ad-hoc-filters" >}}).
## Use interval and range variables
You can use some global built-in variables in query variables: `$__interval`, `$__interval_ms`, `$__range`, `$__range_s`, and `$__range_ms`.
For more information, refer to [Global built-in variables]({{< relref "../../../dashboards/variables/add-template-variables#global-variables" >}}).
| docs/sources/datasources/loki/template-variables/index.md | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0002539984416216612,
0.00018919215654022992,
0.00016562308883294463,
0.00017416029004380107,
0.0000327069683407899
] |
{
"id": 5,
"code_window": [
"\n",
"export const testDataSource = (\n",
" dataSourceName: string,\n",
" dependencies: TestDataSourceDependencies = {\n",
" getDatasourceSrv,\n",
" getBackendSrv,\n",
" }\n",
"): ThunkResult<void> => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editRoute = DATASOURCES_ROUTES.Edit,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 92
} | import { useContext, useEffect } from 'react';
import { DataSourcePluginMeta, DataSourceSettings, NavModelItem } from '@grafana/data';
import { cleanUpAction } from 'app/core/actions/cleanUp';
import appEvents from 'app/core/app_events';
import { contextSrv } from 'app/core/core';
import { getNavModel } from 'app/core/selectors/navModel';
import { AccessControlAction, useDispatch, useSelector } from 'app/types';
import { ShowConfirmModalEvent } from 'app/types/events';
import { DataSourceRights } from '../types';
import { constructDataSourceExploreUrl } from '../utils';
import {
initDataSourceSettings,
testDataSource,
loadDataSource,
loadDataSources,
loadDataSourcePlugins,
addDataSource,
updateDataSource,
deleteLoadedDataSource,
} from './actions';
import { DataSourcesRoutesContext } from './contexts';
import { getDataSourceLoadingNav, buildNavModel, getDataSourceNav } from './navModel';
import { getDataSource, getDataSourceMeta } from './selectors';
export const useInitDataSourceSettings = (uid: string) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(initDataSourceSettings(uid));
return function cleanUp() {
dispatch(
cleanUpAction({
cleanupAction: (state) => state.dataSourceSettings,
})
);
};
}, [uid, dispatch]);
};
export const useTestDataSource = (uid: string) => {
const dispatch = useDispatch();
return () => dispatch(testDataSource(uid));
};
export const useLoadDataSources = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadDataSources());
}, [dispatch]);
};
export const useLoadDataSource = (uid: string) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadDataSource(uid));
}, [dispatch, uid]);
};
export const useLoadDataSourcePlugins = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadDataSourcePlugins());
}, [dispatch]);
};
export const useAddDatasource = () => {
const dispatch = useDispatch();
const dataSourcesRoutes = useDataSourcesRoutes();
return (plugin: DataSourcePluginMeta) => {
dispatch(addDataSource(plugin, dataSourcesRoutes.Edit));
};
};
export const useUpdateDatasource = () => {
const dispatch = useDispatch();
return async (dataSource: DataSourceSettings) => dispatch(updateDataSource(dataSource));
};
export const useDeleteLoadedDataSource = () => {
const dispatch = useDispatch();
const { name } = useSelector((state) => state.dataSources.dataSource);
return () => {
appEvents.publish(
new ShowConfirmModalEvent({
title: 'Delete',
text: `Are you sure you want to delete the "${name}" data source?`,
yesText: 'Delete',
icon: 'trash-alt',
onConfirm: () => dispatch(deleteLoadedDataSource()),
})
);
};
};
export const useDataSource = (uid: string) => {
return useSelector((state) => getDataSource(state.dataSources, uid));
};
export const useDataSourceExploreUrl = (uid: string) => {
const dataSource = useDataSource(uid);
return constructDataSourceExploreUrl(dataSource);
};
export const useDataSourceMeta = (pluginType: string): DataSourcePluginMeta => {
return useSelector((state) => getDataSourceMeta(state.dataSources, pluginType));
};
export const useDataSourceSettings = () => {
return useSelector((state) => state.dataSourceSettings);
};
export const useDataSourceSettingsNav = (dataSourceId: string, pageId: string | null) => {
const dataSource = useDataSource(dataSourceId);
const { plugin, loadError, loading } = useDataSourceSettings();
const navIndex = useSelector((state) => state.navIndex);
const navIndexId = pageId ? `datasource-${pageId}-${dataSourceId}` : `datasource-settings-${dataSourceId}`;
if (loadError) {
const node: NavModelItem = {
text: loadError,
subTitle: 'Data Source Error',
icon: 'exclamation-triangle',
};
return {
node: node,
main: node,
};
}
if (loading || !plugin) {
return getNavModel(navIndex, navIndexId, getDataSourceLoadingNav('settings'));
}
return getNavModel(navIndex, navIndexId, getDataSourceNav(buildNavModel(dataSource, plugin), pageId || 'settings'));
};
export const useDataSourceRights = (uid: string): DataSourceRights => {
const dataSource = useDataSource(uid);
const readOnly = dataSource.readOnly === true;
const hasWriteRights = contextSrv.hasPermissionInMetadata(AccessControlAction.DataSourcesWrite, dataSource);
const hasDeleteRights = contextSrv.hasPermissionInMetadata(AccessControlAction.DataSourcesDelete, dataSource);
return {
readOnly,
hasWriteRights,
hasDeleteRights,
};
};
export const useDataSourcesRoutes = () => {
return useContext(DataSourcesRoutesContext);
};
| public/app/features/datasources/state/hooks.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.9944025874137878,
0.11525395512580872,
0.0001673925289651379,
0.0008601757581345737,
0.3099873960018158
] |
{
"id": 5,
"code_window": [
"\n",
"export const testDataSource = (\n",
" dataSourceName: string,\n",
" dependencies: TestDataSourceDependencies = {\n",
" getDatasourceSrv,\n",
" getBackendSrv,\n",
" }\n",
"): ThunkResult<void> => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editRoute = DATASOURCES_ROUTES.Edit,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 92
} | package store
import (
"fmt"
"github.com/grafana/grafana/pkg/services/user"
)
// Really just spitballing here :) this should hook into a system that can give better display info
func GetUserIDString(user *user.SignedInUser) string {
if user == nil {
return ""
}
if user.IsAnonymous {
return "anon"
}
if user.ApiKeyID > 0 {
return fmt.Sprintf("key:%d", user.UserID)
}
if user.IsRealUser() {
return fmt.Sprintf("user:%d:%s", user.UserID, user.Login)
}
return fmt.Sprintf("sys:%d:%s", user.UserID, user.Login)
}
| pkg/services/store/auth.go | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0001743605243973434,
0.00016968378622550517,
0.00016236689407378435,
0.00017232394020538777,
0.0000052402037908905186
] |
{
"id": 5,
"code_window": [
"\n",
"export const testDataSource = (\n",
" dataSourceName: string,\n",
" dependencies: TestDataSourceDependencies = {\n",
" getDatasourceSrv,\n",
" getBackendSrv,\n",
" }\n",
"): ThunkResult<void> => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editRoute = DATASOURCES_ROUTES.Edit,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 92
} | ---
aliases:
- ../../features/panels/bar_gauge/
- ../../panels/visualizations/bar-gauge-panel/
- ../../visualizations/bar-gauge-panel/
description: Bar gauge panel options
keywords:
- grafana
- bar
- bar gauge
title: Bar gauge
weight: 200
---
# Bar gauge
The bar gauge simplifies your data by reducing every field to a single value. You choose how Grafana calculates the reduction.
This panel can show one or more bar gauges depending on how many series, rows, or columns your query returns.
{{< figure src="/static/img/docs/v66/bar_gauge_cover.png" max-width="1025px" caption="Stat panel" >}}
## Value options
Use the following options to refine how your visualization displays the value:
### Show
Choose how Grafana displays your data.
#### Calculate
Show a calculated value based on all rows.
- **Calculation -** Select a reducer function that Grafana will use to reduce many fields to a single value. For a list of available calculations, refer to [Calculation types]({{< relref "../../calculation-types/" >}}).
- **Fields -** Select the fields display in the panel.
#### All values
Show a separate stat for every row. If you select this option, then you can also limit the number of rows to display.
- **Limit -** The maximum number of rows to display. Default is 5,000.
- **Fields -** Select the fields display in the panel.
## Bar gauge options
Adjust how the bar gauge is displayed.
### Orientation
Choose a stacking direction.
- **Auto -** Grafana selects what it thinks is the best orientation.
- **Horizontal -** Bars stretch horizontally, left to right.
- **Vertical -** Bars stretch vertically, bottom to top.
### Display mode
Choose a display mode.
- **Gradient -** Threshold levels define a gradient.
- **Retro LCD -** The gauge is split into small cells that are lit or unlit.
- **Basic -** Single color based on the matching threshold.
### Show unfilled area
Select this if you want to render the unfilled region of the bars as dark gray. Not applicable to Retro LCD display mode.
### Min width
Limit the minimum width of the bar column in the vertical direction.
Automatically show x-axis scrollbar when there is a large amount of data.
### Min height
Limit the minimum height of the bar row in the horizontal direction.
Automatically show y-axis scrollbar when there is a large amount of data.
| docs/sources/panels-visualizations/visualizations/bar-gauge/index.md | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00018941141024697572,
0.00017330364789813757,
0.00016694367513991892,
0.0001721585722407326,
0.00000674880084261531
] |
{
"id": 5,
"code_window": [
"\n",
"export const testDataSource = (\n",
" dataSourceName: string,\n",
" dependencies: TestDataSourceDependencies = {\n",
" getDatasourceSrv,\n",
" getBackendSrv,\n",
" }\n",
"): ThunkResult<void> => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editRoute = DATASOURCES_ROUTES.Edit,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 92
} | import React from 'react';
import { MenuGroup } from '../Menu/MenuGroup';
import { MenuItem } from '../Menu/MenuItem';
const menuItems = [
{
label: 'Test',
items: [
{ label: 'First', ariaLabel: 'First' },
{ label: 'Second', ariaLabel: 'Second' },
{ label: 'Third', ariaLabel: 'Third' },
{ label: 'Fourth', ariaLabel: 'Fourth' },
{ label: 'Fifth', ariaLabel: 'Fifth' },
],
},
];
export const renderMenuItems = () => {
return menuItems.map((group, index) => (
<MenuGroup key={`${group.label}${index}`} label={group.label}>
{group.items.map((item) => (
<MenuItem key={item.label} label={item.label} />
))}
</MenuGroup>
));
};
| packages/grafana-ui/src/components/ContextMenu/ContextMenuStoryHelper.tsx | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017651794769335538,
0.00017376890173181891,
0.0001691895886324346,
0.00017559918342158198,
0.000003259718369008624
] |
{
"id": 6,
"code_window": [
" }\n",
"): ThunkResult<void> => {\n",
" return async (dispatch: ThunkDispatch, getState) => {\n",
" const dsApi = await dependencies.getDatasourceSrv().get(dataSourceName);\n",
"\n",
" if (!dsApi.testDatasource) {\n",
" return;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const editLink = editRoute.replace(/:uid/gi, dataSourceName);\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 99
} | import { thunkTester } from 'test/core/thunk/thunkTester';
import { AppPluginMeta, DataSourceSettings, PluginMetaInfo, PluginType } from '@grafana/data';
import { FetchError } from '@grafana/runtime';
import { ThunkResult, ThunkDispatch } from 'app/types';
import { getMockDataSource } from '../__mocks__';
import * as api from '../api';
import { DATASOURCES_ROUTES } from '../constants';
import { trackDataSourceCreated, trackDataSourceTested } from '../tracking';
import { GenericDataSourcePlugin } from '../types';
import {
InitDataSourceSettingDependencies,
testDataSource,
TestDataSourceDependencies,
initDataSourceSettings,
loadDataSource,
addDataSource,
} from './actions';
import {
initDataSourceSettingsSucceeded,
initDataSourceSettingsFailed,
testDataSourceStarting,
testDataSourceSucceeded,
testDataSourceFailed,
dataSourceLoaded,
dataSourcesLoaded,
} from './reducers';
jest.mock('../api');
jest.mock('app/core/services/backend_srv');
jest.mock('app/core/core');
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as unknown as object),
getDataSourceSrv: jest.fn().mockReturnValue({ reload: jest.fn() }),
getBackendSrv: jest.fn().mockReturnValue({ get: jest.fn() }),
}));
jest.mock('../tracking', () => ({
trackDataSourceCreated: jest.fn(),
trackDataSourceTested: jest.fn(),
}));
const getBackendSrvMock = () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
}),
withNoBackendCache: jest.fn().mockImplementationOnce((cb) => cb()),
} as any);
const failDataSourceTest = async (error: object) => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw error;
}),
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
return dispatchedActions;
};
describe('loadDataSource()', () => {
it('should resolve to a data-source if a UID was used for fetching', async () => {
const dataSourceMock = getMockDataSource();
const dispatch = jest.fn();
const getState = jest.fn();
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
const dataSource = await loadDataSource(dataSourceMock.uid)(dispatch, getState, undefined);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded(dataSource));
expect(dataSource).toBe(dataSourceMock);
});
it('should resolve to an empty data-source if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
const dataSource = await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(dataSource).toEqual({});
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded({} as DataSourceSettings));
});
it('should redirect to a URL which uses the UID if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(window.location.href).toBe(`/datasources/edit/${uid}`);
});
});
describe('initDataSourceSettings', () => {
describe('when pageId is missing', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dispatchedActions = await thunkTester({}).givenThunk(initDataSourceSettings).whenThunkIsDispatched('');
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Invalid UID'))]);
});
});
describe('when pageId is a valid', () => {
it('then initDataSourceSettingsSucceeded should be dispatched', async () => {
const dataSource = { type: 'app' };
const dataSourceMeta = { id: 'some id' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => {}),
getDataSource: jest.fn().mockReturnValue(dataSource),
getDataSourceMeta: jest.fn().mockReturnValue(dataSourceMeta),
importDataSourcePlugin: jest.fn().mockReturnValue({} as GenericDataSourcePlugin),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(256, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsSucceeded({} as GenericDataSourcePlugin)]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(256);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
expect(dependencies.getDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSource).toHaveBeenCalledWith({}, 256);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledWith({}, 'app');
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledTimes(1);
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledWith(dataSourceMeta);
});
});
describe('when plugin loading fails', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dataSource = { type: 'app' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn().mockImplementation(() => {
throw new Error('Error loading plugin');
}),
getDataSource: jest.fn(),
getDataSourceMeta: jest.fn(),
importDataSourcePlugin: jest.fn(),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(301, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Error loading plugin'))]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(301);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
});
});
});
describe('testDataSource', () => {
describe('when a datasource is tested', () => {
it('then testDataSourceStarting and testDataSourceSucceeded should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
type: 'cloudwatch',
uid: 'CW1234',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
status: '',
message: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('CloudWatch', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'cloudwatch',
datasource_uid: 'CW1234',
grafana_version: '1.0',
success: true,
});
});
it('then testDataSourceFailed should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw new Error('Error testing datasource');
}),
type: 'azure-monitor',
uid: 'azM0nit0R',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const result = {
message: 'Error testing datasource',
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
datasource_uid: 'azM0nit0R',
grafana_version: '1.0',
success: false,
});
});
it('then testDataSourceFailed should be dispatched with response error message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response data message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response statusText', async () => {
const result = {
message: 'HTTP error Bad Request',
};
const error: FetchError = {
config: {
url: '',
},
data: {},
statusText: 'Bad Request',
status: 400,
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
});
});
describe('addDataSource', () => {
it('it creates a datasource and calls trackDataSourceCreated ', async () => {
const meta: AppPluginMeta = {
id: 'azure-monitor',
module: '',
baseUrl: 'xxx',
info: { version: '1.2.3' } as PluginMetaInfo,
type: PluginType.datasource,
name: 'test DS',
};
const state = {
dataSources: {
dataSources: [],
},
};
const dataSourceMock = { datasource: { uid: 'azure23' }, meta };
(api.createDataSource as jest.Mock).mockResolvedValueOnce(dataSourceMock);
(api.getDataSources as jest.Mock).mockResolvedValueOnce([]);
const dispatchedActions = await thunkTester(state).givenThunk(addDataSource).whenThunkIsDispatched(meta);
expect(dispatchedActions).toEqual([dataSourcesLoaded([])]);
expect(trackDataSourceCreated).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
plugin_version: '1.2.3',
datasource_uid: 'azure23',
grafana_version: '1.0',
editLink: DATASOURCES_ROUTES.Edit.replace(':uid', 'azure23'),
});
});
});
| public/app/features/datasources/state/actions.test.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.014551939442753792,
0.0023170800413936377,
0.00016236735973507166,
0.00029614282539114356,
0.0036856848746538162
] |
{
"id": 6,
"code_window": [
" }\n",
"): ThunkResult<void> => {\n",
" return async (dispatch: ThunkDispatch, getState) => {\n",
" const dsApi = await dependencies.getDatasourceSrv().get(dataSourceName);\n",
"\n",
" if (!dsApi.testDatasource) {\n",
" return;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const editLink = editRoute.replace(/:uid/gi, dataSourceName);\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 99
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21,6a1,1,0,0,0-1,1V17a3,3,0,0,1-3,3H7a1,1,0,0,0,0,2H17a5,5,0,0,0,5-5V7A1,1,0,0,0,21,6Zm-3,9V5a3,3,0,0,0-3-3H5A3,3,0,0,0,2,5V15a3,3,0,0,0,3,3H15A3,3,0,0,0,18,15ZM10,4h2V8.86l-.36-.3a1,1,0,0,0-1.28,0l-.36.3ZM4,15V5A1,1,0,0,1,5,4H8v7a1,1,0,0,0,1.65.76L11,10.63l1.35,1.13A1,1,0,0,0,13,12a1.06,1.06,0,0,0,.42-.09A1,1,0,0,0,14,11V4h1a1,1,0,0,1,1,1V15a1,1,0,0,1-1,1H5A1,1,0,0,1,4,15Z"/></svg> | public/img/icons/unicons/notebooks.svg | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017236993880942464,
0.00017236993880942464,
0.00017236993880942464,
0.00017236993880942464,
0
] |
{
"id": 6,
"code_window": [
" }\n",
"): ThunkResult<void> => {\n",
" return async (dispatch: ThunkDispatch, getState) => {\n",
" const dsApi = await dependencies.getDatasourceSrv().get(dataSourceName);\n",
"\n",
" if (!dsApi.testDatasource) {\n",
" return;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const editLink = editRoute.replace(/:uid/gi, dataSourceName);\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 99
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M18,7h-.35A3.45,3.45,0,0,0,18,5.5a3.49,3.49,0,0,0-6-2.44A3.49,3.49,0,0,0,6,5.5,3.45,3.45,0,0,0,6.35,7H6a3,3,0,0,0-3,3v2a1,1,0,0,0,1,1H5v6a3,3,0,0,0,3,3h8a3,3,0,0,0,3-3V13h1a1,1,0,0,0,1-1V10A3,3,0,0,0,18,7ZM11,20H8a1,1,0,0,1-1-1V13h4Zm0-9H5V10A1,1,0,0,1,6,9h5Zm0-4H9.5A1.5,1.5,0,1,1,11,5.5Zm2-1.5A1.5,1.5,0,1,1,14.5,7H13ZM17,19a1,1,0,0,1-1,1H13V13h4Zm2-8H13V9h5a1,1,0,0,1,1,1Z"/></svg> | public/img/icons/unicons/gift.svg | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017055211355909705,
0.00017055211355909705,
0.00017055211355909705,
0.00017055211355909705,
0
] |
{
"id": 6,
"code_window": [
" }\n",
"): ThunkResult<void> => {\n",
" return async (dispatch: ThunkDispatch, getState) => {\n",
" const dsApi = await dependencies.getDatasourceSrv().get(dataSourceName);\n",
"\n",
" if (!dsApi.testDatasource) {\n",
" return;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const editLink = editRoute.replace(/:uid/gi, dataSourceName);\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 99
} | <mjml>
<mj-head>
<!-- ⬇ Don't forget to specifify an email subject below! ⬇ -->
<mj-title>
{{ Subject .Subject "Welcome to Grafana, please complete your sign up!" }}
</mj-title>
<mj-include path="./partials/layout/head.mjml" />
</mj-head>
<mj-body>
<mj-section>
<mj-include path="./partials/layout/header.mjml" />
</mj-section>
<mj-section background-color="#22252b" border="1px solid #2f3037">
<mj-column>
<mj-text>
<h2>Complete the signup</h2>
</mj-text>
<mj-text>
Copy and paste the email verification code in the sign up form <strong>or</strong> use the link below.
</mj-text>
<mj-button background-color="transparent" border="1px solid #44474f" color="#ccccdd" font-size="22px" font-weight="bold">
{{ .Code }}
</mj-button>
<mj-button href="{{ .SignUpUrl }}">
Complete Sign Up
</mj-button>
<mj-text>
You can also copy and paste this link into your browser directly:
</mj-text>
<mj-text>
<a rel="noopener" href="{{ .LinkUrl }}">{{ .SignUpUrl }}</a>
</mj-text>
</mj-column>
</mj-section>
<mj-section>
<mj-include path="./partials/layout/footer.mjml" />
</mj-section>
</mj-body>
</mjml>
| emails/templates/signup_started.mjml | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017690514505375177,
0.000175147972186096,
0.00017412492888979614,
0.00017478090012446046,
0.0000011083870958827902
] |
{
"id": 7,
"code_window": [
" plugin_id: dsApi.type,\n",
" datasource_uid: dsApi.uid,\n",
" success: true,\n",
" });\n",
" } catch (err) {\n",
" let message: string | undefined;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 116
} | import { DataSourcePluginMeta, DataSourceSettings, locationUtil } from '@grafana/data';
import {
config,
DataSourceWithBackend,
getDataSourceSrv,
HealthCheckError,
HealthCheckResultDetails,
isFetchError,
locationService,
} from '@grafana/runtime';
import { updateNavIndex } from 'app/core/actions';
import { contextSrv } from 'app/core/core';
import { getBackendSrv } from 'app/core/services/backend_srv';
import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
import { getPluginSettings } from 'app/features/plugins/pluginSettings';
import { importDataSourcePlugin } from 'app/features/plugins/plugin_loader';
import { DataSourcePluginCategory, ThunkDispatch, ThunkResult } from 'app/types';
import * as api from '../api';
import { DATASOURCES_ROUTES } from '../constants';
import { trackDataSourceCreated, trackDataSourceTested } from '../tracking';
import { findNewName, nameExits } from '../utils';
import { buildCategories } from './buildCategories';
import { buildNavModel } from './navModel';
import {
dataSourceLoaded,
dataSourceMetaLoaded,
dataSourcePluginsLoad,
dataSourcePluginsLoaded,
dataSourcesLoaded,
initDataSourceSettingsFailed,
initDataSourceSettingsSucceeded,
testDataSourceFailed,
testDataSourceStarting,
testDataSourceSucceeded,
} from './reducers';
import { getDataSource, getDataSourceMeta } from './selectors';
export interface DataSourceTypesLoadedPayload {
plugins: DataSourcePluginMeta[];
categories: DataSourcePluginCategory[];
}
export interface InitDataSourceSettingDependencies {
loadDataSource: typeof loadDataSource;
loadDataSourceMeta: typeof loadDataSourceMeta;
getDataSource: typeof getDataSource;
getDataSourceMeta: typeof getDataSourceMeta;
importDataSourcePlugin: typeof importDataSourcePlugin;
}
export interface TestDataSourceDependencies {
getDatasourceSrv: typeof getDataSourceSrv;
getBackendSrv: typeof getBackendSrv;
}
export const initDataSourceSettings = (
uid: string,
dependencies: InitDataSourceSettingDependencies = {
loadDataSource,
loadDataSourceMeta,
getDataSource,
getDataSourceMeta,
importDataSourcePlugin,
}
): ThunkResult<void> => {
return async (dispatch, getState) => {
if (!uid) {
dispatch(initDataSourceSettingsFailed(new Error('Invalid UID')));
return;
}
try {
const loadedDataSource = await dispatch(dependencies.loadDataSource(uid));
await dispatch(dependencies.loadDataSourceMeta(loadedDataSource));
const dataSource = dependencies.getDataSource(getState().dataSources, uid);
const dataSourceMeta = dependencies.getDataSourceMeta(getState().dataSources, dataSource!.type);
const importedPlugin = await dependencies.importDataSourcePlugin(dataSourceMeta);
dispatch(initDataSourceSettingsSucceeded(importedPlugin));
} catch (err) {
if (err instanceof Error) {
dispatch(initDataSourceSettingsFailed(err));
}
}
};
};
export const testDataSource = (
dataSourceName: string,
dependencies: TestDataSourceDependencies = {
getDatasourceSrv,
getBackendSrv,
}
): ThunkResult<void> => {
return async (dispatch: ThunkDispatch, getState) => {
const dsApi = await dependencies.getDatasourceSrv().get(dataSourceName);
if (!dsApi.testDatasource) {
return;
}
dispatch(testDataSourceStarting());
dependencies.getBackendSrv().withNoBackendCache(async () => {
try {
const result = await dsApi.testDatasource();
dispatch(testDataSourceSucceeded(result));
trackDataSourceTested({
grafana_version: config.buildInfo.version,
plugin_id: dsApi.type,
datasource_uid: dsApi.uid,
success: true,
});
} catch (err) {
let message: string | undefined;
let details: HealthCheckResultDetails;
if (err instanceof HealthCheckError) {
message = err.message;
details = err.details;
} else if (isFetchError(err)) {
message = err.data.message ?? `HTTP error ${err.statusText}`;
} else if (err instanceof Error) {
message = err.message;
}
dispatch(testDataSourceFailed({ message, details }));
trackDataSourceTested({
grafana_version: config.buildInfo.version,
plugin_id: dsApi.type,
datasource_uid: dsApi.uid,
success: false,
});
}
});
};
};
export function loadDataSources(): ThunkResult<void> {
return async (dispatch) => {
const response = await api.getDataSources();
dispatch(dataSourcesLoaded(response));
};
}
export function loadDataSource(uid: string): ThunkResult<Promise<DataSourceSettings>> {
return async (dispatch) => {
let dataSource = await api.getDataSourceByIdOrUid(uid);
// Reload route to use UID instead
// -------------------------------
// In case we were trying to fetch and reference a data-source with an old numeric ID
// (which can happen by referencing it with a "old" URL), we would like to automatically redirect
// to the new URL format using the UID.
// [Please revalidate the following]: Unfortunately we can update the location using react router, but need to fully reload the
// route as the nav model page index is not matching with the url in that case.
// And react router has no way to unmount remount a route.
if (uid !== dataSource.uid) {
window.location.href = locationUtil.assureBaseUrl(`/datasources/edit/${dataSource.uid}`);
// Avoid a flashing error while the reload happens
dataSource = {} as DataSourceSettings;
}
dispatch(dataSourceLoaded(dataSource));
return dataSource;
};
}
export function loadDataSourceMeta(dataSource: DataSourceSettings): ThunkResult<void> {
return async (dispatch) => {
const pluginInfo = (await getPluginSettings(dataSource.type)) as DataSourcePluginMeta;
const plugin = await importDataSourcePlugin(pluginInfo);
const isBackend = plugin.DataSourceClass.prototype instanceof DataSourceWithBackend;
const meta = {
...pluginInfo,
isBackend: pluginInfo.backend || isBackend,
};
dispatch(dataSourceMetaLoaded(meta));
plugin.meta = meta;
dispatch(updateNavIndex(buildNavModel(dataSource, plugin)));
};
}
export function addDataSource(plugin: DataSourcePluginMeta, editRoute = DATASOURCES_ROUTES.Edit): ThunkResult<void> {
return async (dispatch, getStore) => {
await dispatch(loadDataSources());
const dataSources = getStore().dataSources.dataSources;
const isFirstDataSource = dataSources.length === 0;
const newInstance = {
name: plugin.name,
type: plugin.id,
access: 'proxy',
isDefault: isFirstDataSource,
};
if (nameExits(dataSources, newInstance.name)) {
newInstance.name = findNewName(dataSources, newInstance.name);
}
const result = await api.createDataSource(newInstance);
const editLink = editRoute.replace(/:uid/gi, result.datasource.uid);
await getDatasourceSrv().reload();
await contextSrv.fetchUserPermissions();
trackDataSourceCreated({
grafana_version: config.buildInfo.version,
plugin_id: plugin.id,
datasource_uid: result.datasource.uid,
plugin_version: result.meta?.info?.version,
editLink,
});
locationService.push(editLink);
};
}
export function loadDataSourcePlugins(): ThunkResult<void> {
return async (dispatch) => {
dispatch(dataSourcePluginsLoad());
const plugins = await api.getDataSourcePlugins();
const categories = buildCategories(plugins);
dispatch(dataSourcePluginsLoaded({ plugins, categories }));
};
}
export function updateDataSource(dataSource: DataSourceSettings) {
return async (dispatch: (dataSourceSettings: ThunkResult<Promise<DataSourceSettings>>) => DataSourceSettings) => {
await api.updateDataSource(dataSource);
await getDatasourceSrv().reload();
return dispatch(loadDataSource(dataSource.uid));
};
}
export function deleteLoadedDataSource(): ThunkResult<void> {
return async (dispatch, getStore) => {
const { uid } = getStore().dataSources.dataSource;
await api.deleteDataSource(uid);
await getDatasourceSrv().reload();
locationService.push('/datasources');
};
}
| public/app/features/datasources/state/actions.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.9973601698875427,
0.11004883795976639,
0.00016272166976705194,
0.00016866473015397787,
0.3045175075531006
] |
{
"id": 7,
"code_window": [
" plugin_id: dsApi.type,\n",
" datasource_uid: dsApi.uid,\n",
" success: true,\n",
" });\n",
" } catch (err) {\n",
" let message: string | undefined;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 116
} | <svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M17,6c-0.6,0-1,0.4-1,1v7.6L7.7,6.3c-0.4-0.4-1-0.4-1.4,0c-0.4,0.4-0.4,1,0,1.4l8.3,8.3H7c-0.6,0-1,0.4-1,1s0.4,1,1,1h10c0.6,0,1-0.4,1-1V7C18,6.4,17.6,6,17,6z"/></svg> | public/img/icons/solid/arrow-down-right.svg | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00016971048898994923,
0.00016971048898994923,
0.00016971048898994923,
0.00016971048898994923,
0
] |
{
"id": 7,
"code_window": [
" plugin_id: dsApi.type,\n",
" datasource_uid: dsApi.uid,\n",
" success: true,\n",
" });\n",
" } catch (err) {\n",
" let message: string | undefined;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 116
} | import { Location } from 'history';
import { locationUtil, NavModelItem, NavSection } from '@grafana/data';
import { config, reportInteraction } from '@grafana/runtime';
import { t } from 'app/core/internationalization';
import { contextSrv } from 'app/core/services/context_srv';
import { ShowModalReactEvent } from '../../../types/events';
import appEvents from '../../app_events';
import { getFooterLinks } from '../Footer/Footer';
import { OrgSwitcher } from '../OrgSwitcher';
import { HelpModal } from '../help/HelpModal';
export const SEARCH_ITEM_ID = 'search';
export const NAV_MENU_PORTAL_CONTAINER_ID = 'navbar-menu-portal-container';
export const getNavMenuPortalContainer = () => document.getElementById(NAV_MENU_PORTAL_CONTAINER_ID) ?? document.body;
export const enrichConfigItems = (items: NavModelItem[], location: Location<unknown>) => {
const { isSignedIn, user } = contextSrv;
const onOpenShortcuts = () => {
appEvents.publish(new ShowModalReactEvent({ component: HelpModal }));
};
const onOpenOrgSwitcher = () => {
appEvents.publish(new ShowModalReactEvent({ component: OrgSwitcher }));
};
if (!config.featureToggles.topnav && user && user.orgCount > 1) {
const profileNode = items.find((bottomNavItem) => bottomNavItem.id === 'profile');
if (profileNode) {
profileNode.showOrgSwitcher = true;
profileNode.subTitle = `Organization: ${user?.orgName}`;
}
}
if (!isSignedIn && !config.featureToggles.topnav) {
const loginUrl = locationUtil.getUrlForPartial(location, { forceLogin: 'true' });
items.unshift({
icon: 'signout',
id: 'sign-in',
section: NavSection.Config,
target: '_self',
text: t('nav.sign-in', 'Sign in'),
url: loginUrl,
});
}
items.forEach((link) => {
let menuItems = link.children || [];
if (link.id === 'help') {
link.children = [
...menuItems,
...getFooterLinks(),
{
id: 'keyboard-shortcuts',
text: t('nav.help/keyboard-shortcuts', 'Keyboard shortcuts'),
icon: 'keyboard',
onClick: onOpenShortcuts,
},
];
}
if (!config.featureToggles.topnav && link.showOrgSwitcher) {
link.children = [
...menuItems,
{
id: 'switch-organization',
text: t('nav.profile/switch-org', 'Switch organization'),
icon: 'arrow-random',
onClick: onOpenOrgSwitcher,
},
];
}
});
return items;
};
export const enrichWithInteractionTracking = (item: NavModelItem, expandedState: boolean) => {
const onClick = item.onClick;
item.onClick = () => {
reportInteraction('grafana_navigation_item_clicked', {
path: item.url ?? item.id,
state: expandedState ? 'expanded' : 'collapsed',
});
onClick?.();
};
if (item.children) {
item.children = item.children.map((item) => enrichWithInteractionTracking(item, expandedState));
}
return item;
};
export const isMatchOrChildMatch = (itemToCheck: NavModelItem, searchItem?: NavModelItem) => {
return Boolean(itemToCheck === searchItem || hasChildMatch(itemToCheck, searchItem));
};
export const hasChildMatch = (itemToCheck: NavModelItem, searchItem?: NavModelItem): boolean => {
return Boolean(
itemToCheck.children?.some((child) => {
if (child === searchItem) {
return true;
} else {
return hasChildMatch(child, searchItem);
}
})
);
};
const stripQueryParams = (url?: string) => {
return url?.split('?')[0] ?? '';
};
const isBetterMatch = (newMatch: NavModelItem, currentMatch?: NavModelItem) => {
const currentMatchUrl = stripQueryParams(currentMatch?.url);
const newMatchUrl = stripQueryParams(newMatch.url);
return newMatchUrl && newMatchUrl.length > currentMatchUrl?.length;
};
export const getActiveItem = (
navTree: NavModelItem[],
pathname: string,
currentBestMatch?: NavModelItem
): NavModelItem | undefined => {
const dashboardLinkMatch = '/dashboards';
for (const link of navTree) {
const linkWithoutParams = stripQueryParams(link.url);
const linkPathname = locationUtil.stripBaseFromUrl(linkWithoutParams);
if (linkPathname) {
if (linkPathname === pathname) {
// exact match
currentBestMatch = link;
break;
} else if (linkPathname !== '/' && pathname.startsWith(linkPathname)) {
// partial match
if (isBetterMatch(link, currentBestMatch)) {
currentBestMatch = link;
}
} else if (linkPathname === '/alerting/list' && pathname.startsWith('/alerting/notification/')) {
// alert channel match
// TODO refactor routes such that we don't need this custom logic
currentBestMatch = link;
break;
} else if (linkPathname === dashboardLinkMatch && pathname.startsWith('/d/')) {
// dashboard match
// TODO refactor routes such that we don't need this custom logic
if (isBetterMatch(link, currentBestMatch)) {
currentBestMatch = link;
}
}
}
if (link.children) {
currentBestMatch = getActiveItem(link.children, pathname, currentBestMatch);
}
if (stripQueryParams(currentBestMatch?.url) === pathname) {
return currentBestMatch;
}
}
return currentBestMatch;
};
export const isSearchActive = (location: Location<unknown>) => {
const query = new URLSearchParams(location.search);
return query.get('search') === 'open';
};
export function getNavModelItemKey(item: NavModelItem) {
return item.id ?? item.text;
}
| public/app/core/components/NavBar/utils.ts | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0001765494089340791,
0.00017335038864985108,
0.00016740722639951855,
0.00017314855358563364,
0.000002169159870391013
] |
{
"id": 7,
"code_window": [
" plugin_id: dsApi.type,\n",
" datasource_uid: dsApi.uid,\n",
" success: true,\n",
" });\n",
" } catch (err) {\n",
" let message: string | undefined;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 116
} | import React, { useEffect, useState } from 'react';
import { LinkButton, FilterInput, VerticalGroup, HorizontalGroup, Pagination } from '@grafana/ui';
import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA';
import { Page } from 'app/core/components/Page/Page';
import { fetchRoleOptions } from 'app/core/components/RolePicker/api';
import { config } from 'app/core/config';
import { contextSrv, User } from 'app/core/services/context_srv';
import { AccessControlAction, Role, StoreState, Team } from 'app/types';
import { connectWithCleanUp } from '../../core/components/connectWithCleanUp';
import { TeamListRow } from './TeamListRow';
import { deleteTeam, loadTeams, changePage, changeQuery } from './state/actions';
import { initialTeamsState } from './state/reducers';
import { isPermissionTeamAdmin } from './state/selectors';
export interface Props {
teams: Team[];
page: number;
query: string;
noTeams: boolean;
totalPages: number;
hasFetched: boolean;
loadTeams: typeof loadTeams;
deleteTeam: typeof deleteTeam;
changePage: typeof changePage;
changeQuery: typeof changeQuery;
editorsCanAdmin: boolean;
signedInUser: User;
}
export interface State {
roleOptions: Role[];
}
export const TeamList = ({
teams,
page,
query,
noTeams,
totalPages,
hasFetched,
loadTeams,
deleteTeam,
changeQuery,
changePage,
signedInUser,
editorsCanAdmin,
}: Props) => {
const [roleOptions, setRoleOptions] = useState<Role[]>([]);
useEffect(() => {
loadTeams(true);
}, [loadTeams]);
useEffect(() => {
if (contextSrv.licensedAccessControlEnabled() && contextSrv.hasPermission(AccessControlAction.ActionRolesList)) {
fetchRoleOptions().then((roles) => setRoleOptions(roles));
}
}, []);
const canCreate = canCreateTeam(editorsCanAdmin);
const displayRolePicker = shouldDisplayRolePicker();
return (
<Page navId="teams">
<Page.Contents isLoading={!hasFetched}>
{noTeams ? (
<EmptyListCTA
title="You haven't created any teams yet."
buttonIcon="users-alt"
buttonLink="org/teams/new"
buttonTitle=" New team"
buttonDisabled={!contextSrv.hasPermission(AccessControlAction.ActionTeamsCreate)}
proTip="Assign folder and dashboard permissions to teams instead of users to ease administration."
proTipLink=""
proTipLinkTitle=""
proTipTarget="_blank"
/>
) : (
<>
<div className="page-action-bar">
<div className="gf-form gf-form--grow">
<FilterInput placeholder="Search teams" value={query} onChange={changeQuery} />
</div>
<LinkButton href={canCreate ? 'org/teams/new' : '#'} disabled={!canCreate}>
New Team
</LinkButton>
</div>
<div className="admin-list-table">
<VerticalGroup spacing="md">
<table className="filter-table filter-table--hover form-inline">
<thead>
<tr>
<th />
<th>Name</th>
<th>Email</th>
<th>Members</th>
{displayRolePicker && <th>Roles</th>}
<th style={{ width: '1%' }} />
</tr>
</thead>
<tbody>
{teams.map((team) => (
<TeamListRow
key={team.id}
team={team}
roleOptions={roleOptions}
displayRolePicker={displayRolePicker}
isTeamAdmin={isPermissionTeamAdmin({
permission: team.permission,
editorsCanAdmin,
signedInUser,
})}
onDelete={deleteTeam}
/>
))}
</tbody>
</table>
<HorizontalGroup justify="flex-end">
<Pagination
hideWhenSinglePage
currentPage={page}
numberOfPages={totalPages}
onNavigate={changePage}
/>
</HorizontalGroup>
</VerticalGroup>
</div>
</>
)}
</Page.Contents>
</Page>
);
};
function canCreateTeam(editorsCanAdmin: boolean): boolean {
const teamAdmin = contextSrv.hasRole('Admin') || (editorsCanAdmin && contextSrv.hasRole('Editor'));
return contextSrv.hasAccess(AccessControlAction.ActionTeamsCreate, teamAdmin);
}
function shouldDisplayRolePicker(): boolean {
return (
contextSrv.licensedAccessControlEnabled() &&
contextSrv.hasPermission(AccessControlAction.ActionTeamsRolesList) &&
contextSrv.hasPermission(AccessControlAction.ActionRolesList)
);
}
function mapStateToProps(state: StoreState) {
return {
teams: state.teams.teams,
page: state.teams.page,
query: state.teams.query,
perPage: state.teams.perPage,
noTeams: state.teams.noTeams,
totalPages: state.teams.totalPages,
hasFetched: state.teams.hasFetched,
editorsCanAdmin: config.editorsCanAdmin, // this makes the feature toggle mockable/controllable from tests,
signedInUser: contextSrv.user, // this makes the feature toggle mockable/controllable from tests,
};
}
const mapDispatchToProps = {
loadTeams,
deleteTeam,
changePage,
changeQuery,
};
export default connectWithCleanUp(
mapStateToProps,
mapDispatchToProps,
(state) => (state.teams = initialTeamsState)
)(TeamList);
| public/app/features/teams/TeamList.tsx | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00023439625510945916,
0.00017631781520321965,
0.00016875425353646278,
0.0001725372567307204,
0.000014254059351515025
] |
{
"id": 8,
"code_window": [
" trackDataSourceTested({\n",
" grafana_version: config.buildInfo.version,\n",
" plugin_id: dsApi.type,\n",
" datasource_uid: dsApi.uid,\n",
" success: false,\n",
" });\n",
" }\n",
" });\n",
" };\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 136
} | import { reportInteraction } from '@grafana/runtime';
/**
* Used to track data source creation via either the specific plugin page `/plugins/<the-data-source>`
* or the general datasources page `/datasources/new`
*
* This event corresponds to the start event of our data source creation funnel.
* Combined with the end event, it allows answering questions about:
* - Conversion (percentage of user that successfully set up a data source)
* - Time spent on the config page
*
* Changelog:
* - v9.1.7 : logging datasource, datasource_uid, grafana version
*/
export const trackDataSourceCreated = (props: DataSourceCreatedProps) => {
reportInteraction('grafana_ds_add_datasource_clicked', props);
};
type DataSourceCreatedProps = {
grafana_version?: string;
/** The unique id of the newly created data source */
datasource_uid: string;
/** The datasource id (e.g. Cloudwatch, Loki, Prometheus) */
plugin_id: string;
/** The plugin version (especially interesting in external plugins - core plugins are aligned with grafana version) */
plugin_version?: string;
/** The URL that points to the edit page for the datasoruce. We are using this to be able to distinguish between the performance of different datasource edit locations. */
editLink?: string;
};
/**
* Used to track data source testing
*
* This event corresponds to the end event of our data source creation funnel.
* Combined with the start event, it allows answering questions about:
* - Conversion (percentage of user that successfully set up a data source)
* - Time spent on the config page
*
* Changelog:
* - v9.1.7 : logging datasource, datasource_uid, grafana version and success
*/
export const trackDataSourceTested = (props: DataSourceTestedProps) => {
reportInteraction('grafana_ds_test_datasource_clicked', props);
};
type DataSourceTestedProps = {
grafana_version?: string;
/** The unique id of the newly created data source */
datasource_uid: string;
/** The datasource id (e.g. Cloudwatch, Loki, Prometheus) */
plugin_id: string;
/** The plugin version (especially interesting in external plugins - core plugins are aligned with grafana version) */
plugin_version?: string;
/** Whether or not the datasource test succeeded = the datasource was successfully configured */
success: boolean;
};
| public/app/features/datasources/tracking.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.01199441496282816,
0.0025604600086808205,
0.0001627458696020767,
0.0002964253071695566,
0.0042963214218616486
] |
{
"id": 8,
"code_window": [
" trackDataSourceTested({\n",
" grafana_version: config.buildInfo.version,\n",
" plugin_id: dsApi.type,\n",
" datasource_uid: dsApi.uid,\n",
" success: false,\n",
" });\n",
" }\n",
" });\n",
" };\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 136
} | package store
import (
"fmt"
"sync"
"github.com/grafana/grafana/pkg/infra/filestorage"
ac "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/user"
)
type SystemUserType string
// SystemUsersFilterProvider interface internal to `pkg/store` service.
// Used by the Storage service to retrieve path filter for system users
type SystemUsersFilterProvider interface {
GetFilter(user *user.SignedInUser) (map[string]filestorage.PathFilter, error)
}
// SystemUsersProvider interface used by `pkg/store` clients
// Used by Grafana services to retrieve users having access only to their own slice of storage
// For example, service 'Dashboard' could have exclusive access to paths matching `system/dashboard/*`
// by creating a system user with appropriate permissions.
type SystemUsersProvider interface {
GetUser(userType SystemUserType, orgID int64) (*user.SignedInUser, error)
}
//go:generate mockery --name SystemUsers --structname FakeSystemUsers --inpackage --filename system_users_mock.go
type SystemUsers interface {
SystemUsersFilterProvider
SystemUsersProvider
// RegisterUser extension point - allows other Grafana services to register their own user type and assign them path-based permissions
RegisterUser(userType SystemUserType, filterFn func() map[string]filestorage.PathFilter)
}
func ProvideSystemUsersService() SystemUsers {
return &hardcodedSystemUsers{
mutex: sync.RWMutex{},
users: make(map[SystemUserType]map[int64]*user.SignedInUser),
createFilterByUser: make(map[*user.SignedInUser]func() map[string]filestorage.PathFilter),
}
}
type hardcodedSystemUsers struct {
mutex sync.RWMutex
// map of user type -> map of user per orgID
users map[SystemUserType]map[int64]*user.SignedInUser
// map of user -> create filter function. all users of the same type will point to the same function
createFilterByUser map[*user.SignedInUser]func() map[string]filestorage.PathFilter
}
func (h *hardcodedSystemUsers) GetFilter(user *user.SignedInUser) (map[string]filestorage.PathFilter, error) {
h.mutex.Lock()
defer h.mutex.Unlock()
createFn, ok := h.createFilterByUser[user]
if !ok {
return nil, fmt.Errorf("user %s with id %d has not been initialized", user.Login, user.UserID)
}
return createFn(), nil
}
func (h *hardcodedSystemUsers) GetUser(userType SystemUserType, orgID int64) (*user.SignedInUser, error) {
h.mutex.Lock()
defer h.mutex.Unlock()
userPerOrgIdMap, ok := h.users[userType]
if !ok {
return nil, fmt.Errorf("user type %s is unknown", userType)
}
orgSignedInUser, ok := userPerOrgIdMap[orgID]
if ok {
return orgSignedInUser, nil
}
// user for the given org does not yet exist - initialize it
globalUser, globalUserExists := userPerOrgIdMap[ac.GlobalOrgID]
if !globalUserExists {
return nil, fmt.Errorf("initialization error: user type %s should exist for global org id: %d", userType, ac.GlobalOrgID)
}
globalUserFn, globalUserFnExists := h.createFilterByUser[globalUser]
if !globalUserFnExists {
return nil, fmt.Errorf("initialization error: user type %s should be associated with a create filter function", userType)
}
newUser := &user.SignedInUser{
Login: string(userType),
OrgID: orgID,
}
userPerOrgIdMap[orgID] = newUser
h.createFilterByUser[newUser] = globalUserFn
return newUser, nil
}
func (h *hardcodedSystemUsers) RegisterUser(userType SystemUserType, filterFn func() map[string]filestorage.PathFilter) {
h.mutex.Lock()
defer h.mutex.Unlock()
globalUser := &user.SignedInUser{OrgID: ac.GlobalOrgID, Login: string(userType)}
h.users[userType] = map[int64]*user.SignedInUser{ac.GlobalOrgID: globalUser}
h.createFilterByUser[globalUser] = filterFn
}
| pkg/services/store/system_users.go | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0005024894489906728,
0.00019828877702821046,
0.00016567125567235053,
0.0001706882903818041,
0.00009180279448628426
] |
{
"id": 8,
"code_window": [
" trackDataSourceTested({\n",
" grafana_version: config.buildInfo.version,\n",
" plugin_id: dsApi.type,\n",
" datasource_uid: dsApi.uid,\n",
" success: false,\n",
" });\n",
" }\n",
" });\n",
" };\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 136
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="64px" height="64px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#E3E3E3;}
</style>
<g>
<path class="st0" d="M49.4,45.1L62,16.6l-5.8-2.6l0.8-3l-8.6-2.4v-5H43l-0.2-1.4l-9,1.4h-1.1L24.2,0l-0.8,1.8l-6.2-1.7l-1,3.6H7.2
v4.1L2,8.6l4.6,29.9l-1,3.6l-2.3,5.2l0.8,0.3L3.5,50l3.7,1v4.4h35.7l-19,0.2l16.9,4.7l-18-4.7L9.3,55.8l0.6,4l15.9-2.5L41.1,64
l1.4-3.2l0.7,0.2l1.4-5l0.2-0.5h3.6v-1.7l2.3-0.3L49.4,45.1z M48.4,31.2v-12l0.1-0.3c0.2-0.6,0.1-1.2-0.1-1.7v-5.5l5,1.4L48.4,31.2
z M58.1,18.1l-8.2,18.7l5.5-19.9L58.1,18.1z M19.3,3.7L19.3,3.7L19.3,3.7L19.3,3.7z M10.1,6.6h35.4V43H10.1V6.6z M7.2,10.7V23
L5.4,11L7.2,10.7z"/>
<polygon class="st0" points="19.3,3.7 19.3,3.7 19.3,3.7 "/>
<path class="st0" d="M14.4,21.9c0,0.9,0.7,1.7,1.7,1.7h8.4c0.9,0,1.7-0.7,1.7-1.7v-8.4c0-0.9-0.7-1.7-1.7-1.7h-8.4
c-0.9,0-1.7,0.7-1.7,1.7V21.9z"/>
<path class="st0" d="M39.6,26.6h-8.4c-0.9,0-1.7,0.7-1.7,1.7v8.4c0,0.9,0.7,1.7,1.7,1.7h8.4c0.9,0,1.7-0.7,1.7-1.7v-8.4
C41.2,27.4,40.5,26.6,39.6,26.6z"/>
<path class="st0" d="M31.2,11.8c-0.9,0-1.7,0.7-1.7,1.7v8.4c0,0.9,0.7,1.7,1.7,1.7h8.4c0.9,0,1.7-0.7,1.7-1.7v-8.4
c0-0.9-0.7-1.7-1.7-1.7H31.2z"/>
<path class="st0" d="M16.1,26.6c-0.9,0-1.7,0.7-1.7,1.7v8.4c0,0.9,0.7,1.7,1.7,1.7h8.4c0.9,0,1.7-0.7,1.7-1.7v-8.4
c0-0.9-0.7-1.7-1.7-1.7H16.1z"/>
</g>
</svg>
| public/img/icons_dark_theme/icon_snapshots.svg | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0001739074068609625,
0.0001678439584793523,
0.00016463114297948778,
0.00016499336925335228,
0.000004290044671506621
] |
{
"id": 8,
"code_window": [
" trackDataSourceTested({\n",
" grafana_version: config.buildInfo.version,\n",
" plugin_id: dsApi.type,\n",
" datasource_uid: dsApi.uid,\n",
" success: false,\n",
" });\n",
" }\n",
" });\n",
" };\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" editLink,\n"
],
"file_path": "public/app/features/datasources/state/actions.ts",
"type": "add",
"edit_start_line_idx": 136
} | ---
aliases:
- ../basics/timeseries-dimensions/
- ../getting-started/timeseries-dimensions/
- ../guides/timeseries-dimensions/
- /docs/rafana/latest/fundamentals/timeseries-dimensions/
description: time series dimensions
keywords:
- grafana
- intro
- guide
- concepts
- timeseries
- labels
title: Time series dimensions
weight: 600
---
# Time series dimensions
In [Introduction to time series]({{< relref "timeseries/#time-series-databases" >}}), the concept of _labels_, also called _tags_, is introduced:
> Another feature of a TSDB is the ability to filter measurements using _tags_. Each data point is labeled with a tag that adds context information, such as where the measurement was taken.
With time series data, the data often contain more than a single series, and is a set of multiple time series. Many Grafana data sources support this type of data.
{{< figure src="/static/img/docs/example_graph_multi_dim.png" class="docs-image--no-shadow" max-width="850px" >}}
The common case is issuing a single query for a measurement with one or more additional properties as dimensions. For example, querying a temperature measurement along with a location property. In this case, multiple series are returned back from that single query and each series has unique location as a dimension.
To identify unique series within a set of time series, Grafana stores dimensions in _labels_.
## Labels
Each time series in Grafana optionally has labels. Labels are a set of key/value pairs for identifying dimensions. Example labels could be `{location=us}` or `{country=us,state=ma,city=boston}`. Within a set of time series, the combination of its name and labels identifies each series. For example, `temperature {country=us,state=ma,city=boston}` could identify the series of temperature values for the city of Boston in the US.
Different sources of time series data have dimensions stored natively, or common storage patterns that allow the data to be extracted into dimensions.
Time series databases (TSDBs) usually natively support dimensionality. Prometheus also stores dimensions in _labels_. In TSDBs such as Graphite or OpenTSDB the term _tags_ is used instead.
In table databases such SQL, these dimensions are generally the `GROUP BY` parameters of a query.
## Multiple dimensions in table format
In SQL or SQL-like databases that return table responses, additional dimensions are usually represented as columns in the query response table.
### Single dimension
For example, consider a query like:
```sql
SELECT BUCKET(StartTime, 1h), AVG(Temperature) AS Temp, Location FROM T
GROUP BY BUCKET(StartTime, 1h), Location
ORDER BY time asc
```
This query would return a table with three columns with data types time, number, and string respectively:
| StartTime | Temp | Location |
| --------- | ---- | -------- |
| 09:00 | 24 | LGA |
| 09:00 | 20 | BOS |
| 10:00 | 26 | LGA |
| 10:00 | 22 | BOS |
The table format is a _long_ formatted time series, also called _tall_. It has repeated time stamps, and repeated values in Location. In this case, we have two time series in the set that would be identified as `Temp {Location=LGA}` and `Temp {Location=BOS}`.
Individual time series from the set are extracted by using the time typed column `StartTime` as the time index of the time series, the numeric typed column `Temp` as the series name, and the name and values of the string typed `Location` column to build the labels, such as Location=LGA.
### Multiple dimensions
If the query is updated to select and group by more than just one string column, for example, `GROUP BY BUCKET(StartTime, 1h), Location, Sensor`, then an additional dimension is added:
| StartTime | Temp | Location | Sensor |
| --------- | ---- | -------- | ------ |
| 09:00 | 24 | LGA | A |
| 09:00 | 24.1 | LGA | B |
| 09:00 | 20 | BOS | A |
| 09:00 | 20.2 | BOS | B |
| 10:00 | 26 | LGA | A |
| 10:00 | 26.1 | LGA | B |
| 10:00 | 22 | BOS | A |
| 10:00 | 22.2 | BOS | B |
In this case the labels that represent the dimensions will have two keys based on the two string typed columns `Location` and `Sensor`. This data results four series: `Temp {Location=LGA,Sensor=A}`, `Temp {Location=LGA,Sensor=B}`, `Temp {Location=BOS,Sensor=A}`, and `Temp {Location=BOS,Sensor=B}`.
> **Note:** More than one dimension is currently only supported in the Logs queries within the Azure Monitor service as of version 7.1.
> **Note:** Multiple dimensions are not supported in a way that maps to multiple alerts in Grafana, but rather they are treated as multiple conditions to a single alert. For more information, see See the documentation on [creating alerts with multiple series]({{< relref "../../alerting/alerting-rules/create-grafana-managed-rule/#single-and-multi-dimensional-rule" >}}).
### Multiple values
In the case of SQL-like data sources, more than one numeric column can be selected, with or without additional string columns to be used as dimensions. For example, `AVG(Temperature) AS AvgTemp, MAX(Temperature) AS MaxTemp`. This, if combined with multiple dimensions, can result in a lot of series. Selecting multiple values is currently only designed to be used with visualization.
Additional technical information on tabular time series formats and how dimensions are extracted can be found in [the developer documentation on data frames as time series]({{< relref "../../developers/plugins/data-frames/#data-frames-as-time-series" >}}).
| docs/sources/fundamentals/timeseries-dimensions/index.md | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0001779713638825342,
0.0001696390681900084,
0.0001639922265894711,
0.00016824653721414506,
0.000004711729616246885
] |
{
"id": 9,
"code_window": [
"};\n",
"\n",
"export const useTestDataSource = (uid: string) => {\n",
" const dispatch = useDispatch();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" const dataSourcesRoutes = useDataSourcesRoutes();\n"
],
"file_path": "public/app/features/datasources/state/hooks.ts",
"type": "add",
"edit_start_line_idx": 45
} | import { thunkTester } from 'test/core/thunk/thunkTester';
import { AppPluginMeta, DataSourceSettings, PluginMetaInfo, PluginType } from '@grafana/data';
import { FetchError } from '@grafana/runtime';
import { ThunkResult, ThunkDispatch } from 'app/types';
import { getMockDataSource } from '../__mocks__';
import * as api from '../api';
import { DATASOURCES_ROUTES } from '../constants';
import { trackDataSourceCreated, trackDataSourceTested } from '../tracking';
import { GenericDataSourcePlugin } from '../types';
import {
InitDataSourceSettingDependencies,
testDataSource,
TestDataSourceDependencies,
initDataSourceSettings,
loadDataSource,
addDataSource,
} from './actions';
import {
initDataSourceSettingsSucceeded,
initDataSourceSettingsFailed,
testDataSourceStarting,
testDataSourceSucceeded,
testDataSourceFailed,
dataSourceLoaded,
dataSourcesLoaded,
} from './reducers';
jest.mock('../api');
jest.mock('app/core/services/backend_srv');
jest.mock('app/core/core');
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as unknown as object),
getDataSourceSrv: jest.fn().mockReturnValue({ reload: jest.fn() }),
getBackendSrv: jest.fn().mockReturnValue({ get: jest.fn() }),
}));
jest.mock('../tracking', () => ({
trackDataSourceCreated: jest.fn(),
trackDataSourceTested: jest.fn(),
}));
const getBackendSrvMock = () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
}),
withNoBackendCache: jest.fn().mockImplementationOnce((cb) => cb()),
} as any);
const failDataSourceTest = async (error: object) => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw error;
}),
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
return dispatchedActions;
};
describe('loadDataSource()', () => {
it('should resolve to a data-source if a UID was used for fetching', async () => {
const dataSourceMock = getMockDataSource();
const dispatch = jest.fn();
const getState = jest.fn();
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
const dataSource = await loadDataSource(dataSourceMock.uid)(dispatch, getState, undefined);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded(dataSource));
expect(dataSource).toBe(dataSourceMock);
});
it('should resolve to an empty data-source if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
const dataSource = await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(dataSource).toEqual({});
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded({} as DataSourceSettings));
});
it('should redirect to a URL which uses the UID if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(window.location.href).toBe(`/datasources/edit/${uid}`);
});
});
describe('initDataSourceSettings', () => {
describe('when pageId is missing', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dispatchedActions = await thunkTester({}).givenThunk(initDataSourceSettings).whenThunkIsDispatched('');
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Invalid UID'))]);
});
});
describe('when pageId is a valid', () => {
it('then initDataSourceSettingsSucceeded should be dispatched', async () => {
const dataSource = { type: 'app' };
const dataSourceMeta = { id: 'some id' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => {}),
getDataSource: jest.fn().mockReturnValue(dataSource),
getDataSourceMeta: jest.fn().mockReturnValue(dataSourceMeta),
importDataSourcePlugin: jest.fn().mockReturnValue({} as GenericDataSourcePlugin),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(256, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsSucceeded({} as GenericDataSourcePlugin)]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(256);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
expect(dependencies.getDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSource).toHaveBeenCalledWith({}, 256);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledWith({}, 'app');
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledTimes(1);
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledWith(dataSourceMeta);
});
});
describe('when plugin loading fails', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dataSource = { type: 'app' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn().mockImplementation(() => {
throw new Error('Error loading plugin');
}),
getDataSource: jest.fn(),
getDataSourceMeta: jest.fn(),
importDataSourcePlugin: jest.fn(),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(301, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Error loading plugin'))]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(301);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
});
});
});
describe('testDataSource', () => {
describe('when a datasource is tested', () => {
it('then testDataSourceStarting and testDataSourceSucceeded should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
type: 'cloudwatch',
uid: 'CW1234',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
status: '',
message: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('CloudWatch', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'cloudwatch',
datasource_uid: 'CW1234',
grafana_version: '1.0',
success: true,
});
});
it('then testDataSourceFailed should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw new Error('Error testing datasource');
}),
type: 'azure-monitor',
uid: 'azM0nit0R',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const result = {
message: 'Error testing datasource',
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
datasource_uid: 'azM0nit0R',
grafana_version: '1.0',
success: false,
});
});
it('then testDataSourceFailed should be dispatched with response error message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response data message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response statusText', async () => {
const result = {
message: 'HTTP error Bad Request',
};
const error: FetchError = {
config: {
url: '',
},
data: {},
statusText: 'Bad Request',
status: 400,
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
});
});
describe('addDataSource', () => {
it('it creates a datasource and calls trackDataSourceCreated ', async () => {
const meta: AppPluginMeta = {
id: 'azure-monitor',
module: '',
baseUrl: 'xxx',
info: { version: '1.2.3' } as PluginMetaInfo,
type: PluginType.datasource,
name: 'test DS',
};
const state = {
dataSources: {
dataSources: [],
},
};
const dataSourceMock = { datasource: { uid: 'azure23' }, meta };
(api.createDataSource as jest.Mock).mockResolvedValueOnce(dataSourceMock);
(api.getDataSources as jest.Mock).mockResolvedValueOnce([]);
const dispatchedActions = await thunkTester(state).givenThunk(addDataSource).whenThunkIsDispatched(meta);
expect(dispatchedActions).toEqual([dataSourcesLoaded([])]);
expect(trackDataSourceCreated).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
plugin_version: '1.2.3',
datasource_uid: 'azure23',
grafana_version: '1.0',
editLink: DATASOURCES_ROUTES.Edit.replace(':uid', 'azure23'),
});
});
});
| public/app/features/datasources/state/actions.test.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.9968553781509399,
0.1900005340576172,
0.00016422380576841533,
0.00029522046679630876,
0.37698501348495483
] |
{
"id": 9,
"code_window": [
"};\n",
"\n",
"export const useTestDataSource = (uid: string) => {\n",
" const dispatch = useDispatch();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" const dataSourcesRoutes = useDataSourcesRoutes();\n"
],
"file_path": "public/app/features/datasources/state/hooks.ts",
"type": "add",
"edit_start_line_idx": 45
} | import { act, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { LoadingState } from '@grafana/data';
import { setupMockedDataSource } from '../__mocks__/CloudWatchDataSource';
import { RequestMock } from '../__mocks__/Request';
import { validLogsQuery } from '../__mocks__/queries';
import { CloudWatchLogsQuery } from '../types';
import { CloudWatchLink } from './CloudWatchLink';
describe('CloudWatchLink', () => {
it('generates a link with log group names', async () => {
const ds = setupMockedDataSource();
const { rerender } = render(
<CloudWatchLink query={validLogsQuery} datasource={ds.datasource} panelData={undefined} />
);
await waitFor(() => {
expect(screen.getByText('CloudWatch Logs Insights').closest('a')).toHaveAttribute('href', '');
});
await act(async () => {
rerender(
<CloudWatchLink
query={validLogsQuery}
datasource={ds.datasource}
panelData={{
timeRange: RequestMock.range,
request: RequestMock,
state: LoadingState.Done,
series: [],
}}
/>
);
});
await waitFor(() => {
expect(screen.getByText('CloudWatch Logs Insights').closest('a')).toHaveAttribute(
'href',
"https://us-east-2.console.aws.amazon.com/cloudwatch/home?region=us-east-2#logs-insights:queryDetail=~(end~'2016-12-31T16*3a00*3a00.000Z~start~'2016-12-31T15*3a00*3a00.000Z~timeType~'ABSOLUTE~tz~'UTC~editorString~'fields*20*40timestamp*2c*20*40message*20*7c*20sort*20*40timestamp*20desc*20*7c*20limit*2025~isLiveTail~false~source~(~'group-A~'group-B))"
);
});
});
it('generates a link with log group names', async () => {
const ds = setupMockedDataSource();
const query: CloudWatchLogsQuery = {
...validLogsQuery,
logGroupNames: undefined,
logGroups: [
{ arn: 'arn:aws:logs:us-east-1:111111111111:log-group:/aws/lambda/test1', name: '/aws/lambda/test1' },
{ arn: 'arn:aws:logs:us-east-1:111111111111:log-group:/aws/lambda/test2', name: '/aws/lambda/test2' },
],
};
const { rerender } = render(<CloudWatchLink query={query} datasource={ds.datasource} panelData={undefined} />);
await waitFor(() => {
expect(screen.getByText('CloudWatch Logs Insights').closest('a')).toHaveAttribute('href', '');
});
await act(async () => {
rerender(
<CloudWatchLink
query={query}
datasource={ds.datasource}
panelData={{
timeRange: RequestMock.range,
request: RequestMock,
state: LoadingState.Done,
series: [],
}}
/>
);
});
await waitFor(() => {
expect(screen.getByText('CloudWatch Logs Insights').closest('a')).toHaveAttribute(
'href',
"https://us-east-2.console.aws.amazon.com/cloudwatch/home?region=us-east-2#logs-insights:queryDetail=~(end~'2016-12-31T16*3a00*3a00.000Z~start~'2016-12-31T15*3a00*3a00.000Z~timeType~'ABSOLUTE~tz~'UTC~editorString~'fields*20*40timestamp*2c*20*40message*20*7c*20sort*20*40timestamp*20desc*20*7c*20limit*2025~isLiveTail~false~source~(~'arn*3aaws*3alogs*3aus-east-1*3a111111111111*3alog-group*3a*2faws*2flambda*2ftest1~'arn*3aaws*3alogs*3aus-east-1*3a111111111111*3alog-group*3a*2faws*2flambda*2ftest2))"
);
});
});
});
| public/app/plugins/datasource/cloudwatch/components/CloudWatchLink.test.tsx | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00019832918769679964,
0.00017616056720726192,
0.00016731912910472602,
0.00017093209316954017,
0.000011677607290039305
] |
{
"id": 9,
"code_window": [
"};\n",
"\n",
"export const useTestDataSource = (uid: string) => {\n",
" const dispatch = useDispatch();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" const dataSourcesRoutes = useDataSourcesRoutes();\n"
],
"file_path": "public/app/features/datasources/state/hooks.ts",
"type": "add",
"edit_start_line_idx": 45
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="100px" height="100px" viewBox="692 0 100 100" style="enable-background:new 692 0 100 100;" xml:space="preserve">
<style type="text/css">
.st0{fill:#787878;}
</style>
<g>
<path class="st0" d="M780.9,44.8c-3.2,0-5.9,2.1-6.7,5h-18.6c-0.2-1.6-0.6-3.1-1.2-4.6l12.5-7.2c1.5,1.6,3.6,2.5,5.9,2.5
c4.5,0,8.2-3.7,8.2-8.2s-3.7-8.2-8.2-8.2s-8.2,3.7-8.2,8.2c0,0.8,0.1,1.5,0.3,2.3l-12.5,7.2c-0.9-1.3-2.1-2.4-3.3-3.3l2.3-4.1
c0.8,0.2,1.5,0.3,2.4,0.3c4.6,0,8.4-3.8,8.4-8.4s-3.8-8.4-8.4-8.4c-4.6,0-8.4,3.8-8.4,8.4c0,2.4,1,4.6,2.6,6.1l-2.3,4
c-1.4-0.6-3-1-4.6-1.2V12c2.4-0.8,4.2-3.1,4.2-5.8c0-3.4-2.8-6.2-6.2-6.2c-3.4,0-6.2,2.8-6.2,6.2c0,2.7,1.8,5,4.2,5.8v23.3
c-1.6,0.2-3.1,0.6-4.6,1.2l-8.3-14.3c1.1-1.2,1.8-2.8,1.8-4.6c0-3.8-3.1-6.8-6.8-6.8c-3.7,0-6.8,3.1-6.8,6.8s3.1,6.8,6.8,6.8
c0.5,0,1-0.1,1.5-0.2l8.2,14.3c-1.3,1-2.4,2.1-3.4,3.4l-14.3-8.2c0.1-0.5,0.2-1,0.2-1.6c0-3.8-3.1-6.8-6.8-6.8
c-3.7,0-6.8,3.1-6.8,6.8c0,3.8,3.1,6.8,6.8,6.8c1.8,0,3.4-0.7,4.6-1.8l14.3,8.2c-0.6,1.4-1,2.9-1.2,4.5h-5.6
c-0.9-4.1-4.6-7.3-9-7.3c-5.1,0-9.2,4.1-9.2,9.2s4.1,9.2,9.2,9.2c4.4,0,8.1-3.1,9-7.2h5.6c0.2,1.6,0.6,3.1,1.2,4.6l-15.3,8.8
c-1.3-1.3-3.1-2.1-5.1-2.1c-4,0-7.3,3.3-7.3,7.3c0,4,3.3,7.3,7.3,7.3c4,0,7.3-3.3,7.3-7.3c0-0.6-0.1-1.2-0.2-1.8l15.3-8.8
c1,1.3,2.1,2.4,3.4,3.4L717.2,86c-0.5-0.1-1.1-0.2-1.7-0.2c-3.9,0-7.1,3.2-7.1,7.1c0,3.9,3.2,7.1,7.1,7.1s7.1-3.2,7.1-7.1
c0-1.9-0.8-3.7-2-5l11.9-20.7c1.4,0.6,2.9,1,4.5,1.2V74c-3.6,0.9-6.2,4.1-6.2,8c0,4.5,3.7,8.2,8.2,8.2s8.2-3.7,8.2-8.2
c0-3.8-2.7-7.1-6.2-8v-5.6c1.6-0.2,3.1-0.6,4.6-1.2l9.8,17c-1.3,1.3-2.1,3.1-2.1,5.1c0,4,3.3,7.3,7.3,7.3c4,0,7.3-3.3,7.3-7.3
s-3.3-7.3-7.3-7.3c-0.6,0-1.2,0.1-1.8,0.2L749,65.2c1.3-0.9,2.4-2,3.3-3.3l1.8,1c-0.3,0.9-0.5,1.9-0.5,2.9c0,5.3,4.3,9.6,9.6,9.6
s9.6-4.3,9.6-9.6c0-5.3-4.3-9.6-9.6-9.6c-2.8,0-5.3,1.2-7.1,3.2l-1.8-1c0.6-1.4,1-3,1.2-4.6h18.6c0.9,2.9,3.6,5,6.7,5
c3.9,0,7-3.1,7-7C788,48,784.8,44.8,780.9,44.8z M780.9,55.7c-2.1,0-3.8-1.7-3.8-3.8c0-2.1,1.7-3.8,3.8-3.8c2.1,0,3.8,1.7,3.8,3.8
C784.8,54,783.1,55.7,780.9,55.7z M739.1,64.6c-7,0-12.7-5.7-12.7-12.7s5.7-12.7,12.7-12.7s12.7,5.7,12.7,12.7
S746.1,64.6,739.1,64.6z M767.7,32.4c0-2.8,2.3-5,5-5c2.8,0,5,2.3,5,5s-2.3,5-5,5C770,37.4,767.7,35.2,767.7,32.4z M759,26.4
c0,2.9-2.4,5.3-5.3,5.3c-2.9,0-5.3-2.4-5.3-5.3s2.4-5.3,5.3-5.3C756.6,21.1,759,23.5,759,26.4z M736,6.2c0-1.7,1.3-3,3-3
c1.7,0,3,1.3,3,3c0,1.7-1.3,3-3,3C737.4,9.2,736,7.8,736,6.2z M715.6,17.6c0-2,1.6-3.6,3.6-3.6c2,0,3.6,1.6,3.6,3.6
c0,2-1.6,3.6-3.6,3.6C717.3,21.3,715.6,19.6,715.6,17.6z M704.8,35.7c-2,0-3.6-1.6-3.6-3.6c0-2,1.6-3.6,3.6-3.6s3.6,1.6,3.6,3.6
C708.5,34.1,706.8,35.7,704.8,35.7z M707.9,57.8c-3.3,0-6-2.7-6-6c0-3.3,2.7-6,6-6c3.3,0,6,2.7,6,6
C713.9,55.1,711.2,57.8,707.9,57.8z M707.5,72.4c0,2.3-1.9,4.1-4.1,4.1s-4.1-1.9-4.1-4.1c0-2.3,1.9-4.1,4.1-4.1
S707.5,70.2,707.5,72.4z M719.4,92.9c0,2.2-1.8,3.9-3.9,3.9c-2.2,0-3.9-1.8-3.9-3.9s1.8-3.9,3.9-3.9
C717.7,88.9,719.4,90.7,719.4,92.9z M739.1,87c-2.8,0-5-2.3-5-5s2.3-5,5-5c2.8,0,5,2.3,5,5S741.8,87,739.1,87z M764.8,89.3
c0,2.3-1.9,4.1-4.1,4.1c-2.3,0-4.1-1.9-4.1-4.1s1.9-4.1,4.1-4.1C762.9,85.2,764.8,87,764.8,89.3z M763.2,59.5
c3.5,0,6.4,2.9,6.4,6.4s-2.9,6.4-6.4,6.4c-3.5,0-6.4-2.9-6.4-6.4S759.7,59.5,763.2,59.5z"/>
</g>
</svg>
| public/img/icn-app.svg | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0005980397691018879,
0.00028818956343457103,
0.000167438032804057,
0.00019364025502000004,
0.00017989565094467252
] |
{
"id": 9,
"code_window": [
"};\n",
"\n",
"export const useTestDataSource = (uid: string) => {\n",
" const dispatch = useDispatch();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" const dataSourcesRoutes = useDataSourcesRoutes();\n"
],
"file_path": "public/app/features/datasources/state/hooks.ts",
"type": "add",
"edit_start_line_idx": 45
} | import { waitFor } from '@testing-library/react';
import { ExploreId } from '../../../../types';
import { withinExplore } from './setup';
export const assertQueryHistoryExists = async (query: string, exploreId: ExploreId = ExploreId.left) => {
const selector = withinExplore(exploreId);
expect(await selector.findByText('1 queries')).toBeInTheDocument();
const queryItem = selector.getByLabelText('Query text');
expect(queryItem).toHaveTextContent(query);
};
export const assertQueryHistory = async (expectedQueryTexts: string[], exploreId: ExploreId = ExploreId.left) => {
const selector = withinExplore(exploreId);
await waitFor(() => {
expect(selector.getByText(new RegExp(`${expectedQueryTexts.length} queries`))).toBeInTheDocument();
const queryTexts = selector.getAllByLabelText('Query text');
expectedQueryTexts.forEach((expectedQueryText, queryIndex) => {
expect(queryTexts[queryIndex]).toHaveTextContent(expectedQueryText);
});
});
};
export const assertQueryHistoryComment = async (
expectedQueryComments: string[],
exploreId: ExploreId = ExploreId.left
) => {
const selector = withinExplore(exploreId);
await waitFor(() => {
expect(selector.getByText(new RegExp(`${expectedQueryComments.length} queries`))).toBeInTheDocument();
const queryComments = selector.getAllByLabelText('Query comment');
expectedQueryComments.forEach((expectedQueryText, queryIndex) => {
expect(queryComments[queryIndex]).toHaveTextContent(expectedQueryText);
});
});
};
export const assertQueryHistoryIsStarred = async (expectedStars: boolean[], exploreId: ExploreId = ExploreId.left) => {
const selector = withinExplore(exploreId);
const starButtons = selector.getAllByRole('button', { name: /Star query|Unstar query/ });
await waitFor(() =>
expectedStars.forEach((starred, queryIndex) => {
expect(starButtons[queryIndex]).toHaveAccessibleName(starred ? 'Unstar query' : 'Star query');
})
);
};
export const assertQueryHistoryTabIsSelected = (
tabName: 'Query history' | 'Starred' | 'Settings',
exploreId: ExploreId = ExploreId.left
) => {
expect(withinExplore(exploreId).getByRole('tab', { name: `Tab ${tabName}`, selected: true })).toBeInTheDocument();
};
export const assertDataSourceFilterVisibility = (visible: boolean, exploreId: ExploreId = ExploreId.left) => {
const filterInput = withinExplore(exploreId).queryByLabelText('Filter queries for data sources(s)');
if (visible) {
expect(filterInput).toBeInTheDocument();
} else {
expect(filterInput).not.toBeInTheDocument();
}
};
export const assertQueryHistoryElementsShown = (
shown: number,
total: number,
exploreId: ExploreId = ExploreId.left
) => {
expect(withinExplore(exploreId).queryByText(`Showing ${shown} of ${total}`)).toBeInTheDocument();
};
export const assertLoadMoreQueryHistoryNotVisible = (exploreId: ExploreId = ExploreId.left) => {
expect(withinExplore(exploreId).queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument();
};
| public/app/features/explore/spec/helper/assert.ts | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00027838689857162535,
0.0001886386307887733,
0.00016653967031743377,
0.00016934427549131215,
0.00003615489913499914
] |
{
"id": 10,
"code_window": [
"\n",
" return () => dispatch(testDataSource(uid));\n",
"};\n",
"\n",
"export const useLoadDataSources = () => {\n",
" const dispatch = useDispatch();\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return () => dispatch(testDataSource(uid, dataSourcesRoutes.Edit));\n"
],
"file_path": "public/app/features/datasources/state/hooks.ts",
"type": "replace",
"edit_start_line_idx": 46
} | import { DataSourcePluginMeta, DataSourceSettings, locationUtil } from '@grafana/data';
import {
config,
DataSourceWithBackend,
getDataSourceSrv,
HealthCheckError,
HealthCheckResultDetails,
isFetchError,
locationService,
} from '@grafana/runtime';
import { updateNavIndex } from 'app/core/actions';
import { contextSrv } from 'app/core/core';
import { getBackendSrv } from 'app/core/services/backend_srv';
import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
import { getPluginSettings } from 'app/features/plugins/pluginSettings';
import { importDataSourcePlugin } from 'app/features/plugins/plugin_loader';
import { DataSourcePluginCategory, ThunkDispatch, ThunkResult } from 'app/types';
import * as api from '../api';
import { DATASOURCES_ROUTES } from '../constants';
import { trackDataSourceCreated, trackDataSourceTested } from '../tracking';
import { findNewName, nameExits } from '../utils';
import { buildCategories } from './buildCategories';
import { buildNavModel } from './navModel';
import {
dataSourceLoaded,
dataSourceMetaLoaded,
dataSourcePluginsLoad,
dataSourcePluginsLoaded,
dataSourcesLoaded,
initDataSourceSettingsFailed,
initDataSourceSettingsSucceeded,
testDataSourceFailed,
testDataSourceStarting,
testDataSourceSucceeded,
} from './reducers';
import { getDataSource, getDataSourceMeta } from './selectors';
export interface DataSourceTypesLoadedPayload {
plugins: DataSourcePluginMeta[];
categories: DataSourcePluginCategory[];
}
export interface InitDataSourceSettingDependencies {
loadDataSource: typeof loadDataSource;
loadDataSourceMeta: typeof loadDataSourceMeta;
getDataSource: typeof getDataSource;
getDataSourceMeta: typeof getDataSourceMeta;
importDataSourcePlugin: typeof importDataSourcePlugin;
}
export interface TestDataSourceDependencies {
getDatasourceSrv: typeof getDataSourceSrv;
getBackendSrv: typeof getBackendSrv;
}
export const initDataSourceSettings = (
uid: string,
dependencies: InitDataSourceSettingDependencies = {
loadDataSource,
loadDataSourceMeta,
getDataSource,
getDataSourceMeta,
importDataSourcePlugin,
}
): ThunkResult<void> => {
return async (dispatch, getState) => {
if (!uid) {
dispatch(initDataSourceSettingsFailed(new Error('Invalid UID')));
return;
}
try {
const loadedDataSource = await dispatch(dependencies.loadDataSource(uid));
await dispatch(dependencies.loadDataSourceMeta(loadedDataSource));
const dataSource = dependencies.getDataSource(getState().dataSources, uid);
const dataSourceMeta = dependencies.getDataSourceMeta(getState().dataSources, dataSource!.type);
const importedPlugin = await dependencies.importDataSourcePlugin(dataSourceMeta);
dispatch(initDataSourceSettingsSucceeded(importedPlugin));
} catch (err) {
if (err instanceof Error) {
dispatch(initDataSourceSettingsFailed(err));
}
}
};
};
export const testDataSource = (
dataSourceName: string,
dependencies: TestDataSourceDependencies = {
getDatasourceSrv,
getBackendSrv,
}
): ThunkResult<void> => {
return async (dispatch: ThunkDispatch, getState) => {
const dsApi = await dependencies.getDatasourceSrv().get(dataSourceName);
if (!dsApi.testDatasource) {
return;
}
dispatch(testDataSourceStarting());
dependencies.getBackendSrv().withNoBackendCache(async () => {
try {
const result = await dsApi.testDatasource();
dispatch(testDataSourceSucceeded(result));
trackDataSourceTested({
grafana_version: config.buildInfo.version,
plugin_id: dsApi.type,
datasource_uid: dsApi.uid,
success: true,
});
} catch (err) {
let message: string | undefined;
let details: HealthCheckResultDetails;
if (err instanceof HealthCheckError) {
message = err.message;
details = err.details;
} else if (isFetchError(err)) {
message = err.data.message ?? `HTTP error ${err.statusText}`;
} else if (err instanceof Error) {
message = err.message;
}
dispatch(testDataSourceFailed({ message, details }));
trackDataSourceTested({
grafana_version: config.buildInfo.version,
plugin_id: dsApi.type,
datasource_uid: dsApi.uid,
success: false,
});
}
});
};
};
export function loadDataSources(): ThunkResult<void> {
return async (dispatch) => {
const response = await api.getDataSources();
dispatch(dataSourcesLoaded(response));
};
}
export function loadDataSource(uid: string): ThunkResult<Promise<DataSourceSettings>> {
return async (dispatch) => {
let dataSource = await api.getDataSourceByIdOrUid(uid);
// Reload route to use UID instead
// -------------------------------
// In case we were trying to fetch and reference a data-source with an old numeric ID
// (which can happen by referencing it with a "old" URL), we would like to automatically redirect
// to the new URL format using the UID.
// [Please revalidate the following]: Unfortunately we can update the location using react router, but need to fully reload the
// route as the nav model page index is not matching with the url in that case.
// And react router has no way to unmount remount a route.
if (uid !== dataSource.uid) {
window.location.href = locationUtil.assureBaseUrl(`/datasources/edit/${dataSource.uid}`);
// Avoid a flashing error while the reload happens
dataSource = {} as DataSourceSettings;
}
dispatch(dataSourceLoaded(dataSource));
return dataSource;
};
}
export function loadDataSourceMeta(dataSource: DataSourceSettings): ThunkResult<void> {
return async (dispatch) => {
const pluginInfo = (await getPluginSettings(dataSource.type)) as DataSourcePluginMeta;
const plugin = await importDataSourcePlugin(pluginInfo);
const isBackend = plugin.DataSourceClass.prototype instanceof DataSourceWithBackend;
const meta = {
...pluginInfo,
isBackend: pluginInfo.backend || isBackend,
};
dispatch(dataSourceMetaLoaded(meta));
plugin.meta = meta;
dispatch(updateNavIndex(buildNavModel(dataSource, plugin)));
};
}
export function addDataSource(plugin: DataSourcePluginMeta, editRoute = DATASOURCES_ROUTES.Edit): ThunkResult<void> {
return async (dispatch, getStore) => {
await dispatch(loadDataSources());
const dataSources = getStore().dataSources.dataSources;
const isFirstDataSource = dataSources.length === 0;
const newInstance = {
name: plugin.name,
type: plugin.id,
access: 'proxy',
isDefault: isFirstDataSource,
};
if (nameExits(dataSources, newInstance.name)) {
newInstance.name = findNewName(dataSources, newInstance.name);
}
const result = await api.createDataSource(newInstance);
const editLink = editRoute.replace(/:uid/gi, result.datasource.uid);
await getDatasourceSrv().reload();
await contextSrv.fetchUserPermissions();
trackDataSourceCreated({
grafana_version: config.buildInfo.version,
plugin_id: plugin.id,
datasource_uid: result.datasource.uid,
plugin_version: result.meta?.info?.version,
editLink,
});
locationService.push(editLink);
};
}
export function loadDataSourcePlugins(): ThunkResult<void> {
return async (dispatch) => {
dispatch(dataSourcePluginsLoad());
const plugins = await api.getDataSourcePlugins();
const categories = buildCategories(plugins);
dispatch(dataSourcePluginsLoaded({ plugins, categories }));
};
}
export function updateDataSource(dataSource: DataSourceSettings) {
return async (dispatch: (dataSourceSettings: ThunkResult<Promise<DataSourceSettings>>) => DataSourceSettings) => {
await api.updateDataSource(dataSource);
await getDatasourceSrv().reload();
return dispatch(loadDataSource(dataSource.uid));
};
}
export function deleteLoadedDataSource(): ThunkResult<void> {
return async (dispatch, getStore) => {
const { uid } = getStore().dataSources.dataSource;
await api.deleteDataSource(uid);
await getDatasourceSrv().reload();
locationService.push('/datasources');
};
}
| public/app/features/datasources/state/actions.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.9752066731452942,
0.12593701481819153,
0.0001688899501459673,
0.003373262006789446,
0.2746463716030121
] |
{
"id": 10,
"code_window": [
"\n",
" return () => dispatch(testDataSource(uid));\n",
"};\n",
"\n",
"export const useLoadDataSources = () => {\n",
" const dispatch = useDispatch();\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return () => dispatch(testDataSource(uid, dataSourcesRoutes.Edit));\n"
],
"file_path": "public/app/features/datasources/state/hooks.ts",
"type": "replace",
"edit_start_line_idx": 46
} | package provisioning
import (
"context"
"errors"
"testing"
"time"
dashboardstore "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/provisioning/dashboards"
"github.com/grafana/grafana/pkg/services/provisioning/utils"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
)
func TestProvisioningServiceImpl(t *testing.T) {
t.Run("Restart dashboard provisioning and stop service", func(t *testing.T) {
serviceTest := setup()
err := serviceTest.service.ProvisionDashboards(context.Background())
assert.Nil(t, err)
serviceTest.startService()
serviceTest.waitForPollChanges()
assert.Equal(t, 1, len(serviceTest.mock.Calls.PollChanges), "PollChanges should have been called")
err = serviceTest.service.ProvisionDashboards(context.Background())
assert.Nil(t, err)
serviceTest.waitForPollChanges()
assert.Equal(t, 2, len(serviceTest.mock.Calls.PollChanges), "PollChanges should have been called 2 times")
pollingCtx := serviceTest.mock.Calls.PollChanges[0].(context.Context)
assert.Equal(t, context.Canceled, pollingCtx.Err(), "Polling context from first call should have been cancelled")
assert.True(t, serviceTest.serviceRunning, "Service should be still running")
// Cancelling the root context and stopping the service
serviceTest.cancel()
serviceTest.waitForStop()
assert.False(t, serviceTest.serviceRunning, "Service should not be running")
assert.Equal(t, context.Canceled, serviceTest.serviceError, "Service should have returned canceled error")
})
t.Run("Failed reloading does not stop polling with old provisioned", func(t *testing.T) {
serviceTest := setup()
err := serviceTest.service.ProvisionDashboards(context.Background())
assert.Nil(t, err)
serviceTest.startService()
serviceTest.waitForPollChanges()
assert.Equal(t, 1, len(serviceTest.mock.Calls.PollChanges), "PollChanges should have been called")
serviceTest.mock.ProvisionFunc = func(ctx context.Context) error {
return errors.New("Test error")
}
err = serviceTest.service.ProvisionDashboards(context.Background())
assert.NotNil(t, err)
serviceTest.waitForPollChanges()
// This should have been called with the old provisioner, after the last one failed.
assert.Equal(t, 2, len(serviceTest.mock.Calls.PollChanges), "PollChanges should have been called 2 times")
assert.True(t, serviceTest.serviceRunning, "Service should be still running")
// Cancelling the root context and stopping the service
serviceTest.cancel()
})
}
type serviceTestStruct struct {
waitForPollChanges func()
waitForStop func()
waitTimeout time.Duration
serviceRunning bool
serviceError error
startService func()
cancel func()
mock *dashboards.ProvisionerMock
service *ProvisioningServiceImpl
}
func setup() *serviceTestStruct {
serviceTest := &serviceTestStruct{}
serviceTest.waitTimeout = time.Second
pollChangesChannel := make(chan context.Context)
serviceStopped := make(chan interface{})
serviceTest.mock = dashboards.NewDashboardProvisionerMock()
serviceTest.mock.PollChangesFunc = func(ctx context.Context) {
pollChangesChannel <- ctx
}
serviceTest.service = newProvisioningServiceImpl(
func(context.Context, string, dashboardstore.DashboardProvisioningService, org.Service, utils.DashboardStore) (dashboards.DashboardProvisioner, error) {
return serviceTest.mock, nil
},
nil,
nil,
nil,
)
serviceTest.service.Cfg = setting.NewCfg()
ctx, cancel := context.WithCancel(context.Background())
serviceTest.cancel = cancel
serviceTest.startService = func() {
go func() {
serviceTest.serviceRunning = true
serviceTest.serviceError = serviceTest.service.Run(ctx)
serviceTest.serviceRunning = false
serviceStopped <- true
}()
}
serviceTest.waitForPollChanges = func() {
timeoutChan := time.After(serviceTest.waitTimeout)
select {
case <-pollChangesChannel:
case <-timeoutChan:
}
}
serviceTest.waitForStop = func() {
timeoutChan := time.After(serviceTest.waitTimeout)
select {
case <-serviceStopped:
case <-timeoutChan:
}
}
return serviceTest
}
| pkg/services/provisioning/provisioning_test.go | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017673923866823316,
0.0001722890156088397,
0.00016856304137036204,
0.0001717850536806509,
0.000002457636810504482
] |
{
"id": 10,
"code_window": [
"\n",
" return () => dispatch(testDataSource(uid));\n",
"};\n",
"\n",
"export const useLoadDataSources = () => {\n",
" const dispatch = useDispatch();\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return () => dispatch(testDataSource(uid, dataSourcesRoutes.Edit));\n"
],
"file_path": "public/app/features/datasources/state/hooks.ts",
"type": "replace",
"edit_start_line_idx": 46
} | import { FieldMatcherID, fieldMatchers, FieldType, MutableDataFrame } from '@grafana/data';
import { BarAlignment, GraphDrawStyle, GraphTransform, LineInterpolation, StackingMode } from '@grafana/schema';
import { preparePlotFrame } from '../GraphNG/utils';
import { getStackingGroups, preparePlotData2, timeFormatToTemplate } from './utils';
describe('timeFormatToTemplate', () => {
it.each`
format | expected
${'HH:mm:ss'} | ${'{HH}:{mm}:{ss}'}
${'HH:mm'} | ${'{HH}:{mm}'}
${'MM/DD HH:mm'} | ${'{MM}/{DD} {HH}:{mm}'}
${'MM/DD'} | ${'{MM}/{DD}'}
${'YYYY-MM'} | ${'{YYYY}-{MM}'}
${'YYYY'} | ${'{YYYY}'}
`('should convert $format to $expected', ({ format, expected }) => {
expect(timeFormatToTemplate(format)).toEqual(expected);
});
});
describe('preparePlotData2', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [9997, 9998, 9999] },
{ name: 'a', values: [-10, 20, 10] },
{ name: 'b', values: [10, 10, 10] },
{ name: 'c', values: [20, 20, 20] },
],
});
it('creates array from DataFrame', () => {
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
9997,
9998,
9999,
],
[
-10,
20,
10,
],
[
10,
10,
10,
],
[
20,
20,
20,
],
]
`);
});
describe('transforms', () => {
it('negative-y transform', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [9997, 9998, 9999] },
{ name: 'a', values: [-10, 20, 10] },
{ name: 'b', values: [10, 10, 10] },
{ name: 'c', values: [20, 20, 20], config: { custom: { transform: GraphTransform.NegativeY } } },
],
});
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
9997,
9998,
9999,
],
[
-10,
20,
10,
],
[
10,
10,
10,
],
[
-20,
-20,
-20,
],
]
`);
});
it('negative-y transform with null/undefined values', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [9997, 9998, 9999] },
{ name: 'a', values: [-10, 20, 10, 30] },
{ name: 'b', values: [10, 10, 10, null] },
{ name: 'c', values: [null, 20, 20, 20], config: { custom: { transform: GraphTransform.NegativeY } } },
{ name: 'd', values: [20, 20, 20, null], config: { custom: { transform: GraphTransform.NegativeY } } },
{ name: 'e', values: [20, null, 20, 20], config: { custom: { transform: GraphTransform.NegativeY } } },
{ name: 'f', values: [10, 10, 10, undefined] },
{ name: 'g', values: [undefined, 20, 20, 20], config: { custom: { transform: GraphTransform.NegativeY } } },
{ name: 'h', values: [20, 20, 20, undefined], config: { custom: { transform: GraphTransform.NegativeY } } },
{ name: 'i', values: [20, undefined, 20, 20], config: { custom: { transform: GraphTransform.NegativeY } } },
],
});
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
9997,
9998,
9999,
undefined,
],
[
-10,
20,
10,
30,
],
[
10,
10,
10,
null,
],
[
null,
-20,
-20,
-20,
],
[
-20,
-20,
-20,
null,
],
[
-20,
null,
-20,
-20,
],
[
10,
10,
10,
undefined,
],
[
undefined,
-20,
-20,
-20,
],
[
-20,
-20,
-20,
undefined,
],
[
-20,
undefined,
-20,
-20,
],
]
`);
});
it('constant transform', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [9997, 9998, 9999] },
{ name: 'a', values: [-10, 20, 10], config: { custom: { transform: GraphTransform.Constant } } },
{ name: 'b', values: [10, 10, 10] },
{ name: 'c', values: [20, 20, 20] },
],
});
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
9997,
9998,
9999,
],
[
-10,
undefined,
undefined,
],
[
10,
10,
10,
],
[
20,
20,
20,
],
]
`);
});
});
describe('stacking', () => {
it('none', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [9997, 9998, 9999] },
{
name: 'a',
values: [-10, 20, 10],
config: { custom: { stacking: { mode: StackingMode.None } } },
},
{
name: 'b',
values: [10, 10, 10],
config: { custom: { stacking: { mode: StackingMode.None } } },
},
{
name: 'c',
values: [20, 20, 20],
config: { custom: { stacking: { mode: StackingMode.None } } },
},
],
});
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
9997,
9998,
9999,
],
[
-10,
20,
10,
],
[
10,
10,
10,
],
[
20,
20,
20,
],
]
`);
});
it('standard', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [9997, 9998, 9999] },
{
name: 'a',
values: [-10, 20, 10],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' } } },
},
{
name: 'b',
values: [10, 10, 10],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' } } },
},
{
name: 'c',
values: [20, 20, 20],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' } } },
},
],
});
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
9997,
9998,
9999,
],
[
-10,
20,
10,
],
[
10,
10,
10,
],
[
30,
30,
30,
],
]
`);
});
it('standard with negative y transform', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [9997, 9998, 9999] },
{
name: 'a',
values: [-10, 20, 10],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' } } },
},
{
name: 'b',
values: [10, 10, 10],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' } } },
},
{
name: 'c',
values: [20, 20, 20],
config: {
custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' }, transform: GraphTransform.NegativeY },
},
},
{
name: 'd',
values: [10, 10, 10],
config: {
custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' }, transform: GraphTransform.NegativeY },
},
},
],
});
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
9997,
9998,
9999,
],
[
-10,
20,
10,
],
[
10,
10,
10,
],
[
-30,
0,
-10,
],
[
-40,
-10,
-20,
],
]
`);
});
it('standard with multiple groups', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [9997, 9998, 9999] },
{
name: 'a',
values: [-10, 20, 10],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' } } },
},
{
name: 'b',
values: [10, 10, 10],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' } } },
},
{
name: 'c',
values: [20, 20, 20],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' } } },
},
{
name: 'd',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackB' } } },
},
{
name: 'e',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackB' } } },
},
{
name: 'f',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackB' } } },
},
],
});
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
9997,
9998,
9999,
],
[
-10,
20,
10,
],
[
10,
10,
10,
],
[
30,
30,
30,
],
[
1,
2,
3,
],
[
2,
4,
6,
],
[
3,
6,
9,
],
]
`);
});
it('standard with multiple groups and hidden fields', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [9997, 9998, 9999] },
{
name: 'a',
values: [-10, 20, 10],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' }, hideFrom: { viz: true } } },
},
{
// Will ignore a series as stacking base as it's hidden from viz
name: 'b',
values: [10, 10, 10],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackA' } } },
},
{
name: 'd',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackB' } } },
},
{
name: 'e',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackB' }, hideFrom: { viz: true } } },
},
{
// Will ignore e series as stacking base as it's hidden from viz
name: 'f',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'stackB' } } },
},
],
});
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
9997,
9998,
9999,
],
[
-10,
20,
10,
],
[
10,
10,
10,
],
[
1,
2,
3,
],
[
1,
2,
3,
],
[
2,
4,
6,
],
]
`);
});
});
it('accumulates stacks only at indices where stacking group has at least 1 value', () => {
// extracted data from plot in panel-graph/graph-ng-stacking2.json
const frameData = [
[[1639976945832], [1000]],
[
[1639803285888, 1639976945832, 1640150605776, 1641192565440],
[2500, 600, 350, 500],
],
[
[1639803285888, 1639976945832, 1640150605776, 1640324265720],
[28000, 3100, 36000, 2800],
],
[
[1639976945832, 1640324265720, 1640497925664],
[255, 651, 50],
],
[
[1639803285888, 1639976945832],
[5000, 1231],
],
[
[
1639455966000, 1639629625944, 1639803285888, 1639976945832, 1640150605776, 1640324265720, 1640497925664,
1640671585608, 1640845245552, 1641018905496,
],
[122, 123, 12345, 23456, 34567, 12345, 8000, 3000, 1000, 21],
],
[[1641539885328], [20]],
[
[1641192565440, 1641539885328],
[210, 321],
],
[
[1640671585608, 1641539885328],
[210, 210],
],
[
[1639803285888, 1639976945832, 1640150605776, 1640497925664, 1640845245552],
[250, 852, 1234, 321, 432],
],
[
[
1640324265720, 1640497925664, 1640671585608, 1640845245552, 1641018905496, 1641192565440, 1641366225384,
1641539885328, 1641713545272, 1641887205216, 1642060865160, 1642234525104, 1642408185048,
],
[543, 18000, 17000, 12000, 8500, 8000, 5000, 3000, 2500, 2200, 3000, 1520, 665.35],
],
[[1641887205216], [800]],
[
[
1640150605776, 1640324265720, 1640497925664, 1640671585608, 1640845245552, 1641018905496, 1641192565440,
1641366225384, 1641539885328, 1641713545272, 1641887205216, 1642060865160, 1642234525104,
],
[14173, 14805, 5600, 5950, 775, 725, 1450, 3175, 1850, 1025, 2700, 4825, 3600],
],
[[1642234525104], [1675]],
[[1640150605776], [433.16]],
[
[
1640324265720, 1640497925664, 1640671585608, 1640845245552, 1641018905496, 1641192565440, 1641366225384,
1641539885328, 1641713545272, 1641887205216, 1642060865160, 1642234525104, 1642408185048,
],
[
41250, 45150, 45870.16, 38728.17, 39931.77, 39831.8, 38252.06, 44332.92, 51359.74, 56155.84, 55676.92,
55323.84, 13830.96,
],
],
[
[1640845245552, 1641018905496],
[52.89, 569.57],
],
[
[
1641018905496, 1641192565440, 1641366225384, 1641539885328, 1641713545272, 1641887205216, 1642060865160,
1642234525104, 1642408185048,
],
[2140.34, 4074.92, 1557.85, 1097.74, 692.06, 758.67, 957.56, 1470.49, 198.18],
],
];
const names = 'abcdefghijklmnopqrstuvwxyz'.split('').reverse();
const dfs = frameData.map(([xs, ys]) => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: xs },
{
name: names.pop()!,
values: ys,
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'A' } } },
},
],
});
return df;
});
const df = preparePlotFrame(dfs, {
x: fieldMatchers.get(FieldMatcherID.firstTimeField).get({}),
y: fieldMatchers.get(FieldMatcherID.numeric).get({}),
})!;
expect(preparePlotData2(df, getStackingGroups(df))).toMatchInlineSnapshot(`
[
[
1639455966000,
1639629625944,
1639803285888,
1639976945832,
1640150605776,
1640324265720,
1640497925664,
1640671585608,
1640845245552,
1641018905496,
1641192565440,
1641366225384,
1641539885328,
1641713545272,
1641887205216,
1642060865160,
1642234525104,
1642408185048,
],
[
0,
0,
0,
1000,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
],
[
0,
0,
2500,
1600,
350,
0,
0,
0,
0,
0,
500,
0,
0,
0,
0,
0,
0,
0,
],
[
0,
0,
30500,
4700,
36350,
2800,
0,
0,
0,
0,
500,
0,
0,
0,
0,
0,
0,
0,
],
[
0,
0,
30500,
4955,
36350,
3451,
50,
0,
0,
0,
500,
0,
0,
0,
0,
0,
0,
0,
],
[
0,
0,
35500,
6186,
36350,
3451,
50,
0,
0,
0,
500,
0,
0,
0,
0,
0,
0,
0,
],
[
122,
123,
47845,
29642,
70917,
15796,
8050,
3000,
1000,
21,
500,
0,
0,
0,
0,
0,
0,
0,
],
[
122,
123,
47845,
29642,
70917,
15796,
8050,
3000,
1000,
21,
500,
0,
20,
0,
0,
0,
0,
0,
],
[
122,
123,
47845,
29642,
70917,
15796,
8050,
3000,
1000,
21,
710,
0,
341,
0,
0,
0,
0,
0,
],
[
122,
123,
47845,
29642,
70917,
15796,
8050,
3210,
1000,
21,
710,
0,
551,
0,
0,
0,
0,
0,
],
[
122,
123,
48095,
30494,
72151,
15796,
8371,
3210,
1432,
21,
710,
0,
551,
0,
0,
0,
0,
0,
],
[
122,
123,
48095,
30494,
72151,
16339,
26371,
20210,
13432,
8521,
8710,
5000,
3551,
2500,
2200,
3000,
1520,
665.35,
],
[
122,
123,
48095,
30494,
72151,
16339,
26371,
20210,
13432,
8521,
8710,
5000,
3551,
2500,
3000,
3000,
1520,
665.35,
],
[
122,
123,
48095,
30494,
86324,
31144,
31971,
26160,
14207,
9246,
10160,
8175,
5401,
3525,
5700,
7825,
5120,
665.35,
],
[
122,
123,
48095,
30494,
86324,
31144,
31971,
26160,
14207,
9246,
10160,
8175,
5401,
3525,
5700,
7825,
6795,
665.35,
],
[
122,
123,
48095,
30494,
86757.16,
31144,
31971,
26160,
14207,
9246,
10160,
8175,
5401,
3525,
5700,
7825,
6795,
665.35,
],
[
122,
123,
48095,
30494,
86757.16,
72394,
77121,
72030.16,
52935.17,
49177.77,
49991.8,
46427.06,
49733.92,
54884.74,
61855.84,
63501.92,
62118.84,
14496.31,
],
[
122,
123,
48095,
30494,
86757.16,
72394,
77121,
72030.16,
52988.06,
49747.34,
49991.8,
46427.06,
49733.92,
54884.74,
61855.84,
63501.92,
62118.84,
14496.31,
],
[
122,
123,
48095,
30494,
86757.16,
72394,
77121,
72030.16,
52988.06,
51887.67999999999,
54066.72,
47984.909999999996,
50831.659999999996,
55576.799999999996,
62614.509999999995,
64459.479999999996,
63589.329999999994,
14694.49,
],
]
`);
});
});
describe('auto stacking groups', () => {
test('split on stacking mode', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [0, 1, 2] },
{
name: 'b',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Percent } } },
},
{
name: 'c',
values: [4, 5, 6],
config: { custom: { stacking: { mode: StackingMode.Normal } } },
},
],
});
expect(getStackingGroups(df)).toMatchInlineSnapshot(`
[
{
"dir": 1,
"series": [
1,
],
},
{
"dir": 1,
"series": [
2,
],
},
]
`);
});
test('split pos/neg', () => {
// since we expect most series to be Pos, we try to bail early when scanning all values
// as soon as we find a value >= 0, it's assumed Pos, else Neg
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [0, 1, 2] },
{
name: 'a',
values: [-1, null, -3],
config: { custom: { stacking: { mode: StackingMode.Normal } } },
},
{
name: 'b',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal } } },
},
{
name: 'c',
values: [0, 0, 0],
config: { custom: { stacking: { mode: StackingMode.Normal } } },
},
{
name: 'd',
values: [null, -0, null],
config: { custom: { stacking: { mode: StackingMode.Normal } } },
},
],
});
expect(getStackingGroups(df)).toMatchInlineSnapshot(`
[
{
"dir": -1,
"series": [
1,
4,
],
},
{
"dir": 1,
"series": [
2,
3,
],
},
]
`);
});
test('split pos/neg with NegY', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [0, 1, 2] },
{
name: 'a',
values: [-1, null, -3],
config: { custom: { stacking: { mode: StackingMode.Normal }, transform: GraphTransform.NegativeY } },
},
{
name: 'b',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal } } },
},
{
name: 'c',
values: [0, 0, 0],
config: { custom: { stacking: { mode: StackingMode.Normal } } },
},
{
name: 'd',
values: [-0, null, 3],
config: { custom: { stacking: { mode: StackingMode.Normal }, transform: GraphTransform.NegativeY } },
},
],
});
expect(getStackingGroups(df)).toMatchInlineSnapshot(`
[
{
"dir": 1,
"series": [
1,
2,
3,
4,
],
},
]
`);
});
test('split on drawStyle, lineInterpolation, barAlignment', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [0, 1, 2] },
{
name: 'a',
values: [1, 2, 3],
config: {
custom: {
drawStyle: GraphDrawStyle.Bars,
barAlignment: BarAlignment.After,
stacking: { mode: StackingMode.Normal },
},
},
},
{
name: 'b',
values: [1, 2, 3],
config: {
custom: {
drawStyle: GraphDrawStyle.Bars,
barAlignment: BarAlignment.Before,
stacking: { mode: StackingMode.Normal },
},
},
},
{
name: 'c',
values: [1, 2, 3],
config: {
custom: {
drawStyle: GraphDrawStyle.Line,
lineInterpolation: LineInterpolation.Linear,
stacking: { mode: StackingMode.Normal },
},
},
},
{
name: 'd',
values: [1, 2, 3],
config: {
custom: {
drawStyle: GraphDrawStyle.Line,
lineInterpolation: LineInterpolation.Smooth,
stacking: { mode: StackingMode.Normal },
},
},
},
{
name: 'e',
values: [1, 2, 3],
config: { custom: { drawStyle: GraphDrawStyle.Points, stacking: { mode: StackingMode.Normal } } },
},
],
});
expect(getStackingGroups(df)).toMatchInlineSnapshot(`
[
{
"dir": 1,
"series": [
1,
],
},
{
"dir": 1,
"series": [
2,
],
},
{
"dir": 1,
"series": [
3,
],
},
{
"dir": 1,
"series": [
4,
],
},
{
"dir": 1,
"series": [
5,
],
},
]
`);
});
test('split on axis & units (scaleKey)', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [0, 1, 2] },
{
name: 'a',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal } }, unit: 'ft' },
},
{
name: 'b',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal } }, unit: 'degrees' },
},
],
});
expect(getStackingGroups(df)).toMatchInlineSnapshot(`
[
{
"dir": 1,
"series": [
1,
],
},
{
"dir": 1,
"series": [
2,
],
},
]
`);
});
test('split on explicit stacking group & mode & pos/neg w/NegY', () => {
const df = new MutableDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [0, 1, 2] },
{
name: 'a',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'A' } } },
},
{
name: 'b',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'A' } } },
},
{
name: 'c',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Percent, group: 'A' } } },
},
{
name: 'd',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Normal, group: 'B' } } },
},
{
name: 'e',
values: [1, 2, 3],
config: { custom: { stacking: { mode: StackingMode.Percent, group: 'B' } } },
},
{
name: 'e',
values: [1, 2, 3],
config: {
custom: { stacking: { mode: StackingMode.Percent, group: 'B' }, transform: GraphTransform.NegativeY },
},
},
],
});
expect(getStackingGroups(df)).toMatchInlineSnapshot(`
[
{
"dir": 1,
"series": [
1,
2,
],
},
{
"dir": 1,
"series": [
3,
],
},
{
"dir": 1,
"series": [
4,
],
},
{
"dir": 1,
"series": [
5,
],
},
{
"dir": -1,
"series": [
6,
],
},
]
`);
});
});
| packages/grafana-ui/src/components/uPlot/utils.test.ts | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00017685774946585298,
0.00017248757649213076,
0.00016577838687226176,
0.00017279846360906959,
0.0000022863614503876306
] |
{
"id": 10,
"code_window": [
"\n",
" return () => dispatch(testDataSource(uid));\n",
"};\n",
"\n",
"export const useLoadDataSources = () => {\n",
" const dispatch = useDispatch();\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return () => dispatch(testDataSource(uid, dataSourcesRoutes.Edit));\n"
],
"file_path": "public/app/features/datasources/state/hooks.ts",
"type": "replace",
"edit_start_line_idx": 46
} | {
"template_files": {
"foo": "bar"
},
"alertmanager_config": {
"mute_time_intervals": [
{
"name": "foo",
"time_intervals": [
{
"years": [
"2020:2022",
"2030"
]
}
]
}
],
"receivers": [
{
"email_configs": [
{
"auth_password": "shh",
"auth_username": "admin",
"from": "bar",
"headers": {
"Bazz": "buzz"
},
"html": "there",
"text": "hi",
"to": "foo"
}
],
"name": "am"
}
],
"route": {
"continue": false,
"group_by": [
"alertname"
],
"receiver": "am",
"routes": [
{
"continue": false,
"receiver": "am"
}
]
},
"templates": []
}
}
| pkg/services/ngalert/api/tooling/definitions/alertmanager_test_artifact.json | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00018033295054920018,
0.0001735645200824365,
0.00016963575035333633,
0.00017276534345000982,
0.0000033298381367785623
] |
{
"id": 11,
"code_window": [
" /** The plugin version (especially interesting in external plugins - core plugins are aligned with grafana version) */\n",
" plugin_version?: string;\n",
" /** Whether or not the datasource test succeeded = the datasource was successfully configured */\n",
" success: boolean;\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" /** The URL that points to the edit page for the datasoruce. We are using this to be able to distinguish between the performance of different datasource edit locations. */\n",
" editLink?: string;\n"
],
"file_path": "public/app/features/datasources/tracking.ts",
"type": "add",
"edit_start_line_idx": 55
} | import { thunkTester } from 'test/core/thunk/thunkTester';
import { AppPluginMeta, DataSourceSettings, PluginMetaInfo, PluginType } from '@grafana/data';
import { FetchError } from '@grafana/runtime';
import { ThunkResult, ThunkDispatch } from 'app/types';
import { getMockDataSource } from '../__mocks__';
import * as api from '../api';
import { DATASOURCES_ROUTES } from '../constants';
import { trackDataSourceCreated, trackDataSourceTested } from '../tracking';
import { GenericDataSourcePlugin } from '../types';
import {
InitDataSourceSettingDependencies,
testDataSource,
TestDataSourceDependencies,
initDataSourceSettings,
loadDataSource,
addDataSource,
} from './actions';
import {
initDataSourceSettingsSucceeded,
initDataSourceSettingsFailed,
testDataSourceStarting,
testDataSourceSucceeded,
testDataSourceFailed,
dataSourceLoaded,
dataSourcesLoaded,
} from './reducers';
jest.mock('../api');
jest.mock('app/core/services/backend_srv');
jest.mock('app/core/core');
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as unknown as object),
getDataSourceSrv: jest.fn().mockReturnValue({ reload: jest.fn() }),
getBackendSrv: jest.fn().mockReturnValue({ get: jest.fn() }),
}));
jest.mock('../tracking', () => ({
trackDataSourceCreated: jest.fn(),
trackDataSourceTested: jest.fn(),
}));
const getBackendSrvMock = () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
}),
withNoBackendCache: jest.fn().mockImplementationOnce((cb) => cb()),
} as any);
const failDataSourceTest = async (error: object) => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw error;
}),
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
return dispatchedActions;
};
describe('loadDataSource()', () => {
it('should resolve to a data-source if a UID was used for fetching', async () => {
const dataSourceMock = getMockDataSource();
const dispatch = jest.fn();
const getState = jest.fn();
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
const dataSource = await loadDataSource(dataSourceMock.uid)(dispatch, getState, undefined);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded(dataSource));
expect(dataSource).toBe(dataSourceMock);
});
it('should resolve to an empty data-source if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
const dataSource = await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(dataSource).toEqual({});
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(dataSourceLoaded({} as DataSourceSettings));
});
it('should redirect to a URL which uses the UID if an ID (deprecated) was used for fetching', async () => {
const id = 123;
const uid = 'uid';
const dataSourceMock = getMockDataSource({ id, uid });
const dispatch = jest.fn();
const getState = jest.fn();
// @ts-ignore
delete window.location;
window.location = {} as Location;
(api.getDataSourceByIdOrUid as jest.Mock).mockResolvedValueOnce(dataSourceMock);
// Fetch the datasource by ID
await loadDataSource(id.toString())(dispatch, getState, undefined);
expect(window.location.href).toBe(`/datasources/edit/${uid}`);
});
});
describe('initDataSourceSettings', () => {
describe('when pageId is missing', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dispatchedActions = await thunkTester({}).givenThunk(initDataSourceSettings).whenThunkIsDispatched('');
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Invalid UID'))]);
});
});
describe('when pageId is a valid', () => {
it('then initDataSourceSettingsSucceeded should be dispatched', async () => {
const dataSource = { type: 'app' };
const dataSourceMeta = { id: 'some id' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => {}),
getDataSource: jest.fn().mockReturnValue(dataSource),
getDataSourceMeta: jest.fn().mockReturnValue(dataSourceMeta),
importDataSourcePlugin: jest.fn().mockReturnValue({} as GenericDataSourcePlugin),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(256, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsSucceeded({} as GenericDataSourcePlugin)]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(256);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
expect(dependencies.getDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSource).toHaveBeenCalledWith({}, 256);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.getDataSourceMeta).toHaveBeenCalledWith({}, 'app');
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledTimes(1);
expect(dependencies.importDataSourcePlugin).toHaveBeenCalledWith(dataSourceMeta);
});
});
describe('when plugin loading fails', () => {
it('then initDataSourceSettingsFailed should be dispatched', async () => {
const dataSource = { type: 'app' };
const dependencies: InitDataSourceSettingDependencies = {
loadDataSource: jest.fn((): ThunkResult<void> => (dispatch: ThunkDispatch, getState) => dataSource) as any,
loadDataSourceMeta: jest.fn().mockImplementation(() => {
throw new Error('Error loading plugin');
}),
getDataSource: jest.fn(),
getDataSourceMeta: jest.fn(),
importDataSourcePlugin: jest.fn(),
};
const state = {
dataSourceSettings: {},
dataSources: {},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(initDataSourceSettings)
.whenThunkIsDispatched(301, dependencies);
expect(dispatchedActions).toEqual([initDataSourceSettingsFailed(new Error('Error loading plugin'))]);
expect(dependencies.loadDataSource).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSource).toHaveBeenCalledWith(301);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledTimes(1);
expect(dependencies.loadDataSourceMeta).toHaveBeenCalledWith(dataSource);
});
});
});
describe('testDataSource', () => {
describe('when a datasource is tested', () => {
it('then testDataSourceStarting and testDataSourceSucceeded should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockReturnValue({
status: '',
message: '',
}),
type: 'cloudwatch',
uid: 'CW1234',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const state = {
testingStatus: {
status: '',
message: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('CloudWatch', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceSucceeded(state.testingStatus)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'cloudwatch',
datasource_uid: 'CW1234',
grafana_version: '1.0',
success: true,
});
});
it('then testDataSourceFailed should be dispatched', async () => {
const dependencies: TestDataSourceDependencies = {
getDatasourceSrv: () =>
({
get: jest.fn().mockReturnValue({
testDatasource: jest.fn().mockImplementation(() => {
throw new Error('Error testing datasource');
}),
type: 'azure-monitor',
uid: 'azM0nit0R',
}),
} as any),
getBackendSrv: getBackendSrvMock,
};
const result = {
message: 'Error testing datasource',
};
const state = {
testingStatus: {
message: '',
status: '',
},
};
const dispatchedActions = await thunkTester(state)
.givenThunk(testDataSource)
.whenThunkIsDispatched('Azure Monitor', dependencies);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
expect(trackDataSourceTested).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
datasource_uid: 'azM0nit0R',
grafana_version: '1.0',
success: false,
});
});
it('then testDataSourceFailed should be dispatched with response error message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response data message', async () => {
const result = {
message: 'Response error message',
};
const error: FetchError = {
config: {
url: '',
},
data: { message: 'Response error message' },
status: 400,
statusText: 'Bad Request',
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
it('then testDataSourceFailed should be dispatched with response statusText', async () => {
const result = {
message: 'HTTP error Bad Request',
};
const error: FetchError = {
config: {
url: '',
},
data: {},
statusText: 'Bad Request',
status: 400,
};
const dispatchedActions = await failDataSourceTest(error);
expect(dispatchedActions).toEqual([testDataSourceStarting(), testDataSourceFailed(result)]);
});
});
});
describe('addDataSource', () => {
it('it creates a datasource and calls trackDataSourceCreated ', async () => {
const meta: AppPluginMeta = {
id: 'azure-monitor',
module: '',
baseUrl: 'xxx',
info: { version: '1.2.3' } as PluginMetaInfo,
type: PluginType.datasource,
name: 'test DS',
};
const state = {
dataSources: {
dataSources: [],
},
};
const dataSourceMock = { datasource: { uid: 'azure23' }, meta };
(api.createDataSource as jest.Mock).mockResolvedValueOnce(dataSourceMock);
(api.getDataSources as jest.Mock).mockResolvedValueOnce([]);
const dispatchedActions = await thunkTester(state).givenThunk(addDataSource).whenThunkIsDispatched(meta);
expect(dispatchedActions).toEqual([dataSourcesLoaded([])]);
expect(trackDataSourceCreated).toHaveBeenCalledWith({
plugin_id: 'azure-monitor',
plugin_version: '1.2.3',
datasource_uid: 'azure23',
grafana_version: '1.0',
editLink: DATASOURCES_ROUTES.Edit.replace(':uid', 'azure23'),
});
});
});
| public/app/features/datasources/state/actions.test.ts | 1 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.0010806239442899823,
0.00026027916464954615,
0.00016492322902195156,
0.000170482016983442,
0.0002245687210233882
] |
{
"id": 11,
"code_window": [
" /** The plugin version (especially interesting in external plugins - core plugins are aligned with grafana version) */\n",
" plugin_version?: string;\n",
" /** Whether or not the datasource test succeeded = the datasource was successfully configured */\n",
" success: boolean;\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" /** The URL that points to the edit page for the datasoruce. We are using this to be able to distinguish between the performance of different datasource edit locations. */\n",
" editLink?: string;\n"
],
"file_path": "public/app/features/datasources/tracking.ts",
"type": "add",
"edit_start_line_idx": 55
} | package expr
import (
"context"
"time"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/setting"
)
// DatasourceType is the string constant used as the datasource when the property is in Datasource.Type.
// Type in requests is used to identify what type of data source plugin the request belongs to.
const DatasourceType = "__expr__"
// DatasourceUID is the string constant used as the datasource name in requests
// to identify it as an expression command when use in Datasource.UID.
const DatasourceUID = DatasourceType
// DatasourceID is the fake datasource id used in requests to identify it as an
// expression command.
const DatasourceID = -100
// OldDatasourceUID is the datasource uid used in requests to identify it as an
// expression command. It goes with the query root level datasourceUID property. It was accidentally
// set to the Id and is now kept for backwards compatibility. The newer Datasource.UID property
// should be used instead and should be set to "__expr__".
const OldDatasourceUID = "-100"
// IsDataSource checks if the uid points to an expression query
func IsDataSource(uid string) bool {
return uid == DatasourceUID || uid == OldDatasourceUID
}
// Service is service representation for expression handling.
type Service struct {
cfg *setting.Cfg
dataService backend.QueryDataHandler
dataSourceService datasources.DataSourceService
}
func ProvideService(cfg *setting.Cfg, pluginClient plugins.Client, dataSourceService datasources.DataSourceService) *Service {
return &Service{
cfg: cfg,
dataService: pluginClient,
dataSourceService: dataSourceService,
}
}
func (s *Service) isDisabled() bool {
if s.cfg == nil {
return true
}
return !s.cfg.ExpressionsEnabled
}
// BuildPipeline builds a pipeline from a request.
func (s *Service) BuildPipeline(req *Request) (DataPipeline, error) {
return s.buildPipeline(req)
}
// ExecutePipeline executes an expression pipeline and returns all the results.
func (s *Service) ExecutePipeline(ctx context.Context, now time.Time, pipeline DataPipeline) (*backend.QueryDataResponse, error) {
res := backend.NewQueryDataResponse()
vars, err := pipeline.execute(ctx, now, s)
if err != nil {
return nil, err
}
for refID, val := range vars {
res.Responses[refID] = backend.DataResponse{
Frames: val.Values.AsDataFrames(refID),
}
}
return res, nil
}
func DataSourceModel() *datasources.DataSource {
return &datasources.DataSource{
Id: DatasourceID,
Uid: DatasourceUID,
Name: DatasourceUID,
Type: DatasourceType,
JsonData: simplejson.New(),
SecureJsonData: make(map[string][]byte),
}
}
| pkg/expr/service.go | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.007857103832066059,
0.0018032555235549808,
0.00016883456555660814,
0.0001852681307354942,
0.0027433375362306833
] |
{
"id": 11,
"code_window": [
" /** The plugin version (especially interesting in external plugins - core plugins are aligned with grafana version) */\n",
" plugin_version?: string;\n",
" /** Whether or not the datasource test succeeded = the datasource was successfully configured */\n",
" success: boolean;\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" /** The URL that points to the edit page for the datasoruce. We are using this to be able to distinguish between the performance of different datasource edit locations. */\n",
" editLink?: string;\n"
],
"file_path": "public/app/features/datasources/tracking.ts",
"type": "add",
"edit_start_line_idx": 55
} | package mocks
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/aws-sdk-go/service/cloudwatch/cloudwatchiface"
"github.com/stretchr/testify/mock"
)
type FakeMetricsAPI struct {
Metrics []*cloudwatch.Metric
OwningAccounts []*string
MetricsPerPage int
}
func (c *FakeMetricsAPI) ListMetricsPages(input *cloudwatch.ListMetricsInput, fn func(*cloudwatch.ListMetricsOutput, bool) bool) error {
if c.MetricsPerPage == 0 {
c.MetricsPerPage = 1000
}
chunks := chunkSlice(c.Metrics, c.MetricsPerPage)
for i, metrics := range chunks {
response := fn(&cloudwatch.ListMetricsOutput{
Metrics: metrics,
OwningAccounts: c.OwningAccounts,
}, i+1 == len(chunks))
if !response {
break
}
}
return nil
}
func chunkSlice(slice []*cloudwatch.Metric, chunkSize int) [][]*cloudwatch.Metric {
var chunks [][]*cloudwatch.Metric
for {
if len(slice) == 0 {
break
}
if len(slice) < chunkSize {
chunkSize = len(slice)
}
chunks = append(chunks, slice[0:chunkSize])
slice = slice[chunkSize:]
}
return chunks
}
type MetricsAPI struct {
cloudwatchiface.CloudWatchAPI
mock.Mock
}
func (m *MetricsAPI) GetMetricDataWithContext(ctx aws.Context, input *cloudwatch.GetMetricDataInput, opts ...request.Option) (*cloudwatch.GetMetricDataOutput, error) {
args := m.Called(ctx, input, opts)
return args.Get(0).(*cloudwatch.GetMetricDataOutput), args.Error(1)
}
| pkg/tsdb/cloudwatch/mocks/cloudwatch_metric_api.go | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00019754728418774903,
0.0001760267186909914,
0.00016548842540942132,
0.00017368601402267814,
0.000009473500540480018
] |
{
"id": 11,
"code_window": [
" /** The plugin version (especially interesting in external plugins - core plugins are aligned with grafana version) */\n",
" plugin_version?: string;\n",
" /** Whether or not the datasource test succeeded = the datasource was successfully configured */\n",
" success: boolean;\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" /** The URL that points to the edit page for the datasoruce. We are using this to be able to distinguish between the performance of different datasource edit locations. */\n",
" editLink?: string;\n"
],
"file_path": "public/app/features/datasources/tracking.ts",
"type": "add",
"edit_start_line_idx": 55
} | package loginattempttest
import (
"context"
"github.com/grafana/grafana/pkg/services/loginattempt"
)
var _ loginattempt.Service = new(FakeLoginAttemptService)
type FakeLoginAttemptService struct {
ExpectedValid bool
ExpectedErr error
}
func (f FakeLoginAttemptService) Add(ctx context.Context, username, IPAddress string) error {
return f.ExpectedErr
}
func (f FakeLoginAttemptService) Reset(ctx context.Context, username string) error {
return f.ExpectedErr
}
func (f FakeLoginAttemptService) Validate(ctx context.Context, username string) (bool, error) {
return f.ExpectedValid, f.ExpectedErr
}
| pkg/services/loginattempt/loginattempttest/fake.go | 0 | https://github.com/grafana/grafana/commit/9b2abe7613bb334d8dead9d1c28d6daa67b28f1c | [
0.00021030075731687248,
0.000194106440176256,
0.0001641804410610348,
0.00020783809304703027,
0.000021184740035096183
] |
{
"id": 0,
"code_window": [
" * This is because Svelte does not itself revert to defaults when a prop is undefined.\n",
" * See https://github.com/storybookjs/storybook/issues/21470#issuecomment-1467056479\n",
" *\n",
" * We listen for the RESET_STORY_ARGS event and store the storyId to be reset\n",
" * We then use this in the renderToCanvas function to force remount the story\n",
" *\n",
" * This is only necessary in Svelte v4\n",
" */\n",
"const storyIdsToRemountFromResetArgsEvent = new Set<string>();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 38
} | import { expect } from '@storybook/test';
import { within, userEvent, waitFor } from '@storybook/testing-library';
import {
UPDATE_STORY_ARGS,
STORY_ARGS_UPDATED,
RESET_STORY_ARGS,
STORY_RENDERED,
} from '@storybook/core-events';
import { addons } from '@storybook/preview-api';
import ButtonView from './views/ButtonJavaScript.svelte';
export default {
component: ButtonView,
};
export const RemountOnResetStoryArgs = {
play: async ({ canvasElement, id }) => {
const canvas = await within(canvasElement);
const channel = addons.getChannel();
// Just to ensure the story is always in a clean state from the beginning, not really part of the test
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
const button = await canvas.getByRole('button');
await expect(button).toHaveTextContent('You clicked: 0');
await userEvent.click(button);
await expect(button).toHaveTextContent('You clicked: 1');
await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
await expect(button).toHaveTextContent('Changed: 1');
// expect that all state and args are reset after RESET_STORY_ARGS because Svelte needs to remount the component
// most other renderers would have 'You clicked: 1' here because they don't remount the component
// if this doesn't fully remount it would be 'undefined: 1' because undefined args are used as is in Svelte, and the state is kept
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await waitFor(async () =>
expect(await within(canvasElement).getByRole('button')).toHaveTextContent('You clicked: 0')
);
},
};
| code/renderers/svelte/template/stories/args.stories.js | 1 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.0008807015256024897,
0.00040293188067153096,
0.000194263513549231,
0.00027951030642725527,
0.0002485683071427047
] |
{
"id": 0,
"code_window": [
" * This is because Svelte does not itself revert to defaults when a prop is undefined.\n",
" * See https://github.com/storybookjs/storybook/issues/21470#issuecomment-1467056479\n",
" *\n",
" * We listen for the RESET_STORY_ARGS event and store the storyId to be reset\n",
" * We then use this in the renderToCanvas function to force remount the story\n",
" *\n",
" * This is only necessary in Svelte v4\n",
" */\n",
"const storyIdsToRemountFromResetArgsEvent = new Set<string>();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 38
} | import type { Plugin } from 'vite';
import { vite } from '@storybook/csf-plugin';
import type { Options } from '@storybook/types';
export async function csfPlugin(config: Options): Promise<Plugin> {
const { presets } = config;
const addons = await presets.apply('addons', []);
const docsOptions =
// @ts-expect-error - not sure what type to use here
addons.find((a) => [a, a.name].includes('@storybook/addon-docs'))?.options ?? {};
// TODO: looks like unplugin can return an array of plugins
return vite(docsOptions?.csfPluginOptions) as Plugin;
}
| code/builders/builder-vite/src/plugins/csf-plugin.ts | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017142240540124476,
0.0001681544235907495,
0.00016488644178025424,
0.0001681544235907495,
0.0000032679818104952574
] |
{
"id": 0,
"code_window": [
" * This is because Svelte does not itself revert to defaults when a prop is undefined.\n",
" * See https://github.com/storybookjs/storybook/issues/21470#issuecomment-1467056479\n",
" *\n",
" * We listen for the RESET_STORY_ARGS event and store the storyId to be reset\n",
" * We then use this in the renderToCanvas function to force remount the story\n",
" *\n",
" * This is only necessary in Svelte v4\n",
" */\n",
"const storyIdsToRemountFromResetArgsEvent = new Set<string>();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 38
} | # Storybook Webpack preset for React
This package is a [preset](https://storybook.js.org/docs/react/addons/writing-presets#presets-api) that configures Storybook's webpack settings for handling React.
It's an internal package that's not intended to be used directly by users.
- More info on [Storybook for React](https://storybook.js.org/docs/react/get-started)
| code/presets/react-webpack/README.md | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00016098699416033924,
0.00016098699416033924,
0.00016098699416033924,
0.00016098699416033924,
0
] |
{
"id": 0,
"code_window": [
" * This is because Svelte does not itself revert to defaults when a prop is undefined.\n",
" * See https://github.com/storybookjs/storybook/issues/21470#issuecomment-1467056479\n",
" *\n",
" * We listen for the RESET_STORY_ARGS event and store the storyId to be reset\n",
" * We then use this in the renderToCanvas function to force remount the story\n",
" *\n",
" * This is only necessary in Svelte v4\n",
" */\n",
"const storyIdsToRemountFromResetArgsEvent = new Set<string>();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 38
} | ```ts
// MyComponent.stories.ts
import type { Meta } from '@storybook/angular';
import { MyComponent } from './MyComponent.component';
const meta: Meta<MyComponent> = {
/* 👇 The title prop is optional.
* See https://storybook.js.org/docs/configure/#configure-story-loading
* to learn how to generate automatic titles
*/
title: 'Path/To/MyComponent',
component: MyComponent,
decorators: [ ... ],
parameters: { ... },
};
export default meta;
```
| docs/snippets/angular/my-component-story-mandatory-export.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017005861445795745,
0.00016792240785434842,
0.0001652831124374643,
0.00016842551121953875,
0.0000019817812244582456
] |
{
"id": 1,
"code_window": [
" */\n",
"const storyIdsToRemountFromResetArgsEvent = new Set<string>();\n",
"if (IS_SVELTE_V4) {\n",
" addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {\n",
" storyIdsToRemountFromResetArgsEvent.add(storyId);\n",
" });\n",
"}\n",
"const componentsByDomElementV4 = new Map<SvelteRenderer['canvasElement'], svelte.SvelteComponent>();\n",
"\n",
"function renderToCanvasV4(\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {\n",
" storyIdsToRemountFromResetArgsEvent.add(storyId);\n",
"});\n",
"\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import type { RenderContext, ArgsStoryFn } from '@storybook/types';
import { RESET_STORY_ARGS } from '@storybook/core-events';
/*
! DO NOT change these PreviewRender and createSvelte5Props imports to relative paths, it will break them.
! Relative imports will be compiled at build time by tsup, but we need Svelte to compile them
! when compiling the rest of the Svelte files.
*/
import PreviewRender from '@storybook/svelte/internal/PreviewRender.svelte';
// @ts-expect-error Don't know why TS doesn't pick up the types export here
import { createSvelte5Props } from '@storybook/svelte/internal/createSvelte5Props';
import { addons } from '@storybook/preview-api';
import * as svelte from 'svelte';
import { VERSION as SVELTE_VERSION } from 'svelte/compiler';
import type { SvelteRenderer } from './types';
const IS_SVELTE_V4 = Number(SVELTE_VERSION[0]) <= 4;
export function renderToCanvas(
renderContext: RenderContext<SvelteRenderer>,
canvasElement: SvelteRenderer['canvasElement']
) {
if (IS_SVELTE_V4) {
return renderToCanvasV4(renderContext, canvasElement);
} else {
return renderToCanvasV5(renderContext, canvasElement);
}
}
/**
* This is a workaround for the issue that when resetting args,
* the story needs to be remounted completely to revert to the component's default props.
* This is because Svelte does not itself revert to defaults when a prop is undefined.
* See https://github.com/storybookjs/storybook/issues/21470#issuecomment-1467056479
*
* We listen for the RESET_STORY_ARGS event and store the storyId to be reset
* We then use this in the renderToCanvas function to force remount the story
*
* This is only necessary in Svelte v4
*/
const storyIdsToRemountFromResetArgsEvent = new Set<string>();
if (IS_SVELTE_V4) {
addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {
storyIdsToRemountFromResetArgsEvent.add(storyId);
});
}
const componentsByDomElementV4 = new Map<SvelteRenderer['canvasElement'], svelte.SvelteComponent>();
function renderToCanvasV4(
{
storyFn,
title,
name,
showMain,
showError,
storyContext,
forceRemount,
}: RenderContext<SvelteRenderer>,
canvasElement: SvelteRenderer['canvasElement']
) {
function unmount(canvasElementToUnmount: SvelteRenderer['canvasElement']) {
if (!componentsByDomElementV4.has(canvasElementToUnmount)) {
return;
}
componentsByDomElementV4.get(canvasElementToUnmount)!.$destroy();
componentsByDomElementV4.delete(canvasElementToUnmount);
canvasElementToUnmount.innerHTML = '';
}
const existingComponent = componentsByDomElementV4.get(canvasElement);
let remount = forceRemount;
if (storyIdsToRemountFromResetArgsEvent.has(storyContext.id)) {
remount = true;
storyIdsToRemountFromResetArgsEvent.delete(storyContext.id);
}
if (remount) {
unmount(canvasElement);
}
if (!existingComponent || remount) {
const mountedComponent = new PreviewRender({
target: canvasElement,
props: {
storyFn,
storyContext,
name,
title,
showError,
},
});
componentsByDomElementV4.set(canvasElement, mountedComponent);
} else {
existingComponent.$set({
storyFn,
storyContext,
name,
title,
showError,
});
}
showMain();
// unmount the component when the story changes
return () => {
unmount(canvasElement);
};
}
const componentsByDomElementV5 = new Map<
SvelteRenderer['canvasElement'],
{ mountedComponent: ReturnType<(typeof svelte)['mount']>; props: RenderContext }
>();
function renderToCanvasV5(
{
storyFn,
title,
name,
showMain,
showError,
storyContext,
forceRemount,
}: RenderContext<SvelteRenderer>,
canvasElement: SvelteRenderer['canvasElement']
) {
function unmount(canvasElementToUnmount: SvelteRenderer['canvasElement']) {
const { mountedComponent } = componentsByDomElementV5.get(canvasElementToUnmount) ?? {};
if (!mountedComponent) {
return;
}
svelte.unmount(mountedComponent);
componentsByDomElementV5.delete(canvasElementToUnmount);
}
const existingComponent = componentsByDomElementV5.get(canvasElement);
if (forceRemount) {
unmount(canvasElement);
}
if (!existingComponent || forceRemount) {
const props = createSvelte5Props({
storyFn,
storyContext,
name,
title,
showError,
});
const mountedComponent = svelte.mount(PreviewRender, {
target: canvasElement,
props,
});
componentsByDomElementV5.set(canvasElement, { mountedComponent, props });
} else {
// We need to mutate the existing props for Svelte reactivity to work, we can't just re-assign them
Object.assign(existingComponent.props, {
storyFn,
storyContext,
name,
title,
showError,
});
}
showMain();
// unmount the component when the story changes
return () => {
unmount(canvasElement);
};
}
export const render: ArgsStoryFn<SvelteRenderer> = (args, context) => {
const { id, component: Component } = context;
if (!Component) {
throw new Error(
`Unable to render story ${id} as the component annotation is missing from the default export`
);
}
return { Component, props: args };
};
| code/renderers/svelte/src/render.ts | 1 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.9992071986198425,
0.39217275381088257,
0.0001666684984229505,
0.0034271650947630405,
0.46696794033050537
] |
{
"id": 1,
"code_window": [
" */\n",
"const storyIdsToRemountFromResetArgsEvent = new Set<string>();\n",
"if (IS_SVELTE_V4) {\n",
" addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {\n",
" storyIdsToRemountFromResetArgsEvent.add(storyId);\n",
" });\n",
"}\n",
"const componentsByDomElementV4 = new Map<SvelteRenderer['canvasElement'], svelte.SvelteComponent>();\n",
"\n",
"function renderToCanvasV4(\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {\n",
" storyIdsToRemountFromResetArgsEvent.add(storyId);\n",
"});\n",
"\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 42
} | ```tsx
// .storybook/preview.tsx
import React from 'react';
import { Preview } from '@storybook/react';
const preview: Preview = {
decorators: [
(Story) => (
<div style={{ margin: '3em' }}>
{/* 👇 Decorators in Storybook also accept a function. Replace <Story/> with Story() to enable it */}
<Story />
</div>
),
],
};
export default preview;
```
| docs/snippets/react/storybook-preview-global-decorator.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.0001744915934978053,
0.00017410621512681246,
0.00017361862410325557,
0.00017420845688320696,
3.6364582456371863e-7
] |
{
"id": 1,
"code_window": [
" */\n",
"const storyIdsToRemountFromResetArgsEvent = new Set<string>();\n",
"if (IS_SVELTE_V4) {\n",
" addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {\n",
" storyIdsToRemountFromResetArgsEvent.add(storyId);\n",
" });\n",
"}\n",
"const componentsByDomElementV4 = new Map<SvelteRenderer['canvasElement'], svelte.SvelteComponent>();\n",
"\n",
"function renderToCanvasV4(\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {\n",
" storyIdsToRemountFromResetArgsEvent.add(storyId);\n",
"});\n",
"\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import { Preview, composeConfigs } from '@storybook/preview-api';
import type {
Renderer,
ComponentTitle,
Path,
ProjectAnnotations,
ModuleExports,
StoryIndex,
} from '@storybook/types';
import { Channel } from '@storybook/channels';
import { ExternalDocsContext } from './ExternalDocsContext';
type MetaExports = ModuleExports;
class ConstantMap<TKey, TValue extends string> {
entries = new Map<TKey, TValue>();
constructor(private prefix: string) {}
get(key: TKey) {
if (!this.entries.has(key)) {
this.entries.set(key, `${this.prefix}${this.entries.size}` as TValue);
}
return this.entries.get(key);
}
}
export class ExternalPreview<TRenderer extends Renderer = Renderer> extends Preview<TRenderer> {
private importPaths = new ConstantMap<MetaExports, Path>('./importPath/');
private titles = new ConstantMap<MetaExports, ComponentTitle>('title-');
private storyIndex: StoryIndex = { v: 4, entries: {} };
private moduleExportsByImportPath: Record<Path, ModuleExports> = {};
constructor(public projectAnnotations: ProjectAnnotations<TRenderer>) {
const importFn = (path: Path) => {
return Promise.resolve(this.moduleExportsByImportPath[path]);
};
const getProjectAnnotations = () =>
composeConfigs<TRenderer>([
{ parameters: { docs: { story: { inline: true } } } },
this.projectAnnotations,
]);
super(importFn, getProjectAnnotations, new Channel({}));
}
async getStoryIndexFromServer() {
return this.storyIndex;
}
processMetaExports = (metaExports: MetaExports) => {
const importPath = this.importPaths.get(metaExports);
this.moduleExportsByImportPath[importPath] = metaExports;
const title = metaExports.default.title || this.titles.get(metaExports);
const csfFile = this.storyStoreValue.processCSFFileWithCache<TRenderer>(
metaExports,
importPath,
title
);
Object.values(csfFile.stories).forEach(({ id, name }) => {
this.storyIndex.entries[id] = {
id,
importPath,
title,
name,
type: 'story',
};
});
this.onStoriesChanged({ storyIndex: this.storyIndex });
return csfFile;
};
docsContext = () => {
return new ExternalDocsContext(
this.channel,
this.storyStoreValue,
this.renderStoryToElement.bind(this),
this.processMetaExports.bind(this)
);
};
}
| code/ui/blocks/src/blocks/external/ExternalPreview.ts | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.0003036188136320561,
0.0001867817045422271,
0.00016568973660469055,
0.00016915991727728397,
0.000042146533814957365
] |
{
"id": 1,
"code_window": [
" */\n",
"const storyIdsToRemountFromResetArgsEvent = new Set<string>();\n",
"if (IS_SVELTE_V4) {\n",
" addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {\n",
" storyIdsToRemountFromResetArgsEvent.add(storyId);\n",
" });\n",
"}\n",
"const componentsByDomElementV4 = new Map<SvelteRenderer['canvasElement'], svelte.SvelteComponent>();\n",
"\n",
"function renderToCanvasV4(\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {\n",
" storyIdsToRemountFromResetArgsEvent.add(storyId);\n",
"});\n",
"\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import { defineConfig, mergeConfig } from 'vitest/config';
import { sep, posix } from 'path';
import { vitestCommonConfig } from '../../vitest.workspace';
export default mergeConfig(
vitestCommonConfig,
defineConfig({
test: {
environment: 'jsdom',
name: __dirname.split(sep).slice(-2).join(posix.sep),
},
})
);
| code/addons/storysource/vitest.config.ts | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017783635121304542,
0.0001749142538756132,
0.00017199217109009624,
0.0001749142538756132,
0.0000029220900614745915
] |
{
"id": 2,
"code_window": [
"\n",
" const existingComponent = componentsByDomElementV5.get(canvasElement);\n",
"\n",
" if (forceRemount) {\n",
" unmount(canvasElement);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let remount = forceRemount;\n",
" if (storyIdsToRemountFromResetArgsEvent.has(storyContext.id)) {\n",
" remount = true;\n",
" storyIdsToRemountFromResetArgsEvent.delete(storyContext.id);\n",
" }\n",
"\n",
" if (remount) {\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 139
} | import { expect } from '@storybook/test';
import { within, userEvent, waitFor } from '@storybook/testing-library';
import {
UPDATE_STORY_ARGS,
STORY_ARGS_UPDATED,
RESET_STORY_ARGS,
STORY_RENDERED,
} from '@storybook/core-events';
import { addons } from '@storybook/preview-api';
import ButtonView from './views/ButtonJavaScript.svelte';
export default {
component: ButtonView,
};
export const RemountOnResetStoryArgs = {
play: async ({ canvasElement, id }) => {
const canvas = await within(canvasElement);
const channel = addons.getChannel();
// Just to ensure the story is always in a clean state from the beginning, not really part of the test
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
const button = await canvas.getByRole('button');
await expect(button).toHaveTextContent('You clicked: 0');
await userEvent.click(button);
await expect(button).toHaveTextContent('You clicked: 1');
await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
await expect(button).toHaveTextContent('Changed: 1');
// expect that all state and args are reset after RESET_STORY_ARGS because Svelte needs to remount the component
// most other renderers would have 'You clicked: 1' here because they don't remount the component
// if this doesn't fully remount it would be 'undefined: 1' because undefined args are used as is in Svelte, and the state is kept
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await waitFor(async () =>
expect(await within(canvasElement).getByRole('button')).toHaveTextContent('You clicked: 0')
);
},
};
| code/renderers/svelte/template/stories/args.stories.js | 1 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.013807034119963646,
0.0037194942124187946,
0.00016284365847241133,
0.00017353155999444425,
0.005290426779538393
] |
{
"id": 2,
"code_window": [
"\n",
" const existingComponent = componentsByDomElementV5.get(canvasElement);\n",
"\n",
" if (forceRemount) {\n",
" unmount(canvasElement);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let remount = forceRemount;\n",
" if (storyIdsToRemountFromResetArgsEvent.has(storyContext.id)) {\n",
" remount = true;\n",
" storyIdsToRemountFromResetArgsEvent.delete(storyContext.id);\n",
" }\n",
"\n",
" if (remount) {\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 139
} | import type { Options } from '@storybook/types';
import type { PluginOptions as RDTSPluginOptions } from '@storybook/react-docgen-typescript-plugin';
export interface PluginOptions extends Options {
/**
* Optionally set the package name of a react-scripts fork.
* In most cases, the package is located automatically by this preset.
*/
scriptsPackageName?: string;
/**
* Overrides for Create React App's Webpack configuration.
*/
craOverrides?: {
fileLoaderExcludes?: string[];
};
typescriptOptions?: {
reactDocgen: 'react-docgen-typescript' | 'react-docgen' | false;
reactDocgenTypescriptOptions: RDTSPluginOptions;
};
}
export interface CoreConfig {
builder: {
options?: {
fsCache?: boolean;
lazyCompilation?: boolean;
};
};
}
| code/presets/create-react-app/src/types.ts | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00018145181820727885,
0.0001732746313791722,
0.00016476305609103292,
0.0001734418183332309,
0.000005911150310566882
] |
{
"id": 2,
"code_window": [
"\n",
" const existingComponent = componentsByDomElementV5.get(canvasElement);\n",
"\n",
" if (forceRemount) {\n",
" unmount(canvasElement);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let remount = forceRemount;\n",
" if (storyIdsToRemountFromResetArgsEvent.has(storyContext.id)) {\n",
" remount = true;\n",
" storyIdsToRemountFromResetArgsEvent.delete(storyContext.id);\n",
" }\n",
"\n",
" if (remount) {\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 139
} | import type { NextConfig } from 'next';
import { getCssModuleLocalIdent } from 'next/dist/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent';
import { cssFileResolve } from 'next/dist/build/webpack/config/blocks/css/loaders/file-resolve';
import type { Configuration as WebpackConfig } from 'webpack';
import semver from 'semver';
import { scopedResolve } from '../utils';
// This tries to follow nextjs's css config, please refer to this file for more info:
// https://github.com/vercel/next.js/blob/canary/packages/next/build/webpack-config.ts
export const configureCss = (baseConfig: WebpackConfig, nextConfig: NextConfig): void => {
const rules = baseConfig.module?.rules;
rules?.forEach((rule, i) => {
if (
rule &&
typeof rule !== 'string' &&
rule.test instanceof RegExp &&
rule.test.test('test.css')
) {
rules[i] = {
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
...getImportAndUrlCssLoaderOptions(nextConfig),
modules: {
auto: true,
getLocalIdent: getCssModuleLocalIdent,
},
},
},
require.resolve('postcss-loader'),
],
// We transform the "target.css" files from next.js into Javascript
// for Next.js to support fonts, so it should be ignored by the css-loader.
exclude: /next\/.*\/target.css$/,
};
}
});
rules?.push({
test: /\.(scss|sass)$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 3,
...getImportAndUrlCssLoaderOptions(nextConfig),
modules: { auto: true, getLocalIdent: getCssModuleLocalIdent },
},
},
require.resolve('postcss-loader'),
require.resolve('resolve-url-loader'),
{
loader: require.resolve('sass-loader'),
options: {
sourceMap: true,
sassOptions: nextConfig.sassOptions,
additionalData:
nextConfig.sassOptions?.prependData || nextConfig.sassOptions?.additionalData,
},
},
],
});
};
/**
* webpack v4-v6 api
* https://webpack.js.org/loaders/css-loader/#url
* https://webpack.js.org/loaders/css-loader/#import
*
* webpack v3 api
* https://webpack-3.cdn.bcebos.com/loaders/css-loader/#url
* https://webpack-3.cdn.bcebos.com/loaders/css-loader/#import
*/
const getImportAndUrlCssLoaderOptions = (nextConfig: NextConfig) =>
isCssLoaderV6()
? {
url: {
filter: getUrlResolver(nextConfig),
},
import: {
filter: getImportResolver(nextConfig),
},
}
: {
url: getUrlResolver(nextConfig),
import: getImportResolver(nextConfig),
};
const getUrlResolver = (nextConfig: NextConfig) => (url: string, resourcePath: string) =>
cssFileResolve(url, resourcePath, nextConfig.experimental?.urlImports);
const getImportResolver =
(nextConfig: NextConfig) =>
(url: string | { url: string; media: string }, _: string, resourcePath: string) =>
cssFileResolve(
typeof url === 'string' ? url : url.url,
resourcePath,
nextConfig.experimental?.urlImports
);
const isCssLoaderV6 = () => {
try {
const cssLoaderVersion = require(scopedResolve('css-loader/package.json')).version;
return semver.gte(cssLoaderVersion, '6.0.0');
} catch {
/**
* css-loader isn't a resolvable dependency
* thus storybook webpack 5 manager will
* resolve to use its version which is v5
*/
return false;
}
};
| code/frameworks/nextjs/src/css/webpack.ts | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017453219334129244,
0.0001702192093944177,
0.000166386816999875,
0.00017014563491102308,
0.000002422542593194521
] |
{
"id": 2,
"code_window": [
"\n",
" const existingComponent = componentsByDomElementV5.get(canvasElement);\n",
"\n",
" if (forceRemount) {\n",
" unmount(canvasElement);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let remount = forceRemount;\n",
" if (storyIdsToRemountFromResetArgsEvent.has(storyContext.id)) {\n",
" remount = true;\n",
" storyIdsToRemountFromResetArgsEvent.delete(storyContext.id);\n",
" }\n",
"\n",
" if (remount) {\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 139
} | ```ts
// Button.stories.ts
import type { Meta, StoryObj } from '@storybook/svelte';
import Button from './Button.svelte';
const meta = {
component: Button,
} satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Primary: Story = {
args: {
primary: true,
label: 'Button',
},
};
```
| docs/snippets/svelte/button-story-with-args.ts-4-9.mdx | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00018229098350275308,
0.00017816598119679838,
0.00017600350838620216,
0.00017620348080527037,
0.000002917952542702551
] |
{
"id": 3,
"code_window": [
" unmount(canvasElement);\n",
" }\n",
"\n",
" if (!existingComponent || forceRemount) {\n",
" const props = createSvelte5Props({\n",
" storyFn,\n",
" storyContext,\n",
" name,\n",
" title,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!existingComponent || remount) {\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 143
} | import { expect } from '@storybook/test';
import { within, userEvent, waitFor } from '@storybook/testing-library';
import {
UPDATE_STORY_ARGS,
STORY_ARGS_UPDATED,
RESET_STORY_ARGS,
STORY_RENDERED,
} from '@storybook/core-events';
import { addons } from '@storybook/preview-api';
import ButtonView from './views/ButtonJavaScript.svelte';
export default {
component: ButtonView,
};
export const RemountOnResetStoryArgs = {
play: async ({ canvasElement, id }) => {
const canvas = await within(canvasElement);
const channel = addons.getChannel();
// Just to ensure the story is always in a clean state from the beginning, not really part of the test
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
const button = await canvas.getByRole('button');
await expect(button).toHaveTextContent('You clicked: 0');
await userEvent.click(button);
await expect(button).toHaveTextContent('You clicked: 1');
await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
await expect(button).toHaveTextContent('Changed: 1');
// expect that all state and args are reset after RESET_STORY_ARGS because Svelte needs to remount the component
// most other renderers would have 'You clicked: 1' here because they don't remount the component
// if this doesn't fully remount it would be 'undefined: 1' because undefined args are used as is in Svelte, and the state is kept
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await waitFor(async () =>
expect(await within(canvasElement).getByRole('button')).toHaveTextContent('You clicked: 0')
);
},
};
| code/renderers/svelte/template/stories/args.stories.js | 1 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.0028976374305784702,
0.0007682736031711102,
0.00016575134941376746,
0.0001742196036502719,
0.0010697771795094013
] |
{
"id": 3,
"code_window": [
" unmount(canvasElement);\n",
" }\n",
"\n",
" if (!existingComponent || forceRemount) {\n",
" const props = createSvelte5Props({\n",
" storyFn,\n",
" storyContext,\n",
" name,\n",
" title,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!existingComponent || remount) {\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 143
} | ```ts
// Button.stories.ts
import type { Meta, StoryObj } from '@storybook/angular';
import { Button } from './button.component';
const meta: Meta<Button> = {
component: Button,
};
export default meta;
type Story = StoryObj<Button>;
export const WithLayout: Story = {
parameters: {
layout: 'centered',
},
};
```
| docs/snippets/angular/storybook-story-layout-param.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017783533257897943,
0.00017284027126152068,
0.00016672334459144622,
0.0001739621366141364,
0.000004605287358572241
] |
{
"id": 3,
"code_window": [
" unmount(canvasElement);\n",
" }\n",
"\n",
" if (!existingComponent || forceRemount) {\n",
" const props = createSvelte5Props({\n",
" storyFn,\n",
" storyContext,\n",
" name,\n",
" title,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!existingComponent || remount) {\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 143
} | <base target="_parent" />
<style>
/* While we aren't showing the main block yet, but still preparing, we want everything the user
has rendered, which may or may not be in #storybook-root, to be display none */
.sb-show-preparing-story:not(.sb-show-main) > :not(.sb-preparing-story) {
display: none;
}
.sb-show-preparing-docs:not(.sb-show-main) > :not(.sb-preparing-docs) {
display: none;
}
/* Hide our own blocks when we aren't supposed to be showing them */
:not(.sb-show-preparing-story) > .sb-preparing-story,
:not(.sb-show-preparing-docs) > .sb-preparing-docs,
:not(.sb-show-nopreview) > .sb-nopreview,
:not(.sb-show-errordisplay) > .sb-errordisplay {
display: none;
}
.sb-show-main.sb-main-centered {
margin: 0;
display: flex;
align-items: center;
min-height: 100vh;
}
.sb-show-main.sb-main-centered #storybook-root {
box-sizing: border-box;
margin: auto;
padding: 1rem;
max-height: 100%; /* Hack for centering correctly in IE11 */
}
/* Vertical centering fix for IE11 */
@media screen and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.sb-show-main.sb-main-centered:after {
content: '';
min-height: inherit;
font-size: 0;
}
}
.sb-show-main.sb-main-fullscreen {
margin: 0;
padding: 0;
display: block;
}
.sb-show-main.sb-main-padded {
margin: 0;
padding: 1rem;
display: block;
box-sizing: border-box;
}
.sb-wrapper {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
padding: 20px;
font-family:
'Nunito Sans',
-apple-system,
'.SFNSText-Regular',
'San Francisco',
BlinkMacSystemFont,
'Segoe UI',
'Helvetica Neue',
Helvetica,
Arial,
sans-serif;
-webkit-font-smoothing: antialiased;
overflow: auto;
}
.sb-heading {
font-size: 14px;
font-weight: 600;
letter-spacing: 0.2px;
margin: 10px 0;
padding-right: 25px;
}
.sb-nopreview {
display: flex;
align-content: center;
justify-content: center;
}
.sb-nopreview_main {
margin: auto;
padding: 30px;
border-radius: 10px;
background: rgba(0, 0, 0, 0.03);
}
.sb-nopreview_heading {
text-align: center;
}
.sb-errordisplay {
border: 20px solid rgb(187, 49, 49);
background: #222;
color: #fff;
z-index: 999999;
}
.sb-errordisplay_code {
padding: 10px;
background: #000;
color: #eee;
font-family: 'Operator Mono', 'Fira Code Retina', 'Fira Code', 'FiraCode-Retina', 'Andale Mono',
'Lucida Console', Consolas, Monaco, monospace;
}
.sb-errordisplay pre {
white-space: pre-wrap;
}
@-webkit-keyframes sb-rotate360 {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes sb-rotate360 {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@-webkit-keyframes sb-glow {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.4;
}
}
@keyframes sb-glow {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.4;
}
}
/* We display the preparing loaders *over* the rendering story */
.sb-preparing-story,
.sb-preparing-docs {
background-color: white;
/* Maximum possible z-index. It would be better to use stacking contexts to ensure it's always
on top, but this isn't possible as it would require making CSS changes that could affect user code */
z-index: 2147483647;
}
.sb-loader {
-webkit-animation: sb-rotate360 0.7s linear infinite;
animation: sb-rotate360 0.7s linear infinite;
border-color: rgba(97, 97, 97, 0.29);
border-radius: 50%;
border-style: solid;
border-top-color: #646464;
border-width: 2px;
display: inline-block;
height: 32px;
left: 50%;
margin-left: -16px;
margin-top: -16px;
mix-blend-mode: difference;
overflow: hidden;
position: absolute;
top: 50%;
transition: all 200ms ease-out;
vertical-align: top;
width: 32px;
z-index: 4;
}
.sb-previewBlock {
background: #fff;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 4px;
box-shadow: rgba(0, 0, 0, 0.1) 0 1px 3px 0;
margin: 25px auto 40px;
max-width: 600px;
}
.sb-previewBlock_header {
align-items: center;
box-shadow: rgba(0, 0, 0, 0.1) 0 -1px 0 0 inset;
display: flex;
gap: 14px;
height: 40px;
padding: 0 12px;
}
.sb-previewBlock_icon {
-webkit-animation: sb-glow 1.5s ease-in-out infinite;
animation: sb-glow 1.5s ease-in-out infinite;
background: #e6e6e6;
height: 14px;
width: 14px;
}
.sb-previewBlock_icon:last-child {
margin-left: auto;
}
.sb-previewBlock_body {
-webkit-animation: sb-glow 1.5s ease-in-out infinite;
animation: sb-glow 1.5s ease-in-out infinite;
height: 182px;
position: relative;
}
.sb-argstableBlock {
border-collapse: collapse;
border-spacing: 0;
font-size: 13px;
line-height: 20px;
margin: 25px auto 40px;
max-width: 600px;
text-align: left;
width: 100%;
}
.sb-argstableBlock th:first-of-type,
.sb-argstableBlock td:first-of-type {
padding-left: 20px;
}
.sb-argstableBlock th:nth-of-type(2),
.sb-argstableBlock td:nth-of-type(2) {
width: 35%;
}
.sb-argstableBlock th:nth-of-type(3),
.sb-argstableBlock td:nth-of-type(3) {
width: 15%;
}
.sb-argstableBlock th:last-of-type,
.sb-argstableBlock td:last-of-type {
width: 25%;
padding-right: 20px;
}
.sb-argstableBlock th span,
.sb-argstableBlock td span {
-webkit-animation: sb-glow 1.5s ease-in-out infinite;
animation: sb-glow 1.5s ease-in-out infinite;
background-color: rgba(0, 0, 0, 0.1);
border-radius: 0;
box-shadow: none;
color: transparent;
}
.sb-argstableBlock th {
padding: 10px 15px;
}
.sb-argstableBlock-body {
border-radius: 4px;
box-shadow:
rgba(0, 0, 0, 0.1) 0 1px 3px 1px,
rgba(0, 0, 0, 0.065) 0 0 0 1px;
}
.sb-argstableBlock-body tr {
background: transparent;
overflow: hidden;
}
.sb-argstableBlock-body tr:not(:first-child) {
border-top: 1px solid #e6e6e6;
}
.sb-argstableBlock-body tr:first-child td:first-child {
border-top-left-radius: 4px;
}
.sb-argstableBlock-body tr:first-child td:last-child {
border-top-right-radius: 4px;
}
.sb-argstableBlock-body tr:last-child td:first-child {
border-bottom-left-radius: 4px;
}
.sb-argstableBlock-body tr:last-child td:last-child {
border-bottom-right-radius: 4px;
}
.sb-argstableBlock-body td {
background: #fff;
padding-bottom: 10px;
padding-top: 10px;
vertical-align: top;
}
.sb-argstableBlock-body td:not(:first-of-type) {
padding-left: 15px;
padding-right: 15px;
}
.sb-argstableBlock-body button {
-webkit-animation: sb-glow 1.5s ease-in-out infinite;
animation: sb-glow 1.5s ease-in-out infinite;
background-color: rgba(0, 0, 0, 0.1);
border: 0;
border-radius: 0;
box-shadow: none;
color: transparent;
display: inline;
font-size: 12px;
line-height: 1;
padding: 10px 16px;
}
.sb-argstableBlock-summary {
margin-top: 4px;
}
.sb-argstableBlock-code {
margin-right: 4px;
margin-bottom: 4px;
padding: 2px 5px;
}
</style>
<script>
/* globals window */
/* eslint-disable no-underscore-dangle */
try {
if (window.top !== window) {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.top.__REACT_DEVTOOLS_GLOBAL_HOOK__;
window.__VUE_DEVTOOLS_GLOBAL_HOOK__ = window.top.__VUE_DEVTOOLS_GLOBAL_HOOK__;
window.top.__VUE_DEVTOOLS_CONTEXT__ = window.document;
}
} catch (e) {
// eslint-disable-next-line no-console
console.warn('unable to connect to top frame for connecting dev tools');
}
</script>
| code/lib/core-common/templates/base-preview-head.html | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017783533257897943,
0.00017248692165594548,
0.0001663596776779741,
0.00017289930838160217,
0.0000028386323265294777
] |
{
"id": 3,
"code_window": [
" unmount(canvasElement);\n",
" }\n",
"\n",
" if (!existingComponent || forceRemount) {\n",
" const props = createSvelte5Props({\n",
" storyFn,\n",
" storyContext,\n",
" name,\n",
" title,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!existingComponent || remount) {\n"
],
"file_path": "code/renderers/svelte/src/render.ts",
"type": "replace",
"edit_start_line_idx": 143
} | {
"stories": [
{
"name": "Head Inline",
"parameters": {
"server": { "id": "styles/head_inline" }
}
},
{
"name": "Head Src",
"parameters": {
"server": { "id": "styles/head_src" }
}
},
{
"name": "Body Inline",
"parameters": {
"server": { "id": "styles/body_inline" }
}
},
{
"name": "Body Src",
"parameters": {
"server": { "id": "styles/body_src" }
}
}
]
}
| test-storybooks/server-kitchen-sink/stories/html_content/styles.stories.json | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017442188982386142,
0.0001736354170134291,
0.00017281460168305784,
0.00017366975953336805,
6.566218075931829e-7
] |
{
"id": 4,
"code_window": [
"};\n",
"\n",
"export const RemountOnResetStoryArgs = {\n",
" play: async ({ canvasElement, id }) => {\n",
" const canvas = await within(canvasElement);\n",
" const channel = addons.getChannel();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" play: async ({ canvasElement, id, step }) => {\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 16
} | import { expect } from '@storybook/test';
import { within, userEvent, waitFor } from '@storybook/testing-library';
import {
UPDATE_STORY_ARGS,
STORY_ARGS_UPDATED,
RESET_STORY_ARGS,
STORY_RENDERED,
} from '@storybook/core-events';
import { addons } from '@storybook/preview-api';
import ButtonView from './views/ButtonJavaScript.svelte';
export default {
component: ButtonView,
};
export const RemountOnResetStoryArgs = {
play: async ({ canvasElement, id }) => {
const canvas = await within(canvasElement);
const channel = addons.getChannel();
// Just to ensure the story is always in a clean state from the beginning, not really part of the test
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
const button = await canvas.getByRole('button');
await expect(button).toHaveTextContent('You clicked: 0');
await userEvent.click(button);
await expect(button).toHaveTextContent('You clicked: 1');
await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
await expect(button).toHaveTextContent('Changed: 1');
// expect that all state and args are reset after RESET_STORY_ARGS because Svelte needs to remount the component
// most other renderers would have 'You clicked: 1' here because they don't remount the component
// if this doesn't fully remount it would be 'undefined: 1' because undefined args are used as is in Svelte, and the state is kept
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await waitFor(async () =>
expect(await within(canvasElement).getByRole('button')).toHaveTextContent('You clicked: 0')
);
},
};
| code/renderers/svelte/template/stories/args.stories.js | 1 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.9982692003250122,
0.7865666151046753,
0.0002183650794904679,
0.9962273836135864,
0.39375510811805725
] |
{
"id": 4,
"code_window": [
"};\n",
"\n",
"export const RemountOnResetStoryArgs = {\n",
" play: async ({ canvasElement, id }) => {\n",
" const canvas = await within(canvasElement);\n",
" const channel = addons.getChannel();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" play: async ({ canvasElement, id, step }) => {\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 16
} | import { global } from '@storybook/global';
const { window: globalWindow } = global;
globalWindow.STORYBOOK_ENV = 'HTML';
| code/renderers/html/src/globals.ts | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017134837980847806,
0.00017134837980847806,
0.00017134837980847806,
0.00017134837980847806,
0
] |
{
"id": 4,
"code_window": [
"};\n",
"\n",
"export const RemountOnResetStoryArgs = {\n",
" play: async ({ canvasElement, id }) => {\n",
" const canvas = await within(canvasElement);\n",
" const channel = addons.getChannel();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" play: async ({ canvasElement, id, step }) => {\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 16
} | {
"name": "@storybook/server",
"version": "8.0.0-beta.4",
"description": "Storybook Server renderer",
"keywords": [
"storybook"
],
"homepage": "https://github.com/storybookjs/storybook/tree/next/code/renderers/server",
"bugs": {
"url": "https://github.com/storybookjs/storybook/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/storybookjs/storybook.git",
"directory": "code/renderers/server"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/storybook"
},
"license": "MIT",
"exports": {
".": {
"types": "./dist/index.d.ts",
"node": "./dist/index.js",
"require": "./dist/index.js",
"import": "./dist/index.mjs"
},
"./preset": "./preset.js",
"./dist/entry-preview.mjs": "./dist/entry-preview.mjs",
"./package.json": "./package.json"
},
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"files": [
"dist/**/*",
"template/cli/**/*",
"README.md",
"*.js",
"*.d.ts",
"!src/**/*"
],
"scripts": {
"check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts",
"prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts"
},
"dependencies": {
"@storybook/csf": "^0.1.2",
"@storybook/csf-tools": "workspace:*",
"@storybook/global": "^5.0.0",
"@storybook/preview-api": "workspace:*",
"@storybook/types": "workspace:*",
"@types/fs-extra": "^11.0.1",
"fs-extra": "^11.1.0",
"ts-dedent": "^2.0.0",
"yaml": "^2.3.1"
},
"devDependencies": {
"typescript": "^5.3.2"
},
"engines": {
"node": ">=18.0.0"
},
"publishConfig": {
"access": "public"
},
"bundler": {
"entries": [
"./src/index.ts",
"./src/preset.ts",
"./src/entry-preview.ts"
],
"platform": "browser"
},
"gitHead": "e6a7fd8a655c69780bc20b9749c2699e44beae17"
}
| code/renderers/server/package.json | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017566852329764515,
0.0001723791065160185,
0.0001690056233201176,
0.00017209928773809224,
0.0000022103367882664315
] |
{
"id": 4,
"code_window": [
"};\n",
"\n",
"export const RemountOnResetStoryArgs = {\n",
" play: async ({ canvasElement, id }) => {\n",
" const canvas = await within(canvasElement);\n",
" const channel = addons.getChannel();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" play: async ({ canvasElement, id, step }) => {\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 16
} | # Storybook Logger
Any node logging that is done through storybook should be done through this package.
Examples:
```js
import { logger } from '@storybook/node-logger';
logger.info('Info message');
logger.warn('Warning message');
logger.error('Error message');
```
For more information visit: [storybook.js.org](https://storybook.js.org)
| code/lib/node-logger/README.md | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.000171667939866893,
0.000171472696820274,
0.00017127746832557023,
0.000171472696820274,
1.9523577066138387e-7
] |
{
"id": 5,
"code_window": [
" const canvas = await within(canvasElement);\n",
" const channel = addons.getChannel();\n",
"\n",
" // Just to ensure the story is always in a clean state from the beginning, not really part of the test\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n",
" const button = await canvas.getByRole('button');\n",
" await expect(button).toHaveTextContent('You clicked: 0');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step('Reset story args', async () => {\n",
" // Just to ensure the story is always in a clean state from the beginning, not really part of the test\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 20
} | import type { RenderContext, ArgsStoryFn } from '@storybook/types';
import { RESET_STORY_ARGS } from '@storybook/core-events';
/*
! DO NOT change these PreviewRender and createSvelte5Props imports to relative paths, it will break them.
! Relative imports will be compiled at build time by tsup, but we need Svelte to compile them
! when compiling the rest of the Svelte files.
*/
import PreviewRender from '@storybook/svelte/internal/PreviewRender.svelte';
// @ts-expect-error Don't know why TS doesn't pick up the types export here
import { createSvelte5Props } from '@storybook/svelte/internal/createSvelte5Props';
import { addons } from '@storybook/preview-api';
import * as svelte from 'svelte';
import { VERSION as SVELTE_VERSION } from 'svelte/compiler';
import type { SvelteRenderer } from './types';
const IS_SVELTE_V4 = Number(SVELTE_VERSION[0]) <= 4;
export function renderToCanvas(
renderContext: RenderContext<SvelteRenderer>,
canvasElement: SvelteRenderer['canvasElement']
) {
if (IS_SVELTE_V4) {
return renderToCanvasV4(renderContext, canvasElement);
} else {
return renderToCanvasV5(renderContext, canvasElement);
}
}
/**
* This is a workaround for the issue that when resetting args,
* the story needs to be remounted completely to revert to the component's default props.
* This is because Svelte does not itself revert to defaults when a prop is undefined.
* See https://github.com/storybookjs/storybook/issues/21470#issuecomment-1467056479
*
* We listen for the RESET_STORY_ARGS event and store the storyId to be reset
* We then use this in the renderToCanvas function to force remount the story
*
* This is only necessary in Svelte v4
*/
const storyIdsToRemountFromResetArgsEvent = new Set<string>();
if (IS_SVELTE_V4) {
addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {
storyIdsToRemountFromResetArgsEvent.add(storyId);
});
}
const componentsByDomElementV4 = new Map<SvelteRenderer['canvasElement'], svelte.SvelteComponent>();
function renderToCanvasV4(
{
storyFn,
title,
name,
showMain,
showError,
storyContext,
forceRemount,
}: RenderContext<SvelteRenderer>,
canvasElement: SvelteRenderer['canvasElement']
) {
function unmount(canvasElementToUnmount: SvelteRenderer['canvasElement']) {
if (!componentsByDomElementV4.has(canvasElementToUnmount)) {
return;
}
componentsByDomElementV4.get(canvasElementToUnmount)!.$destroy();
componentsByDomElementV4.delete(canvasElementToUnmount);
canvasElementToUnmount.innerHTML = '';
}
const existingComponent = componentsByDomElementV4.get(canvasElement);
let remount = forceRemount;
if (storyIdsToRemountFromResetArgsEvent.has(storyContext.id)) {
remount = true;
storyIdsToRemountFromResetArgsEvent.delete(storyContext.id);
}
if (remount) {
unmount(canvasElement);
}
if (!existingComponent || remount) {
const mountedComponent = new PreviewRender({
target: canvasElement,
props: {
storyFn,
storyContext,
name,
title,
showError,
},
});
componentsByDomElementV4.set(canvasElement, mountedComponent);
} else {
existingComponent.$set({
storyFn,
storyContext,
name,
title,
showError,
});
}
showMain();
// unmount the component when the story changes
return () => {
unmount(canvasElement);
};
}
const componentsByDomElementV5 = new Map<
SvelteRenderer['canvasElement'],
{ mountedComponent: ReturnType<(typeof svelte)['mount']>; props: RenderContext }
>();
function renderToCanvasV5(
{
storyFn,
title,
name,
showMain,
showError,
storyContext,
forceRemount,
}: RenderContext<SvelteRenderer>,
canvasElement: SvelteRenderer['canvasElement']
) {
function unmount(canvasElementToUnmount: SvelteRenderer['canvasElement']) {
const { mountedComponent } = componentsByDomElementV5.get(canvasElementToUnmount) ?? {};
if (!mountedComponent) {
return;
}
svelte.unmount(mountedComponent);
componentsByDomElementV5.delete(canvasElementToUnmount);
}
const existingComponent = componentsByDomElementV5.get(canvasElement);
if (forceRemount) {
unmount(canvasElement);
}
if (!existingComponent || forceRemount) {
const props = createSvelte5Props({
storyFn,
storyContext,
name,
title,
showError,
});
const mountedComponent = svelte.mount(PreviewRender, {
target: canvasElement,
props,
});
componentsByDomElementV5.set(canvasElement, { mountedComponent, props });
} else {
// We need to mutate the existing props for Svelte reactivity to work, we can't just re-assign them
Object.assign(existingComponent.props, {
storyFn,
storyContext,
name,
title,
showError,
});
}
showMain();
// unmount the component when the story changes
return () => {
unmount(canvasElement);
};
}
export const render: ArgsStoryFn<SvelteRenderer> = (args, context) => {
const { id, component: Component } = context;
if (!Component) {
throw new Error(
`Unable to render story ${id} as the component annotation is missing from the default export`
);
}
return { Component, props: args };
};
| code/renderers/svelte/src/render.ts | 1 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.024677246809005737,
0.002145229373127222,
0.00016567582497373223,
0.0004711245419457555,
0.005375845357775688
] |
{
"id": 5,
"code_window": [
" const canvas = await within(canvasElement);\n",
" const channel = addons.getChannel();\n",
"\n",
" // Just to ensure the story is always in a clean state from the beginning, not really part of the test\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n",
" const button = await canvas.getByRole('button');\n",
" await expect(button).toHaveTextContent('You clicked: 0');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step('Reset story args', async () => {\n",
" // Just to ensure the story is always in a clean state from the beginning, not really part of the test\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 20
} | export const str = (obj: any) => {
if (!obj) {
return '';
}
if (typeof obj === 'string') {
return obj as string;
}
throw new Error(`Description: expected string, got: ${JSON.stringify(obj)}`);
};
| code/lib/docs-tools/src/argTypes/docgen/utils/string.ts | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017351169663015753,
0.00017351169663015753,
0.00017351169663015753,
0.00017351169663015753,
0
] |
{
"id": 5,
"code_window": [
" const canvas = await within(canvasElement);\n",
" const channel = addons.getChannel();\n",
"\n",
" // Just to ensure the story is always in a clean state from the beginning, not really part of the test\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n",
" const button = await canvas.getByRole('button');\n",
" await expect(button).toHaveTextContent('You clicked: 0');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step('Reset story args', async () => {\n",
" // Just to ensure the story is always in a clean state from the beginning, not really part of the test\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 20
} | import { global } from '@storybook/global';
import React, { Fragment, useEffect } from 'react';
import isChromatic from 'chromatic/isChromatic';
import {
Global,
ThemeProvider,
themes,
createReset,
convert,
styled,
useTheme,
} from '@storybook/theming';
import { useArgs, DocsContext as DocsContextProps } from '@storybook/preview-api';
import type { PreviewWeb } from '@storybook/preview-api';
import type { ReactRenderer } from '@storybook/react';
import type { Channel } from '@storybook/channels';
import { DocsContext } from '@storybook/blocks';
import { DocsPageWrapper } from '../blocks/src/components';
const { document } = global;
const ThemeBlock = styled.div<{ side: 'left' | 'right' }>(
{
position: 'absolute',
top: 0,
left: 0,
right: '50vw',
width: '50vw',
height: '100vh',
bottom: 0,
overflow: 'auto',
padding: 10,
},
({ theme }) => ({
background: theme.background.content,
color: theme.color.defaultText,
}),
({ side }) =>
side === 'left'
? {
left: 0,
right: '50vw',
}
: {
right: 0,
left: '50vw',
}
);
const ThemeStack = styled.div(
{
position: 'relative',
minHeight: 'calc(50vh - 15px)',
},
({ theme }) => ({
background: theme.background.content,
color: theme.color.defaultText,
})
);
const PlayFnNotice = styled.div(
{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
borderBottom: '1px solid #ccc',
padding: '3px 8px',
fontSize: '10px',
fontWeight: 'bold',
'> *': {
display: 'block',
},
},
({ theme }) => ({
background: '#fffbd9',
color: theme.color.defaultText,
})
);
const ThemedSetRoot = () => {
const theme = useTheme();
useEffect(() => {
document.body.style.background = theme.background.content;
document.body.style.color = theme.color.defaultText;
});
return null;
};
// eslint-disable-next-line no-underscore-dangle
const preview = (window as any).__STORYBOOK_PREVIEW__ as PreviewWeb<ReactRenderer>;
const channel = (window as any).__STORYBOOK_ADDONS_CHANNEL__ as Channel;
export const loaders = [
/**
* This loader adds a DocsContext to the story, which is required for the most Blocks to work.
* A story will specify which stories they need in the index with:
* parameters: {
* relativeCsfPaths: ['../stories/MyStory.stories.tsx'], // relative to the story
* }
* The DocsContext will then be added via the decorator below.
*/
async ({ parameters: { relativeCsfPaths, attached = true } }) => {
if (!relativeCsfPaths) return {};
const csfFiles = await Promise.all(
(relativeCsfPaths as string[]).map(async (blocksRelativePath) => {
const projectRelativePath = `./ui/blocks/src/${blocksRelativePath.replace(
/^..\//,
''
)}.tsx`;
const entry = preview.storyStore.storyIndex?.importPathToEntry(projectRelativePath);
if (!entry) {
throw new Error(
`Couldn't find story file at ${projectRelativePath} (passed as ${blocksRelativePath})`
);
}
return preview.storyStore.loadCSFFileByStoryId(entry.id);
})
);
const docsContext = new DocsContextProps(
channel,
preview.storyStore,
preview.renderStoryToElement.bind(preview),
csfFiles
);
if (attached && csfFiles[0]) {
docsContext.attachCSFFile(csfFiles[0]);
}
return { docsContext };
},
];
export const decorators = [
// This decorator adds the DocsContext created in the loader above
(Story, { loaded: { docsContext } }) =>
docsContext ? (
<DocsContext.Provider value={docsContext}>
<Story />
</DocsContext.Provider>
) : (
<Story />
),
/**
* This decorator adds wrappers that contains global styles for stories to be targeted by.
* Activated with parameters.docsStyles = true
*/ (Story, { parameters: { docsStyles } }) =>
docsStyles ? (
<DocsPageWrapper>
<Story />
</DocsPageWrapper>
) : (
<Story />
),
/**
* This decorator renders the stories side-by-side, stacked or default based on the theme switcher in the toolbar
*/
(StoryFn, { globals, parameters, playFunction, args }) => {
const defaultTheme =
isChromatic() && !playFunction && args.autoplay !== true ? 'stacked' : 'light';
const theme = globals.theme || parameters.theme || defaultTheme;
switch (theme) {
case 'side-by-side': {
return (
<Fragment>
<ThemeProvider theme={convert(themes.light)}>
<Global styles={createReset} />
</ThemeProvider>
<ThemeProvider theme={convert(themes.light)}>
<ThemeBlock side="left" data-side="left">
<StoryFn />
</ThemeBlock>
</ThemeProvider>
<ThemeProvider theme={convert(themes.dark)}>
<ThemeBlock side="right" data-side="right">
<StoryFn />
</ThemeBlock>
</ThemeProvider>
</Fragment>
);
}
case 'stacked': {
return (
<Fragment>
<ThemeProvider theme={convert(themes.light)}>
<Global styles={createReset} />
</ThemeProvider>
<ThemeProvider theme={convert(themes.light)}>
<ThemeStack data-side="left">
<StoryFn />
</ThemeStack>
</ThemeProvider>
<ThemeProvider theme={convert(themes.dark)}>
<ThemeStack data-side="right">
<StoryFn />
</ThemeStack>
</ThemeProvider>
</Fragment>
);
}
case 'default':
default: {
return (
<ThemeProvider theme={convert(themes[theme])}>
<Global styles={createReset} />
<ThemedSetRoot />
{!parameters.theme && isChromatic() && playFunction && (
<>
<PlayFnNotice>
<span>
Detected play function in Chromatic. Rendering only light theme to avoid
multiple play functions in the same story.
</span>
</PlayFnNotice>
<div style={{ marginBottom: 20 }} />
</>
)}
<StoryFn />
</ThemeProvider>
);
}
}
},
/**
* This decorator shows the current state of the arg named in the
* parameters.withRawArg property, by updating the arg in the onChange function
* this also means that the arg will sync with the control panel
*
* If parameters.withRawArg is not set, this decorator will do nothing
*/
(StoryFn, { parameters, args, hooks }) => {
const [, updateArgs] = useArgs();
if (!parameters.withRawArg) {
return <StoryFn />;
}
return (
<>
<StoryFn
args={{
...args,
onChange: (newValue) => {
updateArgs({ [parameters.withRawArg]: newValue });
args.onChange?.(newValue);
},
}}
/>
<div style={{ marginTop: '1rem' }}>
Current <code>{parameters.withRawArg}</code>:{' '}
<pre>{JSON.stringify(args[parameters.withRawArg], null, 2) || 'undefined'}</pre>
</div>
</>
);
},
];
export const parameters = {
actions: { argTypesRegex: '^on.*' },
options: {
storySort: (a, b) =>
a.title === b.title ? 0 : a.id.localeCompare(b.id, undefined, { numeric: true }),
},
docs: {
theme: themes.light,
toc: {},
},
controls: {
presetColors: [
{ color: '#ff4785', title: 'Coral' },
{ color: '#1EA7FD', title: 'Ocean' },
{ color: 'rgb(252, 82, 31)', title: 'Orange' },
{ color: 'RGBA(255, 174, 0, 0.5)', title: 'Gold' },
{ color: 'hsl(101, 52%, 49%)', title: 'Green' },
{ color: 'HSLA(179,65%,53%,0.5)', title: 'Seafoam' },
{ color: '#6F2CAC', title: 'Purple' },
{ color: '#2A0481', title: 'Ultraviolet' },
{ color: 'black' },
{ color: '#333', title: 'Darkest' },
{ color: '#444', title: 'Darker' },
{ color: '#666', title: 'Dark' },
{ color: '#999', title: 'Mediumdark' },
{ color: '#ddd', title: 'Medium' },
{ color: '#EEE', title: 'Mediumlight' },
{ color: '#F3F3F3', title: 'Light' },
{ color: '#F8F8F8', title: 'Lighter' },
{ color: '#FFFFFF', title: 'Lightest' },
'#fe4a49',
'#FED766',
'rgba(0, 159, 183, 1)',
'HSLA(240,11%,91%,0.5)',
'slategray',
],
},
};
export const globalTypes = {
theme: {
name: 'Theme',
description: 'Global theme for components',
toolbar: {
icon: 'circlehollow',
title: 'Theme',
items: [
{ value: 'light', icon: 'circlehollow', title: 'light' },
{ value: 'dark', icon: 'circle', title: 'dark' },
{ value: 'side-by-side', icon: 'sidebar', title: 'side by side' },
{ value: 'stacked', icon: 'bottombar', title: 'stacked' },
],
},
},
};
| code/ui/.storybook/preview.tsx | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.0028649265877902508,
0.00026247184723615646,
0.0001662374270381406,
0.00017388345440849662,
0.0004683743172790855
] |
{
"id": 5,
"code_window": [
" const canvas = await within(canvasElement);\n",
" const channel = addons.getChannel();\n",
"\n",
" // Just to ensure the story is always in a clean state from the beginning, not really part of the test\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n",
" const button = await canvas.getByRole('button');\n",
" await expect(button).toHaveTextContent('You clicked: 0');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step('Reset story args', async () => {\n",
" // Just to ensure the story is always in a clean state from the beginning, not really part of the test\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 20
} | ```ts
// example-addon/src/babel/babelDefault.ts
import { TransformOptions } from '@babel/core';
export function babelDefault(config: TransformOptions) {
return {
...config,
plugins: [
...config.plugins,
[require.resolve('@babel/plugin-transform-react-jsx'), {}, 'preset'],
],
};
}
```
| docs/snippets/common/storybook-addons-preset-babelDefault.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017433094035368413,
0.00017332241986878216,
0.0001723138993838802,
0.00017332241986878216,
0.0000010085204849019647
] |
{
"id": 6,
"code_window": [
" await expect(button).toHaveTextContent('You clicked: 0');\n",
"\n",
" await userEvent.click(button);\n",
" await expect(button).toHaveTextContent('You clicked: 1');\n",
"\n",
" await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n",
" await expect(button).toHaveTextContent('Changed: 1');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step(\"Update story args with { text: 'Changed' }\", async () => {\n",
" await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 31
} | import { expect } from '@storybook/test';
import { within, userEvent, waitFor } from '@storybook/testing-library';
import {
UPDATE_STORY_ARGS,
STORY_ARGS_UPDATED,
RESET_STORY_ARGS,
STORY_RENDERED,
} from '@storybook/core-events';
import { addons } from '@storybook/preview-api';
import ButtonView from './views/ButtonJavaScript.svelte';
export default {
component: ButtonView,
};
export const RemountOnResetStoryArgs = {
play: async ({ canvasElement, id }) => {
const canvas = await within(canvasElement);
const channel = addons.getChannel();
// Just to ensure the story is always in a clean state from the beginning, not really part of the test
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
const button = await canvas.getByRole('button');
await expect(button).toHaveTextContent('You clicked: 0');
await userEvent.click(button);
await expect(button).toHaveTextContent('You clicked: 1');
await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });
await new Promise((resolve) => {
channel.once(STORY_RENDERED, resolve);
});
await expect(button).toHaveTextContent('Changed: 1');
// expect that all state and args are reset after RESET_STORY_ARGS because Svelte needs to remount the component
// most other renderers would have 'You clicked: 1' here because they don't remount the component
// if this doesn't fully remount it would be 'undefined: 1' because undefined args are used as is in Svelte, and the state is kept
await channel.emit(RESET_STORY_ARGS, { storyId: id });
await waitFor(async () =>
expect(await within(canvasElement).getByRole('button')).toHaveTextContent('You clicked: 0')
);
},
};
| code/renderers/svelte/template/stories/args.stories.js | 1 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.9732599258422852,
0.2674986720085144,
0.000485671975184232,
0.0009162705391645432,
0.3796052038669586
] |
{
"id": 6,
"code_window": [
" await expect(button).toHaveTextContent('You clicked: 0');\n",
"\n",
" await userEvent.click(button);\n",
" await expect(button).toHaveTextContent('You clicked: 1');\n",
"\n",
" await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n",
" await expect(button).toHaveTextContent('Changed: 1');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step(\"Update story args with { text: 'Changed' }\", async () => {\n",
" await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 31
} | <h1>Storybook Storysource Addon</h1>
This addon is used to show stories source in the addon panel.
[Framework Support](https://storybook.js.org/docs/react/api/frameworks-feature-support)

- [Getting Started](#getting-started)
- [Install using preset](#install-using-preset)
- [Theming](#theming)
- [Displaying full source](#displaying-full-source)
## Getting Started
First, install the addon
```sh
yarn add @storybook/addon-storysource --dev
```
You can add configuration for this addon by using a preset or by using the addon config with webpack
### Install using preset
Add the following to your `.storybook/main.js` exports:
```js
export default {
addons: ['@storybook/addon-storysource'],
};
```
You can pass configurations into the addon-storysource loader in your `.storybook/main.js` file, e.g.:
```js
export default {
addons: [
{
name: '@storybook/addon-storysource',
options: {
rule: {
// test: [/\.stories\.jsx?$/], This is default
include: [path.resolve(__dirname, '../src')], // You can specify directories
},
loaderOptions: {
prettierConfig: { printWidth: 80, singleQuote: false },
},
},
},
],
};
```
To customize the `source-loader`, pass `loaderOptions`. Valid configurations are documented in the [`source-loader` README](https://github.com/storybookjs/storybook/tree/next/code/lib/source-loader/README.md#options).
## Theming
Storysource will automatically use the light or dark syntax theme based on your storybook theme. See [Theming Storybook](https://storybook.js.org/docs/react/configure/theming) for more information.

## Displaying full source
Storybook 6.0 introduced an unintentional change to `source-loader`, in which only the source of the selected story is shown in the addon. To restore the old behavior, pass the`injectStoryParameters: false` option.
If you're using `addon-docs`:
```js
export default {
addons: [
{
name: '@storybook/addon-docs',
options: {
sourceLoaderOptions: {
injectStoryParameters: false,
},
},
},
],
};
```
If not:
```js
export default {
addons: [
{
name: '@storybook/addon-storysource',
options: {
loaderOptions: {
injectStoryParameters: false,
},
},
},
],
};
```
This bug will be resolved in a future version of the addon.
| code/addons/storysource/README.md | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.0001745490008033812,
0.00017026477144099772,
0.00016573887842241675,
0.00017049405141733587,
0.000002311488515260862
] |
{
"id": 6,
"code_window": [
" await expect(button).toHaveTextContent('You clicked: 0');\n",
"\n",
" await userEvent.click(button);\n",
" await expect(button).toHaveTextContent('You clicked: 1');\n",
"\n",
" await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n",
" await expect(button).toHaveTextContent('Changed: 1');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step(\"Update story args with { text: 'Changed' }\", async () => {\n",
" await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 31
} | ```ts
// .storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
const config: StorybookConfig = {
framework: '@storybook/your-framework',
stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
addons: [
// Other Storybook addons
'@storybook/addon-interactions', // 👈 Register the addon
],
};
export default config;
```
| docs/snippets/common/storybook-interactions-addon-registration.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017343164654448628,
0.0001719929277896881,
0.00017055422358680516,
0.0001719929277896881,
0.0000014387114788405597
] |
{
"id": 6,
"code_window": [
" await expect(button).toHaveTextContent('You clicked: 0');\n",
"\n",
" await userEvent.click(button);\n",
" await expect(button).toHaveTextContent('You clicked: 1');\n",
"\n",
" await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n",
" await expect(button).toHaveTextContent('Changed: 1');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step(\"Update story args with { text: 'Changed' }\", async () => {\n",
" await channel.emit(UPDATE_STORY_ARGS, { storyId: id, updatedArgs: { text: 'Changed' } });\n",
" await new Promise((resolve) => {\n",
" channel.once(STORY_RENDERED, resolve);\n",
" });\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 31
} | ```ts
// YourComponent.stories.ts|tsx
import type { Meta, StoryObj } from '@storybook/react';
import { YourComponent } from './your-component';
const meta = {
component: YourComponent,
//👇 Creates specific argTypes with options
argTypes: {
propertyA: {
options: ['Item One', 'Item Two', 'Item Three'],
control: { type: 'select' }, // Automatically inferred when 'options' is defined
},
propertyB: {
options: ['Another Item One', 'Another Item Two', 'Another Item Three'],
},
},
} satisfies Meta<typeof YourComponent>;
export default meta;
type Story = StoryObj<typeof meta>;
const someFunction = (valuePropertyA, valuePropertyB) => {
// Do some logic here
};
export const ExampleStory: Story = {
render: (args) => {
const { propertyA, propertyB } = args;
//👇 Assigns the function result to a variable
const someFunctionResult = someFunction(propertyA, propertyB);
return <YourComponent {...args} someProperty={someFunctionResult} />;
},
args: {
propertyA: 'Item One',
propertyB: 'Another Item One',
},
};
```
| docs/snippets/react/component-story-custom-args-complex.ts-4-9.mdx | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.0001757884892867878,
0.00017431673768442124,
0.00017217447748407722,
0.00017473082698415965,
0.0000012664168025366962
] |
{
"id": 7,
"code_window": [
"\n",
" // expect that all state and args are reset after RESET_STORY_ARGS because Svelte needs to remount the component\n",
" // most other renderers would have 'You clicked: 1' here because they don't remount the component\n",
" // if this doesn't fully remount it would be 'undefined: 1' because undefined args are used as is in Svelte, and the state is kept\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await waitFor(async () =>\n",
" expect(await within(canvasElement).getByRole('button')).toHaveTextContent('You clicked: 0')\n",
" );\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step('Reset story args', () => channel.emit(RESET_STORY_ARGS, { storyId: id }));\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 40
} | import type { RenderContext, ArgsStoryFn } from '@storybook/types';
import { RESET_STORY_ARGS } from '@storybook/core-events';
/*
! DO NOT change these PreviewRender and createSvelte5Props imports to relative paths, it will break them.
! Relative imports will be compiled at build time by tsup, but we need Svelte to compile them
! when compiling the rest of the Svelte files.
*/
import PreviewRender from '@storybook/svelte/internal/PreviewRender.svelte';
// @ts-expect-error Don't know why TS doesn't pick up the types export here
import { createSvelte5Props } from '@storybook/svelte/internal/createSvelte5Props';
import { addons } from '@storybook/preview-api';
import * as svelte from 'svelte';
import { VERSION as SVELTE_VERSION } from 'svelte/compiler';
import type { SvelteRenderer } from './types';
const IS_SVELTE_V4 = Number(SVELTE_VERSION[0]) <= 4;
export function renderToCanvas(
renderContext: RenderContext<SvelteRenderer>,
canvasElement: SvelteRenderer['canvasElement']
) {
if (IS_SVELTE_V4) {
return renderToCanvasV4(renderContext, canvasElement);
} else {
return renderToCanvasV5(renderContext, canvasElement);
}
}
/**
* This is a workaround for the issue that when resetting args,
* the story needs to be remounted completely to revert to the component's default props.
* This is because Svelte does not itself revert to defaults when a prop is undefined.
* See https://github.com/storybookjs/storybook/issues/21470#issuecomment-1467056479
*
* We listen for the RESET_STORY_ARGS event and store the storyId to be reset
* We then use this in the renderToCanvas function to force remount the story
*
* This is only necessary in Svelte v4
*/
const storyIdsToRemountFromResetArgsEvent = new Set<string>();
if (IS_SVELTE_V4) {
addons.getChannel().on(RESET_STORY_ARGS, ({ storyId }) => {
storyIdsToRemountFromResetArgsEvent.add(storyId);
});
}
const componentsByDomElementV4 = new Map<SvelteRenderer['canvasElement'], svelte.SvelteComponent>();
function renderToCanvasV4(
{
storyFn,
title,
name,
showMain,
showError,
storyContext,
forceRemount,
}: RenderContext<SvelteRenderer>,
canvasElement: SvelteRenderer['canvasElement']
) {
function unmount(canvasElementToUnmount: SvelteRenderer['canvasElement']) {
if (!componentsByDomElementV4.has(canvasElementToUnmount)) {
return;
}
componentsByDomElementV4.get(canvasElementToUnmount)!.$destroy();
componentsByDomElementV4.delete(canvasElementToUnmount);
canvasElementToUnmount.innerHTML = '';
}
const existingComponent = componentsByDomElementV4.get(canvasElement);
let remount = forceRemount;
if (storyIdsToRemountFromResetArgsEvent.has(storyContext.id)) {
remount = true;
storyIdsToRemountFromResetArgsEvent.delete(storyContext.id);
}
if (remount) {
unmount(canvasElement);
}
if (!existingComponent || remount) {
const mountedComponent = new PreviewRender({
target: canvasElement,
props: {
storyFn,
storyContext,
name,
title,
showError,
},
});
componentsByDomElementV4.set(canvasElement, mountedComponent);
} else {
existingComponent.$set({
storyFn,
storyContext,
name,
title,
showError,
});
}
showMain();
// unmount the component when the story changes
return () => {
unmount(canvasElement);
};
}
const componentsByDomElementV5 = new Map<
SvelteRenderer['canvasElement'],
{ mountedComponent: ReturnType<(typeof svelte)['mount']>; props: RenderContext }
>();
function renderToCanvasV5(
{
storyFn,
title,
name,
showMain,
showError,
storyContext,
forceRemount,
}: RenderContext<SvelteRenderer>,
canvasElement: SvelteRenderer['canvasElement']
) {
function unmount(canvasElementToUnmount: SvelteRenderer['canvasElement']) {
const { mountedComponent } = componentsByDomElementV5.get(canvasElementToUnmount) ?? {};
if (!mountedComponent) {
return;
}
svelte.unmount(mountedComponent);
componentsByDomElementV5.delete(canvasElementToUnmount);
}
const existingComponent = componentsByDomElementV5.get(canvasElement);
if (forceRemount) {
unmount(canvasElement);
}
if (!existingComponent || forceRemount) {
const props = createSvelte5Props({
storyFn,
storyContext,
name,
title,
showError,
});
const mountedComponent = svelte.mount(PreviewRender, {
target: canvasElement,
props,
});
componentsByDomElementV5.set(canvasElement, { mountedComponent, props });
} else {
// We need to mutate the existing props for Svelte reactivity to work, we can't just re-assign them
Object.assign(existingComponent.props, {
storyFn,
storyContext,
name,
title,
showError,
});
}
showMain();
// unmount the component when the story changes
return () => {
unmount(canvasElement);
};
}
export const render: ArgsStoryFn<SvelteRenderer> = (args, context) => {
const { id, component: Component } = context;
if (!Component) {
throw new Error(
`Unable to render story ${id} as the component annotation is missing from the default export`
);
}
return { Component, props: args };
};
| code/renderers/svelte/src/render.ts | 1 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.06852016597986221,
0.004828954581171274,
0.00016450451221317053,
0.0004125355335418135,
0.015185303054749966
] |
{
"id": 7,
"code_window": [
"\n",
" // expect that all state and args are reset after RESET_STORY_ARGS because Svelte needs to remount the component\n",
" // most other renderers would have 'You clicked: 1' here because they don't remount the component\n",
" // if this doesn't fully remount it would be 'undefined: 1' because undefined args are used as is in Svelte, and the state is kept\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await waitFor(async () =>\n",
" expect(await within(canvasElement).getByRole('button')).toHaveTextContent('You clicked: 0')\n",
" );\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step('Reset story args', () => channel.emit(RESET_STORY_ARGS, { storyId: id }));\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 40
} | /**
* This file needs to be run before any other script to ensure dependencies are installed
* Therefore, we cannot transform this file to Typescript, because it would require esbuild to be installed
*/
import { spawn } from 'child_process';
import { join } from 'path';
import { existsSync } from 'fs';
import * as url from 'url';
const logger = console;
const filename = url.fileURLToPath(import.meta.url);
const dirname = url.fileURLToPath(new URL('.', import.meta.url));
const checkDependencies = async () => {
const scriptsPath = join(dirname);
const codePath = join(dirname, '..', 'code');
const tasks = [];
if (!existsSync(join(scriptsPath, 'node_modules'))) {
tasks.push(
spawn('yarn', ['install'], {
cwd: scriptsPath,
shell: true,
stdio: ['inherit', 'inherit', 'inherit'],
})
);
}
if (!existsSync(join(codePath, 'node_modules'))) {
tasks.push(
spawn('yarn', ['install'], {
cwd: codePath,
shell: true,
stdio: ['inherit', 'inherit', 'inherit'],
})
);
}
if (tasks.length > 0) {
logger.log('installing dependencies');
await Promise.all(
tasks.map(
(t) =>
new Promise((res, rej) => {
t.on('exit', (code) => {
if (code !== 0) {
rej();
} else {
res();
}
});
})
)
).catch(() => {
tasks.forEach((t) => t.kill());
throw new Error('Failed to install dependencies');
});
// give the filesystem some time
await new Promise((res) => {
setTimeout(res, 1000);
});
}
};
checkDependencies().catch((e) => {
// eslint-disable-next-line no-console
console.error(e);
process.exit(1);
});
| scripts/check-dependencies.js | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017584513989277184,
0.00017223582835868,
0.00016857654554769397,
0.00017264054622501135,
0.000002154747335225693
] |
{
"id": 7,
"code_window": [
"\n",
" // expect that all state and args are reset after RESET_STORY_ARGS because Svelte needs to remount the component\n",
" // most other renderers would have 'You clicked: 1' here because they don't remount the component\n",
" // if this doesn't fully remount it would be 'undefined: 1' because undefined args are used as is in Svelte, and the state is kept\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await waitFor(async () =>\n",
" expect(await within(canvasElement).getByRole('button')).toHaveTextContent('You clicked: 0')\n",
" );\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step('Reset story args', () => channel.emit(RESET_STORY_ARGS, { storyId: id }));\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 40
} |
export default {
title: "Addons/Actions",
parameters: {
options: {
selectedPanel: "storybook/actions/panel"
}
}
};
export const Multiple_actions_config = {
name: "Multiple actions + config",
parameters: {
actions: [
"click",
"contextmenu",
{
clearOnStoryChange: false
}
],
server: {
id: "addons/actions/story3"
}
}
};
| code/presets/server-webpack/src/lib/compiler/__testfixtures__/actions.snapshot | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017196151020471007,
0.00017066831060219556,
0.00016828987281769514,
0.00017175354878418148,
0.0000016839510408317437
] |
{
"id": 7,
"code_window": [
"\n",
" // expect that all state and args are reset after RESET_STORY_ARGS because Svelte needs to remount the component\n",
" // most other renderers would have 'You clicked: 1' here because they don't remount the component\n",
" // if this doesn't fully remount it would be 'undefined: 1' because undefined args are used as is in Svelte, and the state is kept\n",
" await channel.emit(RESET_STORY_ARGS, { storyId: id });\n",
" await waitFor(async () =>\n",
" expect(await within(canvasElement).getByRole('button')).toHaveTextContent('You clicked: 0')\n",
" );\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" await step('Reset story args', () => channel.emit(RESET_STORY_ARGS, { storyId: id }));\n"
],
"file_path": "code/renderers/svelte/template/stories/args.stories.js",
"type": "replace",
"edit_start_line_idx": 40
} | ```js
// Button.stories.js
export default {
component: 'demo-button',
argTypes: {
variant: {
options: ['primary', 'secondary'],
control: { type: 'radio' },
},
},
};
```
| docs/snippets/web-components/button-story-controls-radio-group.js.mdx | 0 | https://github.com/storybookjs/storybook/commit/982be2deac6c8b3295126737de40f1f88e014a7c | [
0.00017251989629585296,
0.00016935894382186234,
0.0001661979767959565,
0.00016935894382186234,
0.0000031609597499482334
] |
{
"id": 0,
"code_window": [
" ],\n",
" \"scope\": \"resource\",\n",
" \"default\": \"wbr\",\n",
" \"description\": \"%html.format.unformatted.desc%\"\n",
" },\n",
" \"html.format.contentUnformatted\": {\n",
" \"type\": [\n",
" \"string\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"markdownDescription\": \"%html.format.unformatted.desc%\"\n"
],
"file_path": "extensions/html-language-features/package.json",
"type": "replace",
"edit_start_line_idx": 53
} | {
"name": "html-language-features",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"aiKey": "AIF-d9b70cd4-b9f9-4d70-929b-a071c400b217",
"engines": {
"vscode": "0.10.x"
},
"icon": "icons/html.png",
"activationEvents": [
"onLanguage:html",
"onLanguage:handlebars",
"onLanguage:razor"
],
"enableProposedApi": true,
"main": "./client/out/htmlMain",
"scripts": {
"compile": "gulp compile-extension:html-language-features-client compile-extension:html-language-features-server",
"watch": "gulp watch-extension:html-language-features-client watch-extension:html-language-features-server",
"postinstall": "cd server && yarn install",
"install-client-next": "yarn add vscode-languageclient@next"
},
"categories": [
"Programming Languages"
],
"contributes": {
"configuration": {
"id": "html",
"order": 20,
"type": "object",
"title": "HTML",
"properties": {
"html.format.enable": {
"type": "boolean",
"scope": "window",
"default": true,
"description": "%html.format.enable.desc%"
},
"html.format.wrapLineLength": {
"type": "integer",
"scope": "resource",
"default": 120,
"description": "%html.format.wrapLineLength.desc%"
},
"html.format.unformatted": {
"type": [
"string",
"null"
],
"scope": "resource",
"default": "wbr",
"description": "%html.format.unformatted.desc%"
},
"html.format.contentUnformatted": {
"type": [
"string",
"null"
],
"scope": "resource",
"default": "pre,code,textarea",
"description": "%html.format.contentUnformatted.desc%"
},
"html.format.indentInnerHtml": {
"type": "boolean",
"scope": "resource",
"default": false,
"description": "%html.format.indentInnerHtml.desc%"
},
"html.format.preserveNewLines": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "%html.format.preserveNewLines.desc%"
},
"html.format.maxPreserveNewLines": {
"type": [
"number",
"null"
],
"scope": "resource",
"default": null,
"description": "%html.format.maxPreserveNewLines.desc%"
},
"html.format.indentHandlebars": {
"type": "boolean",
"scope": "resource",
"default": false,
"description": "%html.format.indentHandlebars.desc%"
},
"html.format.endWithNewline": {
"type": "boolean",
"scope": "resource",
"default": false,
"description": "%html.format.endWithNewline.desc%"
},
"html.format.extraLiners": {
"type": [
"string",
"null"
],
"scope": "resource",
"default": "head, body, /html",
"description": "%html.format.extraLiners.desc%"
},
"html.format.wrapAttributes": {
"type": "string",
"scope": "resource",
"default": "auto",
"enum": [
"auto",
"force",
"force-aligned",
"force-expand-multiline",
"aligned-multiple"
],
"enumDescriptions": [
"%html.format.wrapAttributes.auto%",
"%html.format.wrapAttributes.force%",
"%html.format.wrapAttributes.forcealign%",
"%html.format.wrapAttributes.forcemultiline%",
"%html.format.wrapAttributes.alignedmultiple%"
],
"description": "%html.format.wrapAttributes.desc%"
},
"html.suggest.angular1": {
"type": "boolean",
"scope": "resource",
"default": false,
"description": "%html.suggest.angular1.desc%"
},
"html.suggest.ionic": {
"type": "boolean",
"scope": "resource",
"default": false,
"description": "%html.suggest.ionic.desc%"
},
"html.suggest.html5": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "%html.suggest.html5.desc%"
},
"html.validate.scripts": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "%html.validate.scripts%"
},
"html.validate.styles": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "%html.validate.styles%"
},
"html.autoClosingTags": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "%html.autoClosingTags%"
},
"html.trace.server": {
"type": "string",
"scope": "window",
"enum": [
"off",
"messages",
"verbose"
],
"default": "off",
"description": "%html.trace.server.desc%"
}
}
}
},
"dependencies": {
"vscode-extension-telemetry": "0.0.18",
"vscode-languageclient": "^5.1.0-next.9",
"vscode-nls": "^4.0.0"
},
"devDependencies": {
"@types/node": "^8.10.25"
}
}
| extensions/html-language-features/package.json | 1 | https://github.com/microsoft/vscode/commit/60b4b9939e5460ca3b9dc63340b6a42340207427 | [
0.9932340979576111,
0.05318935215473175,
0.00016512683941982687,
0.0005342491203919053,
0.22157301008701324
] |
{
"id": 0,
"code_window": [
" ],\n",
" \"scope\": \"resource\",\n",
" \"default\": \"wbr\",\n",
" \"description\": \"%html.format.unformatted.desc%\"\n",
" },\n",
" \"html.format.contentUnformatted\": {\n",
" \"type\": [\n",
" \"string\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"markdownDescription\": \"%html.format.unformatted.desc%\"\n"
],
"file_path": "extensions/html-language-features/package.json",
"type": "replace",
"edit_start_line_idx": 53
} | code-processed.iss | build/win32/.gitignore | 0 | https://github.com/microsoft/vscode/commit/60b4b9939e5460ca3b9dc63340b6a42340207427 | [
0.00016958091873675585,
0.00016958091873675585,
0.00016958091873675585,
0.00016958091873675585,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.