hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 2, "code_window": [ "\t\t// Note that there is currently no way to undo the file creation :/\n", "\t\tconst workspaceEdit = new vscode.WorkspaceEdit();\n", "\t\tworkspaceEdit.createFile(uri, { contents: file });\n", "\n", "\t\tconst pasteEdit = new vscode.DocumentPasteEdit(snippet);\n", "\t\tpasteEdit.additionalEdit = workspaceEdit;\n", "\t\treturn pasteEdit;\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst pasteEdit = new vscode.DocumentPasteEdit(snippet.snippet);\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/copyPaste.ts", "type": "replace", "edit_start_line_idx": 75 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { ITextDocument } from '../types/textDocument'; export class InMemoryDocument implements ITextDocument { constructor( public readonly uri: vscode.Uri, private readonly _contents: string, public readonly version = 0, ) { } getText(): string { return this._contents; } }
extensions/markdown-language-features/src/client/inMemoryDocument.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017884949920699, 0.00017314637079834938, 0.00016532896552234888, 0.0001752606185618788, 0.000005718610736948904 ]
{ "id": 2, "code_window": [ "\t\t// Note that there is currently no way to undo the file creation :/\n", "\t\tconst workspaceEdit = new vscode.WorkspaceEdit();\n", "\t\tworkspaceEdit.createFile(uri, { contents: file });\n", "\n", "\t\tconst pasteEdit = new vscode.DocumentPasteEdit(snippet);\n", "\t\tpasteEdit.additionalEdit = workspaceEdit;\n", "\t\treturn pasteEdit;\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst pasteEdit = new vscode.DocumentPasteEdit(snippet.snippet);\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/copyPaste.ts", "type": "replace", "edit_start_line_idx": 75 }
{ "displayName": "Powershell Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in Powershell files." }
extensions/powershell/package.nls.json
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017275528807658702, 0.00017275528807658702, 0.00017275528807658702, 0.00017275528807658702, 0 ]
{ "id": 3, "code_window": [ "\t\t\t// noop\n", "\t\t}\n", "\t}\n", "\n", "\tconst snippet = createUriListSnippet(document, uris);\n", "\tif (!snippet) {\n", "\t\treturn undefined;\n", "\t}\n", "\n", "\treturn {\n", "\t\tsnippet: snippet,\n", "\t\tlabel: uris.length > 1\n", "\t\t\t? vscode.l10n.t('Insert uri links')\n", "\t\t\t: vscode.l10n.t('Insert uri link')\n", "\t};\n", "}\n", "\n", "interface UriListSnippetOptions {\n", "\treadonly placeholderText?: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn createUriListSnippet(document, uris);\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import * as vscode from 'vscode'; import * as URI from 'vscode-uri'; import { Schemes } from '../../util/schemes'; export const imageFileExtensions = new Set<string>([ 'bmp', 'gif', 'ico', 'jpe', 'jpeg', 'jpg', 'png', 'psd', 'svg', 'tga', 'tif', 'tiff', 'webp', ]); const videoFileExtensions = new Set<string>([ 'ogg', 'mp4' ]); export function registerDropIntoEditorSupport(selector: vscode.DocumentSelector) { return vscode.languages.registerDocumentDropEditProvider(selector, new class implements vscode.DocumentDropEditProvider { async provideDocumentDropEdits(document: vscode.TextDocument, _position: vscode.Position, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken): Promise<vscode.DocumentDropEdit | undefined> { const enabled = vscode.workspace.getConfiguration('markdown', document).get('editor.drop.enabled', true); if (!enabled) { return undefined; } const snippet = await tryGetUriListSnippet(document, dataTransfer, token); if (!snippet) { return undefined; } const edit = new vscode.DocumentDropEdit(snippet.snippet); edit.label = snippet.label; return edit; } }, { id: 'insertLink', dropMimeTypes: [ 'text/uri-list' ] }); } export async function tryGetUriListSnippet(document: vscode.TextDocument, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken): Promise<{ snippet: vscode.SnippetString; label: string } | undefined> { const urlList = await dataTransfer.get('text/uri-list')?.asString(); if (!urlList || token.isCancellationRequested) { return undefined; } const uris: vscode.Uri[] = []; for (const resource of urlList.split(/\r?\n/g)) { try { uris.push(vscode.Uri.parse(resource)); } catch { // noop } } const snippet = createUriListSnippet(document, uris); if (!snippet) { return undefined; } return { snippet: snippet, label: uris.length > 1 ? vscode.l10n.t('Insert uri links') : vscode.l10n.t('Insert uri link') }; } interface UriListSnippetOptions { readonly placeholderText?: string; readonly placeholderStartIndex?: number; /** * Should the snippet be for an image? * * If `undefined`, tries to infer this from the uri. */ readonly insertAsImage?: boolean; readonly separator?: string; } export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): vscode.SnippetString | undefined { if (!uris.length) { return undefined; } const dir = getDocumentDir(document); const snippet = new vscode.SnippetString(); uris.forEach((uri, i) => { const mdPath = getMdPath(dir, uri); const ext = URI.Utils.extname(uri).toLowerCase().replace('.', ''); const insertAsImage = typeof options?.insertAsImage === 'undefined' ? imageFileExtensions.has(ext) : !!options.insertAsImage; const insertAsVideo = videoFileExtensions.has(ext); if (insertAsVideo) { snippet.appendText(`<video src="${mdPath}" controls title="`); snippet.appendPlaceholder('Title'); snippet.appendText('"></video>'); } else { snippet.appendText(insertAsImage ? '![' : '['); const placeholderText = options?.placeholderText ?? (insertAsImage ? 'Alt text' : 'label'); const placeholderIndex = typeof options?.placeholderStartIndex !== 'undefined' ? options?.placeholderStartIndex + i : undefined; snippet.appendPlaceholder(placeholderText, placeholderIndex); snippet.appendText(`](${mdPath})`); } if (i < uris.length - 1 && uris.length > 1) { snippet.appendText(options?.separator ?? ' '); } }); return snippet; } function getMdPath(dir: vscode.Uri | undefined, file: vscode.Uri) { if (dir && dir.scheme === file.scheme && dir.authority === file.authority) { if (file.scheme === Schemes.file) { // On windows, we must use the native `path.relative` to generate the relative path // so that drive-letters are resolved cast insensitively. However we then want to // convert back to a posix path to insert in to the document. const relativePath = path.relative(dir.fsPath, file.fsPath); return encodeURI(path.posix.normalize(relativePath.split(path.sep).join(path.posix.sep))); } return encodeURI(path.posix.relative(dir.path, file.path)); } return file.toString(false); } function getDocumentDir(document: vscode.TextDocument): vscode.Uri | undefined { const docUri = getParentDocumentUri(document); if (docUri.scheme === Schemes.untitled) { return vscode.workspace.workspaceFolders?.[0]?.uri; } return URI.Utils.dirname(docUri); } export function getParentDocumentUri(document: vscode.TextDocument): vscode.Uri { if (document.uri.scheme === Schemes.notebookCell) { for (const notebook of vscode.workspace.notebookDocuments) { for (const cell of notebook.getCells()) { if (cell.document === document) { return notebook.uri; } } } } return document.uri; }
extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts
1
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.998094379901886, 0.07996869832277298, 0.00016711711941752583, 0.0016262970166280866, 0.23967158794403076 ]
{ "id": 3, "code_window": [ "\t\t\t// noop\n", "\t\t}\n", "\t}\n", "\n", "\tconst snippet = createUriListSnippet(document, uris);\n", "\tif (!snippet) {\n", "\t\treturn undefined;\n", "\t}\n", "\n", "\treturn {\n", "\t\tsnippet: snippet,\n", "\t\tlabel: uris.length > 1\n", "\t\t\t? vscode.l10n.t('Insert uri links')\n", "\t\t\t: vscode.l10n.t('Insert uri link')\n", "\t};\n", "}\n", "\n", "interface UriListSnippetOptions {\n", "\treadonly placeholderText?: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn createUriListSnippet(document, uris);\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview'; import { IFindInputOptions } from 'vs/base/browser/ui/findinput/findInput'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { ContextScopedFindInput } from 'vs/platform/history/browser/contextScopedHistoryWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { NotebookFindFilters } from 'vs/workbench/contrib/notebook/browser/contrib/find/findFilters'; import { NotebookFindInputFilterButton } from 'vs/workbench/contrib/notebook/browser/contrib/find/notebookFindReplaceWidget'; import * as nls from 'vs/nls'; export class SearchFindInput extends ContextScopedFindInput { private _findFilter: NotebookFindInputFilterButton; private _filterChecked: boolean = false; private _visible: boolean = false; constructor( container: HTMLElement | null, contextViewProvider: IContextViewProvider, options: IFindInputOptions, contextKeyService: IContextKeyService, readonly contextMenuService: IContextMenuService, readonly instantiationService: IInstantiationService, readonly filters: NotebookFindFilters, filterStartVisiblitity: boolean ) { super(container, contextViewProvider, options, contextKeyService); this._findFilter = this._register( new NotebookFindInputFilterButton( filters, contextMenuService, instantiationService, options, nls.localize('searchFindInputNotebookFilter.label', "Notebook Find Filters") )); this.inputBox.paddingRight = (this.caseSensitive?.width() ?? 0) + (this.wholeWords?.width() ?? 0) + (this.regex?.width() ?? 0) + this._findFilter.width; this.controls.appendChild(this._findFilter.container); this._findFilter.container.classList.add('monaco-custom-toggle'); this.filterVisible = filterStartVisiblitity; } set filterVisible(show: boolean) { this._findFilter.container.style.display = show ? '' : 'none'; this._visible = show; this.updateStyles(); } override setEnabled(enabled: boolean) { super.setEnabled(enabled); if (enabled && (!this._filterChecked || !this._visible)) { this.regex?.enable(); } else { this.regex?.disable(); } } updateStyles() { // filter is checked if it's in a non-default state this._filterChecked = !this.filters.markupInput || this.filters.markupPreview || !this.filters.codeInput || !this.filters.codeOutput; // for now, allow the default state to enable regex, since it would be strange for regex to suddenly // be disabled when a notebook is opened. However, since regex isn't supported for outputs, this should // be revisted. if (this.regex) { if ((this.filters.markupPreview || this.filters.codeOutput) && this._filterChecked && this._visible) { this.regex.disable(); this.regex.domNode.tabIndex = -1; this.regex.domNode.classList.toggle('disabled', true); } else { this.regex.enable(); this.regex.domNode.tabIndex = 0; this.regex.domNode.classList.toggle('disabled', false); } } this._findFilter.applyStyles(this._filterChecked); } }
src/vs/workbench/contrib/search/browser/searchFindInput.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.0001757093850756064, 0.00017126224702224135, 0.00016129552386701107, 0.00017223539180122316, 0.000004152594556217082 ]
{ "id": 3, "code_window": [ "\t\t\t// noop\n", "\t\t}\n", "\t}\n", "\n", "\tconst snippet = createUriListSnippet(document, uris);\n", "\tif (!snippet) {\n", "\t\treturn undefined;\n", "\t}\n", "\n", "\treturn {\n", "\t\tsnippet: snippet,\n", "\t\tlabel: uris.length > 1\n", "\t\t\t? vscode.l10n.t('Insert uri links')\n", "\t\t\t: vscode.l10n.t('Insert uri link')\n", "\t};\n", "}\n", "\n", "interface UriListSnippetOptions {\n", "\treadonly placeholderText?: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn createUriListSnippet(document, uris);\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { tmpdir } from 'os'; import { realcase, realcaseSync, realpath, realpathSync } from 'vs/base/node/extpath'; import { Promises } from 'vs/base/node/pfs'; import { flakySuite, getRandomTestPath } from 'vs/base/test/node/testUtils'; flakySuite('Extpath', () => { let testDir: string; setup(() => { testDir = getRandomTestPath(tmpdir(), 'vsctests', 'extpath'); return Promises.mkdir(testDir, { recursive: true }); }); teardown(() => { return Promises.rm(testDir); }); test('realcaseSync', async () => { // assume case insensitive file system if (process.platform === 'win32' || process.platform === 'darwin') { const upper = testDir.toUpperCase(); const real = realcaseSync(upper); if (real) { // can be null in case of permission errors assert.notStrictEqual(real, upper); assert.strictEqual(real.toUpperCase(), upper); assert.strictEqual(real, testDir); } } // linux, unix, etc. -> assume case sensitive file system else { let real = realcaseSync(testDir); assert.strictEqual(real, testDir); real = realcaseSync(testDir.toUpperCase()); assert.strictEqual(real, testDir.toUpperCase()); } }); test('realcase', async () => { // assume case insensitive file system if (process.platform === 'win32' || process.platform === 'darwin') { const upper = testDir.toUpperCase(); const real = await realcase(upper); if (real) { // can be null in case of permission errors assert.notStrictEqual(real, upper); assert.strictEqual(real.toUpperCase(), upper); assert.strictEqual(real, testDir); } } // linux, unix, etc. -> assume case sensitive file system else { let real = await realcase(testDir); assert.strictEqual(real, testDir); real = await realcase(testDir.toUpperCase()); assert.strictEqual(real, testDir.toUpperCase()); } }); test('realpath', async () => { const realpathVal = await realpath(testDir); assert.ok(realpathVal); }); test('realpathSync', () => { const realpath = realpathSync(testDir); assert.ok(realpath); }); });
src/vs/base/test/node/extpath.test.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017495105566922575, 0.00017305900109931827, 0.00017016306810546666, 0.00017318857135251164, 0.0000015594127944495995 ]
{ "id": 3, "code_window": [ "\t\t\t// noop\n", "\t\t}\n", "\t}\n", "\n", "\tconst snippet = createUriListSnippet(document, uris);\n", "\tif (!snippet) {\n", "\t\treturn undefined;\n", "\t}\n", "\n", "\treturn {\n", "\t\tsnippet: snippet,\n", "\t\tlabel: uris.length > 1\n", "\t\t\t? vscode.l10n.t('Insert uri links')\n", "\t\t\t: vscode.l10n.t('Insert uri link')\n", "\t};\n", "}\n", "\n", "interface UriListSnippetOptions {\n", "\treadonly placeholderText?: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn createUriListSnippet(document, uris);\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as assert from 'assert'; import { Selection, workspace, CancellationTokenSource, CompletionTriggerKind, ConfigurationTarget, CompletionContext } from 'vscode'; import { withRandomFileEditor, closeAllEditors } from './testUtils'; import { expandEmmetAbbreviation } from '../abbreviationActions'; import { DefaultCompletionItemProvider } from '../defaultCompletionProvider'; const completionProvider = new DefaultCompletionItemProvider(); const htmlContents = ` <body class="header"> <ul class="nav main"> <li class="item1">img</li> <li class="item2">hithere</li> ul>li ul>li*2 ul>li.item$*2 ul>li.item$@44*2 <div i </ul> <style> .boo { display: dn; m10 } </style> <span></span> (ul>li.item$)*2 (ul>li.item$)*2+span (div>dl>(dt+dd)*2) <script type="text/html"> span.hello </script> <script type="text/javascript"> span.bye </script> </body> `; const invokeCompletionContext: CompletionContext = { triggerKind: CompletionTriggerKind.Invoke, triggerCharacter: undefined, }; suite('Tests for Expand Abbreviations (HTML)', () => { const oldValueForExcludeLanguages = workspace.getConfiguration('emmet').inspect('excludeLanguages'); const oldValueForIncludeLanguages = workspace.getConfiguration('emmet').inspect('includeLanguages'); teardown(closeAllEditors); test('Expand snippets (HTML)', () => { return testExpandAbbreviation('html', new Selection(3, 23, 3, 23), 'img', '<img src=\"\" alt=\"\">'); }); test('Expand snippets in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(3, 23, 3, 23), 'img', '<img src=\"\" alt=\"\">'); }); test('Expand snippets when no parent node (HTML)', () => { return withRandomFileEditor('img', 'html', async (editor, _doc) => { editor.selection = new Selection(0, 3, 0, 3); await expandEmmetAbbreviation(null); assert.strictEqual(editor.document.getText(), '<img src=\"\" alt=\"\">'); return Promise.resolve(); }); }); test('Expand snippets when no parent node in completion list (HTML)', () => { return withRandomFileEditor('img', 'html', async (editor, _doc) => { editor.selection = new Selection(0, 3, 0, 3); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); if (!completionPromise) { assert.strictEqual(!completionPromise, false, `Got unexpected undefined instead of a completion promise`); return Promise.resolve(); } const completionList = await completionPromise; assert.strictEqual(completionList && completionList.items && completionList.items.length > 0, true); if (completionList) { assert.strictEqual(completionList.items[0].label, 'img'); assert.strictEqual(((<string>completionList.items[0].documentation) || '').replace(/\|/g, ''), '<img src=\"\" alt=\"\">'); } return Promise.resolve(); }); }); test('Expand abbreviation (HTML)', () => { return testExpandAbbreviation('html', new Selection(5, 25, 5, 25), 'ul>li', '<ul>\n\t\t\t<li></li>\n\t\t</ul>'); }); test('Expand abbreviation in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(5, 25, 5, 25), 'ul>li', '<ul>\n\t<li></li>\n</ul>'); }); test('Expand text that is neither an abbreviation nor a snippet to tags (HTML)', () => { return testExpandAbbreviation('html', new Selection(4, 20, 4, 27), 'hithere', '<hithere></hithere>'); }); test('Do not Expand text that is neither an abbreviation nor a snippet to tags in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(4, 20, 4, 27), 'hithere', '<hithere></hithere>', true); }); test('Expand abbreviation with repeaters (HTML)', () => { return testExpandAbbreviation('html', new Selection(6, 27, 6, 27), 'ul>li*2', '<ul>\n\t\t\t<li></li>\n\t\t\t<li></li>\n\t\t</ul>'); }); test('Expand abbreviation with repeaters in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(6, 27, 6, 27), 'ul>li*2', '<ul>\n\t<li></li>\n\t<li></li>\n</ul>'); }); test('Expand abbreviation with numbered repeaters (HTML)', () => { return testExpandAbbreviation('html', new Selection(7, 33, 7, 33), 'ul>li.item$*2', '<ul>\n\t\t\t<li class="item1"></li>\n\t\t\t<li class="item2"></li>\n\t\t</ul>'); }); test('Expand abbreviation with numbered repeaters in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(7, 33, 7, 33), 'ul>li.item$*2', '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); }); test('Expand abbreviation with numbered repeaters with offset (HTML)', () => { return testExpandAbbreviation('html', new Selection(8, 36, 8, 36), 'ul>li.item$@44*2', '<ul>\n\t\t\t<li class="item44"></li>\n\t\t\t<li class="item45"></li>\n\t\t</ul>'); }); test('Expand abbreviation with numbered repeaters with offset in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(8, 36, 8, 36), 'ul>li.item$@44*2', '<ul>\n\t<li class="item44"></li>\n\t<li class="item45"></li>\n</ul>'); }); test('Expand abbreviation with numbered repeaters in groups (HTML)', () => { return testExpandAbbreviation('html', new Selection(17, 16, 17, 16), '(ul>li.item$)*2', '<ul>\n\t\t<li class="item1"></li>\n\t</ul>\n\t<ul>\n\t\t<li class="item2"></li>\n\t</ul>'); }); test('Expand abbreviation with numbered repeaters in groups in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(17, 16, 17, 16), '(ul>li.item$)*2', '<ul>\n\t<li class="item1"></li>\n</ul>\n<ul>\n\t<li class="item2"></li>\n</ul>'); }); test('Expand abbreviation with numbered repeaters in groups with sibling in the end (HTML)', () => { return testExpandAbbreviation('html', new Selection(18, 21, 18, 21), '(ul>li.item$)*2+span', '<ul>\n\t\t<li class="item1"></li>\n\t</ul>\n\t<ul>\n\t\t<li class="item2"></li>\n\t</ul>\n\t<span></span>'); }); test('Expand abbreviation with numbered repeaters in groups with sibling in the end in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(18, 21, 18, 21), '(ul>li.item$)*2+span', '<ul>\n\t<li class="item1"></li>\n</ul>\n<ul>\n\t<li class="item2"></li>\n</ul>\n<span></span>'); }); test('Expand abbreviation with nested groups (HTML)', () => { return testExpandAbbreviation('html', new Selection(19, 19, 19, 19), '(div>dl>(dt+dd)*2)', '<div>\n\t\t<dl>\n\t\t\t<dt></dt>\n\t\t\t<dd></dd>\n\t\t\t<dt></dt>\n\t\t\t<dd></dd>\n\t\t</dl>\n\t</div>'); }); test('Expand abbreviation with nested groups in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(19, 19, 19, 19), '(div>dl>(dt+dd)*2)', '<div>\n\t<dl>\n\t\t<dt></dt>\n\t\t<dd></dd>\n\t\t<dt></dt>\n\t\t<dd></dd>\n\t</dl>\n</div>'); }); test('Expand tag that is opened, but not closed (HTML)', () => { return testExpandAbbreviation('html', new Selection(9, 6, 9, 6), '<div', '<div></div>'); }); test('Do not Expand tag that is opened, but not closed in completion list (HTML)', () => { return testHtmlCompletionProvider(new Selection(9, 6, 9, 6), '<div', '<div></div>', true); }); test('No expanding text inside open tag (HTML)', () => { return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(2, 4, 2, 4); await expandEmmetAbbreviation(null); assert.strictEqual(editor.document.getText(), htmlContents); return Promise.resolve(); }); }); test('No expanding text inside open tag in completion list (HTML)', () => { return withRandomFileEditor(htmlContents, 'html', (editor, _doc) => { editor.selection = new Selection(2, 4, 2, 4); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`); return Promise.resolve(); }); }); test('No expanding text inside open tag when there is no closing tag (HTML)', () => { return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(9, 8, 9, 8); await expandEmmetAbbreviation(null); assert.strictEqual(editor.document.getText(), htmlContents); return Promise.resolve(); }); }); test('No expanding text inside open tag when there is no closing tag in completion list (HTML)', () => { return withRandomFileEditor(htmlContents, 'html', (editor, _doc) => { editor.selection = new Selection(9, 8, 9, 8); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`); return Promise.resolve(); }); }); test('No expanding text inside open tag when there is no closing tag when there is no parent node (HTML)', () => { const fileContents = '<img s'; return withRandomFileEditor(fileContents, 'html', async (editor, _doc) => { editor.selection = new Selection(0, 6, 0, 6); await expandEmmetAbbreviation(null); assert.strictEqual(editor.document.getText(), fileContents); return Promise.resolve(); }); }); test('No expanding text in completion list inside open tag when there is no closing tag when there is no parent node (HTML)', () => { const fileContents = '<img s'; return withRandomFileEditor(fileContents, 'html', (editor, _doc) => { editor.selection = new Selection(0, 6, 0, 6); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`); return Promise.resolve(); }); }); test('Expand css when inside style tag (HTML)', () => { return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(13, 16, 13, 19); const expandPromise = expandEmmetAbbreviation({ language: 'css' }); if (!expandPromise) { return Promise.resolve(); } await expandPromise; assert.strictEqual(editor.document.getText(), htmlContents.replace('m10', 'margin: 10px;')); return Promise.resolve(); }); }); test('Expand css when inside style tag in completion list (HTML)', () => { const abbreviation = 'm10'; const expandedText = 'margin: 10px;'; return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(13, 16, 13, 19); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); if (!completionPromise) { assert.strictEqual(1, 2, `Problem with expanding m10`); return Promise.resolve(); } const completionList = await completionPromise; if (!completionList || !completionList.items || !completionList.items.length) { assert.strictEqual(1, 2, `Problem with expanding m10`); return Promise.resolve(); } const emmetCompletionItem = completionList.items[0]; assert.strictEqual(emmetCompletionItem.label, expandedText, `Label of completion item doesnt match.`); assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`); assert.strictEqual(emmetCompletionItem.filterText, abbreviation, `FilterText of completion item doesnt match.`); return Promise.resolve(); }); }); test('No expanding text inside style tag if position is not for property name (HTML)', () => { return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(13, 14, 13, 14); await expandEmmetAbbreviation(null); assert.strictEqual(editor.document.getText(), htmlContents); return Promise.resolve(); }); }); test('Expand css when inside style attribute (HTML)', () => { const styleAttributeContent = '<div style="m10" class="hello"></div>'; return withRandomFileEditor(styleAttributeContent, 'html', async (editor, _doc) => { editor.selection = new Selection(0, 15, 0, 15); const expandPromise = expandEmmetAbbreviation(null); if (!expandPromise) { return Promise.resolve(); } await expandPromise; assert.strictEqual(editor.document.getText(), styleAttributeContent.replace('m10', 'margin: 10px;')); return Promise.resolve(); }); }); test('Expand css when inside style attribute in completion list (HTML)', () => { const abbreviation = 'm10'; const expandedText = 'margin: 10px;'; return withRandomFileEditor('<div style="m10" class="hello"></div>', 'html', async (editor, _doc) => { editor.selection = new Selection(0, 15, 0, 15); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); if (!completionPromise) { assert.strictEqual(1, 2, `Problem with expanding m10`); return Promise.resolve(); } const completionList = await completionPromise; if (!completionList || !completionList.items || !completionList.items.length) { assert.strictEqual(1, 2, `Problem with expanding m10`); return Promise.resolve(); } const emmetCompletionItem = completionList.items[0]; assert.strictEqual(emmetCompletionItem.label, expandedText, `Label of completion item doesnt match.`); assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`); assert.strictEqual(emmetCompletionItem.filterText, abbreviation, `FilterText of completion item doesnt match.`); return Promise.resolve(); }); }); test('Expand html when inside script tag with html type (HTML)', () => { return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(21, 12, 21, 12); const expandPromise = expandEmmetAbbreviation(null); if (!expandPromise) { return Promise.resolve(); } await expandPromise; assert.strictEqual(editor.document.getText(), htmlContents.replace('span.hello', '<span class="hello"></span>')); return Promise.resolve(); }); }); test('Expand html in completion list when inside script tag with html type (HTML)', () => { const abbreviation = 'span.hello'; const expandedText = '<span class="hello"></span>'; return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(21, 12, 21, 12); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); if (!completionPromise) { assert.strictEqual(1, 2, `Problem with expanding span.hello`); return Promise.resolve(); } const completionList = await completionPromise; if (!completionList || !completionList.items || !completionList.items.length) { assert.strictEqual(1, 2, `Problem with expanding span.hello`); return Promise.resolve(); } const emmetCompletionItem = completionList.items[0]; assert.strictEqual(emmetCompletionItem.label, abbreviation, `Label of completion item doesnt match.`); assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`); return Promise.resolve(); }); }); test('No expanding text inside script tag with javascript type (HTML)', () => { return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(24, 12, 24, 12); await expandEmmetAbbreviation(null); assert.strictEqual(editor.document.getText(), htmlContents); return Promise.resolve(); }); }); test('No expanding text in completion list inside script tag with javascript type (HTML)', () => { return withRandomFileEditor(htmlContents, 'html', (editor, _doc) => { editor.selection = new Selection(24, 12, 24, 12); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`); return Promise.resolve(); }); }); test('Expand html when inside script tag with javascript type if js is mapped to html (HTML)', async () => { await workspace.getConfiguration('emmet').update('includeLanguages', { 'javascript': 'html' }, ConfigurationTarget.Global); await withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(24, 10, 24, 10); const expandPromise = expandEmmetAbbreviation(null); if (!expandPromise) { return Promise.resolve(); } await expandPromise; assert.strictEqual(editor.document.getText(), htmlContents.replace('span.bye', '<span class="bye"></span>')); }); return workspace.getConfiguration('emmet').update('includeLanguages', oldValueForIncludeLanguages || {}, ConfigurationTarget.Global); }); test('Expand html in completion list when inside script tag with javascript type if js is mapped to html (HTML)', async () => { const abbreviation = 'span.bye'; const expandedText = '<span class="bye"></span>'; await workspace.getConfiguration('emmet').update('includeLanguages', { 'javascript': 'html' }, ConfigurationTarget.Global); await withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = new Selection(24, 10, 24, 10); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); if (!completionPromise) { assert.strictEqual(1, 2, `Problem with expanding span.bye`); return Promise.resolve(); } const completionList = await completionPromise; if (!completionList || !completionList.items || !completionList.items.length) { assert.strictEqual(1, 2, `Problem with expanding span.bye`); return Promise.resolve(); } const emmetCompletionItem = completionList.items[0]; assert.strictEqual(emmetCompletionItem.label, abbreviation, `Label of completion item (${emmetCompletionItem.label}) doesnt match.`); assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`); return Promise.resolve(); }); return workspace.getConfiguration('emmet').update('includeLanguages', oldValueForIncludeLanguages || {}, ConfigurationTarget.Global); }); // test('No expanding when html is excluded in the settings', () => { // return workspace.getConfiguration('emmet').update('excludeLanguages', ['html'], ConfigurationTarget.Global).then(() => { // return testExpandAbbreviation('html', new Selection(9, 6, 9, 6), '', '', true).then(() => { // return workspace.getConfiguration('emmet').update('excludeLanguages', oldValueForExcludeLanguages ? oldValueForExcludeLanguages.globalValue : undefined, ConfigurationTarget.Global); // }); // }); // }); test('No expanding when html is excluded in the settings in completion list', async () => { await workspace.getConfiguration('emmet').update('excludeLanguages', ['html'], ConfigurationTarget.Global); await testHtmlCompletionProvider(new Selection(9, 6, 9, 6), '', '', true); return workspace.getConfiguration('emmet').update('excludeLanguages', oldValueForExcludeLanguages ? oldValueForExcludeLanguages.globalValue : undefined, ConfigurationTarget.Global); }); // test('No expanding when php (mapped syntax) is excluded in the settings', () => { // return workspace.getConfiguration('emmet').update('excludeLanguages', ['php'], ConfigurationTarget.Global).then(() => { // return testExpandAbbreviation('php', new Selection(9, 6, 9, 6), '', '', true).then(() => { // return workspace.getConfiguration('emmet').update('excludeLanguages', oldValueForExcludeLanguages ? oldValueForExcludeLanguages.globalValue : undefined, ConfigurationTarget.Global); // }); // }); // }); }); suite('Tests for jsx, xml and xsl', () => { const oldValueForSyntaxProfiles = workspace.getConfiguration('emmet').inspect('syntaxProfiles'); teardown(closeAllEditors); test('Expand abbreviation with className instead of class in jsx', () => { return withRandomFileEditor('ul.nav', 'javascriptreact', async (editor, _doc) => { editor.selection = new Selection(0, 6, 0, 6); await expandEmmetAbbreviation({ language: 'javascriptreact' }); assert.strictEqual(editor.document.getText(), '<ul className="nav"></ul>'); return Promise.resolve(); }); }); test('Expand abbreviation with self closing tags for jsx', () => { return withRandomFileEditor('img', 'javascriptreact', async (editor, _doc) => { editor.selection = new Selection(0, 6, 0, 6); await expandEmmetAbbreviation({ language: 'javascriptreact' }); assert.strictEqual(editor.document.getText(), '<img src="" alt="" />'); return Promise.resolve(); }); }); test('Expand abbreviation with single quotes for jsx', async () => { await workspace.getConfiguration('emmet').update('syntaxProfiles', { jsx: { 'attr_quotes': 'single' } }, ConfigurationTarget.Global); return withRandomFileEditor('img', 'javascriptreact', async (editor, _doc) => { editor.selection = new Selection(0, 6, 0, 6); await expandEmmetAbbreviation({ language: 'javascriptreact' }); assert.strictEqual(editor.document.getText(), '<img src=\'\' alt=\'\' />'); return workspace.getConfiguration('emmet').update('syntaxProfiles', oldValueForSyntaxProfiles ? oldValueForSyntaxProfiles.globalValue : undefined, ConfigurationTarget.Global); }); }); test('Expand abbreviation with self closing tags for xml', () => { return withRandomFileEditor('img', 'xml', async (editor, _doc) => { editor.selection = new Selection(0, 6, 0, 6); await expandEmmetAbbreviation({ language: 'xml' }); assert.strictEqual(editor.document.getText(), '<img src="" alt=""/>'); return Promise.resolve(); }); }); test('Expand abbreviation with no self closing tags for html', () => { return withRandomFileEditor('img', 'html', async (editor, _doc) => { editor.selection = new Selection(0, 6, 0, 6); await expandEmmetAbbreviation({ language: 'html' }); assert.strictEqual(editor.document.getText(), '<img src="" alt="">'); return Promise.resolve(); }); }); test('Expand abbreviation with condition containing less than sign for jsx', () => { return withRandomFileEditor('if (foo < 10) { span.bar', 'javascriptreact', async (editor, _doc) => { editor.selection = new Selection(0, 27, 0, 27); await expandEmmetAbbreviation({ language: 'javascriptreact' }); assert.strictEqual(editor.document.getText(), 'if (foo < 10) { <span className="bar"></span>'); return Promise.resolve(); }); }); test('No expanding text inside open tag in completion list (jsx)', () => { return testNoCompletion('jsx', htmlContents, new Selection(2, 4, 2, 4)); }); test('No expanding tag that is opened, but not closed in completion list (jsx)', () => { return testNoCompletion('jsx', htmlContents, new Selection(9, 6, 9, 6)); }); test('No expanding text inside open tag when there is no closing tag in completion list (jsx)', () => { return testNoCompletion('jsx', htmlContents, new Selection(9, 8, 9, 8)); }); test('No expanding text in completion list inside open tag when there is no closing tag when there is no parent node (jsx)', () => { return testNoCompletion('jsx', '<img s', new Selection(0, 6, 0, 6)); }); }); function testExpandAbbreviation(syntax: string, selection: Selection, abbreviation: string, expandedText: string, shouldFail?: boolean): Thenable<any> { return withRandomFileEditor(htmlContents, syntax, async (editor, _doc) => { editor.selection = selection; const expandPromise = expandEmmetAbbreviation(null); if (!expandPromise) { if (!shouldFail) { assert.strictEqual(1, 2, `Problem with expanding ${abbreviation} to ${expandedText}`); } return Promise.resolve(); } await expandPromise; assert.strictEqual(editor.document.getText(), htmlContents.replace(abbreviation, expandedText)); return Promise.resolve(); }); } function testHtmlCompletionProvider(selection: Selection, abbreviation: string, expandedText: string, shouldFail?: boolean): Thenable<any> { return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => { editor.selection = selection; const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); if (!completionPromise) { if (!shouldFail) { assert.strictEqual(1, 2, `Problem with expanding ${abbreviation} to ${expandedText}`); } return Promise.resolve(); } const completionList = await completionPromise; if (!completionList || !completionList.items || !completionList.items.length) { if (!shouldFail) { assert.strictEqual(1, 2, `Problem with expanding ${abbreviation} to ${expandedText}`); } return Promise.resolve(); } const emmetCompletionItem = completionList.items[0]; assert.strictEqual(emmetCompletionItem.label, abbreviation, `Label of completion item doesnt match.`); assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`); return Promise.resolve(); }); } function testNoCompletion(syntax: string, fileContents: string, selection: Selection): Thenable<any> { return withRandomFileEditor(fileContents, syntax, (editor, _doc) => { editor.selection = selection; const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`); return Promise.resolve(); }); }
extensions/emmet/src/test/abbreviationAction.test.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017579049745108932, 0.0001712789962766692, 0.00016310489445459098, 0.00017168649355880916, 0.0000026612751753418706 ]
{ "id": 4, "code_window": [ "\n", "\treadonly separator?: string;\n", "}\n", "\n", "export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): vscode.SnippetString | undefined {\n", "\tif (!uris.length) {\n", "\t\treturn undefined;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\n", "export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): { snippet: vscode.SnippetString; label: string } | undefined {\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 99 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { Schemes } from '../../util/schemes'; import { getNewFileName } from './copyFiles'; import { createUriListSnippet, tryGetUriListSnippet } from './dropIntoEditor'; const supportedImageMimes = new Set([ 'image/png', 'image/jpg', ]); class PasteEditProvider implements vscode.DocumentPasteEditProvider { async provideDocumentPasteEdits( document: vscode.TextDocument, _ranges: readonly vscode.Range[], dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken, ): Promise<vscode.DocumentPasteEdit | undefined> { const enabled = vscode.workspace.getConfiguration('markdown', document).get('experimental.editor.pasteLinks.enabled', true); if (!enabled) { return; } if (document.uri.scheme === Schemes.notebookCell) { return; } for (const imageMime of supportedImageMimes) { const item = dataTransfer.get(imageMime); const file = item?.asFile(); if (item && file) { const edit = await this._makeCreateImagePasteEdit(document, file, token); if (token.isCancellationRequested) { return; } if (edit) { return edit; } } } const snippet = await tryGetUriListSnippet(document, dataTransfer, token); return snippet ? new vscode.DocumentPasteEdit(snippet.snippet) : undefined; } private async _makeCreateImagePasteEdit(document: vscode.TextDocument, file: vscode.DataTransferFile, token: vscode.CancellationToken): Promise<vscode.DocumentPasteEdit | undefined> { if (file.uri) { // If file is already in workspace, we don't want to create a copy of it const workspaceFolder = vscode.workspace.getWorkspaceFolder(file.uri); if (workspaceFolder) { const snippet = createUriListSnippet(document, [file.uri]); return snippet ? new vscode.DocumentPasteEdit(snippet) : undefined; } } const uri = await getNewFileName(document, file); if (token.isCancellationRequested) { return; } const snippet = createUriListSnippet(document, [uri]); if (!snippet) { return; } // Note that there is currently no way to undo the file creation :/ const workspaceEdit = new vscode.WorkspaceEdit(); workspaceEdit.createFile(uri, { contents: file }); const pasteEdit = new vscode.DocumentPasteEdit(snippet); pasteEdit.additionalEdit = workspaceEdit; return pasteEdit; } } export function registerPasteSupport(selector: vscode.DocumentSelector,) { return vscode.languages.registerDocumentPasteEditProvider(selector, new PasteEditProvider(), { pasteMimeTypes: [ 'text/uri-list', ...supportedImageMimes, ] }); }
extensions/markdown-language-features/src/languageFeatures/copyFiles/copyPaste.ts
1
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.999248206615448, 0.44339001178741455, 0.00021322170505300164, 0.04504989832639694, 0.4855717420578003 ]
{ "id": 4, "code_window": [ "\n", "\treadonly separator?: string;\n", "}\n", "\n", "export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): vscode.SnippetString | undefined {\n", "\tif (!uris.length) {\n", "\t\treturn undefined;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\n", "export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): { snippet: vscode.SnippetString; label: string } | undefined {\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 99 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { ITextModel } from 'vs/editor/common/model'; import { IModelService } from 'vs/editor/common/services/model'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ITerminalInstance, ITerminalService, IXtermTerminal } from 'vs/workbench/contrib/terminal/browser/terminal'; import type { Terminal } from 'xterm'; import { ITerminalCommand, TerminalCapability } from 'vs/platform/terminal/common/capabilities/capabilities'; import { IQuickInputService, IQuickPick, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput'; import { AudioCue, IAudioCueService } from 'vs/platform/audioCues/browser/audioCueService'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { withNullAsUndefined } from 'vs/base/common/types'; import { BufferContentTracker } from 'vs/workbench/contrib/terminalContrib/accessibility/browser/bufferContentTracker'; import { ILogService } from 'vs/platform/log/common/log'; import { IEditorViewState } from 'vs/editor/common/editorCommon'; import { TerminalAccessibleWidget } from 'vs/workbench/contrib/terminalContrib/accessibility/browser/terminalAccessibleWidget'; import { TerminalContextKeys } from 'vs/workbench/contrib/terminal/common/terminalContextKey'; export const enum NavigationType { Next = 'next', Previous = 'previous' } interface IAccessibleBufferQuickPickItem extends IQuickPickItem { lineNumber: number; exitCode?: number; } export const enum ClassName { AccessibleBuffer = 'accessible-buffer', Active = 'active' } export class AccessibleBufferWidget extends TerminalAccessibleWidget { private _isUpdating: boolean = false; private _pendingUpdates = 0; private _bufferTracker: BufferContentTracker; private _cursorPosition: { lineNumber: number; column: number } | undefined; constructor( _instance: Pick<ITerminalInstance, 'shellType' | 'capabilities' | 'onDidRequestFocus' | 'resource'>, _xterm: Pick<IXtermTerminal, 'shellIntegration' | 'getFont'> & { raw: Terminal }, @IInstantiationService _instantiationService: IInstantiationService, @IModelService _modelService: IModelService, @IConfigurationService _configurationService: IConfigurationService, @IQuickInputService private readonly _quickInputService: IQuickInputService, @IAudioCueService private readonly _audioCueService: IAudioCueService, @IContextKeyService _contextKeyService: IContextKeyService, @ILogService private readonly _logService: ILogService, @ITerminalService _terminalService: ITerminalService ) { super(ClassName.AccessibleBuffer, _instance, _xterm, TerminalContextKeys.accessibleBufferFocus, _instantiationService, _modelService, _configurationService, _contextKeyService, _terminalService); this._bufferTracker = _instantiationService.createInstance(BufferContentTracker, _xterm); this.element.ariaRoleDescription = localize('terminal.integrated.accessibleBuffer', 'Terminal buffer'); this.updateEditor(); this.add(this.editorWidget.onDidFocusEditorText(async () => { if (this.element.classList.contains(ClassName.Active)) { // the user has focused the editor via mouse or // Go to Command was run so we've already updated the editor return; } // if the editor is focused via tab, we need to update the model // and show it this.registerListeners(); await this.updateEditor(); this.element.classList.add(ClassName.Active); })); } navigateToCommand(type: NavigationType): void { const currentLine = this.editorWidget.getPosition()?.lineNumber || this._getDefaultCursorPosition()?.lineNumber; const commands = this._getCommandsWithEditorLine(); if (!commands?.length || !currentLine) { return; } const filteredCommands = type === NavigationType.Previous ? commands.filter(c => c.lineNumber < currentLine).sort((a, b) => b.lineNumber - a.lineNumber) : commands.filter(c => c.lineNumber > currentLine).sort((a, b) => a.lineNumber - b.lineNumber); if (!filteredCommands.length) { return; } this._cursorPosition = { lineNumber: filteredCommands[0].lineNumber, column: 1 }; this._resetPosition(); } private _getEditorLineForCommand(command: ITerminalCommand): number | undefined { let line = command.marker?.line; if (line === undefined || !command.command.length || line < 0) { return; } line = this._bufferTracker.bufferToEditorLineMapping.get(line); if (!line) { return; } return line + 1; } private _getCommandsWithEditorLine(): ICommandWithEditorLine[] | undefined { const commands = this._instance.capabilities.get(TerminalCapability.CommandDetection)?.commands; if (!commands?.length) { return; } const result: ICommandWithEditorLine[] = []; for (const command of commands) { const lineNumber = this._getEditorLineForCommand(command); if (!lineNumber) { continue; } result.push({ command, lineNumber }); } return result; } async createQuickPick(): Promise<IQuickPick<IAccessibleBufferQuickPickItem> | undefined> { this._cursorPosition = withNullAsUndefined(this.editorWidget.getPosition()); const commands = this._getCommandsWithEditorLine(); if (!commands) { return; } const quickPickItems: IAccessibleBufferQuickPickItem[] = []; for (const { command, lineNumber } of commands) { const line = this._getEditorLineForCommand(command); if (!line) { continue; } quickPickItems.push( { label: localize('terminal.integrated.symbolQuickPick.labelNoExitCode', '{0}', command.command), lineNumber, exitCode: command.exitCode }); } const quickPick = this._quickInputService.createQuickPick<IAccessibleBufferQuickPickItem>(); quickPick.canSelectMany = false; quickPick.onDidChangeActive(() => { const activeItem = quickPick.activeItems[0]; if (!activeItem) { return; } if (activeItem.exitCode) { this._audioCueService.playAudioCue(AudioCue.error, true); } this.editorWidget.revealLine(activeItem.lineNumber, 0); }); quickPick.onDidHide(() => { this._resetPosition(); quickPick.dispose(); }); quickPick.onDidAccept(() => { const item = quickPick.activeItems[0]; const model = this.editorWidget.getModel(); if (!model) { return; } if (!item && this._cursorPosition) { this._resetPosition(); } else { this._cursorPosition = { lineNumber: item.lineNumber, column: 1 }; } this.editorWidget.focus(); return; }); quickPick.items = quickPickItems.reverse(); return quickPick; } private _resetPosition(): void { this._cursorPosition = this._cursorPosition ?? this._getDefaultCursorPosition(); if (!this._cursorPosition) { return; } this.editorWidget.setPosition(this._cursorPosition); this.editorWidget.setScrollPosition({ scrollTop: this.editorWidget.getTopForLineNumber(this._cursorPosition.lineNumber) }); } override layout(): void { if (this._bufferTracker) { this._bufferTracker.reset(); } super.layout(); } async updateEditor(dataChanged?: boolean): Promise<void> { if (this._isUpdating) { this._pendingUpdates++; return; } this._isUpdating = true; const model = await this._updateModel(dataChanged); if (!model) { return; } this._isUpdating = false; if (this._pendingUpdates) { this._logService.debug('TerminalAccessibleBuffer._updateEditor: pending updates', this._pendingUpdates); this._pendingUpdates--; await this.updateEditor(dataChanged); } } override registerListeners(): void { super.registerListeners(); this._xterm.raw.onWriteParsed(async () => { if (this._xterm.raw.buffer.active.baseY === 0) { await this.updateEditor(true); } }); const onRequestUpdateEditor = Event.latch(this._xterm.raw.onScroll); this._listeners.push(onRequestUpdateEditor(async () => await this.updateEditor(true))); } private _getDefaultCursorPosition(): { lineNumber: number; column: number } | undefined { const modelLineCount = this.editorWidget.getModel()?.getLineCount(); return modelLineCount ? { lineNumber: modelLineCount, column: 1 } : undefined; } private async _updateModel(dataChanged?: boolean): Promise<ITextModel> { const linesBefore = this._bufferTracker.lines.length; this._bufferTracker.update(); const linesAfter = this._bufferTracker.lines.length; const modelChanged = linesBefore !== linesAfter; // Save the view state before the update if it was set by the user let savedViewState: IEditorViewState | undefined; if (dataChanged) { savedViewState = withNullAsUndefined(this.editorWidget.saveViewState()); } let model = this.editorWidget.getModel(); const text = this._bufferTracker.lines.join('\n'); if (model) { model.setValue(text); } else { model = await this.getTextModel(this._instance.resource.with({ fragment: `${ClassName.AccessibleBuffer}-${text}` })); } this.editorWidget.setModel(model); // If the model changed due to new data, restore the view state // If the model changed due to a refresh or the cursor is a the top, set to the bottom of the buffer // Otherwise, don't change the position const positionTopOfBuffer = this.editorWidget.getPosition()?.lineNumber === 1 && this.editorWidget.getPosition()?.column === 1; if (savedViewState) { this.editorWidget.restoreViewState(savedViewState); } else if (modelChanged || positionTopOfBuffer) { const defaultPosition = this._getDefaultCursorPosition(); if (defaultPosition) { this.editorWidget.setPosition(defaultPosition); this.editorWidget.setScrollPosition({ scrollTop: this.editorWidget.getTopForLineNumber(defaultPosition.lineNumber) }); } } return model!; } } interface ICommandWithEditorLine { command: ITerminalCommand; lineNumber: number }
src/vs/workbench/contrib/terminalContrib/accessibility/browser/terminalAccessibleBuffer.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00028296111850067973, 0.00017528710304759443, 0.0001644163712626323, 0.00017164058226626366, 0.000021314332116162404 ]
{ "id": 4, "code_window": [ "\n", "\treadonly separator?: string;\n", "}\n", "\n", "export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): vscode.SnippetString | undefined {\n", "\tif (!uris.length) {\n", "\t\treturn undefined;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\n", "export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): { snippet: vscode.SnippetString; label: string } | undefined {\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 99 }
{ "comments": { "lineComment": "#" }, "brackets": [ [ "{", "}" ], [ "[", "]" ], [ "(", ")" ] ], "autoClosingPairs": [ [ "{", "}" ], [ "[", "]" ], [ "(", ")" ], { "open": "'", "close": "'", "notIn": [ "string", "comment" ] }, { "open": "\"", "close": "\"", "notIn": [ "string", "comment" ] } ] }
extensions/make/language-configuration.json
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017437414498999715, 0.00017303247295785695, 0.00017199724970851094, 0.00017305798246525228, 7.857079253881238e-7 ]
{ "id": 4, "code_window": [ "\n", "\treadonly separator?: string;\n", "}\n", "\n", "export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): vscode.SnippetString | undefined {\n", "\tif (!uris.length) {\n", "\t\treturn undefined;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\n", "export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): { snippet: vscode.SnippetString; label: string } | undefined {\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 99 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { URI } from 'vs/base/common/uri'; import { workbenchInstantiationService, TestEditorService } from 'vs/workbench/test/browser/workbenchTestServices'; import { IModelService } from 'vs/editor/common/services/model'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { LanguageService } from 'vs/editor/common/services/languageService'; import { RangeHighlightDecorations } from 'vs/workbench/browser/codeeditor'; import { TextModel } from 'vs/editor/common/model/textModel'; import { createTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor'; import { Range, IRange } from 'vs/editor/common/core/range'; import { Position } from 'vs/editor/common/core/position'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { ModelService } from 'vs/editor/common/services/modelService'; import { CoreNavigationCommands } from 'vs/editor/browser/coreCommands'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { createTextModel } from 'vs/editor/test/common/testTextModel'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { DisposableStore } from 'vs/base/common/lifecycle'; suite('Editor - Range decorations', () => { let disposables: DisposableStore; let instantiationService: TestInstantiationService; let codeEditor: ICodeEditor; let model: TextModel; let text: string; let testObject: RangeHighlightDecorations; const modelsToDispose: TextModel[] = []; setup(() => { disposables = new DisposableStore(); instantiationService = <TestInstantiationService>workbenchInstantiationService(undefined, disposables); instantiationService.stub(IEditorService, new TestEditorService()); instantiationService.stub(ILanguageService, LanguageService); instantiationService.stub(IModelService, stubModelService(instantiationService)); text = 'LINE1' + '\n' + 'LINE2' + '\n' + 'LINE3' + '\n' + 'LINE4' + '\r\n' + 'LINE5'; model = aModel(URI.file('some_file')); codeEditor = createTestCodeEditor(model); instantiationService.stub(IEditorService, 'activeEditor', { get resource() { return codeEditor.getModel()!.uri; } }); instantiationService.stub(IEditorService, 'activeTextEditorControl', codeEditor); testObject = instantiationService.createInstance(RangeHighlightDecorations); }); teardown(() => { codeEditor.dispose(); modelsToDispose.forEach(model => model.dispose()); disposables.dispose(); }); test('highlight range for the resource if it is an active editor', function () { const range: IRange = new Range(1, 1, 1, 1); testObject.highlightRange({ resource: model.uri, range }); const actuals = rangeHighlightDecorations(model); assert.deepStrictEqual(actuals, [range]); }); test('remove highlight range', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); testObject.removeHighlightRange(); const actuals = rangeHighlightDecorations(model); assert.deepStrictEqual(actuals, []); }); test('highlight range for the resource removes previous highlight', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); const range: IRange = new Range(2, 2, 4, 3); testObject.highlightRange({ resource: model.uri, range }); const actuals = rangeHighlightDecorations(model); assert.deepStrictEqual(actuals, [range]); }); test('highlight range for a new resource removes highlight of previous resource', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); const anotherModel = prepareActiveEditor('anotherModel'); const range: IRange = new Range(2, 2, 4, 3); testObject.highlightRange({ resource: anotherModel.uri, range }); let actuals = rangeHighlightDecorations(model); assert.deepStrictEqual(actuals, []); actuals = rangeHighlightDecorations(anotherModel); assert.deepStrictEqual(actuals, [range]); }); test('highlight is removed on model change', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); prepareActiveEditor('anotherModel'); const actuals = rangeHighlightDecorations(model); assert.deepStrictEqual(actuals, []); }); test('highlight is removed on cursor position change', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); codeEditor.trigger('mouse', CoreNavigationCommands.MoveTo.id, { position: new Position(2, 1) }); const actuals = rangeHighlightDecorations(model); assert.deepStrictEqual(actuals, []); }); test('range is not highlight if not active editor', function () { const model = aModel(URI.file('some model')); testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); const actuals = rangeHighlightDecorations(model); assert.deepStrictEqual(actuals, []); }); test('previous highlight is not removed if not active editor', function () { const range = new Range(1, 1, 1, 1); testObject.highlightRange({ resource: model.uri, range }); const model1 = aModel(URI.file('some model')); testObject.highlightRange({ resource: model1.uri, range: { startLineNumber: 2, startColumn: 1, endLineNumber: 2, endColumn: 1 } }); const actuals = rangeHighlightDecorations(model); assert.deepStrictEqual(actuals, [range]); }); function prepareActiveEditor(resource: string): TextModel { const model = aModel(URI.file(resource)); codeEditor.setModel(model); return model; } function aModel(resource: URI, content: string = text): TextModel { const model = createTextModel(content, undefined, undefined, resource); modelsToDispose.push(model); return model; } function rangeHighlightDecorations(m: TextModel): IRange[] { const rangeHighlights: IRange[] = []; for (const dec of m.getAllDecorations()) { if (dec.options.className === 'rangeHighlight') { rangeHighlights.push(dec.range); } } rangeHighlights.sort(Range.compareRangesUsingStarts); return rangeHighlights; } function stubModelService(instantiationService: TestInstantiationService): IModelService { instantiationService.stub(IConfigurationService, new TestConfigurationService()); instantiationService.stub(IThemeService, new TestThemeService()); return instantiationService.createInstance(ModelService); } });
src/vs/workbench/test/browser/codeeditor.test.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017743543139658868, 0.00017314236902166158, 0.00016299715207424015, 0.00017427990678697824, 0.000003689826144182007 ]
{ "id": 5, "code_window": [ "\t}\n", "\n", "\tconst dir = getDocumentDir(document);\n", "\n", "\tconst snippet = new vscode.SnippetString();\n", "\turis.forEach((uri, i) => {\n", "\t\tconst mdPath = getMdPath(dir, uri);\n", "\n", "\t\tconst ext = URI.Utils.extname(uri).toLowerCase().replace('.', '');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tlet insertedLinkCount = 0;\n", "\tlet insertedImageCount = 0;\n", "\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 107 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import * as vscode from 'vscode'; import * as URI from 'vscode-uri'; import { Schemes } from '../../util/schemes'; export const imageFileExtensions = new Set<string>([ 'bmp', 'gif', 'ico', 'jpe', 'jpeg', 'jpg', 'png', 'psd', 'svg', 'tga', 'tif', 'tiff', 'webp', ]); const videoFileExtensions = new Set<string>([ 'ogg', 'mp4' ]); export function registerDropIntoEditorSupport(selector: vscode.DocumentSelector) { return vscode.languages.registerDocumentDropEditProvider(selector, new class implements vscode.DocumentDropEditProvider { async provideDocumentDropEdits(document: vscode.TextDocument, _position: vscode.Position, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken): Promise<vscode.DocumentDropEdit | undefined> { const enabled = vscode.workspace.getConfiguration('markdown', document).get('editor.drop.enabled', true); if (!enabled) { return undefined; } const snippet = await tryGetUriListSnippet(document, dataTransfer, token); if (!snippet) { return undefined; } const edit = new vscode.DocumentDropEdit(snippet.snippet); edit.label = snippet.label; return edit; } }, { id: 'insertLink', dropMimeTypes: [ 'text/uri-list' ] }); } export async function tryGetUriListSnippet(document: vscode.TextDocument, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken): Promise<{ snippet: vscode.SnippetString; label: string } | undefined> { const urlList = await dataTransfer.get('text/uri-list')?.asString(); if (!urlList || token.isCancellationRequested) { return undefined; } const uris: vscode.Uri[] = []; for (const resource of urlList.split(/\r?\n/g)) { try { uris.push(vscode.Uri.parse(resource)); } catch { // noop } } const snippet = createUriListSnippet(document, uris); if (!snippet) { return undefined; } return { snippet: snippet, label: uris.length > 1 ? vscode.l10n.t('Insert uri links') : vscode.l10n.t('Insert uri link') }; } interface UriListSnippetOptions { readonly placeholderText?: string; readonly placeholderStartIndex?: number; /** * Should the snippet be for an image? * * If `undefined`, tries to infer this from the uri. */ readonly insertAsImage?: boolean; readonly separator?: string; } export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): vscode.SnippetString | undefined { if (!uris.length) { return undefined; } const dir = getDocumentDir(document); const snippet = new vscode.SnippetString(); uris.forEach((uri, i) => { const mdPath = getMdPath(dir, uri); const ext = URI.Utils.extname(uri).toLowerCase().replace('.', ''); const insertAsImage = typeof options?.insertAsImage === 'undefined' ? imageFileExtensions.has(ext) : !!options.insertAsImage; const insertAsVideo = videoFileExtensions.has(ext); if (insertAsVideo) { snippet.appendText(`<video src="${mdPath}" controls title="`); snippet.appendPlaceholder('Title'); snippet.appendText('"></video>'); } else { snippet.appendText(insertAsImage ? '![' : '['); const placeholderText = options?.placeholderText ?? (insertAsImage ? 'Alt text' : 'label'); const placeholderIndex = typeof options?.placeholderStartIndex !== 'undefined' ? options?.placeholderStartIndex + i : undefined; snippet.appendPlaceholder(placeholderText, placeholderIndex); snippet.appendText(`](${mdPath})`); } if (i < uris.length - 1 && uris.length > 1) { snippet.appendText(options?.separator ?? ' '); } }); return snippet; } function getMdPath(dir: vscode.Uri | undefined, file: vscode.Uri) { if (dir && dir.scheme === file.scheme && dir.authority === file.authority) { if (file.scheme === Schemes.file) { // On windows, we must use the native `path.relative` to generate the relative path // so that drive-letters are resolved cast insensitively. However we then want to // convert back to a posix path to insert in to the document. const relativePath = path.relative(dir.fsPath, file.fsPath); return encodeURI(path.posix.normalize(relativePath.split(path.sep).join(path.posix.sep))); } return encodeURI(path.posix.relative(dir.path, file.path)); } return file.toString(false); } function getDocumentDir(document: vscode.TextDocument): vscode.Uri | undefined { const docUri = getParentDocumentUri(document); if (docUri.scheme === Schemes.untitled) { return vscode.workspace.workspaceFolders?.[0]?.uri; } return URI.Utils.dirname(docUri); } export function getParentDocumentUri(document: vscode.TextDocument): vscode.Uri { if (document.uri.scheme === Schemes.notebookCell) { for (const notebook of vscode.workspace.notebookDocuments) { for (const cell of notebook.getCells()) { if (cell.document === document) { return notebook.uri; } } } } return document.uri; }
extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts
1
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.9981051683425903, 0.23316209018230438, 0.00016947682888712734, 0.0017606483306735754, 0.409366637468338 ]
{ "id": 5, "code_window": [ "\t}\n", "\n", "\tconst dir = getDocumentDir(document);\n", "\n", "\tconst snippet = new vscode.SnippetString();\n", "\turis.forEach((uri, i) => {\n", "\t\tconst mdPath = getMdPath(dir, uri);\n", "\n", "\t\tconst ext = URI.Utils.extname(uri).toLowerCase().replace('.', '');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tlet insertedLinkCount = 0;\n", "\tlet insertedImageCount = 0;\n", "\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 107 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IDragAndDropData } from 'vs/base/browser/dnd'; import { IIdentityProvider, IListDragAndDrop, IListDragOverReaction, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { ElementsDragAndDropData } from 'vs/base/browser/ui/list/listView'; import { IListStyles } from 'vs/base/browser/ui/list/listWidget'; import { ComposedTreeDelegate, TreeFindMode as TreeFindMode, IAbstractTreeOptions, IAbstractTreeOptionsUpdate } from 'vs/base/browser/ui/tree/abstractTree'; import { ICompressedTreeElement, ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; import { getVisibleState, isFilterResult } from 'vs/base/browser/ui/tree/indexTreeModel'; import { CompressibleObjectTree, ICompressibleKeyboardNavigationLabelProvider, ICompressibleObjectTreeOptions, ICompressibleTreeRenderer, IObjectTreeOptions, IObjectTreeSetChildrenOptions, ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { IAsyncDataSource, ICollapseStateChangeEvent, IObjectTreeElement, ITreeContextMenuEvent, ITreeDragAndDrop, ITreeEvent, ITreeFilter, ITreeMouseEvent, ITreeNode, ITreeRenderer, ITreeSorter, TreeError, TreeFilterResult, TreeVisibility, WeakMapper } from 'vs/base/browser/ui/tree/tree'; import { CancelablePromise, createCancelablePromise, Promises, timeout } from 'vs/base/common/async'; import { Codicon } from 'vs/base/common/codicons'; import { ThemeIcon } from 'vs/base/common/themables'; import { isCancellationError, onUnexpectedError } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { Iterable } from 'vs/base/common/iterator'; import { DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle'; import { ScrollEvent } from 'vs/base/common/scrollable'; import { isIterable } from 'vs/base/common/types'; interface IAsyncDataTreeNode<TInput, T> { element: TInput | T; readonly parent: IAsyncDataTreeNode<TInput, T> | null; readonly children: IAsyncDataTreeNode<TInput, T>[]; readonly id?: string | null; refreshPromise: Promise<void> | undefined; hasChildren: boolean; stale: boolean; slow: boolean; collapsedByDefault: boolean | undefined; } interface IAsyncDataTreeNodeRequiredProps<TInput, T> extends Partial<IAsyncDataTreeNode<TInput, T>> { readonly element: TInput | T; readonly parent: IAsyncDataTreeNode<TInput, T> | null; readonly hasChildren: boolean; } function createAsyncDataTreeNode<TInput, T>(props: IAsyncDataTreeNodeRequiredProps<TInput, T>): IAsyncDataTreeNode<TInput, T> { return { ...props, children: [], refreshPromise: undefined, stale: true, slow: false, collapsedByDefault: undefined }; } function isAncestor<TInput, T>(ancestor: IAsyncDataTreeNode<TInput, T>, descendant: IAsyncDataTreeNode<TInput, T>): boolean { if (!descendant.parent) { return false; } else if (descendant.parent === ancestor) { return true; } else { return isAncestor(ancestor, descendant.parent); } } function intersects<TInput, T>(node: IAsyncDataTreeNode<TInput, T>, other: IAsyncDataTreeNode<TInput, T>): boolean { return node === other || isAncestor(node, other) || isAncestor(other, node); } interface IDataTreeListTemplateData<T> { templateData: T; } type AsyncDataTreeNodeMapper<TInput, T, TFilterData> = WeakMapper<ITreeNode<IAsyncDataTreeNode<TInput, T> | null, TFilterData>, ITreeNode<TInput | T, TFilterData>>; class AsyncDataTreeNodeWrapper<TInput, T, TFilterData> implements ITreeNode<TInput | T, TFilterData> { get element(): T { return this.node.element!.element as T; } get children(): ITreeNode<T, TFilterData>[] { return this.node.children.map(node => new AsyncDataTreeNodeWrapper(node)); } get depth(): number { return this.node.depth; } get visibleChildrenCount(): number { return this.node.visibleChildrenCount; } get visibleChildIndex(): number { return this.node.visibleChildIndex; } get collapsible(): boolean { return this.node.collapsible; } get collapsed(): boolean { return this.node.collapsed; } get visible(): boolean { return this.node.visible; } get filterData(): TFilterData | undefined { return this.node.filterData; } constructor(private node: ITreeNode<IAsyncDataTreeNode<TInput, T> | null, TFilterData>) { } } class AsyncDataTreeRenderer<TInput, T, TFilterData, TTemplateData> implements ITreeRenderer<IAsyncDataTreeNode<TInput, T>, TFilterData, IDataTreeListTemplateData<TTemplateData>> { readonly templateId: string; private renderedNodes = new Map<IAsyncDataTreeNode<TInput, T>, IDataTreeListTemplateData<TTemplateData>>(); constructor( protected renderer: ITreeRenderer<T, TFilterData, TTemplateData>, protected nodeMapper: AsyncDataTreeNodeMapper<TInput, T, TFilterData>, readonly onDidChangeTwistieState: Event<IAsyncDataTreeNode<TInput, T>> ) { this.templateId = renderer.templateId; } renderTemplate(container: HTMLElement): IDataTreeListTemplateData<TTemplateData> { const templateData = this.renderer.renderTemplate(container); return { templateData }; } renderElement(node: ITreeNode<IAsyncDataTreeNode<TInput, T>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void { this.renderer.renderElement(this.nodeMapper.map(node) as ITreeNode<T, TFilterData>, index, templateData.templateData, height); } renderTwistie(element: IAsyncDataTreeNode<TInput, T>, twistieElement: HTMLElement): boolean { if (element.slow) { twistieElement.classList.add(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading)); return true; } else { twistieElement.classList.remove(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading)); return false; } } disposeElement(node: ITreeNode<IAsyncDataTreeNode<TInput, T>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void { this.renderer.disposeElement?.(this.nodeMapper.map(node) as ITreeNode<T, TFilterData>, index, templateData.templateData, height); } disposeTemplate(templateData: IDataTreeListTemplateData<TTemplateData>): void { this.renderer.disposeTemplate(templateData.templateData); } dispose(): void { this.renderedNodes.clear(); } } function asTreeEvent<TInput, T>(e: ITreeEvent<IAsyncDataTreeNode<TInput, T> | null>): ITreeEvent<T> { return { browserEvent: e.browserEvent, elements: e.elements.map(e => e!.element as T) }; } function asTreeMouseEvent<TInput, T>(e: ITreeMouseEvent<IAsyncDataTreeNode<TInput, T> | null>): ITreeMouseEvent<T> { return { browserEvent: e.browserEvent, element: e.element && e.element.element as T, target: e.target }; } function asTreeContextMenuEvent<TInput, T>(e: ITreeContextMenuEvent<IAsyncDataTreeNode<TInput, T> | null>): ITreeContextMenuEvent<T> { return { browserEvent: e.browserEvent, element: e.element && e.element.element as T, anchor: e.anchor }; } class AsyncDataTreeElementsDragAndDropData<TInput, T, TContext> extends ElementsDragAndDropData<T, TContext> { override set context(context: TContext | undefined) { this.data.context = context; } override get context(): TContext | undefined { return this.data.context; } constructor(private data: ElementsDragAndDropData<IAsyncDataTreeNode<TInput, T>, TContext>) { super(data.elements.map(node => node.element as T)); } } function asAsyncDataTreeDragAndDropData<TInput, T>(data: IDragAndDropData): IDragAndDropData { if (data instanceof ElementsDragAndDropData) { return new AsyncDataTreeElementsDragAndDropData(data); } return data; } class AsyncDataTreeNodeListDragAndDrop<TInput, T> implements IListDragAndDrop<IAsyncDataTreeNode<TInput, T>> { constructor(private dnd: ITreeDragAndDrop<T>) { } getDragURI(node: IAsyncDataTreeNode<TInput, T>): string | null { return this.dnd.getDragURI(node.element as T); } getDragLabel(nodes: IAsyncDataTreeNode<TInput, T>[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(nodes.map(node => node.element as T), originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { this.dnd.onDragStart?.(asAsyncDataTreeDragAndDropData(data), originalEvent); } onDragOver(data: IDragAndDropData, targetNode: IAsyncDataTreeNode<TInput, T> | undefined, targetIndex: number | undefined, originalEvent: DragEvent, raw = true): boolean | IListDragOverReaction { return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element as T, targetIndex, originalEvent); } drop(data: IDragAndDropData, targetNode: IAsyncDataTreeNode<TInput, T> | undefined, targetIndex: number | undefined, originalEvent: DragEvent): void { this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element as T, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { this.dnd.onDragEnd?.(originalEvent); } } function asObjectTreeOptions<TInput, T, TFilterData>(options?: IAsyncDataTreeOptions<T, TFilterData>): IObjectTreeOptions<IAsyncDataTreeNode<TInput, T>, TFilterData> | undefined { return options && { ...options, collapseByDefault: true, identityProvider: options.identityProvider && { getId(el) { return options.identityProvider!.getId(el.element as T); } }, dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd), multipleSelectionController: options.multipleSelectionController && { isSelectionSingleChangeEvent(e) { return options.multipleSelectionController!.isSelectionSingleChangeEvent({ ...e, element: e.element } as any); }, isSelectionRangeChangeEvent(e) { return options.multipleSelectionController!.isSelectionRangeChangeEvent({ ...e, element: e.element } as any); } }, accessibilityProvider: options.accessibilityProvider && { ...options.accessibilityProvider, getPosInSet: undefined, getSetSize: undefined, getRole: options.accessibilityProvider!.getRole ? (el) => { return options.accessibilityProvider!.getRole!(el.element as T); } : () => 'treeitem', isChecked: options.accessibilityProvider!.isChecked ? (e) => { return !!(options.accessibilityProvider?.isChecked!(e.element as T)); } : undefined, getAriaLabel(e) { return options.accessibilityProvider!.getAriaLabel(e.element as T); }, getWidgetAriaLabel() { return options.accessibilityProvider!.getWidgetAriaLabel(); }, getWidgetRole: options.accessibilityProvider!.getWidgetRole ? () => options.accessibilityProvider!.getWidgetRole!() : () => 'tree', getAriaLevel: options.accessibilityProvider!.getAriaLevel && (node => { return options.accessibilityProvider!.getAriaLevel!(node.element as T); }), getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (node => { return options.accessibilityProvider!.getActiveDescendantId!(node.element as T); }) }, filter: options.filter && { filter(e, parentVisibility) { return options.filter!.filter(e.element as T, parentVisibility); } }, keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && { ...options.keyboardNavigationLabelProvider, getKeyboardNavigationLabel(e) { return options.keyboardNavigationLabelProvider!.getKeyboardNavigationLabel(e.element as T); } }, sorter: undefined, expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === 'undefined' ? undefined : ( typeof options.expandOnlyOnTwistieClick !== 'function' ? options.expandOnlyOnTwistieClick : ( e => (options.expandOnlyOnTwistieClick as ((e: T) => boolean))(e.element as T) ) ), defaultFindVisibility: e => { if (e.hasChildren && e.stale) { return TreeVisibility.Visible; } else if (typeof options.defaultFindVisibility === 'number') { return options.defaultFindVisibility; } else if (typeof options.defaultFindVisibility === 'undefined') { return TreeVisibility.Recurse; } else { return (options.defaultFindVisibility as ((e: T) => TreeVisibility))(e.element as T); } } }; } export interface IAsyncDataTreeOptionsUpdate extends IAbstractTreeOptionsUpdate { } export interface IAsyncDataTreeUpdateChildrenOptions<T> extends IObjectTreeSetChildrenOptions<T> { } export interface IAsyncDataTreeOptions<T, TFilterData = void> extends IAsyncDataTreeOptionsUpdate, Pick<IAbstractTreeOptions<T, TFilterData>, Exclude<keyof IAbstractTreeOptions<T, TFilterData>, 'collapseByDefault'>> { readonly collapseByDefault?: { (e: T): boolean }; readonly identityProvider?: IIdentityProvider<T>; readonly sorter?: ITreeSorter<T>; readonly autoExpandSingleChildren?: boolean; } export interface IAsyncDataTreeViewState { readonly focus?: string[]; readonly selection?: string[]; readonly expanded?: string[]; readonly scrollTop?: number; } interface IAsyncDataTreeViewStateContext<TInput, T> { readonly viewState: IAsyncDataTreeViewState; readonly selection: IAsyncDataTreeNode<TInput, T>[]; readonly focus: IAsyncDataTreeNode<TInput, T>[]; } function dfs<TInput, T>(node: IAsyncDataTreeNode<TInput, T>, fn: (node: IAsyncDataTreeNode<TInput, T>) => void): void { fn(node); node.children.forEach(child => dfs(child, fn)); } export class AsyncDataTree<TInput, T, TFilterData = void> implements IDisposable { protected readonly tree: ObjectTree<IAsyncDataTreeNode<TInput, T>, TFilterData>; protected readonly root: IAsyncDataTreeNode<TInput, T>; private readonly nodes = new Map<null | T, IAsyncDataTreeNode<TInput, T>>(); private readonly sorter?: ITreeSorter<T>; private readonly collapseByDefault?: { (e: T): boolean }; private readonly subTreeRefreshPromises = new Map<IAsyncDataTreeNode<TInput, T>, Promise<void>>(); private readonly refreshPromises = new Map<IAsyncDataTreeNode<TInput, T>, CancelablePromise<Iterable<T>>>(); protected readonly identityProvider?: IIdentityProvider<T>; private readonly autoExpandSingleChildren: boolean; private readonly _onDidRender = new Emitter<void>(); protected readonly _onDidChangeNodeSlowState = new Emitter<IAsyncDataTreeNode<TInput, T>>(); protected readonly nodeMapper: AsyncDataTreeNodeMapper<TInput, T, TFilterData> = new WeakMapper(node => new AsyncDataTreeNodeWrapper(node)); protected readonly disposables = new DisposableStore(); get onDidScroll(): Event<ScrollEvent> { return this.tree.onDidScroll; } get onDidChangeFocus(): Event<ITreeEvent<T>> { return Event.map(this.tree.onDidChangeFocus, asTreeEvent); } get onDidChangeSelection(): Event<ITreeEvent<T>> { return Event.map(this.tree.onDidChangeSelection, asTreeEvent); } get onKeyDown(): Event<KeyboardEvent> { return this.tree.onKeyDown; } get onMouseClick(): Event<ITreeMouseEvent<T>> { return Event.map(this.tree.onMouseClick, asTreeMouseEvent); } get onMouseDblClick(): Event<ITreeMouseEvent<T>> { return Event.map(this.tree.onMouseDblClick, asTreeMouseEvent); } get onContextMenu(): Event<ITreeContextMenuEvent<T>> { return Event.map(this.tree.onContextMenu, asTreeContextMenuEvent); } get onTap(): Event<ITreeMouseEvent<T>> { return Event.map(this.tree.onTap, asTreeMouseEvent); } get onPointer(): Event<ITreeMouseEvent<T>> { return Event.map(this.tree.onPointer, asTreeMouseEvent); } get onDidFocus(): Event<void> { return this.tree.onDidFocus; } get onDidBlur(): Event<void> { return this.tree.onDidBlur; } /** * To be used internally only! * @deprecated */ get onDidChangeModel(): Event<void> { return this.tree.onDidChangeModel; } get onDidChangeCollapseState(): Event<ICollapseStateChangeEvent<IAsyncDataTreeNode<TInput, T> | null, TFilterData>> { return this.tree.onDidChangeCollapseState; } get onDidUpdateOptions(): Event<IAsyncDataTreeOptionsUpdate> { return this.tree.onDidUpdateOptions; } get onDidChangeFindOpenState(): Event<boolean> { return this.tree.onDidChangeFindOpenState; } get findMode(): TreeFindMode { return this.tree.findMode; } set findMode(mode: TreeFindMode) { this.tree.findMode = mode; } readonly onDidChangeFindMode: Event<TreeFindMode>; get expandOnlyOnTwistieClick(): boolean | ((e: T) => boolean) { if (typeof this.tree.expandOnlyOnTwistieClick === 'boolean') { return this.tree.expandOnlyOnTwistieClick; } const fn = this.tree.expandOnlyOnTwistieClick; return element => fn(this.nodes.get((element === this.root.element ? null : element) as T) || null); } get onDidDispose(): Event<void> { return this.tree.onDidDispose; } constructor( protected user: string, container: HTMLElement, delegate: IListVirtualDelegate<T>, renderers: ITreeRenderer<T, TFilterData, any>[], private dataSource: IAsyncDataSource<TInput, T>, options: IAsyncDataTreeOptions<T, TFilterData> = {} ) { this.identityProvider = options.identityProvider; this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren; this.sorter = options.sorter; this.collapseByDefault = options.collapseByDefault; this.tree = this.createTree(user, container, delegate, renderers, options); this.onDidChangeFindMode = this.tree.onDidChangeFindMode; this.root = createAsyncDataTreeNode({ element: undefined!, parent: null, hasChildren: true }); if (this.identityProvider) { this.root = { ...this.root, id: null }; } this.nodes.set(null, this.root); this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables); } protected createTree( user: string, container: HTMLElement, delegate: IListVirtualDelegate<T>, renderers: ITreeRenderer<T, TFilterData, any>[], options: IAsyncDataTreeOptions<T, TFilterData> ): ObjectTree<IAsyncDataTreeNode<TInput, T>, TFilterData> { const objectTreeDelegate = new ComposedTreeDelegate<TInput | T, IAsyncDataTreeNode<TInput, T>>(delegate); const objectTreeRenderers = renderers.map(r => new AsyncDataTreeRenderer(r, this.nodeMapper, this._onDidChangeNodeSlowState.event)); const objectTreeOptions = asObjectTreeOptions<TInput, T, TFilterData>(options) || {}; return new ObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions); } updateOptions(options: IAsyncDataTreeOptionsUpdate = {}): void { this.tree.updateOptions(options); } get options(): IAsyncDataTreeOptions<T, TFilterData> { return this.tree.options as IAsyncDataTreeOptions<T, TFilterData>; } // Widget getHTMLElement(): HTMLElement { return this.tree.getHTMLElement(); } get contentHeight(): number { return this.tree.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.tree.onDidChangeContentHeight; } get scrollTop(): number { return this.tree.scrollTop; } set scrollTop(scrollTop: number) { this.tree.scrollTop = scrollTop; } get scrollLeft(): number { return this.tree.scrollLeft; } set scrollLeft(scrollLeft: number) { this.tree.scrollLeft = scrollLeft; } get scrollHeight(): number { return this.tree.scrollHeight; } get renderHeight(): number { return this.tree.renderHeight; } get lastVisibleElement(): T { return this.tree.lastVisibleElement!.element as T; } get ariaLabel(): string { return this.tree.ariaLabel; } set ariaLabel(value: string) { this.tree.ariaLabel = value; } domFocus(): void { this.tree.domFocus(); } layout(height?: number, width?: number): void { this.tree.layout(height, width); } style(styles: IListStyles): void { this.tree.style(styles); } // Model getInput(): TInput | undefined { return this.root.element as TInput; } async setInput(input: TInput, viewState?: IAsyncDataTreeViewState): Promise<void> { this.refreshPromises.forEach(promise => promise.cancel()); this.refreshPromises.clear(); this.root.element = input!; const viewStateContext = viewState && { viewState, focus: [], selection: [] } as IAsyncDataTreeViewStateContext<TInput, T>; await this._updateChildren(input, true, false, viewStateContext); if (viewStateContext) { this.tree.setFocus(viewStateContext.focus); this.tree.setSelection(viewStateContext.selection); } if (viewState && typeof viewState.scrollTop === 'number') { this.scrollTop = viewState.scrollTop; } } async updateChildren(element: TInput | T = this.root.element, recursive = true, rerender = false, options?: IAsyncDataTreeUpdateChildrenOptions<T>): Promise<void> { await this._updateChildren(element, recursive, rerender, undefined, options); } private async _updateChildren(element: TInput | T = this.root.element, recursive = true, rerender = false, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>, options?: IAsyncDataTreeUpdateChildrenOptions<T>): Promise<void> { if (typeof this.root.element === 'undefined') { throw new TreeError(this.user, 'Tree input not set'); } if (this.root.refreshPromise) { await this.root.refreshPromise; await Event.toPromise(this._onDidRender.event); } const node = this.getDataNode(element); await this.refreshAndRenderNode(node, recursive, viewStateContext, options); if (rerender) { try { this.tree.rerender(node); } catch { // missing nodes are fine, this could've resulted from // parallel refresh calls, removing `node` altogether } } } resort(element: TInput | T = this.root.element, recursive = true): void { this.tree.resort(this.getDataNode(element), recursive); } hasNode(element: TInput | T): boolean { return element === this.root.element || this.nodes.has(element as T); } // View rerender(element?: T): void { if (element === undefined || element === this.root.element) { this.tree.rerender(); return; } const node = this.getDataNode(element); this.tree.rerender(node); } updateWidth(element: T): void { const node = this.getDataNode(element); this.tree.updateWidth(node); } // Tree getNode(element: TInput | T = this.root.element): ITreeNode<TInput | T, TFilterData> { const dataNode = this.getDataNode(element); const node = this.tree.getNode(dataNode === this.root ? null : dataNode); return this.nodeMapper.map(node); } collapse(element: T, recursive: boolean = false): boolean { const node = this.getDataNode(element); return this.tree.collapse(node === this.root ? null : node, recursive); } async expand(element: T, recursive: boolean = false): Promise<boolean> { if (typeof this.root.element === 'undefined') { throw new TreeError(this.user, 'Tree input not set'); } if (this.root.refreshPromise) { await this.root.refreshPromise; await Event.toPromise(this._onDidRender.event); } const node = this.getDataNode(element); if (this.tree.hasElement(node) && !this.tree.isCollapsible(node)) { return false; } if (node.refreshPromise) { await this.root.refreshPromise; await Event.toPromise(this._onDidRender.event); } if (node !== this.root && !node.refreshPromise && !this.tree.isCollapsed(node)) { return false; } const result = this.tree.expand(node === this.root ? null : node, recursive); if (node.refreshPromise) { await this.root.refreshPromise; await Event.toPromise(this._onDidRender.event); } return result; } toggleCollapsed(element: T, recursive: boolean = false): boolean { return this.tree.toggleCollapsed(this.getDataNode(element), recursive); } expandAll(): void { this.tree.expandAll(); } collapseAll(): void { this.tree.collapseAll(); } isCollapsible(element: T): boolean { return this.tree.isCollapsible(this.getDataNode(element)); } isCollapsed(element: TInput | T): boolean { return this.tree.isCollapsed(this.getDataNode(element)); } triggerTypeNavigation(): void { this.tree.triggerTypeNavigation(); } openFind(): void { this.tree.openFind(); } closeFind(): void { this.tree.closeFind(); } refilter(): void { this.tree.refilter(); } setAnchor(element: T | undefined): void { this.tree.setAnchor(typeof element === 'undefined' ? undefined : this.getDataNode(element)); } getAnchor(): T | undefined { const node = this.tree.getAnchor(); return node?.element as T; } setSelection(elements: T[], browserEvent?: UIEvent): void { const nodes = elements.map(e => this.getDataNode(e)); this.tree.setSelection(nodes, browserEvent); } getSelection(): T[] { const nodes = this.tree.getSelection(); return nodes.map(n => n!.element as T); } setFocus(elements: T[], browserEvent?: UIEvent): void { const nodes = elements.map(e => this.getDataNode(e)); this.tree.setFocus(nodes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent): void { this.tree.focusNext(n, loop, browserEvent); } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent): void { this.tree.focusPrevious(n, loop, browserEvent); } focusNextPage(browserEvent?: UIEvent): Promise<void> { return this.tree.focusNextPage(browserEvent); } focusPreviousPage(browserEvent?: UIEvent): Promise<void> { return this.tree.focusPreviousPage(browserEvent); } focusLast(browserEvent?: UIEvent): void { this.tree.focusLast(browserEvent); } focusFirst(browserEvent?: UIEvent): void { this.tree.focusFirst(browserEvent); } getFocus(): T[] { const nodes = this.tree.getFocus(); return nodes.map(n => n!.element as T); } reveal(element: T, relativeTop?: number): void { this.tree.reveal(this.getDataNode(element), relativeTop); } getRelativeTop(element: T): number | null { return this.tree.getRelativeTop(this.getDataNode(element)); } // Tree navigation getParentElement(element: T): TInput | T { const node = this.tree.getParentElement(this.getDataNode(element)); return (node && node.element)!; } getFirstElementChild(element: TInput | T = this.root.element): TInput | T | undefined { const dataNode = this.getDataNode(element); const node = this.tree.getFirstElementChild(dataNode === this.root ? null : dataNode); return (node && node.element)!; } // Implementation private getDataNode(element: TInput | T): IAsyncDataTreeNode<TInput, T> { const node: IAsyncDataTreeNode<TInput, T> | undefined = this.nodes.get((element === this.root.element ? null : element) as T); if (!node) { throw new TreeError(this.user, `Data tree node not found: ${element}`); } return node; } private async refreshAndRenderNode(node: IAsyncDataTreeNode<TInput, T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>, options?: IAsyncDataTreeUpdateChildrenOptions<T>): Promise<void> { await this.refreshNode(node, recursive, viewStateContext); this.render(node, viewStateContext, options); } private async refreshNode(node: IAsyncDataTreeNode<TInput, T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): Promise<void> { let result: Promise<void> | undefined; this.subTreeRefreshPromises.forEach((refreshPromise, refreshNode) => { if (!result && intersects(refreshNode, node)) { result = refreshPromise.then(() => this.refreshNode(node, recursive, viewStateContext)); } }); if (result) { return result; } if (node !== this.root) { const treeNode = this.tree.getNode(node); if (treeNode.collapsed) { node.hasChildren = !!this.dataSource.hasChildren(node.element!); node.stale = true; return; } } return this.doRefreshSubTree(node, recursive, viewStateContext); } private async doRefreshSubTree(node: IAsyncDataTreeNode<TInput, T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): Promise<void> { let done: () => void; node.refreshPromise = new Promise(c => done = c); this.subTreeRefreshPromises.set(node, node.refreshPromise); node.refreshPromise.finally(() => { node.refreshPromise = undefined; this.subTreeRefreshPromises.delete(node); }); try { const childrenToRefresh = await this.doRefreshNode(node, recursive, viewStateContext); node.stale = false; await Promises.settled(childrenToRefresh.map(child => this.doRefreshSubTree(child, recursive, viewStateContext))); } finally { done!(); } } private async doRefreshNode(node: IAsyncDataTreeNode<TInput, T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): Promise<IAsyncDataTreeNode<TInput, T>[]> { node.hasChildren = !!this.dataSource.hasChildren(node.element!); let childrenPromise: Promise<Iterable<T>>; if (!node.hasChildren) { childrenPromise = Promise.resolve(Iterable.empty()); } else { const children = this.doGetChildren(node); if (isIterable(children)) { childrenPromise = Promise.resolve(children); } else { const slowTimeout = timeout(800); slowTimeout.then(() => { node.slow = true; this._onDidChangeNodeSlowState.fire(node); }, _ => null); childrenPromise = children.finally(() => slowTimeout.cancel()); } } try { const children = await childrenPromise; return this.setChildren(node, children, recursive, viewStateContext); } catch (err) { if (node !== this.root && this.tree.hasElement(node)) { this.tree.collapse(node); } if (isCancellationError(err)) { return []; } throw err; } finally { if (node.slow) { node.slow = false; this._onDidChangeNodeSlowState.fire(node); } } } private doGetChildren(node: IAsyncDataTreeNode<TInput, T>): Promise<Iterable<T>> | Iterable<T> { let result = this.refreshPromises.get(node); if (result) { return result; } const children = this.dataSource.getChildren(node.element!); if (isIterable(children)) { return this.processChildren(children); } else { result = createCancelablePromise(async () => this.processChildren(await children)); this.refreshPromises.set(node, result); return result.finally(() => { this.refreshPromises.delete(node); }); } } private _onDidChangeCollapseState({ node, deep }: ICollapseStateChangeEvent<IAsyncDataTreeNode<TInput, T> | null, any>): void { if (node.element === null) { return; } if (!node.collapsed && node.element.stale) { if (deep) { this.collapse(node.element.element as T); } else { this.refreshAndRenderNode(node.element, false) .catch(onUnexpectedError); } } } private setChildren(node: IAsyncDataTreeNode<TInput, T>, childrenElementsIterable: Iterable<T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): IAsyncDataTreeNode<TInput, T>[] { const childrenElements = [...childrenElementsIterable]; // perf: if the node was and still is a leaf, avoid all this hassle if (node.children.length === 0 && childrenElements.length === 0) { return []; } const nodesToForget = new Map<T, IAsyncDataTreeNode<TInput, T>>(); const childrenTreeNodesById = new Map<string, { node: IAsyncDataTreeNode<TInput, T>; collapsed: boolean }>(); for (const child of node.children) { nodesToForget.set(child.element as T, child); if (this.identityProvider) { const collapsed = this.tree.isCollapsed(child); childrenTreeNodesById.set(child.id!, { node: child, collapsed }); } } const childrenToRefresh: IAsyncDataTreeNode<TInput, T>[] = []; const children = childrenElements.map<IAsyncDataTreeNode<TInput, T>>(element => { const hasChildren = !!this.dataSource.hasChildren(element); if (!this.identityProvider) { const asyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, hasChildren }); if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) { asyncDataTreeNode.collapsedByDefault = false; childrenToRefresh.push(asyncDataTreeNode); } return asyncDataTreeNode; } const id = this.identityProvider.getId(element).toString(); const result = childrenTreeNodesById.get(id); if (result) { const asyncDataTreeNode = result.node; nodesToForget.delete(asyncDataTreeNode.element as T); this.nodes.delete(asyncDataTreeNode.element as T); this.nodes.set(element, asyncDataTreeNode); asyncDataTreeNode.element = element; asyncDataTreeNode.hasChildren = hasChildren; if (recursive) { if (result.collapsed) { asyncDataTreeNode.children.forEach(node => dfs(node, node => this.nodes.delete(node.element as T))); asyncDataTreeNode.children.splice(0, asyncDataTreeNode.children.length); asyncDataTreeNode.stale = true; } else { childrenToRefresh.push(asyncDataTreeNode); } } else if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) { asyncDataTreeNode.collapsedByDefault = false; childrenToRefresh.push(asyncDataTreeNode); } return asyncDataTreeNode; } const childAsyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, id, hasChildren }); if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id) > -1) { viewStateContext.focus.push(childAsyncDataTreeNode); } if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id) > -1) { viewStateContext.selection.push(childAsyncDataTreeNode); } if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id) > -1) { childrenToRefresh.push(childAsyncDataTreeNode); } else if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) { childAsyncDataTreeNode.collapsedByDefault = false; childrenToRefresh.push(childAsyncDataTreeNode); } return childAsyncDataTreeNode; }); for (const node of nodesToForget.values()) { dfs(node, node => this.nodes.delete(node.element as T)); } for (const child of children) { this.nodes.set(child.element as T, child); } node.children.splice(0, node.children.length, ...children); // TODO@joao this doesn't take filter into account if (node !== this.root && this.autoExpandSingleChildren && children.length === 1 && childrenToRefresh.length === 0) { children[0].collapsedByDefault = false; childrenToRefresh.push(children[0]); } return childrenToRefresh; } protected render(node: IAsyncDataTreeNode<TInput, T>, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>, options?: IAsyncDataTreeUpdateChildrenOptions<T>): void { const children = node.children.map(node => this.asTreeElement(node, viewStateContext)); const objectTreeOptions: IObjectTreeSetChildrenOptions<IAsyncDataTreeNode<TInput, T>> | undefined = options && { ...options, diffIdentityProvider: options!.diffIdentityProvider && { getId(node: IAsyncDataTreeNode<TInput, T>): { toString(): string } { return options!.diffIdentityProvider!.getId(node.element as T); } } }; this.tree.setChildren(node === this.root ? null : node, children, objectTreeOptions); if (node !== this.root) { this.tree.setCollapsible(node, node.hasChildren); } this._onDidRender.fire(); } protected asTreeElement(node: IAsyncDataTreeNode<TInput, T>, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): IObjectTreeElement<IAsyncDataTreeNode<TInput, T>> { if (node.stale) { return { element: node, collapsible: node.hasChildren, collapsed: true }; } let collapsed: boolean | undefined; if (viewStateContext && viewStateContext.viewState.expanded && node.id && viewStateContext.viewState.expanded.indexOf(node.id) > -1) { collapsed = false; } else { collapsed = node.collapsedByDefault; } node.collapsedByDefault = undefined; return { element: node, children: node.hasChildren ? Iterable.map(node.children, child => this.asTreeElement(child, viewStateContext)) : [], collapsible: node.hasChildren, collapsed }; } protected processChildren(children: Iterable<T>): Iterable<T> { if (this.sorter) { children = [...children].sort(this.sorter.compare.bind(this.sorter)); } return children; } // view state getViewState(): IAsyncDataTreeViewState { if (!this.identityProvider) { throw new TreeError(this.user, 'Can\'t get tree view state without an identity provider'); } const getId = (element: T) => this.identityProvider!.getId(element).toString(); const focus = this.getFocus().map(getId); const selection = this.getSelection().map(getId); const expanded: string[] = []; const root = this.tree.getNode(); const stack = [root]; while (stack.length > 0) { const node = stack.pop()!; if (node !== root && node.collapsible && !node.collapsed) { expanded.push(getId(node.element!.element as T)); } stack.push(...node.children); } return { focus, selection, expanded, scrollTop: this.scrollTop }; } dispose(): void { this.disposables.dispose(); } } type CompressibleAsyncDataTreeNodeMapper<TInput, T, TFilterData> = WeakMapper<ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>>, TFilterData>, ITreeNode<ICompressedTreeNode<TInput | T>, TFilterData>>; class CompressibleAsyncDataTreeNodeWrapper<TInput, T, TFilterData> implements ITreeNode<ICompressedTreeNode<TInput | T>, TFilterData> { get element(): ICompressedTreeNode<TInput | T> { return { elements: this.node.element.elements.map(e => e.element), incompressible: this.node.element.incompressible }; } get children(): ITreeNode<ICompressedTreeNode<TInput | T>, TFilterData>[] { return this.node.children.map(node => new CompressibleAsyncDataTreeNodeWrapper(node)); } get depth(): number { return this.node.depth; } get visibleChildrenCount(): number { return this.node.visibleChildrenCount; } get visibleChildIndex(): number { return this.node.visibleChildIndex; } get collapsible(): boolean { return this.node.collapsible; } get collapsed(): boolean { return this.node.collapsed; } get visible(): boolean { return this.node.visible; } get filterData(): TFilterData | undefined { return this.node.filterData; } constructor(private node: ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>>, TFilterData>) { } } class CompressibleAsyncDataTreeRenderer<TInput, T, TFilterData, TTemplateData> implements ICompressibleTreeRenderer<IAsyncDataTreeNode<TInput, T>, TFilterData, IDataTreeListTemplateData<TTemplateData>> { readonly templateId: string; private renderedNodes = new Map<IAsyncDataTreeNode<TInput, T>, IDataTreeListTemplateData<TTemplateData>>(); private disposables: IDisposable[] = []; constructor( protected renderer: ICompressibleTreeRenderer<T, TFilterData, TTemplateData>, protected nodeMapper: AsyncDataTreeNodeMapper<TInput, T, TFilterData>, private compressibleNodeMapperProvider: () => CompressibleAsyncDataTreeNodeMapper<TInput, T, TFilterData>, readonly onDidChangeTwistieState: Event<IAsyncDataTreeNode<TInput, T>> ) { this.templateId = renderer.templateId; } renderTemplate(container: HTMLElement): IDataTreeListTemplateData<TTemplateData> { const templateData = this.renderer.renderTemplate(container); return { templateData }; } renderElement(node: ITreeNode<IAsyncDataTreeNode<TInput, T>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void { this.renderer.renderElement(this.nodeMapper.map(node) as ITreeNode<T, TFilterData>, index, templateData.templateData, height); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void { this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node) as ITreeNode<ICompressedTreeNode<T>, TFilterData>, index, templateData.templateData, height); } renderTwistie(element: IAsyncDataTreeNode<TInput, T>, twistieElement: HTMLElement): boolean { if (element.slow) { twistieElement.classList.add(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading)); return true; } else { twistieElement.classList.remove(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading)); return false; } } disposeElement(node: ITreeNode<IAsyncDataTreeNode<TInput, T>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void { this.renderer.disposeElement?.(this.nodeMapper.map(node) as ITreeNode<T, TFilterData>, index, templateData.templateData, height); } disposeCompressedElements(node: ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void { this.renderer.disposeCompressedElements?.(this.compressibleNodeMapperProvider().map(node) as ITreeNode<ICompressedTreeNode<T>, TFilterData>, index, templateData.templateData, height); } disposeTemplate(templateData: IDataTreeListTemplateData<TTemplateData>): void { this.renderer.disposeTemplate(templateData.templateData); } dispose(): void { this.renderedNodes.clear(); this.disposables = dispose(this.disposables); } } export interface ITreeCompressionDelegate<T> { isIncompressible(element: T): boolean; } function asCompressibleObjectTreeOptions<TInput, T, TFilterData>(options?: ICompressibleAsyncDataTreeOptions<T, TFilterData>): ICompressibleObjectTreeOptions<IAsyncDataTreeNode<TInput, T>, TFilterData> | undefined { const objectTreeOptions = options && asObjectTreeOptions(options); return objectTreeOptions && { ...objectTreeOptions, keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && { ...objectTreeOptions.keyboardNavigationLabelProvider, getCompressedNodeKeyboardNavigationLabel(els) { return options!.keyboardNavigationLabelProvider!.getCompressedNodeKeyboardNavigationLabel(els.map(e => e.element as T)); } } }; } export interface ICompressibleAsyncDataTreeOptions<T, TFilterData = void> extends IAsyncDataTreeOptions<T, TFilterData> { readonly compressionEnabled?: boolean; readonly keyboardNavigationLabelProvider?: ICompressibleKeyboardNavigationLabelProvider<T>; } export interface ICompressibleAsyncDataTreeOptionsUpdate extends IAsyncDataTreeOptionsUpdate { readonly compressionEnabled?: boolean; } export class CompressibleAsyncDataTree<TInput, T, TFilterData = void> extends AsyncDataTree<TInput, T, TFilterData> { protected declare readonly tree: CompressibleObjectTree<IAsyncDataTreeNode<TInput, T>, TFilterData>; protected readonly compressibleNodeMapper: CompressibleAsyncDataTreeNodeMapper<TInput, T, TFilterData> = new WeakMapper(node => new CompressibleAsyncDataTreeNodeWrapper(node)); private filter?: ITreeFilter<T, TFilterData>; constructor( user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, private compressionDelegate: ITreeCompressionDelegate<T>, renderers: ICompressibleTreeRenderer<T, TFilterData, any>[], dataSource: IAsyncDataSource<TInput, T>, options: ICompressibleAsyncDataTreeOptions<T, TFilterData> = {} ) { super(user, container, virtualDelegate, renderers, dataSource, options); this.filter = options.filter; } protected override createTree( user: string, container: HTMLElement, delegate: IListVirtualDelegate<T>, renderers: ICompressibleTreeRenderer<T, TFilterData, any>[], options: ICompressibleAsyncDataTreeOptions<T, TFilterData> ): ObjectTree<IAsyncDataTreeNode<TInput, T>, TFilterData> { const objectTreeDelegate = new ComposedTreeDelegate<TInput | T, IAsyncDataTreeNode<TInput, T>>(delegate); const objectTreeRenderers = renderers.map(r => new CompressibleAsyncDataTreeRenderer(r, this.nodeMapper, () => this.compressibleNodeMapper, this._onDidChangeNodeSlowState.event)); const objectTreeOptions = asCompressibleObjectTreeOptions<TInput, T, TFilterData>(options) || {}; return new CompressibleObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions); } protected override asTreeElement(node: IAsyncDataTreeNode<TInput, T>, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): ICompressedTreeElement<IAsyncDataTreeNode<TInput, T>> { return { incompressible: this.compressionDelegate.isIncompressible(node.element as T), ...super.asTreeElement(node, viewStateContext) }; } override updateOptions(options: ICompressibleAsyncDataTreeOptionsUpdate = {}): void { this.tree.updateOptions(options); } override getViewState(): IAsyncDataTreeViewState { if (!this.identityProvider) { throw new TreeError(this.user, 'Can\'t get tree view state without an identity provider'); } const getId = (element: T) => this.identityProvider!.getId(element).toString(); const focus = this.getFocus().map(getId); const selection = this.getSelection().map(getId); const expanded: string[] = []; const root = this.tree.getCompressedTreeNode(); const stack = [root]; while (stack.length > 0) { const node = stack.pop()!; if (node !== root && node.collapsible && !node.collapsed) { for (const asyncNode of node.element!.elements) { expanded.push(getId(asyncNode.element as T)); } } stack.push(...node.children); } return { focus, selection, expanded, scrollTop: this.scrollTop }; } protected override render(node: IAsyncDataTreeNode<TInput, T>, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): void { if (!this.identityProvider) { return super.render(node, viewStateContext); } // Preserve traits across compressions. Hacky but does the trick. // This is hard to fix properly since it requires rewriting the traits // across trees and lists. Let's just keep it this way for now. const getId = (element: T) => this.identityProvider!.getId(element).toString(); const getUncompressedIds = (nodes: IAsyncDataTreeNode<TInput, T>[]): Set<string> => { const result = new Set<string>(); for (const node of nodes) { const compressedNode = this.tree.getCompressedTreeNode(node === this.root ? null : node); if (!compressedNode.element) { continue; } for (const node of compressedNode.element.elements) { result.add(getId(node.element as T)); } } return result; }; const oldSelection = getUncompressedIds(this.tree.getSelection() as IAsyncDataTreeNode<TInput, T>[]); const oldFocus = getUncompressedIds(this.tree.getFocus() as IAsyncDataTreeNode<TInput, T>[]); super.render(node, viewStateContext); const selection = this.getSelection(); let didChangeSelection = false; const focus = this.getFocus(); let didChangeFocus = false; const visit = (node: ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>> | null, TFilterData>) => { const compressedNode = node.element; if (compressedNode) { for (let i = 0; i < compressedNode.elements.length; i++) { const id = getId(compressedNode.elements[i].element as T); const element = compressedNode.elements[compressedNode.elements.length - 1].element as T; // github.com/microsoft/vscode/issues/85938 if (oldSelection.has(id) && selection.indexOf(element) === -1) { selection.push(element); didChangeSelection = true; } if (oldFocus.has(id) && focus.indexOf(element) === -1) { focus.push(element); didChangeFocus = true; } } } node.children.forEach(visit); }; visit(this.tree.getCompressedTreeNode(node === this.root ? null : node)); if (didChangeSelection) { this.setSelection(selection); } if (didChangeFocus) { this.setFocus(focus); } } // For compressed async data trees, `TreeVisibility.Recurse` doesn't currently work // and we have to filter everything beforehand // Related to #85193 and #85835 protected override processChildren(children: Iterable<T>): Iterable<T> { if (this.filter) { children = Iterable.filter(children, e => { const result = this.filter!.filter(e, TreeVisibility.Visible); const visibility = getVisibility(result); if (visibility === TreeVisibility.Recurse) { throw new Error('Recursive tree visibility not supported in async data compressed trees'); } return visibility === TreeVisibility.Visible; }); } return super.processChildren(children); } } function getVisibility<TFilterData>(filterResult: TreeFilterResult<TFilterData>): TreeVisibility { if (typeof filterResult === 'boolean') { return filterResult ? TreeVisibility.Visible : TreeVisibility.Hidden; } else if (isFilterResult(filterResult)) { return getVisibleState(filterResult.visibility); } else { return getVisibleState(filterResult); } }
src/vs/base/browser/ui/tree/asyncDataTree.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.0002086185704683885, 0.00017303861386608332, 0.00016570142179261893, 0.00017274376295972615, 0.000004821654329134617 ]
{ "id": 5, "code_window": [ "\t}\n", "\n", "\tconst dir = getDocumentDir(document);\n", "\n", "\tconst snippet = new vscode.SnippetString();\n", "\turis.forEach((uri, i) => {\n", "\t\tconst mdPath = getMdPath(dir, uri);\n", "\n", "\t\tconst ext = URI.Utils.extname(uri).toLowerCase().replace('.', '');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tlet insertedLinkCount = 0;\n", "\tlet insertedImageCount = 0;\n", "\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 107 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, markAsSingleton } from 'vs/base/common/lifecycle'; class WindowManager { public static readonly INSTANCE = new WindowManager(); // --- Zoom Level private _zoomLevel: number = 0; public getZoomLevel(): number { return this._zoomLevel; } public setZoomLevel(zoomLevel: number, isTrusted: boolean): void { if (this._zoomLevel === zoomLevel) { return; } this._zoomLevel = zoomLevel; } // --- Zoom Factor private _zoomFactor: number = 1; public getZoomFactor(): number { return this._zoomFactor; } public setZoomFactor(zoomFactor: number): void { this._zoomFactor = zoomFactor; } // --- Fullscreen private _fullscreen: boolean = false; private readonly _onDidChangeFullscreen = new Emitter<void>(); public readonly onDidChangeFullscreen: Event<void> = this._onDidChangeFullscreen.event; public setFullscreen(fullscreen: boolean): void { if (this._fullscreen === fullscreen) { return; } this._fullscreen = fullscreen; this._onDidChangeFullscreen.fire(); } public isFullscreen(): boolean { return this._fullscreen; } } /** * See https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#monitoring_screen_resolution_or_zoom_level_changes */ class DevicePixelRatioMonitor extends Disposable { private readonly _onDidChange = this._register(new Emitter<void>()); public readonly onDidChange = this._onDidChange.event; private readonly _listener: () => void; private _mediaQueryList: MediaQueryList | null; constructor() { super(); this._listener = () => this._handleChange(true); this._mediaQueryList = null; this._handleChange(false); } private _handleChange(fireEvent: boolean): void { this._mediaQueryList?.removeEventListener('change', this._listener); this._mediaQueryList = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`); this._mediaQueryList.addEventListener('change', this._listener); if (fireEvent) { this._onDidChange.fire(); } } } class PixelRatioImpl extends Disposable { private readonly _onDidChange = this._register(new Emitter<number>()); public readonly onDidChange = this._onDidChange.event; private _value: number; public get value(): number { return this._value; } constructor() { super(); this._value = this._getPixelRatio(); const dprMonitor = this._register(new DevicePixelRatioMonitor()); this._register(dprMonitor.onDidChange(() => { this._value = this._getPixelRatio(); this._onDidChange.fire(this._value); })); } private _getPixelRatio(): number { const ctx: any = document.createElement('canvas').getContext('2d'); const dpr = window.devicePixelRatio || 1; const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; return dpr / bsr; } } class PixelRatioFacade { private _pixelRatioMonitor: PixelRatioImpl | null = null; private _getOrCreatePixelRatioMonitor(): PixelRatioImpl { if (!this._pixelRatioMonitor) { this._pixelRatioMonitor = markAsSingleton(new PixelRatioImpl()); } return this._pixelRatioMonitor; } /** * Get the current value. */ public get value(): number { return this._getOrCreatePixelRatioMonitor().value; } /** * Listen for changes. */ public get onDidChange(): Event<number> { return this._getOrCreatePixelRatioMonitor().onDidChange; } } export function addMatchMediaChangeListener(query: string | MediaQueryList, callback: (this: MediaQueryList, ev: MediaQueryListEvent) => any): void { if (typeof query === 'string') { query = window.matchMedia(query); } query.addEventListener('change', callback); } /** * Returns the pixel ratio. * * This is useful for rendering <canvas> elements at native screen resolution or for being used as * a cache key when storing font measurements. Fonts might render differently depending on resolution * and any measurements need to be discarded for example when a window is moved from a monitor to another. */ export const PixelRatio = new PixelRatioFacade(); /** A zoom index, e.g. 1, 2, 3 */ export function setZoomLevel(zoomLevel: number, isTrusted: boolean): void { WindowManager.INSTANCE.setZoomLevel(zoomLevel, isTrusted); } export function getZoomLevel(): number { return WindowManager.INSTANCE.getZoomLevel(); } /** The zoom scale for an index, e.g. 1, 1.2, 1.4 */ export function getZoomFactor(): number { return WindowManager.INSTANCE.getZoomFactor(); } export function setZoomFactor(zoomFactor: number): void { WindowManager.INSTANCE.setZoomFactor(zoomFactor); } export function setFullscreen(fullscreen: boolean): void { WindowManager.INSTANCE.setFullscreen(fullscreen); } export function isFullscreen(): boolean { return WindowManager.INSTANCE.isFullscreen(); } export const onDidChangeFullscreen = WindowManager.INSTANCE.onDidChangeFullscreen; const userAgent = navigator.userAgent; export const isFirefox = (userAgent.indexOf('Firefox') >= 0); export const isWebKit = (userAgent.indexOf('AppleWebKit') >= 0); export const isChrome = (userAgent.indexOf('Chrome') >= 0); export const isSafari = (!isChrome && (userAgent.indexOf('Safari') >= 0)); export const isWebkitWebView = (!isChrome && !isSafari && isWebKit); export const isElectron = (userAgent.indexOf('Electron/') >= 0); export const isAndroid = (userAgent.indexOf('Android') >= 0); let standalone = false; if (window.matchMedia) { const standaloneMatchMedia = window.matchMedia('(display-mode: standalone) or (display-mode: window-controls-overlay)'); const fullScreenMatchMedia = window.matchMedia('(display-mode: fullscreen)'); standalone = standaloneMatchMedia.matches; addMatchMediaChangeListener(standaloneMatchMedia, ({ matches }) => { // entering fullscreen would change standaloneMatchMedia.matches to false // if standalone is true (running as PWA) and entering fullscreen, skip this change if (standalone && fullScreenMatchMedia.matches) { return; } // otherwise update standalone (browser to PWA or PWA to browser) standalone = matches; }); } export function isStandalone(): boolean { return standalone; } // Visible means that the feature is enabled, not necessarily being rendered // e.g. visible is true even in fullscreen mode where the controls are hidden // See docs at https://developer.mozilla.org/en-US/docs/Web/API/WindowControlsOverlay/visible export function isWCOEnabled(): boolean { return (navigator as any)?.windowControlsOverlay?.visible; }
src/vs/base/browser/browser.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.0014537422684952617, 0.00022969847486820072, 0.00016365777992177755, 0.0001712834055069834, 0.00026712697581388056 ]
{ "id": 5, "code_window": [ "\t}\n", "\n", "\tconst dir = getDocumentDir(document);\n", "\n", "\tconst snippet = new vscode.SnippetString();\n", "\turis.forEach((uri, i) => {\n", "\t\tconst mdPath = getMdPath(dir, uri);\n", "\n", "\t\tconst ext = URI.Utils.extname(uri).toLowerCase().replace('.', '');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tlet insertedLinkCount = 0;\n", "\tlet insertedImageCount = 0;\n", "\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 107 }
[ { "c": "swagger", "t": "source.yaml string.unquoted.plain.out.yaml entity.name.tag.yaml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_plus_experimental": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_plus_experimental": "entity.name.tag: #800000" } }, { "c": ":", "t": "source.yaml punctuation.separator.key-value.mapping.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": " ", "t": "source.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": "'", "t": "source.yaml string.quoted.single.yaml punctuation.definition.string.begin.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.single.yaml: #0F4A85", "light_plus_experimental": "string.quoted.single.yaml: #0000FF" } }, { "c": "2.0", "t": "source.yaml string.quoted.single.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.single.yaml: #0F4A85", "light_plus_experimental": "string.quoted.single.yaml: #0000FF" } }, { "c": "'", "t": "source.yaml string.quoted.single.yaml punctuation.definition.string.end.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.single.yaml: #0F4A85", "light_plus_experimental": "string.quoted.single.yaml: #0000FF" } }, { "c": "info", "t": "source.yaml string.unquoted.plain.out.yaml entity.name.tag.yaml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_plus_experimental": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_plus_experimental": "entity.name.tag: #800000" } }, { "c": ":", "t": "source.yaml punctuation.separator.key-value.mapping.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": " ", "t": "source.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": "description", "t": "source.yaml string.unquoted.plain.out.yaml entity.name.tag.yaml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_plus_experimental": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_plus_experimental": "entity.name.tag: #800000" } }, { "c": ":", "t": "source.yaml punctuation.separator.key-value.mapping.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": " ", "t": "source.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": "'", "t": "source.yaml string.quoted.single.yaml punctuation.definition.string.begin.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.single.yaml: #0F4A85", "light_plus_experimental": "string.quoted.single.yaml: #0000FF" } }, { "c": "The API Management Service API defines an updated and refined version", "t": "source.yaml string.quoted.single.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.single.yaml: #0F4A85", "light_plus_experimental": "string.quoted.single.yaml: #0000FF" } }, { "c": " of the concepts currently known as Developer, APP, and API Product in Edge. Of", "t": "source.yaml string.quoted.single.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.single.yaml: #0F4A85", "light_plus_experimental": "string.quoted.single.yaml: #0000FF" } }, { "c": " note is the introduction of the API concept, missing previously from Edge", "t": "source.yaml string.quoted.single.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.single.yaml: #0F4A85", "light_plus_experimental": "string.quoted.single.yaml: #0000FF" } }, { "c": " ", "t": "source.yaml string.quoted.single.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.single.yaml: #0F4A85", "light_plus_experimental": "string.quoted.single.yaml: #0000FF" } }, { "c": "'", "t": "source.yaml string.quoted.single.yaml punctuation.definition.string.end.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.single.yaml: #0F4A85", "light_plus_experimental": "string.quoted.single.yaml: #0000FF" } }, { "c": " ", "t": "source.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": "title", "t": "source.yaml string.unquoted.plain.out.yaml entity.name.tag.yaml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_plus_experimental": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_plus_experimental": "entity.name.tag: #800000" } }, { "c": ":", "t": "source.yaml punctuation.separator.key-value.mapping.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": " ", "t": "source.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": "API Management Service API", "t": "source.yaml string.unquoted.plain.out.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.unquoted.plain.out.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.unquoted.plain.out.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.unquoted.plain.out.yaml: #0F4A85", "light_plus_experimental": "string.unquoted.plain.out.yaml: #0000FF" } }, { "c": " ", "t": "source.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": "version", "t": "source.yaml string.unquoted.plain.out.yaml entity.name.tag.yaml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_plus_experimental": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_plus_experimental": "entity.name.tag: #800000" } }, { "c": ":", "t": "source.yaml punctuation.separator.key-value.mapping.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": " ", "t": "source.yaml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #CCCCCC", "hc_light": "default: #292929", "light_plus_experimental": "default: #3B3B3B" } }, { "c": "initial", "t": "source.yaml string.unquoted.plain.out.yaml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.unquoted.plain.out.yaml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.unquoted.plain.out.yaml: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.unquoted.plain.out.yaml: #0F4A85", "light_plus_experimental": "string.unquoted.plain.out.yaml: #0000FF" } } ]
extensions/vscode-colorize-tests/test/colorize-results/issue-6303_yaml.json
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017659435980021954, 0.00017453385225962847, 0.00017164139717351645, 0.00017475892673246562, 0.0000012065465853083879 ]
{ "id": 6, "code_window": [ "\t\tconst insertAsImage = typeof options?.insertAsImage === 'undefined' ? imageFileExtensions.has(ext) : !!options.insertAsImage;\n", "\t\tconst insertAsVideo = videoFileExtensions.has(ext);\n", "\n", "\t\tif (insertAsVideo) {\n", "\t\t\tsnippet.appendText(`<video src=\"${mdPath}\" controls title=\"`);\n", "\t\t\tsnippet.appendPlaceholder('Title');\n", "\t\t\tsnippet.appendText('\"></video>');\n", "\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tinsertedImageCount++;\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import * as vscode from 'vscode'; import * as URI from 'vscode-uri'; import { Schemes } from '../../util/schemes'; export const imageFileExtensions = new Set<string>([ 'bmp', 'gif', 'ico', 'jpe', 'jpeg', 'jpg', 'png', 'psd', 'svg', 'tga', 'tif', 'tiff', 'webp', ]); const videoFileExtensions = new Set<string>([ 'ogg', 'mp4' ]); export function registerDropIntoEditorSupport(selector: vscode.DocumentSelector) { return vscode.languages.registerDocumentDropEditProvider(selector, new class implements vscode.DocumentDropEditProvider { async provideDocumentDropEdits(document: vscode.TextDocument, _position: vscode.Position, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken): Promise<vscode.DocumentDropEdit | undefined> { const enabled = vscode.workspace.getConfiguration('markdown', document).get('editor.drop.enabled', true); if (!enabled) { return undefined; } const snippet = await tryGetUriListSnippet(document, dataTransfer, token); if (!snippet) { return undefined; } const edit = new vscode.DocumentDropEdit(snippet.snippet); edit.label = snippet.label; return edit; } }, { id: 'insertLink', dropMimeTypes: [ 'text/uri-list' ] }); } export async function tryGetUriListSnippet(document: vscode.TextDocument, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken): Promise<{ snippet: vscode.SnippetString; label: string } | undefined> { const urlList = await dataTransfer.get('text/uri-list')?.asString(); if (!urlList || token.isCancellationRequested) { return undefined; } const uris: vscode.Uri[] = []; for (const resource of urlList.split(/\r?\n/g)) { try { uris.push(vscode.Uri.parse(resource)); } catch { // noop } } const snippet = createUriListSnippet(document, uris); if (!snippet) { return undefined; } return { snippet: snippet, label: uris.length > 1 ? vscode.l10n.t('Insert uri links') : vscode.l10n.t('Insert uri link') }; } interface UriListSnippetOptions { readonly placeholderText?: string; readonly placeholderStartIndex?: number; /** * Should the snippet be for an image? * * If `undefined`, tries to infer this from the uri. */ readonly insertAsImage?: boolean; readonly separator?: string; } export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): vscode.SnippetString | undefined { if (!uris.length) { return undefined; } const dir = getDocumentDir(document); const snippet = new vscode.SnippetString(); uris.forEach((uri, i) => { const mdPath = getMdPath(dir, uri); const ext = URI.Utils.extname(uri).toLowerCase().replace('.', ''); const insertAsImage = typeof options?.insertAsImage === 'undefined' ? imageFileExtensions.has(ext) : !!options.insertAsImage; const insertAsVideo = videoFileExtensions.has(ext); if (insertAsVideo) { snippet.appendText(`<video src="${mdPath}" controls title="`); snippet.appendPlaceholder('Title'); snippet.appendText('"></video>'); } else { snippet.appendText(insertAsImage ? '![' : '['); const placeholderText = options?.placeholderText ?? (insertAsImage ? 'Alt text' : 'label'); const placeholderIndex = typeof options?.placeholderStartIndex !== 'undefined' ? options?.placeholderStartIndex + i : undefined; snippet.appendPlaceholder(placeholderText, placeholderIndex); snippet.appendText(`](${mdPath})`); } if (i < uris.length - 1 && uris.length > 1) { snippet.appendText(options?.separator ?? ' '); } }); return snippet; } function getMdPath(dir: vscode.Uri | undefined, file: vscode.Uri) { if (dir && dir.scheme === file.scheme && dir.authority === file.authority) { if (file.scheme === Schemes.file) { // On windows, we must use the native `path.relative` to generate the relative path // so that drive-letters are resolved cast insensitively. However we then want to // convert back to a posix path to insert in to the document. const relativePath = path.relative(dir.fsPath, file.fsPath); return encodeURI(path.posix.normalize(relativePath.split(path.sep).join(path.posix.sep))); } return encodeURI(path.posix.relative(dir.path, file.path)); } return file.toString(false); } function getDocumentDir(document: vscode.TextDocument): vscode.Uri | undefined { const docUri = getParentDocumentUri(document); if (docUri.scheme === Schemes.untitled) { return vscode.workspace.workspaceFolders?.[0]?.uri; } return URI.Utils.dirname(docUri); } export function getParentDocumentUri(document: vscode.TextDocument): vscode.Uri { if (document.uri.scheme === Schemes.notebookCell) { for (const notebook of vscode.workspace.notebookDocuments) { for (const cell of notebook.getCells()) { if (cell.document === document) { return notebook.uri; } } } } return document.uri; }
extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts
1
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.9983974099159241, 0.11154231429100037, 0.00016434129793196917, 0.0003198902995791286, 0.3132288455963135 ]
{ "id": 6, "code_window": [ "\t\tconst insertAsImage = typeof options?.insertAsImage === 'undefined' ? imageFileExtensions.has(ext) : !!options.insertAsImage;\n", "\t\tconst insertAsVideo = videoFileExtensions.has(ext);\n", "\n", "\t\tif (insertAsVideo) {\n", "\t\t\tsnippet.appendText(`<video src=\"${mdPath}\" controls title=\"`);\n", "\t\t\tsnippet.appendPlaceholder('Title');\n", "\t\t\tsnippet.appendText('\"></video>');\n", "\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tinsertedImageCount++;\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CharCode } from 'vs/base/common/charCode'; import { ITextBuffer } from 'vs/editor/common/model'; class SpacesDiffResult { public spacesDiff: number = 0; public looksLikeAlignment: boolean = false; } /** * Compute the diff in spaces between two line's indentation. */ function spacesDiff(a: string, aLength: number, b: string, bLength: number, result: SpacesDiffResult): void { result.spacesDiff = 0; result.looksLikeAlignment = false; // This can go both ways (e.g.): // - a: "\t" // - b: "\t " // => This should count 1 tab and 4 spaces let i: number; for (i = 0; i < aLength && i < bLength; i++) { const aCharCode = a.charCodeAt(i); const bCharCode = b.charCodeAt(i); if (aCharCode !== bCharCode) { break; } } let aSpacesCnt = 0, aTabsCount = 0; for (let j = i; j < aLength; j++) { const aCharCode = a.charCodeAt(j); if (aCharCode === CharCode.Space) { aSpacesCnt++; } else { aTabsCount++; } } let bSpacesCnt = 0, bTabsCount = 0; for (let j = i; j < bLength; j++) { const bCharCode = b.charCodeAt(j); if (bCharCode === CharCode.Space) { bSpacesCnt++; } else { bTabsCount++; } } if (aSpacesCnt > 0 && aTabsCount > 0) { return; } if (bSpacesCnt > 0 && bTabsCount > 0) { return; } const tabsDiff = Math.abs(aTabsCount - bTabsCount); const spacesDiff = Math.abs(aSpacesCnt - bSpacesCnt); if (tabsDiff === 0) { // check if the indentation difference might be caused by alignment reasons // sometime folks like to align their code, but this should not be used as a hint result.spacesDiff = spacesDiff; if (spacesDiff > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a.length && bSpacesCnt < b.length) { if (b.charCodeAt(bSpacesCnt) !== CharCode.Space && a.charCodeAt(bSpacesCnt - 1) === CharCode.Space) { if (a.charCodeAt(a.length - 1) === CharCode.Comma) { // This looks like an alignment desire: e.g. // const a = b + c, // d = b - c; result.looksLikeAlignment = true; } } } return; } if (spacesDiff % tabsDiff === 0) { result.spacesDiff = spacesDiff / tabsDiff; return; } } /** * Result for a guessIndentation */ export interface IGuessedIndentation { /** * If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent? */ tabSize: number; /** * Is indentation based on spaces? */ insertSpaces: boolean; } export function guessIndentation(source: ITextBuffer, defaultTabSize: number, defaultInsertSpaces: boolean): IGuessedIndentation { // Look at most at the first 10k lines const linesCount = Math.min(source.getLineCount(), 10000); let linesIndentedWithTabsCount = 0; // number of lines that contain at least one tab in indentation let linesIndentedWithSpacesCount = 0; // number of lines that contain only spaces in indentation let previousLineText = ''; // content of latest line that contained non-whitespace chars let previousLineIndentation = 0; // index at which latest line contained the first non-whitespace char const ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7]; // prefer even guesses for `tabSize`, limit to [2, 8]. const MAX_ALLOWED_TAB_SIZE_GUESS = 8; // max(ALLOWED_TAB_SIZE_GUESSES) = 8 const spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores const tmp = new SpacesDiffResult(); for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) { const currentLineLength = source.getLineLength(lineNumber); const currentLineText = source.getLineContent(lineNumber); // if the text buffer is chunk based, so long lines are cons-string, v8 will flattern the string when we check charCode. // checking charCode on chunks directly is cheaper. const useCurrentLineText = (currentLineLength <= 65536); let currentLineHasContent = false; // does `currentLineText` contain non-whitespace chars let currentLineIndentation = 0; // index at which `currentLineText` contains the first non-whitespace char let currentLineSpacesCount = 0; // count of spaces found in `currentLineText` indentation let currentLineTabsCount = 0; // count of tabs found in `currentLineText` indentation for (let j = 0, lenJ = currentLineLength; j < lenJ; j++) { const charCode = (useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j)); if (charCode === CharCode.Tab) { currentLineTabsCount++; } else if (charCode === CharCode.Space) { currentLineSpacesCount++; } else { // Hit non whitespace character on this line currentLineHasContent = true; currentLineIndentation = j; break; } } // Ignore empty or only whitespace lines if (!currentLineHasContent) { continue; } if (currentLineTabsCount > 0) { linesIndentedWithTabsCount++; } else if (currentLineSpacesCount > 1) { linesIndentedWithSpacesCount++; } spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation, tmp); if (tmp.looksLikeAlignment) { // if defaultInsertSpaces === true && the spaces count == tabSize, we may want to count it as valid indentation // // - item1 // - item2 // // otherwise skip this line entirely // // const a = 1, // b = 2; if (!(defaultInsertSpaces && defaultTabSize === tmp.spacesDiff)) { continue; } } const currentSpacesDiff = tmp.spacesDiff; if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) { spacesDiffCount[currentSpacesDiff]++; } previousLineText = currentLineText; previousLineIndentation = currentLineIndentation; } let insertSpaces = defaultInsertSpaces; if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) { insertSpaces = (linesIndentedWithTabsCount < linesIndentedWithSpacesCount); } let tabSize = defaultTabSize; // Guess tabSize only if inserting spaces... if (insertSpaces) { let tabSizeScore = (insertSpaces ? 0 : 0.1 * linesCount); // console.log("score threshold: " + tabSizeScore); ALLOWED_TAB_SIZE_GUESSES.forEach((possibleTabSize) => { const possibleTabSizeScore = spacesDiffCount[possibleTabSize]; if (possibleTabSizeScore > tabSizeScore) { tabSizeScore = possibleTabSizeScore; tabSize = possibleTabSize; } }); // Let a tabSize of 2 win even if it is not the maximum // (only in case 4 was guessed) if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) { tabSize = 2; } } // console.log('--------------------------'); // console.log('linesIndentedWithTabsCount: ' + linesIndentedWithTabsCount + ', linesIndentedWithSpacesCount: ' + linesIndentedWithSpacesCount); // console.log('spacesDiffCount: ' + spacesDiffCount); // console.log('tabSize: ' + tabSize + ', tabSizeScore: ' + tabSizeScore); return { insertSpaces: insertSpaces, tabSize: tabSize }; }
src/vs/editor/common/model/indentationGuesser.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.0001769621594576165, 0.00017143362492788583, 0.00016571881133131683, 0.00017222865426447242, 0.0000028103311251470586 ]
{ "id": 6, "code_window": [ "\t\tconst insertAsImage = typeof options?.insertAsImage === 'undefined' ? imageFileExtensions.has(ext) : !!options.insertAsImage;\n", "\t\tconst insertAsVideo = videoFileExtensions.has(ext);\n", "\n", "\t\tif (insertAsVideo) {\n", "\t\t\tsnippet.appendText(`<video src=\"${mdPath}\" controls title=\"`);\n", "\t\t\tsnippet.appendPlaceholder('Title');\n", "\t\t\tsnippet.appendText('\"></video>');\n", "\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tinsertedImageCount++;\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { UriDto } from 'vs/base/common/uri'; import { IChannel } from 'vs/base/parts/ipc/common/ipc'; import { IStorageDatabase, IStorageItemsChangeEvent, IUpdateRequest } from 'vs/base/parts/storage/common/storage'; import { IUserDataProfile } from 'vs/platform/userDataProfile/common/userDataProfile'; import { ISerializedSingleFolderWorkspaceIdentifier, ISerializedWorkspaceIdentifier, IEmptyWorkspaceIdentifier, IAnyWorkspaceIdentifier } from 'vs/platform/workspace/common/workspace'; export type Key = string; export type Value = string; export type Item = [Key, Value]; export interface IBaseSerializableStorageRequest { /** * Profile to correlate storage. Only used when no * workspace is provided. Can be undefined to denote * application scope. */ readonly profile: UriDto<IUserDataProfile> | undefined; /** * Workspace to correlate storage. Can be undefined to * denote application or profile scope depending on profile. */ readonly workspace: ISerializedWorkspaceIdentifier | ISerializedSingleFolderWorkspaceIdentifier | IEmptyWorkspaceIdentifier | undefined; /** * Additional payload for the request to perform. */ readonly payload?: unknown; } export interface ISerializableUpdateRequest extends IBaseSerializableStorageRequest { insert?: Item[]; delete?: Key[]; } export interface ISerializableItemsChangeEvent { readonly changed?: Item[]; readonly deleted?: Key[]; } abstract class BaseStorageDatabaseClient extends Disposable implements IStorageDatabase { abstract readonly onDidChangeItemsExternal: Event<IStorageItemsChangeEvent>; constructor( protected channel: IChannel, protected profile: UriDto<IUserDataProfile> | undefined, protected workspace: IAnyWorkspaceIdentifier | undefined ) { super(); } async getItems(): Promise<Map<string, string>> { const serializableRequest: IBaseSerializableStorageRequest = { profile: this.profile, workspace: this.workspace }; const items: Item[] = await this.channel.call('getItems', serializableRequest); return new Map(items); } updateItems(request: IUpdateRequest): Promise<void> { const serializableRequest: ISerializableUpdateRequest = { profile: this.profile, workspace: this.workspace }; if (request.insert) { serializableRequest.insert = Array.from(request.insert.entries()); } if (request.delete) { serializableRequest.delete = Array.from(request.delete.values()); } return this.channel.call('updateItems', serializableRequest); } abstract close(): Promise<void>; } abstract class BaseProfileAwareStorageDatabaseClient extends BaseStorageDatabaseClient { private readonly _onDidChangeItemsExternal = this._register(new Emitter<IStorageItemsChangeEvent>()); readonly onDidChangeItemsExternal = this._onDidChangeItemsExternal.event; constructor(channel: IChannel, profile: UriDto<IUserDataProfile> | undefined) { super(channel, profile, undefined); this.registerListeners(); } private registerListeners(): void { this._register(this.channel.listen<ISerializableItemsChangeEvent>('onDidChangeStorage', { profile: this.profile })((e: ISerializableItemsChangeEvent) => this.onDidChangeStorage(e))); } private onDidChangeStorage(e: ISerializableItemsChangeEvent): void { if (Array.isArray(e.changed) || Array.isArray(e.deleted)) { this._onDidChangeItemsExternal.fire({ changed: e.changed ? new Map(e.changed) : undefined, deleted: e.deleted ? new Set<string>(e.deleted) : undefined }); } } } export class ApplicationStorageDatabaseClient extends BaseProfileAwareStorageDatabaseClient { constructor(channel: IChannel) { super(channel, undefined); } async close(): Promise<void> { // The application storage database is shared across all instances so // we do not close it from the window. However we dispose the // listener for external changes because we no longer interested in it. this.dispose(); } } export class ProfileStorageDatabaseClient extends BaseProfileAwareStorageDatabaseClient { constructor(channel: IChannel, profile: UriDto<IUserDataProfile>) { super(channel, profile); } async close(): Promise<void> { // The profile storage database is shared across all instances of // the same profile so we do not close it from the window. // However we dispose the listener for external changes because // we no longer interested in it. this.dispose(); } } export class WorkspaceStorageDatabaseClient extends BaseStorageDatabaseClient implements IStorageDatabase { readonly onDidChangeItemsExternal = Event.None; // unsupported for workspace storage because we only ever write from one window constructor(channel: IChannel, workspace: IAnyWorkspaceIdentifier) { super(channel, undefined, workspace); } async close(): Promise<void> { // The workspace storage database is only used in this instance // but we do not need to close it from here, the main process // can take care of that. this.dispose(); } } export class StorageClient { constructor(private readonly channel: IChannel) { } isUsed(path: string): Promise<boolean> { const serializableRequest: ISerializableUpdateRequest = { payload: path, profile: undefined, workspace: undefined }; return this.channel.call('isUsed', serializableRequest); } }
src/vs/platform/storage/common/storageIpc.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.0001759333536028862, 0.00017037798534147441, 0.00016242588753812015, 0.00017085425497498363, 0.0000036551462017087033 ]
{ "id": 6, "code_window": [ "\t\tconst insertAsImage = typeof options?.insertAsImage === 'undefined' ? imageFileExtensions.has(ext) : !!options.insertAsImage;\n", "\t\tconst insertAsVideo = videoFileExtensions.has(ext);\n", "\n", "\t\tif (insertAsVideo) {\n", "\t\t\tsnippet.appendText(`<video src=\"${mdPath}\" controls title=\"`);\n", "\t\t\tsnippet.appendPlaceholder('Title');\n", "\t\t\tsnippet.appendText('\"></video>');\n", "\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tinsertedImageCount++;\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { ActionBar, IActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Button } from 'vs/base/browser/ui/button/button'; import { renderLabelWithIcons } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { IIdentityProvider, IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { DefaultKeyboardNavigationDelegate, IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ITreeContextMenuEvent, ITreeFilter, ITreeNode, ITreeRenderer, ITreeSorter, TreeFilterResult, TreeVisibility } from 'vs/base/browser/ui/tree/tree'; import { Action, ActionRunner, IAction, Separator } from 'vs/base/common/actions'; import { RunOnceScheduler, disposableTimeout } from 'vs/base/common/async'; import { Color, RGBA } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { KeyCode } from 'vs/base/common/keyCodes'; import { Disposable, IDisposable, MutableDisposable, dispose } from 'vs/base/common/lifecycle'; import { fuzzyContains } from 'vs/base/common/strings'; import { isDefined } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import 'vs/css!./media/testing'; import { MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer'; import { localize } from 'vs/nls'; import { DropdownWithPrimaryActionViewItem } from 'vs/platform/actions/browser/dropdownWithPrimaryActionViewItem'; import { MenuEntryActionViewItem, createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, MenuId, MenuItemAction } from 'vs/platform/actions/common/actions'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { UnmanagedProgress } from 'vs/platform/progress/common/progress'; import { IStorageService, StorageScope, StorageTarget, WillSaveStateReason } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles'; import { foreground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { ThemeIcon } from 'vs/base/common/themables'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { HierarchicalByLocationProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByLocation'; import { ByNameTestItemElement, HierarchicalByNameProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByName'; import { ITestTreeProjection, TestExplorerTreeElement, TestItemTreeElement, TestTreeErrorMessage } from 'vs/workbench/contrib/testing/browser/explorerProjections/index'; import { getTestItemContextOverlay } from 'vs/workbench/contrib/testing/browser/explorerProjections/testItemContextOverlay'; import { TestingObjectTree } from 'vs/workbench/contrib/testing/browser/explorerProjections/testingObjectTree'; import { ISerializedTestTreeCollapseState } from 'vs/workbench/contrib/testing/browser/explorerProjections/testingViewState'; import * as icons from 'vs/workbench/contrib/testing/browser/icons'; import { TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter'; import { ITestingProgressUiService } from 'vs/workbench/contrib/testing/browser/testingProgressUiService'; import { TestingConfigKeys, getTestingConfiguration } from 'vs/workbench/contrib/testing/common/configuration'; import { TestCommandId, TestExplorerViewMode, TestExplorerViewSorting, Testing, labelForTestInState } from 'vs/workbench/contrib/testing/common/constants'; import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue'; import { ITestExplorerFilterState, TestExplorerFilterState, TestFilterTerm } from 'vs/workbench/contrib/testing/common/testExplorerFilterState'; import { TestId } from 'vs/workbench/contrib/testing/common/testId'; import { ITestProfileService, canUseProfileWithTest } from 'vs/workbench/contrib/testing/common/testProfileService'; import { TestResultItemChangeReason } from 'vs/workbench/contrib/testing/common/testResult'; import { ITestResultService } from 'vs/workbench/contrib/testing/common/testResultService'; import { IMainThreadTestCollection, ITestService, testCollectionIsEmpty } from 'vs/workbench/contrib/testing/common/testService'; import { ITestRunProfile, InternalTestItem, TestItemExpandState, TestResultState, TestRunProfileBitset } from 'vs/workbench/contrib/testing/common/testTypes'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; import { ITestingPeekOpener } from 'vs/workbench/contrib/testing/common/testingPeekOpener'; import { cmpPriority, isFailedState, isStateWithResult } from 'vs/workbench/contrib/testing/common/testingStates'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITestingContinuousRunService } from 'vs/workbench/contrib/testing/common/testingContinuousRunService'; const enum LastFocusState { Input, Tree, } export class TestingExplorerView extends ViewPane { public viewModel!: TestingExplorerViewModel; private filterActionBar = this._register(new MutableDisposable()); private container!: HTMLElement; private treeHeader!: HTMLElement; private discoveryProgress = this._register(new MutableDisposable<UnmanagedProgress>()); private readonly filter = this._register(new MutableDisposable<TestingExplorerFilter>()); private readonly filterFocusListener = this._register(new MutableDisposable()); private readonly dimensions = { width: 0, height: 0 }; private lastFocusState = LastFocusState.Input; public get focusedTreeElements() { return this.viewModel.tree.getFocus().filter(isDefined); } constructor( options: IViewletViewOptions, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IConfigurationService configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITestService private readonly testService: ITestService, @ITelemetryService telemetryService: ITelemetryService, @ITestingProgressUiService private readonly testProgressService: ITestingProgressUiService, @ITestProfileService private readonly testProfileService: ITestProfileService, @ICommandService private readonly commandService: ICommandService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); const relayout = this._register(new RunOnceScheduler(() => this.layoutBody(), 1)); this._register(this.onDidChangeViewWelcomeState(() => { if (!this.shouldShowWelcome()) { relayout.schedule(); } })); this._register(testService.collection.onBusyProvidersChange(busy => { this.updateDiscoveryProgress(busy); })); this._register(testProfileService.onDidChange(() => this.updateActions())); } public override shouldShowWelcome() { return this.viewModel?.welcomeExperience === WelcomeExperience.ForWorkspace ?? true; } public override focus() { super.focus(); if (this.lastFocusState === LastFocusState.Tree) { this.viewModel.tree.domFocus(); } else { this.filter.value?.focus(); } } /** * Gets include/exclude items in the tree, based either on visible tests * or a use selection. */ public getTreeIncludeExclude(profile?: ITestRunProfile, filterToType: 'visible' | 'selected' = 'visible') { const projection = this.viewModel.projection.value; if (!projection) { return { include: [], exclude: [] }; } if (projection instanceof ByNameTestItemElement) { return { include: [...this.testService.collection.rootItems], exclude: [], }; } // To calculate includes and excludes, we include the first children that // have a majority of their items included too, and then apply exclusions. const include = new Set<InternalTestItem>(); const exclude: InternalTestItem[] = []; const attempt = (element: TestExplorerTreeElement, alreadyIncluded: boolean) => { // sanity check hasElement since updates are debounced and they may exist // but not be rendered yet if (!(element instanceof TestItemTreeElement) || !this.viewModel.tree.hasElement(element)) { return; } // If the current node is not visible or runnable in the current profile, it's excluded const inTree = this.viewModel.tree.getNode(element); if (!inTree.visible) { if (alreadyIncluded) { exclude.push(element.test); } return; } // If it's not already included but most of its children are, then add it // if it can be run under the current profile (when specified) if ( // If it's not already included... !alreadyIncluded // And it can be run using the current profile (if any) && (!profile || canUseProfileWithTest(profile, element.test)) // And either it's a leaf node or most children are included, the include it. && (inTree.children.length === 0 || inTree.visibleChildrenCount * 2 >= inTree.children.length) // And not if we're only showing a single of its children, since it // probably fans out later. (Worse case we'll directly include its single child) && inTree.visibleChildrenCount !== 1 ) { include.add(element.test); alreadyIncluded = true; } // Recurse ✨ for (const child of element.children) { attempt(child, alreadyIncluded); } }; if (filterToType === 'selected') { const sel = this.viewModel.tree.getSelection().filter(isDefined); if (sel.length) { L: for (const node of sel) { if (node instanceof TestItemTreeElement) { // avoid adding an item if its parent is already included for (let i: TestItemTreeElement | null = node; i; i = i.parent) { if (include.has(i.test)) { continue L; } } include.add(node.test); node.children.forEach(c => attempt(c, true)); } } return { include: [...include], exclude }; } } for (const root of this.testService.collection.rootItems) { const element = projection.getElementByTestId(root.item.extId); if (!element) { continue; } if (profile && !canUseProfileWithTest(profile, root)) { continue; } // single controllers won't have visible root ID nodes, handle that case specially if (!this.viewModel.tree.hasElement(element)) { const visibleChildren = [...element.children].reduce((acc, c) => this.viewModel.tree.hasElement(c) && this.viewModel.tree.getNode(c).visible ? acc + 1 : acc, 0); // note we intentionally check children > 0 here, unlike above, since // we don't want to bother dispatching to controllers who have no discovered tests if (element.children.size > 0 && visibleChildren * 2 >= element.children.size) { include.add(element.test); element.children.forEach(c => attempt(c, true)); } else { element.children.forEach(c => attempt(c, false)); } } else { attempt(element, false); } } return { include: [...include], exclude }; } /** * @override */ protected override renderBody(container: HTMLElement): void { super.renderBody(container); this.container = dom.append(container, dom.$('.test-explorer')); this.treeHeader = dom.append(this.container, dom.$('.test-explorer-header')); this.filterActionBar.value = this.createFilterActionBar(); const messagesContainer = dom.append(this.treeHeader, dom.$('.test-explorer-messages')); this._register(this.testProgressService.onTextChange(text => { const hadText = !!messagesContainer.innerText; const hasText = !!text; messagesContainer.innerText = text; if (hadText !== hasText) { this.layoutBody(); } })); const listContainer = dom.append(this.container, dom.$('.test-explorer-tree')); this.viewModel = this.instantiationService.createInstance(TestingExplorerViewModel, listContainer, this.onDidChangeBodyVisibility); this._register(this.viewModel.tree.onDidFocus(() => this.lastFocusState = LastFocusState.Tree)); this._register(this.viewModel.onChangeWelcomeVisibility(() => this._onDidChangeViewWelcomeState.fire())); this._register(this.viewModel); this._onDidChangeViewWelcomeState.fire(); } /** @override */ public override getActionViewItem(action: IAction): IActionViewItem | undefined { switch (action.id) { case TestCommandId.FilterAction: this.filter.value = this.instantiationService.createInstance(TestingExplorerFilter, action); this.filterFocusListener.value = this.filter.value.onDidFocus(() => this.lastFocusState = LastFocusState.Input); return this.filter.value; case TestCommandId.RunSelectedAction: return this.getRunGroupDropdown(TestRunProfileBitset.Run, action); case TestCommandId.DebugSelectedAction: return this.getRunGroupDropdown(TestRunProfileBitset.Debug, action); default: return super.getActionViewItem(action); } } /** @inheritdoc */ private getTestConfigGroupActions(group: TestRunProfileBitset) { const profileActions: IAction[] = []; let participatingGroups = 0; let hasConfigurable = false; const defaults = this.testProfileService.getGroupDefaultProfiles(group); for (const { profiles, controller } of this.testProfileService.all()) { let hasAdded = false; for (const profile of profiles) { if (profile.group !== group) { continue; } if (!hasAdded) { hasAdded = true; participatingGroups++; profileActions.push(new Action(`${controller.id}.$root`, controller.label.value, undefined, false)); } hasConfigurable = hasConfigurable || profile.hasConfigurationHandler; profileActions.push(new Action( `${controller.id}.${profile.profileId}`, defaults.includes(profile) ? localize('defaultTestProfile', '{0} (Default)', profile.label) : profile.label, undefined, undefined, () => { const { include, exclude } = this.getTreeIncludeExclude(profile); this.testService.runResolvedTests({ exclude: exclude.map(e => e.item.extId), targets: [{ profileGroup: profile.group, profileId: profile.profileId, controllerId: profile.controllerId, testIds: include.map(i => i.item.extId), }] }); }, )); } } // If there's only one group, don't add a heading for it in the dropdown. if (participatingGroups === 1) { profileActions.shift(); } const postActions: IAction[] = []; if (profileActions.length > 1) { postActions.push(new Action( 'selectDefaultTestConfigurations', localize('selectDefaultConfigs', 'Select Default Profile'), undefined, undefined, () => this.commandService.executeCommand<ITestRunProfile>(TestCommandId.SelectDefaultTestProfiles, group), )); } if (hasConfigurable) { postActions.push(new Action( 'configureTestProfiles', localize('configureTestProfiles', 'Configure Test Profiles'), undefined, undefined, () => this.commandService.executeCommand<ITestRunProfile>(TestCommandId.ConfigureTestProfilesAction, group), )); } return Separator.join(profileActions, postActions); } /** * @override */ public override saveState() { this.filter.value?.saveState(); super.saveState(); } private getRunGroupDropdown(group: TestRunProfileBitset, defaultAction: IAction) { const dropdownActions = this.getTestConfigGroupActions(group); if (dropdownActions.length < 2) { return super.getActionViewItem(defaultAction); } const primaryAction = this.instantiationService.createInstance(MenuItemAction, { id: defaultAction.id, title: defaultAction.label, icon: group === TestRunProfileBitset.Run ? icons.testingRunAllIcon : icons.testingDebugAllIcon, }, undefined, undefined, undefined); const dropdownAction = new Action('selectRunConfig', 'Select Configuration...', 'codicon-chevron-down', true); return this.instantiationService.createInstance( DropdownWithPrimaryActionViewItem, primaryAction, dropdownAction, dropdownActions, '', this.contextMenuService, {} ); } private createFilterActionBar() { const bar = new ActionBar(this.treeHeader, { actionViewItemProvider: action => this.getActionViewItem(action), triggerKeys: { keyDown: false, keys: [] }, }); bar.push(new Action(TestCommandId.FilterAction)); bar.getContainer().classList.add('testing-filter-action-bar'); return bar; } private updateDiscoveryProgress(busy: number) { if (!busy && this.discoveryProgress) { this.discoveryProgress.clear(); } else if (busy && !this.discoveryProgress.value) { this.discoveryProgress.value = this.instantiationService.createInstance(UnmanagedProgress, { location: this.getProgressLocation() }); } } /** * @override */ protected override layoutBody(height = this.dimensions.height, width = this.dimensions.width): void { super.layoutBody(height, width); this.dimensions.height = height; this.dimensions.width = width; this.container.style.height = `${height}px`; this.viewModel.layout(height - this.treeHeader.clientHeight, width); this.filter.value?.layout(width); } } const enum WelcomeExperience { None, ForWorkspace, ForDocument, } class TestingExplorerViewModel extends Disposable { public tree: TestingObjectTree<FuzzyScore>; private filter: TestsFilter; public projection = this._register(new MutableDisposable<ITestTreeProjection>()); private readonly revealTimeout = new MutableDisposable(); private readonly _viewMode = TestingContextKeys.viewMode.bindTo(this.contextKeyService); private readonly _viewSorting = TestingContextKeys.viewSorting.bindTo(this.contextKeyService); private readonly welcomeVisibilityEmitter = new Emitter<WelcomeExperience>(); private readonly actionRunner = new TestExplorerActionRunner(() => this.tree.getSelection().filter(isDefined)); private readonly lastViewState = new StoredValue<ISerializedTestTreeCollapseState>({ key: 'testing.treeState', scope: StorageScope.WORKSPACE, target: StorageTarget.MACHINE, }, this.storageService); private readonly noTestForDocumentWidget: NoTestsForDocumentWidget; /** * Whether there's a reveal request which has not yet been delivered. This * can happen if the user asks to reveal before the test tree is loaded. * We check to see if the reveal request is present on each tree update, * and do it then if so. */ private hasPendingReveal = false; /** * Fires when the visibility of the placeholder state changes. */ public readonly onChangeWelcomeVisibility = this.welcomeVisibilityEmitter.event; /** * Gets whether the welcome should be visible. */ public welcomeExperience = WelcomeExperience.None; public get viewMode() { return this._viewMode.get() ?? TestExplorerViewMode.Tree; } public set viewMode(newMode: TestExplorerViewMode) { if (newMode === this._viewMode.get()) { return; } this._viewMode.set(newMode); this.updatePreferredProjection(); this.storageService.store('testing.viewMode', newMode, StorageScope.WORKSPACE, StorageTarget.USER); } public get viewSorting() { return this._viewSorting.get() ?? TestExplorerViewSorting.ByStatus; } public set viewSorting(newSorting: TestExplorerViewSorting) { if (newSorting === this._viewSorting.get()) { return; } this._viewSorting.set(newSorting); this.tree.resort(null); this.storageService.store('testing.viewSorting', newSorting, StorageScope.WORKSPACE, StorageTarget.USER); } constructor( listContainer: HTMLElement, onDidChangeVisibility: Event<boolean>, @IConfigurationService configurationService: IConfigurationService, @IEditorService editorService: IEditorService, @IMenuService private readonly menuService: IMenuService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @ITestService private readonly testService: ITestService, @ITestExplorerFilterState private readonly filterState: TestExplorerFilterState, @IInstantiationService private readonly instantiationService: IInstantiationService, @IStorageService private readonly storageService: IStorageService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITestResultService private readonly testResults: ITestResultService, @ITestingPeekOpener private readonly peekOpener: ITestingPeekOpener, @ITestProfileService private readonly testProfileService: ITestProfileService, @ITestingContinuousRunService private readonly crService: ITestingContinuousRunService, ) { super(); this.hasPendingReveal = !!filterState.reveal.value; this.noTestForDocumentWidget = this._register(instantiationService.createInstance(NoTestsForDocumentWidget, listContainer)); this._viewMode.set(this.storageService.get('testing.viewMode', StorageScope.WORKSPACE, TestExplorerViewMode.Tree) as TestExplorerViewMode); this._viewSorting.set(this.storageService.get('testing.viewSorting', StorageScope.WORKSPACE, TestExplorerViewSorting.ByLocation) as TestExplorerViewSorting); this.reevaluateWelcomeState(); this.filter = this.instantiationService.createInstance(TestsFilter, testService.collection); this.tree = instantiationService.createInstance( TestingObjectTree, 'Test Explorer List', listContainer, new ListDelegate(), [ instantiationService.createInstance(TestItemRenderer, this.actionRunner), instantiationService.createInstance(ErrorRenderer), ], { identityProvider: instantiationService.createInstance(IdentityProvider), hideTwistiesOfChildlessElements: false, sorter: instantiationService.createInstance(TreeSorter, this), keyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider), accessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider), filter: this.filter, findWidgetEnabled: false }) as TestingObjectTree<FuzzyScore>; // saves the collapse state so that if items are removed or refreshed, they // retain the same state (#170169) const collapseStateSaver = this._register(new RunOnceScheduler(() => { // reuse the last view state to avoid making a bunch of object garbage: const state = this.tree.getOptimizedViewState(this.lastViewState.get({})); const projection = this.projection.value; if (projection) { projection.lastState = state; } }, 3000)); this._register(this.tree.onDidChangeCollapseState(evt => { if (evt.node.element instanceof TestItemTreeElement) { if (!evt.node.collapsed) { this.projection.value?.expandElement(evt.node.element, evt.deep ? Infinity : 0); } collapseStateSaver.schedule(); } })); this._register(this.crService.onDidChange(testId => { if (testId) { // a continuous run test will sort to the top: const elem = this.projection.value?.getElementByTestId(testId); this.tree.resort(elem?.parent && this.tree.hasElement(elem.parent) ? elem.parent : null, false); } })); this._register(onDidChangeVisibility(visible => { if (visible) { this.ensureProjection(); } })); this._register(this.tree.onContextMenu(e => this.onContextMenu(e))); this._register(Event.any( filterState.text.onDidChange, filterState.fuzzy.onDidChange, testService.excluded.onTestExclusionsChanged, )(this.tree.refilter, this.tree)); this._register(this.tree); this._register(this.onChangeWelcomeVisibility(e => { this.noTestForDocumentWidget.setVisible(e === WelcomeExperience.ForDocument); })); this._register(dom.addStandardDisposableListener(this.tree.getHTMLElement(), 'keydown', evt => { if (evt.equals(KeyCode.Enter)) { this.handleExecuteKeypress(evt); } else if (DefaultKeyboardNavigationDelegate.mightProducePrintableCharacter(evt)) { filterState.text.value = evt.browserEvent.key; filterState.focusInput(); } })); this._register(filterState.reveal.onDidChange(id => this.revealById(id, undefined, false))); this._register(onDidChangeVisibility(visible => { if (visible) { filterState.focusInput(); } })); this._register(this.tree.onDidChangeSelection(evt => { if (evt.browserEvent instanceof MouseEvent && (evt.browserEvent.altKey || evt.browserEvent.shiftKey)) { return; // don't focus when alt-clicking to multi select } const selected = evt.elements[0]; if (selected && evt.browserEvent && selected instanceof TestItemTreeElement && selected.children.size === 0 && selected.test.expand === TestItemExpandState.NotExpandable) { this.tryPeekError(selected); } })); let followRunningTests = getTestingConfiguration(configurationService, TestingConfigKeys.FollowRunningTest); this._register(configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(TestingConfigKeys.FollowRunningTest)) { followRunningTests = getTestingConfiguration(configurationService, TestingConfigKeys.FollowRunningTest); } })); let alwaysRevealTestAfterStateChange = getTestingConfiguration(configurationService, TestingConfigKeys.AlwaysRevealTestOnStateChange); this._register(configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(TestingConfigKeys.AlwaysRevealTestOnStateChange)) { alwaysRevealTestAfterStateChange = getTestingConfiguration(configurationService, TestingConfigKeys.AlwaysRevealTestOnStateChange); } })); this._register(testResults.onTestChanged(evt => { if (!followRunningTests) { return; } if (evt.reason !== TestResultItemChangeReason.OwnStateChange) { return; } // follow running tests, or tests whose state changed. Tests that // complete very fast may not enter the running state at all. if (evt.item.ownComputedState !== TestResultState.Running && !(evt.previousState === TestResultState.Queued && isStateWithResult(evt.item.ownComputedState))) { return; } this.revealById(evt.item.item.extId, alwaysRevealTestAfterStateChange, false); })); this._register(testResults.onResultsChanged(() => { this.tree.resort(null); })); this._register(this.testProfileService.onDidChange(() => { this.tree.rerender(); })); const onEditorChange = () => { if (editorService.activeEditor instanceof DiffEditorInput) { this.filter.filterToDocumentUri(editorService.activeEditor.primary.resource); } else { this.filter.filterToDocumentUri(editorService.activeEditor?.resource); } if (this.filterState.isFilteringFor(TestFilterTerm.CurrentDoc)) { this.tree.refilter(); } }; this._register(editorService.onDidActiveEditorChange(onEditorChange)); this._register(this.storageService.onWillSaveState(({ reason, }) => { if (reason === WillSaveStateReason.SHUTDOWN) { this.lastViewState.store(this.tree.getOptimizedViewState()); } })); onEditorChange(); } /** * Re-layout the tree. */ public layout(height?: number, width?: number): void { this.tree.layout(height, width); } /** * Tries to reveal by extension ID. Queues the request if the extension * ID is not currently available. */ private revealById(id: string | undefined, expand = true, focus = true) { if (!id) { this.hasPendingReveal = false; return; } const projection = this.ensureProjection(); // If the item itself is visible in the tree, show it. Otherwise, expand // its closest parent. let expandToLevel = 0; const idPath = [...TestId.fromString(id).idsFromRoot()]; for (let i = idPath.length - 1; i >= expandToLevel; i--) { const element = projection.getElementByTestId(idPath[i].toString()); // Skip all elements that aren't in the tree. if (!element || !this.tree.hasElement(element)) { continue; } // If this 'if' is true, we're at the closest-visible parent to the node // we want to expand. Expand that, and then start the loop again because // we might already have children for it. if (i < idPath.length - 1) { if (expand) { this.tree.expand(element); expandToLevel = i + 1; // avoid an infinite loop if the test does not exist i = idPath.length - 1; // restart the loop since new children may now be visible continue; } } // Otherwise, we've arrived! // If the node or any of its children are excluded, flip on the 'show // excluded tests' checkbox automatically. If we didn't expand, then set // target focus target to the first collapsed element. let focusTarget = element; for (let n: TestItemTreeElement | null = element; n instanceof TestItemTreeElement; n = n.parent) { if (n.test && this.testService.excluded.contains(n.test)) { this.filterState.toggleFilteringFor(TestFilterTerm.Hidden, true); break; } if (!expand && (this.tree.hasElement(n) && this.tree.isCollapsed(n))) { focusTarget = n; } } this.filterState.reveal.value = undefined; this.hasPendingReveal = false; if (focus) { this.tree.domFocus(); } if (this.tree.getRelativeTop(focusTarget) === null) { this.tree.reveal(focusTarget, 0.5); } this.revealTimeout.value = disposableTimeout(() => { this.tree.setFocus([focusTarget]); this.tree.setSelection([focusTarget]); }, 1); return; } // If here, we've expanded all parents we can. Waiting on data to come // in to possibly show the revealed test. this.hasPendingReveal = true; } /** * Collapse all items in the tree. */ public async collapseAll() { this.tree.collapseAll(); } /** * Tries to peek the first test error, if the item is in a failed state. */ private tryPeekError(item: TestItemTreeElement) { const lookup = item.test && this.testResults.getStateById(item.test.item.extId); return lookup && lookup[1].tasks.some(s => isFailedState(s.state)) ? this.peekOpener.tryPeekFirstError(lookup[0], lookup[1], { preserveFocus: true }) : false; } private onContextMenu(evt: ITreeContextMenuEvent<TestExplorerTreeElement | null>) { const element = evt.element; if (!(element instanceof TestItemTreeElement)) { return; } const { actions } = getActionableElementActions(this.contextKeyService, this.menuService, this.testService, this.crService, this.testProfileService, element); this.contextMenuService.showContextMenu({ getAnchor: () => evt.anchor, getActions: () => actions.secondary, getActionsContext: () => element, actionRunner: this.actionRunner, }); } private handleExecuteKeypress(evt: IKeyboardEvent) { const focused = this.tree.getFocus(); const selected = this.tree.getSelection(); let targeted: (TestExplorerTreeElement | null)[]; if (focused.length === 1 && selected.includes(focused[0])) { evt.browserEvent?.preventDefault(); targeted = selected; } else { targeted = focused; } const toRun = targeted .filter((e): e is TestItemTreeElement => e instanceof TestItemTreeElement); if (toRun.length) { this.testService.runTests({ group: TestRunProfileBitset.Run, tests: toRun.map(t => t.test), }); } } private reevaluateWelcomeState() { const shouldShowWelcome = this.testService.collection.busyProviders === 0 && testCollectionIsEmpty(this.testService.collection); const welcomeExperience = shouldShowWelcome ? (this.filterState.isFilteringFor(TestFilterTerm.CurrentDoc) ? WelcomeExperience.ForDocument : WelcomeExperience.ForWorkspace) : WelcomeExperience.None; if (welcomeExperience !== this.welcomeExperience) { this.welcomeExperience = welcomeExperience; this.welcomeVisibilityEmitter.fire(welcomeExperience); } } private ensureProjection() { return this.projection.value ?? this.updatePreferredProjection(); } private updatePreferredProjection() { this.projection.clear(); const lastState = this.lastViewState.get({}); if (this._viewMode.get() === TestExplorerViewMode.List) { this.projection.value = this.instantiationService.createInstance(HierarchicalByNameProjection, lastState); } else { this.projection.value = this.instantiationService.createInstance(HierarchicalByLocationProjection, lastState); } const scheduler = new RunOnceScheduler(() => this.applyProjectionChanges(), 200); this.projection.value.onUpdate(() => { if (!scheduler.isScheduled()) { scheduler.schedule(); } }); this.applyProjectionChanges(); return this.projection.value; } private applyProjectionChanges() { this.reevaluateWelcomeState(); this.projection.value?.applyTo(this.tree); this.tree.refilter(); if (this.hasPendingReveal) { this.revealById(this.filterState.reveal.value); } } /** * Gets the selected tests from the tree. */ public getSelectedTests() { return this.tree.getSelection(); } } const enum FilterResult { Exclude, Inherit, Include, } const hasNodeInOrParentOfUri = (collection: IMainThreadTestCollection, ident: IUriIdentityService, testUri: URI, fromNode?: string) => { const queue: Iterable<string>[] = [fromNode ? [fromNode] : collection.rootIds]; while (queue.length) { for (const id of queue.pop()!) { const node = collection.getNodeById(id); if (!node) { continue; } if (!node.item.uri || !ident.extUri.isEqualOrParent(testUri, node.item.uri)) { continue; } // Only show nodes that can be expanded (and might have a child with // a range) or ones that have a physical location. if (node.item.range || node.expand === TestItemExpandState.Expandable) { return true; } queue.push(node.children); } } return false; }; class TestsFilter implements ITreeFilter<TestExplorerTreeElement> { private documentUri: URI | undefined; constructor( private readonly collection: IMainThreadTestCollection, @ITestExplorerFilterState private readonly state: ITestExplorerFilterState, @ITestService private readonly testService: ITestService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, ) { } /** * @inheritdoc */ public filter(element: TestItemTreeElement): TreeFilterResult<void> { if (element instanceof TestTreeErrorMessage) { return TreeVisibility.Visible; } if ( element.test && !this.state.isFilteringFor(TestFilterTerm.Hidden) && this.testService.excluded.contains(element.test) ) { return TreeVisibility.Hidden; } switch (Math.min(this.testFilterText(element), this.testLocation(element), this.testState(element), this.testTags(element))) { case FilterResult.Exclude: return TreeVisibility.Hidden; case FilterResult.Include: return TreeVisibility.Visible; default: return TreeVisibility.Recurse; } } public filterToDocumentUri(uri: URI | undefined) { this.documentUri = uri; } private testTags(element: TestItemTreeElement): FilterResult { if (!this.state.includeTags.size && !this.state.excludeTags.size) { return FilterResult.Include; } return (this.state.includeTags.size ? element.test.item.tags.some(t => this.state.includeTags.has(t)) : true) && element.test.item.tags.every(t => !this.state.excludeTags.has(t)) ? FilterResult.Include : FilterResult.Inherit; } private testState(element: TestItemTreeElement): FilterResult { if (this.state.isFilteringFor(TestFilterTerm.Failed)) { return isFailedState(element.state) ? FilterResult.Include : FilterResult.Inherit; } if (this.state.isFilteringFor(TestFilterTerm.Executed)) { return element.state !== TestResultState.Unset ? FilterResult.Include : FilterResult.Inherit; } return FilterResult.Include; } private testLocation(element: TestItemTreeElement): FilterResult { if (!this.documentUri) { return FilterResult.Include; } if (!this.state.isFilteringFor(TestFilterTerm.CurrentDoc) || !(element instanceof TestItemTreeElement)) { return FilterResult.Include; } if (hasNodeInOrParentOfUri(this.collection, this.uriIdentityService, this.documentUri, element.test.item.extId)) { return FilterResult.Include; } return FilterResult.Inherit; } private testFilterText(element: TestItemTreeElement) { if (this.state.globList.length === 0) { return FilterResult.Include; } const fuzzy = this.state.fuzzy.value; for (let e: TestItemTreeElement | null = element; e; e = e.parent) { // start as included if the first glob is a negation let included = this.state.globList[0].include === false ? FilterResult.Include : FilterResult.Inherit; const data = e.label.toLowerCase(); for (const { include, text } of this.state.globList) { if (fuzzy ? fuzzyContains(data, text) : data.includes(text)) { included = include ? FilterResult.Include : FilterResult.Exclude; } } if (included !== FilterResult.Inherit) { return included; } } return FilterResult.Inherit; } } class TreeSorter implements ITreeSorter<TestExplorerTreeElement> { constructor( private readonly viewModel: TestingExplorerViewModel, @ITestingContinuousRunService private readonly crService: ITestingContinuousRunService, ) { } public compare(a: TestExplorerTreeElement, b: TestExplorerTreeElement): number { if (a instanceof TestTreeErrorMessage || b instanceof TestTreeErrorMessage) { return (a instanceof TestTreeErrorMessage ? -1 : 0) + (b instanceof TestTreeErrorMessage ? 1 : 0); } const crDelta = +this.crService.isSpecificallyEnabledFor(b.test.item.extId) - +this.crService.isSpecificallyEnabledFor(a.test.item.extId); if (crDelta !== 0) { return crDelta; } const durationDelta = (b.duration || 0) - (a.duration || 0); if (this.viewModel.viewSorting === TestExplorerViewSorting.ByDuration && durationDelta !== 0) { return durationDelta; } const stateDelta = cmpPriority(a.state, b.state); if (this.viewModel.viewSorting === TestExplorerViewSorting.ByStatus && stateDelta !== 0) { return stateDelta; } let inSameLocation = false; if (a instanceof TestItemTreeElement && b instanceof TestItemTreeElement && a.test.item.uri && b.test.item.uri && a.test.item.uri.toString() === b.test.item.uri.toString() && a.test.item.range && b.test.item.range) { inSameLocation = true; const delta = a.test.item.range.startLineNumber - b.test.item.range.startLineNumber; if (delta !== 0) { return delta; } } // If tests are in the same location and there's no preferred sortText, // keep the extension's insertion order (#163449). return inSameLocation && !a.sortText && !b.sortText ? 0 : (a.sortText || a.label).localeCompare(b.sortText || b.label); } } class NoTestsForDocumentWidget extends Disposable { private readonly el: HTMLElement; constructor( container: HTMLElement, @ITestExplorerFilterState filterState: ITestExplorerFilterState ) { super(); const el = this.el = dom.append(container, dom.$('.testing-no-test-placeholder')); const emptyParagraph = dom.append(el, dom.$('p')); emptyParagraph.innerText = localize('testingNoTest', 'No tests were found in this file.'); const buttonLabel = localize('testingFindExtension', 'Show Workspace Tests'); const button = this._register(new Button(el, { title: buttonLabel, ...defaultButtonStyles })); button.label = buttonLabel; this._register(button.onDidClick(() => filterState.toggleFilteringFor(TestFilterTerm.CurrentDoc, false))); } public setVisible(isVisible: boolean) { this.el.classList.toggle('visible', isVisible); } } class TestExplorerActionRunner extends ActionRunner { constructor(private getSelectedTests: () => ReadonlyArray<TestExplorerTreeElement>) { super(); } protected override async runAction(action: IAction, context: TestExplorerTreeElement): Promise<any> { if (!(action instanceof MenuItemAction)) { return super.runAction(action, context); } const selection = this.getSelectedTests(); const contextIsSelected = selection.some(s => s === context); const actualContext = contextIsSelected ? selection : [context]; const actionable = actualContext.filter((t): t is TestItemTreeElement => t instanceof TestItemTreeElement); await action.run(...actionable); } } const getLabelForTestTreeElement = (element: TestItemTreeElement) => { let label = labelForTestInState(element.description || element.label, element.state); if (element instanceof TestItemTreeElement) { if (element.duration !== undefined) { label = localize({ key: 'testing.treeElementLabelDuration', comment: ['{0} is the original label in testing.treeElementLabel, {1} is a duration'], }, '{0}, in {1}', label, formatDuration(element.duration)); } if (element.retired) { label = localize({ key: 'testing.treeElementLabelOutdated', comment: ['{0} is the original label in testing.treeElementLabel'], }, '{0}, outdated result', label); } } return label; }; class ListAccessibilityProvider implements IListAccessibilityProvider<TestExplorerTreeElement> { getWidgetAriaLabel(): string { return localize('testExplorer', "Test Explorer"); } getAriaLabel(element: TestExplorerTreeElement): string { return element instanceof TestTreeErrorMessage ? element.description : getLabelForTestTreeElement(element); } } class TreeKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<TestExplorerTreeElement> { getKeyboardNavigationLabel(element: TestExplorerTreeElement) { return element instanceof TestTreeErrorMessage ? element.message : element.label; } } class ListDelegate implements IListVirtualDelegate<TestExplorerTreeElement> { getHeight(_element: TestExplorerTreeElement) { return 22; } getTemplateId(element: TestExplorerTreeElement) { if (element instanceof TestTreeErrorMessage) { return ErrorRenderer.ID; } return TestItemRenderer.ID; } } class IdentityProvider implements IIdentityProvider<TestExplorerTreeElement> { public getId(element: TestExplorerTreeElement) { return element.treeId; } } interface IErrorTemplateData { label: HTMLElement; } class ErrorRenderer implements ITreeRenderer<TestTreeErrorMessage, FuzzyScore, IErrorTemplateData> { static readonly ID = 'error'; private readonly renderer: MarkdownRenderer; constructor(@IInstantiationService instantionService: IInstantiationService) { this.renderer = instantionService.createInstance(MarkdownRenderer, {}); } get templateId(): string { return ErrorRenderer.ID; } renderTemplate(container: HTMLElement): IErrorTemplateData { const label = dom.append(container, dom.$('.error')); return { label }; } renderElement({ element }: ITreeNode<TestTreeErrorMessage, FuzzyScore>, _: number, data: IErrorTemplateData): void { if (typeof element.message === 'string') { data.label.innerText = element.message; } else { const result = this.renderer.render(element.message, { inline: true }); data.label.appendChild(result.element); } data.label.title = element.description; } disposeTemplate(): void { // noop } } interface IActionableElementTemplateData { current?: TestItemTreeElement; label: HTMLElement; icon: HTMLElement; wrapper: HTMLElement; actionBar: ActionBar; elementDisposable: IDisposable[]; templateDisposable: IDisposable[]; } class TestItemRenderer extends Disposable implements ITreeRenderer<TestItemTreeElement, FuzzyScore, IActionableElementTemplateData> { public static readonly ID = 'testItem'; constructor( private readonly actionRunner: TestExplorerActionRunner, @IMenuService private readonly menuService: IMenuService, @ITestService protected readonly testService: ITestService, @ITestProfileService protected readonly profiles: ITestProfileService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IInstantiationService private readonly instantiationService: IInstantiationService, @ITestingContinuousRunService private readonly crService: ITestingContinuousRunService, ) { super(); } /** * @inheritdoc */ public readonly templateId = TestItemRenderer.ID; /** * @inheritdoc */ public renderTemplate(container: HTMLElement): IActionableElementTemplateData { const wrapper = dom.append(container, dom.$('.test-item')); const icon = dom.append(wrapper, dom.$('.computed-state')); const label = dom.append(wrapper, dom.$('.label')); dom.append(wrapper, dom.$(ThemeIcon.asCSSSelector(icons.testingHiddenIcon))); const actionBar = new ActionBar(wrapper, { actionRunner: this.actionRunner, actionViewItemProvider: action => action instanceof MenuItemAction ? this.instantiationService.createInstance(MenuEntryActionViewItem, action, undefined) : undefined }); const crListener = this.crService.onDidChange(changed => { if (templateData.current && (!changed || changed === templateData.current.test.item.extId)) { this.fillActionBar(templateData.current, templateData); } }); const templateData: IActionableElementTemplateData = { wrapper, label, actionBar, icon, elementDisposable: [], templateDisposable: [actionBar, crListener] }; return templateData; } /** * @inheritdoc */ disposeTemplate(templateData: IActionableElementTemplateData): void { dispose(templateData.templateDisposable); templateData.templateDisposable = []; } /** * @inheritdoc */ disposeElement(_element: ITreeNode<TestItemTreeElement, FuzzyScore>, _: number, templateData: IActionableElementTemplateData): void { dispose(templateData.elementDisposable); templateData.elementDisposable = []; } private fillActionBar(element: TestItemTreeElement, data: IActionableElementTemplateData) { const { actions, contextOverlay } = getActionableElementActions(this.contextKeyService, this.menuService, this.testService, this.crService, this.profiles, element); data.actionBar.domNode.classList.toggle('testing-is-continuous-run', !!contextOverlay.getContextKeyValue(TestingContextKeys.isContinuousModeOn.key)); data.actionBar.clear(); data.actionBar.context = element; data.actionBar.push(actions.primary, { icon: true, label: false }); } /** * @inheritdoc */ public renderElement(node: ITreeNode<TestItemTreeElement, FuzzyScore>, _depth: number, data: IActionableElementTemplateData): void { data.current = node.element; this.fillActionBar(node.element, data); const testHidden = this.testService.excluded.contains(node.element.test); data.wrapper.classList.toggle('test-is-hidden', testHidden); const icon = icons.testingStatesToIcons.get( node.element.test.expand === TestItemExpandState.BusyExpanding || node.element.test.item.busy ? TestResultState.Running : node.element.state); data.icon.className = 'computed-state ' + (icon ? ThemeIcon.asClassName(icon) : ''); if (node.element.retired) { data.icon.className += ' retired'; } data.label.title = getLabelForTestTreeElement(node.element); if (node.element.label.trim()) { dom.reset(data.label, ...renderLabelWithIcons(node.element.label)); } else { data.label.textContent = String.fromCharCode(0xA0); // &nbsp; } let description = node.element.description; if (node.element.duration !== undefined) { description = description ? `${description}: ${formatDuration(node.element.duration)}` : formatDuration(node.element.duration); } if (description) { dom.append(data.label, dom.$('span.test-label-description', {}, description)); } } } const formatDuration = (ms: number) => { if (ms < 10) { return `${ms.toFixed(1)}ms`; } if (ms < 1_000) { return `${ms.toFixed(0)}ms`; } return `${(ms / 1000).toFixed(1)}s`; }; const getActionableElementActions = ( contextKeyService: IContextKeyService, menuService: IMenuService, testService: ITestService, crService: ITestingContinuousRunService, profiles: ITestProfileService, element: TestItemTreeElement, ) => { const test = element instanceof TestItemTreeElement ? element.test : undefined; const contextKeys: [string, unknown][] = getTestItemContextOverlay(test, test ? profiles.capabilitiesForTest(test) : 0); contextKeys.push(['view', Testing.ExplorerViewId]); if (test) { const ctrl = testService.getTestController(test.controllerId); const supportsCr = !!ctrl && profiles.getControllerProfiles(ctrl.id).some(p => p.supportsContinuousRun); contextKeys.push([ TestingContextKeys.canRefreshTests.key, !!ctrl?.canRefresh.value && TestId.isRoot(test.item.extId), ], [ TestingContextKeys.testItemIsHidden.key, testService.excluded.contains(test) ], [ TestingContextKeys.isContinuousModeOn.key, supportsCr && crService.isSpecificallyEnabledFor(test.item.extId) ], [ TestingContextKeys.isParentRunningContinuously.key, supportsCr && crService.isEnabledForAParentOf(test.item.extId) ], [ TestingContextKeys.supportsContinuousRun.key, supportsCr, ]); } const contextOverlay = contextKeyService.createOverlay(contextKeys); const menu = menuService.createMenu(MenuId.TestItem, contextOverlay); try { const primary: IAction[] = []; const secondary: IAction[] = []; const result = { primary, secondary }; createAndFillInActionBarActions(menu, { shouldForwardArgs: true, }, result, 'inline'); return { actions: result, contextOverlay }; } finally { menu.dispose(); } }; registerThemingParticipant((theme, collector) => { if (theme.type === 'dark') { const foregroundColor = theme.getColor(foreground); if (foregroundColor) { const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, 0.65)); collector.addRule(`.test-explorer .test-explorer-messages { color: ${fgWithOpacity}; }`); } } });
src/vs/workbench/contrib/testing/browser/testingExplorerView.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017635896801948547, 0.00017208287317771465, 0.00016411814431194216, 0.0001725393085507676, 0.000002728763320192229 ]
{ "id": 7, "code_window": [ "\t\t\tsnippet.appendText(`<video src=\"${mdPath}\" controls title=\"`);\n", "\t\t\tsnippet.appendPlaceholder('Title');\n", "\t\t\tsnippet.appendText('\"></video>');\n", "\t\t} else {\n", "\t\t\tsnippet.appendText(insertAsImage ? '![' : '[');\n", "\n", "\t\t\tconst placeholderText = options?.placeholderText ?? (insertAsImage ? 'Alt text' : 'label');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (insertAsImage) {\n", "\t\t\t\tinsertedImageCount++;\n", "\t\t\t} else {\n", "\t\t\t\tinsertedLinkCount++;\n", "\t\t\t}\n", "\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 119 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import * as vscode from 'vscode'; import * as URI from 'vscode-uri'; import { Schemes } from '../../util/schemes'; export const imageFileExtensions = new Set<string>([ 'bmp', 'gif', 'ico', 'jpe', 'jpeg', 'jpg', 'png', 'psd', 'svg', 'tga', 'tif', 'tiff', 'webp', ]); const videoFileExtensions = new Set<string>([ 'ogg', 'mp4' ]); export function registerDropIntoEditorSupport(selector: vscode.DocumentSelector) { return vscode.languages.registerDocumentDropEditProvider(selector, new class implements vscode.DocumentDropEditProvider { async provideDocumentDropEdits(document: vscode.TextDocument, _position: vscode.Position, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken): Promise<vscode.DocumentDropEdit | undefined> { const enabled = vscode.workspace.getConfiguration('markdown', document).get('editor.drop.enabled', true); if (!enabled) { return undefined; } const snippet = await tryGetUriListSnippet(document, dataTransfer, token); if (!snippet) { return undefined; } const edit = new vscode.DocumentDropEdit(snippet.snippet); edit.label = snippet.label; return edit; } }, { id: 'insertLink', dropMimeTypes: [ 'text/uri-list' ] }); } export async function tryGetUriListSnippet(document: vscode.TextDocument, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken): Promise<{ snippet: vscode.SnippetString; label: string } | undefined> { const urlList = await dataTransfer.get('text/uri-list')?.asString(); if (!urlList || token.isCancellationRequested) { return undefined; } const uris: vscode.Uri[] = []; for (const resource of urlList.split(/\r?\n/g)) { try { uris.push(vscode.Uri.parse(resource)); } catch { // noop } } const snippet = createUriListSnippet(document, uris); if (!snippet) { return undefined; } return { snippet: snippet, label: uris.length > 1 ? vscode.l10n.t('Insert uri links') : vscode.l10n.t('Insert uri link') }; } interface UriListSnippetOptions { readonly placeholderText?: string; readonly placeholderStartIndex?: number; /** * Should the snippet be for an image? * * If `undefined`, tries to infer this from the uri. */ readonly insertAsImage?: boolean; readonly separator?: string; } export function createUriListSnippet(document: vscode.TextDocument, uris: readonly vscode.Uri[], options?: UriListSnippetOptions): vscode.SnippetString | undefined { if (!uris.length) { return undefined; } const dir = getDocumentDir(document); const snippet = new vscode.SnippetString(); uris.forEach((uri, i) => { const mdPath = getMdPath(dir, uri); const ext = URI.Utils.extname(uri).toLowerCase().replace('.', ''); const insertAsImage = typeof options?.insertAsImage === 'undefined' ? imageFileExtensions.has(ext) : !!options.insertAsImage; const insertAsVideo = videoFileExtensions.has(ext); if (insertAsVideo) { snippet.appendText(`<video src="${mdPath}" controls title="`); snippet.appendPlaceholder('Title'); snippet.appendText('"></video>'); } else { snippet.appendText(insertAsImage ? '![' : '['); const placeholderText = options?.placeholderText ?? (insertAsImage ? 'Alt text' : 'label'); const placeholderIndex = typeof options?.placeholderStartIndex !== 'undefined' ? options?.placeholderStartIndex + i : undefined; snippet.appendPlaceholder(placeholderText, placeholderIndex); snippet.appendText(`](${mdPath})`); } if (i < uris.length - 1 && uris.length > 1) { snippet.appendText(options?.separator ?? ' '); } }); return snippet; } function getMdPath(dir: vscode.Uri | undefined, file: vscode.Uri) { if (dir && dir.scheme === file.scheme && dir.authority === file.authority) { if (file.scheme === Schemes.file) { // On windows, we must use the native `path.relative` to generate the relative path // so that drive-letters are resolved cast insensitively. However we then want to // convert back to a posix path to insert in to the document. const relativePath = path.relative(dir.fsPath, file.fsPath); return encodeURI(path.posix.normalize(relativePath.split(path.sep).join(path.posix.sep))); } return encodeURI(path.posix.relative(dir.path, file.path)); } return file.toString(false); } function getDocumentDir(document: vscode.TextDocument): vscode.Uri | undefined { const docUri = getParentDocumentUri(document); if (docUri.scheme === Schemes.untitled) { return vscode.workspace.workspaceFolders?.[0]?.uri; } return URI.Utils.dirname(docUri); } export function getParentDocumentUri(document: vscode.TextDocument): vscode.Uri { if (document.uri.scheme === Schemes.notebookCell) { for (const notebook of vscode.workspace.notebookDocuments) { for (const cell of notebook.getCells()) { if (cell.document === document) { return notebook.uri; } } } } return document.uri; }
extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts
1
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.9968372583389282, 0.11188855767250061, 0.00016473651339765638, 0.0001772392279235646, 0.31257835030555725 ]
{ "id": 7, "code_window": [ "\t\t\tsnippet.appendText(`<video src=\"${mdPath}\" controls title=\"`);\n", "\t\t\tsnippet.appendPlaceholder('Title');\n", "\t\t\tsnippet.appendText('\"></video>');\n", "\t\t} else {\n", "\t\t\tsnippet.appendText(insertAsImage ? '![' : '[');\n", "\n", "\t\t\tconst placeholderText = options?.placeholderText ?? (insertAsImage ? 'Alt text' : 'label');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (insertAsImage) {\n", "\t\t\t\tinsertedImageCount++;\n", "\t\t\t} else {\n", "\t\t\t\tinsertedLinkCount++;\n", "\t\t\t}\n", "\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 119 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as vscode from 'vscode'; import { assertNoRpc, createRandomFile, disposeAll, withLogDisabled } from '../utils'; suite('vscode API - workspace events', () => { const disposables: vscode.Disposable[] = []; teardown(() => { assertNoRpc(); disposeAll(disposables); disposables.length = 0; }); test('onWillCreate/onDidCreate', withLogDisabled(async function () { const base = await createRandomFile(); const newUri = base.with({ path: base.path + '-foo' }); let onWillCreate: vscode.FileWillCreateEvent | undefined; let onDidCreate: vscode.FileCreateEvent | undefined; disposables.push(vscode.workspace.onWillCreateFiles(e => onWillCreate = e)); disposables.push(vscode.workspace.onDidCreateFiles(e => onDidCreate = e)); const edit = new vscode.WorkspaceEdit(); edit.createFile(newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.ok(onWillCreate); assert.strictEqual(onWillCreate?.files.length, 1); assert.strictEqual(onWillCreate?.files[0].toString(), newUri.toString()); assert.ok(onDidCreate); assert.strictEqual(onDidCreate?.files.length, 1); assert.strictEqual(onDidCreate?.files[0].toString(), newUri.toString()); })); test('onWillCreate/onDidCreate, make changes, edit another file', withLogDisabled(async function () { const base = await createRandomFile(); const baseDoc = await vscode.workspace.openTextDocument(base); const newUri = base.with({ path: base.path + '-foo' }); disposables.push(vscode.workspace.onWillCreateFiles(e => { const ws = new vscode.WorkspaceEdit(); ws.insert(base, new vscode.Position(0, 0), 'HALLO_NEW'); e.waitUntil(Promise.resolve(ws)); })); const edit = new vscode.WorkspaceEdit(); edit.createFile(newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.strictEqual(baseDoc.getText(), 'HALLO_NEW'); })); test('onWillCreate/onDidCreate, make changes, edit new file fails', withLogDisabled(async function () { const base = await createRandomFile(); const newUri = base.with({ path: base.path + '-foo' }); disposables.push(vscode.workspace.onWillCreateFiles(e => { const ws = new vscode.WorkspaceEdit(); ws.insert(e.files[0], new vscode.Position(0, 0), 'nope'); e.waitUntil(Promise.resolve(ws)); })); const edit = new vscode.WorkspaceEdit(); edit.createFile(newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.strictEqual((await vscode.workspace.fs.readFile(newUri)).toString(), ''); assert.strictEqual((await vscode.workspace.openTextDocument(newUri)).getText(), ''); })); test('onWillDelete/onDidDelete', withLogDisabled(async function () { const base = await createRandomFile(); let onWilldelete: vscode.FileWillDeleteEvent | undefined; let onDiddelete: vscode.FileDeleteEvent | undefined; disposables.push(vscode.workspace.onWillDeleteFiles(e => onWilldelete = e)); disposables.push(vscode.workspace.onDidDeleteFiles(e => onDiddelete = e)); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.ok(onWilldelete); assert.strictEqual(onWilldelete?.files.length, 1); assert.strictEqual(onWilldelete?.files[0].toString(), base.toString()); assert.ok(onDiddelete); assert.strictEqual(onDiddelete?.files.length, 1); assert.strictEqual(onDiddelete?.files[0].toString(), base.toString()); })); test('onWillDelete/onDidDelete, make changes', withLogDisabled(async function () { const base = await createRandomFile(); const newUri = base.with({ path: base.path + '-NEW' }); disposables.push(vscode.workspace.onWillDeleteFiles(e => { const edit = new vscode.WorkspaceEdit(); edit.createFile(newUri); edit.insert(newUri, new vscode.Position(0, 0), 'hahah'); e.waitUntil(Promise.resolve(edit)); })); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); })); test('onWillDelete/onDidDelete, make changes, del another file', withLogDisabled(async function () { const base = await createRandomFile(); const base2 = await createRandomFile(); disposables.push(vscode.workspace.onWillDeleteFiles(e => { if (e.files[0].toString() === base.toString()) { const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base2); e.waitUntil(Promise.resolve(edit)); } })); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); })); test('onWillDelete/onDidDelete, make changes, double delete', withLogDisabled(async function () { const base = await createRandomFile(); let cnt = 0; disposables.push(vscode.workspace.onWillDeleteFiles(e => { if (++cnt === 0) { const edit = new vscode.WorkspaceEdit(); edit.deleteFile(e.files[0]); e.waitUntil(Promise.resolve(edit)); } })); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); })); test('onWillRename/onDidRename', withLogDisabled(async function () { const oldUri = await createRandomFile(); const newUri = oldUri.with({ path: oldUri.path + '-NEW' }); let onWillRename: vscode.FileWillRenameEvent | undefined; let onDidRename: vscode.FileRenameEvent | undefined; disposables.push(vscode.workspace.onWillRenameFiles(e => onWillRename = e)); disposables.push(vscode.workspace.onDidRenameFiles(e => onDidRename = e)); const edit = new vscode.WorkspaceEdit(); edit.renameFile(oldUri, newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.ok(onWillRename); assert.strictEqual(onWillRename?.files.length, 1); assert.strictEqual(onWillRename?.files[0].oldUri.toString(), oldUri.toString()); assert.strictEqual(onWillRename?.files[0].newUri.toString(), newUri.toString()); assert.ok(onDidRename); assert.strictEqual(onDidRename?.files.length, 1); assert.strictEqual(onDidRename?.files[0].oldUri.toString(), oldUri.toString()); assert.strictEqual(onDidRename?.files[0].newUri.toString(), newUri.toString()); })); test('onWillRename - make changes (saved file)', withLogDisabled(function () { return testOnWillRename(false); })); test('onWillRename - make changes (dirty file)', withLogDisabled(function () { return testOnWillRename(true); })); async function testOnWillRename(withDirtyFile: boolean): Promise<void> { const oldUri = await createRandomFile('BAR'); if (withDirtyFile) { const edit = new vscode.WorkspaceEdit(); edit.insert(oldUri, new vscode.Position(0, 0), 'BAR'); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); const oldDocument = await vscode.workspace.openTextDocument(oldUri); assert.ok(oldDocument.isDirty); } const newUri = oldUri.with({ path: oldUri.path + '-NEW' }); const anotherFile = await createRandomFile('BAR'); let onWillRename: vscode.FileWillRenameEvent | undefined; disposables.push(vscode.workspace.onWillRenameFiles(e => { onWillRename = e; const edit = new vscode.WorkspaceEdit(); edit.insert(e.files[0].oldUri, new vscode.Position(0, 0), 'FOO'); edit.replace(anotherFile, new vscode.Range(0, 0, 0, 3), 'FARBOO'); e.waitUntil(Promise.resolve(edit)); })); const edit = new vscode.WorkspaceEdit(); edit.renameFile(oldUri, newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.ok(onWillRename); assert.strictEqual(onWillRename?.files.length, 1); assert.strictEqual(onWillRename?.files[0].oldUri.toString(), oldUri.toString()); assert.strictEqual(onWillRename?.files[0].newUri.toString(), newUri.toString()); const newDocument = await vscode.workspace.openTextDocument(newUri); const anotherDocument = await vscode.workspace.openTextDocument(anotherFile); assert.strictEqual(newDocument.getText(), withDirtyFile ? 'FOOBARBAR' : 'FOOBAR'); assert.strictEqual(anotherDocument.getText(), 'FARBOO'); assert.ok(newDocument.isDirty); assert.ok(anotherDocument.isDirty); } });
extensions/vscode-api-tests/src/singlefolder-tests/workspace.event.test.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.0001780925813363865, 0.00017587468028068542, 0.00017242369358427823, 0.00017622245650272816, 0.0000015379497426692978 ]
{ "id": 7, "code_window": [ "\t\t\tsnippet.appendText(`<video src=\"${mdPath}\" controls title=\"`);\n", "\t\t\tsnippet.appendPlaceholder('Title');\n", "\t\t\tsnippet.appendText('\"></video>');\n", "\t\t} else {\n", "\t\t\tsnippet.appendText(insertAsImage ? '![' : '[');\n", "\n", "\t\t\tconst placeholderText = options?.placeholderText ?? (insertAsImage ? 'Alt text' : 'label');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (insertAsImage) {\n", "\t\t\t\tinsertedImageCount++;\n", "\t\t\t} else {\n", "\t\t\t\tinsertedLinkCount++;\n", "\t\t\t}\n", "\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 119 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as strings from 'vs/base/common/strings'; suite('Strings', () => { test('equalsIgnoreCase', () => { assert(strings.equalsIgnoreCase('', '')); assert(!strings.equalsIgnoreCase('', '1')); assert(!strings.equalsIgnoreCase('1', '')); assert(strings.equalsIgnoreCase('a', 'a')); assert(strings.equalsIgnoreCase('abc', 'Abc')); assert(strings.equalsIgnoreCase('abc', 'ABC')); assert(strings.equalsIgnoreCase('Höhenmeter', 'HÖhenmeter')); assert(strings.equalsIgnoreCase('ÖL', 'Öl')); }); test('beginsWithIgnoreCase', () => { assert(strings.startsWithIgnoreCase('', '')); assert(!strings.startsWithIgnoreCase('', '1')); assert(strings.startsWithIgnoreCase('1', '')); assert(strings.startsWithIgnoreCase('a', 'a')); assert(strings.startsWithIgnoreCase('abc', 'Abc')); assert(strings.startsWithIgnoreCase('abc', 'ABC')); assert(strings.startsWithIgnoreCase('Höhenmeter', 'HÖhenmeter')); assert(strings.startsWithIgnoreCase('ÖL', 'Öl')); assert(strings.startsWithIgnoreCase('alles klar', 'a')); assert(strings.startsWithIgnoreCase('alles klar', 'A')); assert(strings.startsWithIgnoreCase('alles klar', 'alles k')); assert(strings.startsWithIgnoreCase('alles klar', 'alles K')); assert(strings.startsWithIgnoreCase('alles klar', 'ALLES K')); assert(strings.startsWithIgnoreCase('alles klar', 'alles klar')); assert(strings.startsWithIgnoreCase('alles klar', 'ALLES KLAR')); assert(!strings.startsWithIgnoreCase('alles klar', ' ALLES K')); assert(!strings.startsWithIgnoreCase('alles klar', 'ALLES K ')); assert(!strings.startsWithIgnoreCase('alles klar', 'öALLES K ')); assert(!strings.startsWithIgnoreCase('alles klar', ' ')); assert(!strings.startsWithIgnoreCase('alles klar', 'ö')); }); test('compareIgnoreCase', () => { function assertCompareIgnoreCase(a: string, b: string, recurse = true): void { let actual = strings.compareIgnoreCase(a, b); actual = actual > 0 ? 1 : actual < 0 ? -1 : actual; let expected = strings.compare(a.toLowerCase(), b.toLowerCase()); expected = expected > 0 ? 1 : expected < 0 ? -1 : expected; assert.strictEqual(actual, expected, `${a} <> ${b}`); if (recurse) { assertCompareIgnoreCase(b, a, false); } } assertCompareIgnoreCase('', ''); assertCompareIgnoreCase('abc', 'ABC'); assertCompareIgnoreCase('abc', 'ABc'); assertCompareIgnoreCase('abc', 'ABcd'); assertCompareIgnoreCase('abc', 'abcd'); assertCompareIgnoreCase('foo', 'föo'); assertCompareIgnoreCase('Code', 'code'); assertCompareIgnoreCase('Code', 'cöde'); assertCompareIgnoreCase('B', 'a'); assertCompareIgnoreCase('a', 'B'); assertCompareIgnoreCase('b', 'a'); assertCompareIgnoreCase('a', 'b'); assertCompareIgnoreCase('aa', 'ab'); assertCompareIgnoreCase('aa', 'aB'); assertCompareIgnoreCase('aa', 'aA'); assertCompareIgnoreCase('a', 'aa'); assertCompareIgnoreCase('ab', 'aA'); assertCompareIgnoreCase('O', '/'); }); test('compareIgnoreCase (substring)', () => { function assertCompareIgnoreCase(a: string, b: string, aStart: number, aEnd: number, bStart: number, bEnd: number, recurse = true): void { let actual = strings.compareSubstringIgnoreCase(a, b, aStart, aEnd, bStart, bEnd); actual = actual > 0 ? 1 : actual < 0 ? -1 : actual; let expected = strings.compare(a.toLowerCase().substring(aStart, aEnd), b.toLowerCase().substring(bStart, bEnd)); expected = expected > 0 ? 1 : expected < 0 ? -1 : expected; assert.strictEqual(actual, expected, `${a} <> ${b}`); if (recurse) { assertCompareIgnoreCase(b, a, bStart, bEnd, aStart, aEnd, false); } } assertCompareIgnoreCase('', '', 0, 0, 0, 0); assertCompareIgnoreCase('abc', 'ABC', 0, 1, 0, 1); assertCompareIgnoreCase('abc', 'Aabc', 0, 3, 1, 4); assertCompareIgnoreCase('abcABc', 'ABcd', 3, 6, 0, 4); }); test('format', () => { assert.strictEqual(strings.format('Foo Bar'), 'Foo Bar'); assert.strictEqual(strings.format('Foo {0} Bar'), 'Foo {0} Bar'); assert.strictEqual(strings.format('Foo {0} Bar', 'yes'), 'Foo yes Bar'); assert.strictEqual(strings.format('Foo {0} Bar {0}', 'yes'), 'Foo yes Bar yes'); assert.strictEqual(strings.format('Foo {0} Bar {1}{2}', 'yes'), 'Foo yes Bar {1}{2}'); assert.strictEqual(strings.format('Foo {0} Bar {1}{2}', 'yes', undefined), 'Foo yes Bar undefined{2}'); assert.strictEqual(strings.format('Foo {0} Bar {1}{2}', 'yes', 5, false), 'Foo yes Bar 5false'); assert.strictEqual(strings.format('Foo {0} Bar. {1}', '(foo)', '.test'), 'Foo (foo) Bar. .test'); }); test('format2', () => { assert.strictEqual(strings.format2('Foo Bar', {}), 'Foo Bar'); assert.strictEqual(strings.format2('Foo {oops} Bar', {}), 'Foo {oops} Bar'); assert.strictEqual(strings.format2('Foo {foo} Bar', { foo: 'bar' }), 'Foo bar Bar'); assert.strictEqual(strings.format2('Foo {foo} Bar {foo}', { foo: 'bar' }), 'Foo bar Bar bar'); assert.strictEqual(strings.format2('Foo {foo} Bar {bar}{boo}', { foo: 'bar' }), 'Foo bar Bar {bar}{boo}'); assert.strictEqual(strings.format2('Foo {foo} Bar {bar}{boo}', { foo: 'bar', bar: 'undefined' }), 'Foo bar Bar undefined{boo}'); assert.strictEqual(strings.format2('Foo {foo} Bar {bar}{boo}', { foo: 'bar', bar: '5', boo: false }), 'Foo bar Bar 5false'); assert.strictEqual(strings.format2('Foo {foo} Bar. {bar}', { foo: '(foo)', bar: '.test' }), 'Foo (foo) Bar. .test'); }); test('lcut', () => { assert.strictEqual(strings.lcut('foo bar', 0), ''); assert.strictEqual(strings.lcut('foo bar', 1), 'bar'); assert.strictEqual(strings.lcut('foo bar', 3), 'bar'); assert.strictEqual(strings.lcut('foo bar', 4), 'bar'); // Leading whitespace trimmed assert.strictEqual(strings.lcut('foo bar', 5), 'foo bar'); assert.strictEqual(strings.lcut('test string 0.1.2.3', 3), '2.3'); assert.strictEqual(strings.lcut('', 10), ''); assert.strictEqual(strings.lcut('a', 10), 'a'); }); test('escape', () => { assert.strictEqual(strings.escape(''), ''); assert.strictEqual(strings.escape('foo'), 'foo'); assert.strictEqual(strings.escape('foo bar'), 'foo bar'); assert.strictEqual(strings.escape('<foo bar>'), '&lt;foo bar&gt;'); assert.strictEqual(strings.escape('<foo>Hello</foo>'), '&lt;foo&gt;Hello&lt;/foo&gt;'); }); test('ltrim', () => { assert.strictEqual(strings.ltrim('foo', 'f'), 'oo'); assert.strictEqual(strings.ltrim('foo', 'o'), 'foo'); assert.strictEqual(strings.ltrim('http://www.test.de', 'http://'), 'www.test.de'); assert.strictEqual(strings.ltrim('/foo/', '/'), 'foo/'); assert.strictEqual(strings.ltrim('//foo/', '/'), 'foo/'); assert.strictEqual(strings.ltrim('/', ''), '/'); assert.strictEqual(strings.ltrim('/', '/'), ''); assert.strictEqual(strings.ltrim('///', '/'), ''); assert.strictEqual(strings.ltrim('', ''), ''); assert.strictEqual(strings.ltrim('', '/'), ''); }); test('rtrim', () => { assert.strictEqual(strings.rtrim('foo', 'o'), 'f'); assert.strictEqual(strings.rtrim('foo', 'f'), 'foo'); assert.strictEqual(strings.rtrim('http://www.test.de', '.de'), 'http://www.test'); assert.strictEqual(strings.rtrim('/foo/', '/'), '/foo'); assert.strictEqual(strings.rtrim('/foo//', '/'), '/foo'); assert.strictEqual(strings.rtrim('/', ''), '/'); assert.strictEqual(strings.rtrim('/', '/'), ''); assert.strictEqual(strings.rtrim('///', '/'), ''); assert.strictEqual(strings.rtrim('', ''), ''); assert.strictEqual(strings.rtrim('', '/'), ''); }); test('trim', () => { assert.strictEqual(strings.trim(' foo '), 'foo'); assert.strictEqual(strings.trim(' foo'), 'foo'); assert.strictEqual(strings.trim('bar '), 'bar'); assert.strictEqual(strings.trim(' '), ''); assert.strictEqual(strings.trim('foo bar', 'bar'), 'foo '); }); test('trimWhitespace', () => { assert.strictEqual(' foo '.trim(), 'foo'); assert.strictEqual(' foo '.trim(), 'foo'); assert.strictEqual(' foo'.trim(), 'foo'); assert.strictEqual('bar '.trim(), 'bar'); assert.strictEqual(' '.trim(), ''); assert.strictEqual(' '.trim(), ''); }); test('lastNonWhitespaceIndex', () => { assert.strictEqual(strings.lastNonWhitespaceIndex('abc \t \t '), 2); assert.strictEqual(strings.lastNonWhitespaceIndex('abc'), 2); assert.strictEqual(strings.lastNonWhitespaceIndex('abc\t'), 2); assert.strictEqual(strings.lastNonWhitespaceIndex('abc '), 2); assert.strictEqual(strings.lastNonWhitespaceIndex('abc \t \t '), 2); assert.strictEqual(strings.lastNonWhitespaceIndex('abc \t \t abc \t \t '), 11); assert.strictEqual(strings.lastNonWhitespaceIndex('abc \t \t abc \t \t ', 8), 2); assert.strictEqual(strings.lastNonWhitespaceIndex(' \t \t '), -1); }); test('containsRTL', () => { assert.strictEqual(strings.containsRTL('a'), false); assert.strictEqual(strings.containsRTL(''), false); assert.strictEqual(strings.containsRTL(strings.UTF8_BOM_CHARACTER + 'a'), false); assert.strictEqual(strings.containsRTL('hello world!'), false); assert.strictEqual(strings.containsRTL('a📚📚b'), false); assert.strictEqual(strings.containsRTL('هناك حقيقة مثبتة منذ زمن طويل'), true); assert.strictEqual(strings.containsRTL('זוהי עובדה מבוססת שדעתו'), true); }); test('issue #115221: isEmojiImprecise misses ⭐', () => { const codePoint = strings.getNextCodePoint('⭐', '⭐'.length, 0); assert.strictEqual(strings.isEmojiImprecise(codePoint), true); }); test('isBasicASCII', () => { function assertIsBasicASCII(str: string, expected: boolean): void { assert.strictEqual(strings.isBasicASCII(str), expected, str + ` (${str.charCodeAt(0)})`); } assertIsBasicASCII('abcdefghijklmnopqrstuvwxyz', true); assertIsBasicASCII('ABCDEFGHIJKLMNOPQRSTUVWXYZ', true); assertIsBasicASCII('1234567890', true); assertIsBasicASCII('`~!@#$%^&*()-_=+[{]}\\|;:\'",<.>/?', true); assertIsBasicASCII(' ', true); assertIsBasicASCII('\t', true); assertIsBasicASCII('\n', true); assertIsBasicASCII('\r', true); let ALL = '\r\t\n'; for (let i = 32; i < 127; i++) { ALL += String.fromCharCode(i); } assertIsBasicASCII(ALL, true); assertIsBasicASCII(String.fromCharCode(31), false); assertIsBasicASCII(String.fromCharCode(127), false); assertIsBasicASCII('ü', false); assertIsBasicASCII('a📚📚b', false); }); test('createRegExp', () => { // Empty assert.throws(() => strings.createRegExp('', false)); // Escapes appropriately assert.strictEqual(strings.createRegExp('abc', false).source, 'abc'); assert.strictEqual(strings.createRegExp('([^ ,.]*)', false).source, '\\(\\[\\^ ,\\.\\]\\*\\)'); assert.strictEqual(strings.createRegExp('([^ ,.]*)', true).source, '([^ ,.]*)'); // Whole word assert.strictEqual(strings.createRegExp('abc', false, { wholeWord: true }).source, '\\babc\\b'); assert.strictEqual(strings.createRegExp('abc', true, { wholeWord: true }).source, '\\babc\\b'); assert.strictEqual(strings.createRegExp(' abc', true, { wholeWord: true }).source, ' abc\\b'); assert.strictEqual(strings.createRegExp('abc ', true, { wholeWord: true }).source, '\\babc '); assert.strictEqual(strings.createRegExp(' abc ', true, { wholeWord: true }).source, ' abc '); const regExpWithoutFlags = strings.createRegExp('abc', true); assert(!regExpWithoutFlags.global); assert(regExpWithoutFlags.ignoreCase); assert(!regExpWithoutFlags.multiline); const regExpWithFlags = strings.createRegExp('abc', true, { global: true, matchCase: true, multiline: true }); assert(regExpWithFlags.global); assert(!regExpWithFlags.ignoreCase); assert(regExpWithFlags.multiline); }); test('regExpContainsBackreference', () => { assert(strings.regExpContainsBackreference('foo \\5 bar')); assert(strings.regExpContainsBackreference('\\2')); assert(strings.regExpContainsBackreference('(\\d)(\\n)(\\1)')); assert(strings.regExpContainsBackreference('(A).*?\\1')); assert(strings.regExpContainsBackreference('\\\\\\1')); assert(strings.regExpContainsBackreference('foo \\\\\\1')); assert(!strings.regExpContainsBackreference('')); assert(!strings.regExpContainsBackreference('\\\\1')); assert(!strings.regExpContainsBackreference('foo \\\\1')); assert(!strings.regExpContainsBackreference('(A).*?\\\\1')); assert(!strings.regExpContainsBackreference('foo \\d1 bar')); assert(!strings.regExpContainsBackreference('123')); }); test('getLeadingWhitespace', () => { assert.strictEqual(strings.getLeadingWhitespace(' foo'), ' '); assert.strictEqual(strings.getLeadingWhitespace(' foo', 2), ''); assert.strictEqual(strings.getLeadingWhitespace(' foo', 1, 1), ''); assert.strictEqual(strings.getLeadingWhitespace(' foo', 0, 1), ' '); assert.strictEqual(strings.getLeadingWhitespace(' '), ' '); assert.strictEqual(strings.getLeadingWhitespace(' ', 1), ' '); assert.strictEqual(strings.getLeadingWhitespace(' ', 0, 1), ' '); assert.strictEqual(strings.getLeadingWhitespace('\t\tfunction foo(){', 0, 1), '\t'); assert.strictEqual(strings.getLeadingWhitespace('\t\tfunction foo(){', 0, 2), '\t\t'); }); test('fuzzyContains', () => { assert.ok(!strings.fuzzyContains((undefined)!, null!)); assert.ok(strings.fuzzyContains('hello world', 'h')); assert.ok(!strings.fuzzyContains('hello world', 'q')); assert.ok(strings.fuzzyContains('hello world', 'hw')); assert.ok(strings.fuzzyContains('hello world', 'horl')); assert.ok(strings.fuzzyContains('hello world', 'd')); assert.ok(!strings.fuzzyContains('hello world', 'wh')); assert.ok(!strings.fuzzyContains('d', 'dd')); }); test('startsWithUTF8BOM', () => { assert(strings.startsWithUTF8BOM(strings.UTF8_BOM_CHARACTER)); assert(strings.startsWithUTF8BOM(strings.UTF8_BOM_CHARACTER + 'a')); assert(strings.startsWithUTF8BOM(strings.UTF8_BOM_CHARACTER + 'aaaaaaaaaa')); assert(!strings.startsWithUTF8BOM(' ' + strings.UTF8_BOM_CHARACTER)); assert(!strings.startsWithUTF8BOM('foo')); assert(!strings.startsWithUTF8BOM('')); }); test('stripUTF8BOM', () => { assert.strictEqual(strings.stripUTF8BOM(strings.UTF8_BOM_CHARACTER), ''); assert.strictEqual(strings.stripUTF8BOM(strings.UTF8_BOM_CHARACTER + 'foobar'), 'foobar'); assert.strictEqual(strings.stripUTF8BOM('foobar' + strings.UTF8_BOM_CHARACTER), 'foobar' + strings.UTF8_BOM_CHARACTER); assert.strictEqual(strings.stripUTF8BOM('abc'), 'abc'); assert.strictEqual(strings.stripUTF8BOM(''), ''); }); test('containsUppercaseCharacter', () => { [ [null, false], ['', false], ['foo', false], ['föö', false], ['ناك', false], ['מבוססת', false], ['😀', false], ['(#@()*&%()@*#&09827340982374}{:">?></\'\\~`', false], ['Foo', true], ['FOO', true], ['FöÖ', true], ['FöÖ', true], ['\\Foo', true], ].forEach(([str, result]) => { assert.strictEqual(strings.containsUppercaseCharacter(<string>str), result, `Wrong result for ${str}`); }); }); test('containsUppercaseCharacter (ignoreEscapedChars)', () => { [ ['\\Woo', false], ['f\\S\\S', false], ['foo', false], ['Foo', true], ].forEach(([str, result]) => { assert.strictEqual(strings.containsUppercaseCharacter(<string>str, true), result, `Wrong result for ${str}`); }); }); test('uppercaseFirstLetter', () => { [ ['', ''], ['foo', 'Foo'], ['f', 'F'], ['123', '123'], ['.a', '.a'], ].forEach(([inStr, result]) => { assert.strictEqual(strings.uppercaseFirstLetter(inStr), result, `Wrong result for ${inStr}`); }); }); test('getNLines', () => { assert.strictEqual(strings.getNLines('', 5), ''); assert.strictEqual(strings.getNLines('foo', 5), 'foo'); assert.strictEqual(strings.getNLines('foo\nbar', 5), 'foo\nbar'); assert.strictEqual(strings.getNLines('foo\nbar', 2), 'foo\nbar'); assert.strictEqual(strings.getNLines('foo\nbar', 1), 'foo'); assert.strictEqual(strings.getNLines('foo\nbar'), 'foo'); assert.strictEqual(strings.getNLines('foo\nbar\nsomething', 2), 'foo\nbar'); assert.strictEqual(strings.getNLines('foo', 0), ''); }); test('getGraphemeBreakType', () => { assert.strictEqual(strings.getGraphemeBreakType(0xBC1), strings.GraphemeBreakType.SpacingMark); }); test('truncate', () => { assert.strictEqual('hello world', strings.truncate('hello world', 100)); assert.strictEqual('hello…', strings.truncate('hello world', 5)); }); test('replaceAsync', async () => { let i = 0; assert.strictEqual(await strings.replaceAsync('abcabcabcabc', /b(.)/g, async (match, after) => { assert.strictEqual(match, 'bc'); assert.strictEqual(after, 'c'); return `${i++}${after}`; }), 'a0ca1ca2ca3c'); }); test('removeAnsiEscapeCodes', () => { const CSI = '\x1b\['; const sequences = [ // Base cases from https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_ `${CSI}42@`, `${CSI}42 @`, `${CSI}42A`, `${CSI}42 A`, `${CSI}42B`, `${CSI}42C`, `${CSI}42D`, `${CSI}42E`, `${CSI}42F`, `${CSI}42G`, `${CSI}42;42H`, `${CSI}42I`, `${CSI}42J`, `${CSI}?42J`, `${CSI}42K`, `${CSI}?42K`, `${CSI}42L`, `${CSI}42M`, `${CSI}42P`, `${CSI}#P`, `${CSI}3#P`, `${CSI}#Q`, `${CSI}3#Q`, `${CSI}#R`, `${CSI}42S`, `${CSI}?1;2;3S`, `${CSI}42T`, `${CSI}42;42;42;42;42T`, `${CSI}>3T`, `${CSI}42X`, `${CSI}42Z`, `${CSI}42^`, `${CSI}42\``, `${CSI}42a`, `${CSI}42b`, `${CSI}42c`, `${CSI}=42c`, `${CSI}>42c`, `${CSI}42d`, `${CSI}42e`, `${CSI}42;42f`, `${CSI}42g`, `${CSI}3h`, `${CSI}?3h`, `${CSI}42i`, `${CSI}?42i`, `${CSI}3l`, `${CSI}?3l`, `${CSI}3m`, `${CSI}>0;0m`, `${CSI}>0m`, `${CSI}?0m`, `${CSI}42n`, `${CSI}>42n`, `${CSI}?42n`, `${CSI}>42p`, `${CSI}!p`, `${CSI}0;0"p`, `${CSI}42$p`, `${CSI}?42$p`, `${CSI}#p`, `${CSI}3#p`, `${CSI}>42q`, `${CSI}42q`, `${CSI}42 q`, `${CSI}42"q`, `${CSI}#q`, `${CSI}42;42r`, `${CSI}?3r`, `${CSI}0;0;0;0;3$r`, `${CSI}s`, `${CSI}0;0s`, `${CSI}>42s`, `${CSI}?3s`, `${CSI}42;42;42t`, `${CSI}>3t`, `${CSI}42 t`, `${CSI}0;0;0;0;3$t`, `${CSI}u`, `${CSI}42 u`, `${CSI}0;0;0;0;0;0;0;0$v`, `${CSI}42$w`, `${CSI}0;0;0;0'w`, `${CSI}42x`, `${CSI}42*x`, `${CSI}0;0;0;0;0$x`, `${CSI}42#y`, `${CSI}0;0;0;0;0;0*y`, `${CSI}42;0'z`, `${CSI}0;1;2;4$z`, `${CSI}3'{`, `${CSI}#{`, `${CSI}3#{`, `${CSI}0;0;0;0\${`, `${CSI}0;0;0;0#|`, `${CSI}42$|`, `${CSI}42'|`, `${CSI}42*|`, `${CSI}#}`, `${CSI}42'}`, `${CSI}42$}`, `${CSI}42'~`, `${CSI}42$~`, // Common SGR cases: `${CSI}1;31m`, // multiple attrs `${CSI}105m`, // bright background `${CSI}48:5:128m`, // 256 indexed color `${CSI}48;5;128m`, // 256 indexed color alt `${CSI}38:2:0:255:255:255m`, // truecolor `${CSI}38;2;255;255;255m`, // truecolor alt ]; for (const sequence of sequences) { assert.strictEqual(strings.removeAnsiEscapeCodes(`hello${sequence}world`), 'helloworld', `expect to remove ${JSON.stringify(sequence)}`); } }); });
src/vs/base/test/common/strings.test.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017857190687209368, 0.00017406749248038977, 0.00016985814727377146, 0.00017395052418578416, 0.000001615968130863621 ]
{ "id": 7, "code_window": [ "\t\t\tsnippet.appendText(`<video src=\"${mdPath}\" controls title=\"`);\n", "\t\t\tsnippet.appendPlaceholder('Title');\n", "\t\t\tsnippet.appendText('\"></video>');\n", "\t\t} else {\n", "\t\t\tsnippet.appendText(insertAsImage ? '![' : '[');\n", "\n", "\t\t\tconst placeholderText = options?.placeholderText ?? (insertAsImage ? 'Alt text' : 'label');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (insertAsImage) {\n", "\t\t\t\tinsertedImageCount++;\n", "\t\t\t} else {\n", "\t\t\t\tinsertedLinkCount++;\n", "\t\t\t}\n", "\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "add", "edit_start_line_idx": 119 }
<!DOCTYPE html> <html lang="en"> <!--- Preview the icons in the Seti icon font. Use a simple-server or the LiveServer extension to view --> <head> <meta charset="UTF-8"> <title>seti font preview</title> <style> body { font-family: sans-serif; margin: 0; padding: 10px 20px; } .preview { line-height: 2em; } .preview_icon { display: inline-block; width: 32px; text-align: center; } .icon { display: inline-block; font-size: 16px; line-height: 1; } .icon:before { font-family: seti !important; font-style: normal; font-weight: normal !important; vertical-align: top; } .grid { display: grid; grid-template-columns: 0.7fr 0.7fr 1fr 0.7fr 0.7fr 1fr; } .vs { background-color: #FFFFFF; color: #000000; } .vs-dark { background-color: #1E1E1E; color: #D4D4D4; } </style> <script> function fetchThemeFile() { return fetch('./vs-seti-icon-theme.json').then(res => res.json()); } function generateColumn(label, style, associations, htmContent) { htmContent.push('<div class=' + style + '>' + label); const keys = Object.keys(associations).sort(); for (let association of keys) { const id = associations[association]; htmContent.push('<div class="preview"><span class="preview_icon"><span class="icon icon' + id + '"></span></span><span>' + association + '</span></div>'); } htmContent.push('</div>'); } function generateIconsForScheme(label, set, style, htmContent) { generateColumn('language IDs', style, set.languageIds, htmContent); generateColumn('file extensions', style, set.fileExtensions, htmContent); generateColumn('file names', style, set.fileNames, htmContent); } function generateContent(themeFile) { let htmContent = []; let cssContent = []; const version = themeFile.version.substr(themeFile.version.lastIndexOf('/') + 1); cssContent.push('@font-face {font-family: "seti"; src: url("./seti.woff?' + version + '") format("woff"); }'); let iconDefinitions = themeFile.iconDefinitions; for (let id in iconDefinitions) { let def = iconDefinitions[id]; cssContent.push('.icon' + id + ':before { content: "' + def.fontCharacter + '"; color: ' + def.fontColor + '}'); } let style = document.createElement('style'); style.type = 'text/css'; style.media = 'screen'; style.innerHTML = cssContent.join('\n'); document.head.appendChild(style); htmContent.push('<div class="grid">'); generateIconsForScheme('dark', themeFile, 'vs-dark', htmContent); generateIconsForScheme('light', themeFile.light, 'vs', htmContent); htmContent.push('</div>'); document.body.innerHTML += htmContent.join('\n'); } window.addEventListener("load", function () { fetchThemeFile().then(generateContent); }); </script> </head> <body> </body> </html>
extensions/theme-seti/icons/preview.html
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017642691091168672, 0.0001735526748234406, 0.00016811120440252125, 0.0001738178834784776, 0.0000022138794975035125 ]
{ "id": 8, "code_window": [ "\t\tif (i < uris.length - 1 && uris.length > 1) {\n", "\t\t\tsnippet.appendText(options?.separator ?? ' ');\n", "\t\t}\n", "\t});\n", "\treturn snippet;\n", "}\n", "\n", "function getMdPath(dir: vscode.Uri | undefined, file: vscode.Uri) {\n", "\tif (dir && dir.scheme === file.scheme && dir.authority === file.authority) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tlet label: string;\n", "\tif (insertedImageCount > 0 && insertedLinkCount > 0) {\n", "\t\tlabel = vscode.l10n.t('Insert Markdown images and links');\n", "\t} else if (insertedImageCount > 0) {\n", "\t\tlabel = insertedImageCount > 1\n", "\t\t\t? vscode.l10n.t('Insert Markdown images')\n", "\t\t\t: vscode.l10n.t('Insert Markdown image');\n", "\t} else {\n", "\t\tlabel = insertedLinkCount > 1\n", "\t\t\t? vscode.l10n.t('Insert Markdown links')\n", "\t\t\t: vscode.l10n.t('Insert Markdown link');\n", "\t}\n", "\n", "\treturn { snippet, label };\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 132 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { Utils } from 'vscode-uri'; import { Command } from '../commandManager'; import { createUriListSnippet, getParentDocumentUri, imageFileExtensions } from '../languageFeatures/copyFiles/dropIntoEditor'; import { coalesce } from '../util/arrays'; import { Schemes } from '../util/schemes'; export class InsertLinkFromWorkspace implements Command { public readonly id = 'markdown.editor.insertLinkFromWorkspace'; public async execute(resources?: vscode.Uri[]) { const activeEditor = vscode.window.activeTextEditor; if (!activeEditor) { return; } resources ??= await vscode.window.showOpenDialog({ canSelectFiles: true, canSelectFolders: false, canSelectMany: true, openLabel: vscode.l10n.t("Insert link"), title: vscode.l10n.t("Insert link"), defaultUri: getDefaultUri(activeEditor.document), }); return insertLink(activeEditor, resources ?? [], false); } } export class InsertImageFromWorkspace implements Command { public readonly id = 'markdown.editor.insertImageFromWorkspace'; public async execute(resources?: vscode.Uri[]) { const activeEditor = vscode.window.activeTextEditor; if (!activeEditor) { return; } resources ??= await vscode.window.showOpenDialog({ canSelectFiles: true, canSelectFolders: false, canSelectMany: true, filters: { [vscode.l10n.t("Images")]: Array.from(imageFileExtensions) }, openLabel: vscode.l10n.t("Insert image"), title: vscode.l10n.t("Insert image"), defaultUri: getDefaultUri(activeEditor.document), }); return insertLink(activeEditor, resources ?? [], true); } } function getDefaultUri(document: vscode.TextDocument) { const docUri = getParentDocumentUri(document); if (docUri.scheme === Schemes.untitled) { return vscode.workspace.workspaceFolders?.[0]?.uri; } return Utils.dirname(docUri); } async function insertLink(activeEditor: vscode.TextEditor, selectedFiles: vscode.Uri[], insertAsImage: boolean): Promise<void> { if (!selectedFiles.length) { return; } const edit = createInsertLinkEdit(activeEditor, selectedFiles, insertAsImage); await vscode.workspace.applyEdit(edit); } function createInsertLinkEdit(activeEditor: vscode.TextEditor, selectedFiles: vscode.Uri[], insertAsImage: boolean) { const snippetEdits = coalesce(activeEditor.selections.map((selection, i): vscode.SnippetTextEdit | undefined => { const selectionText = activeEditor.document.getText(selection); const snippet = createUriListSnippet(activeEditor.document, selectedFiles, { insertAsImage: insertAsImage, placeholderText: selectionText, placeholderStartIndex: (i + 1) * selectedFiles.length, separator: insertAsImage ? '\n' : ' ', }); return snippet ? new vscode.SnippetTextEdit(selection, snippet) : undefined; })); const edit = new vscode.WorkspaceEdit(); edit.set(activeEditor.document.uri, snippetEdits); return edit; }
extensions/markdown-language-features/src/commands/insertResource.ts
1
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.010932764038443565, 0.0015767598524689674, 0.00016476085875183344, 0.0002484015130903572, 0.003169020637869835 ]
{ "id": 8, "code_window": [ "\t\tif (i < uris.length - 1 && uris.length > 1) {\n", "\t\t\tsnippet.appendText(options?.separator ?? ' ');\n", "\t\t}\n", "\t});\n", "\treturn snippet;\n", "}\n", "\n", "function getMdPath(dir: vscode.Uri | undefined, file: vscode.Uri) {\n", "\tif (dir && dir.scheme === file.scheme && dir.authority === file.authority) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tlet label: string;\n", "\tif (insertedImageCount > 0 && insertedLinkCount > 0) {\n", "\t\tlabel = vscode.l10n.t('Insert Markdown images and links');\n", "\t} else if (insertedImageCount > 0) {\n", "\t\tlabel = insertedImageCount > 1\n", "\t\t\t? vscode.l10n.t('Insert Markdown images')\n", "\t\t\t: vscode.l10n.t('Insert Markdown image');\n", "\t} else {\n", "\t\tlabel = insertedLinkCount > 1\n", "\t\t\t? vscode.l10n.t('Insert Markdown links')\n", "\t\t\t: vscode.l10n.t('Insert Markdown link');\n", "\t}\n", "\n", "\treturn { snippet, label };\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 132 }
parameters: - name: channel type: string default: 1.65.0 - name: targets default: [] type: object # Todo: use 1ES pipeline once extension is installed in ADO steps: - powershell: | . build/azure-pipelines/win32/exec.ps1 Invoke-WebRequest -Uri "https://win.rustup.rs" -Outfile $(Build.ArtifactStagingDirectory)/rustup-init.exe exec { $(Build.ArtifactStagingDirectory)/rustup-init.exe -y --profile minimal --default-toolchain $env:RUSTUP_TOOLCHAIN --default-host x86_64-pc-windows-msvc } echo "##vso[task.prependpath]$env:USERPROFILE\.cargo\bin" env: RUSTUP_TOOLCHAIN: ${{ parameters.channel }} displayName: "Install Rust" - powershell: | . build/azure-pipelines/win32/exec.ps1 exec { rustup default $RUSTUP_TOOLCHAIN } exec { rustup update $RUSTUP_TOOLCHAIN } env: RUSTUP_TOOLCHAIN: ${{ parameters.channel }} displayName: "Set Rust version" - ${{ each target in parameters.targets }}: - script: rustup target add ${{ target }} displayName: "Adding Rust target '${{ target }}'" - powershell: | . build/azure-pipelines/win32/exec.ps1 exec { rustc --version } exec { cargo --version } exec { rustup --version } displayName: "Check Rust versions"
build/azure-pipelines/cli/install-rust-win32.yml
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017622161249164492, 0.00017279309395235032, 0.00016711647913325578, 0.0001739171420922503, 0.000003607974122132873 ]
{ "id": 8, "code_window": [ "\t\tif (i < uris.length - 1 && uris.length > 1) {\n", "\t\t\tsnippet.appendText(options?.separator ?? ' ');\n", "\t\t}\n", "\t});\n", "\treturn snippet;\n", "}\n", "\n", "function getMdPath(dir: vscode.Uri | undefined, file: vscode.Uri) {\n", "\tif (dir && dir.scheme === file.scheme && dir.authority === file.authority) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tlet label: string;\n", "\tif (insertedImageCount > 0 && insertedLinkCount > 0) {\n", "\t\tlabel = vscode.l10n.t('Insert Markdown images and links');\n", "\t} else if (insertedImageCount > 0) {\n", "\t\tlabel = insertedImageCount > 1\n", "\t\t\t? vscode.l10n.t('Insert Markdown images')\n", "\t\t\t: vscode.l10n.t('Insert Markdown image');\n", "\t} else {\n", "\t\tlabel = insertedLinkCount > 1\n", "\t\t\t? vscode.l10n.t('Insert Markdown links')\n", "\t\t\t: vscode.l10n.t('Insert Markdown link');\n", "\t}\n", "\n", "\treturn { snippet, label };\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 132 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { URI } from 'vs/base/common/uri'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { IModelService } from 'vs/editor/common/services/model'; import { ModelService } from 'vs/editor/common/services/modelService'; import { TestLanguageConfigurationService } from 'vs/editor/test/common/modes/testLanguageConfigurationService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { FileService } from 'vs/platform/files/common/fileService'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { ILabelService } from 'vs/platform/label/common/label'; import { ILogService, NullLogService } from 'vs/platform/log/common/log'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { TestWorkspace } from 'vs/platform/workspace/test/common/testWorkspace'; import { FileMatch, FolderMatch, Match, searchComparer, searchMatchComparer, SearchModel, SearchResult } from 'vs/workbench/contrib/search/browser/searchModel'; import { MockLabelService } from 'vs/workbench/services/label/test/common/mockLabelService'; import { IFileMatch, ITextSearchMatch, OneLineRange, QueryType, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { TestContextService } from 'vs/workbench/test/common/workbenchTestServices'; import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { TestEditorGroupsService } from 'vs/workbench/test/browser/workbenchTestServices'; import { NotebookEditorWidgetService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorServiceImpl'; import { createFileUriFromPathFromRoot, getRootName } from 'vs/workbench/contrib/search/test/browser/searchTestCommon'; suite('Search - Viewlet', () => { let instantiation: TestInstantiationService; setup(() => { instantiation = new TestInstantiationService(); instantiation.stub(ILanguageConfigurationService, TestLanguageConfigurationService); instantiation.stub(IModelService, stubModelService(instantiation)); instantiation.stub(INotebookEditorService, stubNotebookEditorService(instantiation)); instantiation.set(IWorkspaceContextService, new TestContextService(TestWorkspace)); instantiation.stub(IUriIdentityService, new UriIdentityService(new FileService(new NullLogService()))); instantiation.stub(ILabelService, new MockLabelService()); instantiation.stub(ILogService, new NullLogService()); }); test('Data Source', function () { const result: SearchResult = aSearchResult(); result.query = { type: QueryType.Text, contentPattern: { pattern: 'foo' }, folderQueries: [{ folder: createFileUriFromPathFromRoot() }] }; result.add([{ resource: createFileUriFromPathFromRoot('/foo'), results: [{ preview: { text: 'bar', matches: { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 1 } }, ranges: { startLineNumber: 1, startColumn: 0, endLineNumber: 1, endColumn: 1 } }] }]); const fileMatch = result.matches()[0]; const lineMatch = fileMatch.matches()[0]; assert.strictEqual(fileMatch.id(), URI.file(`${getRootName()}/foo`).toString()); assert.strictEqual(lineMatch.id(), `${URI.file(`${getRootName()}/foo`).toString()}>[2,1 -> 2,2]b`); }); test('Comparer', () => { const fileMatch1 = aFileMatch('/foo'); const fileMatch2 = aFileMatch('/with/path'); const fileMatch3 = aFileMatch('/with/path/foo'); const lineMatch1 = new Match(fileMatch1, ['bar'], new OneLineRange(0, 1, 1), new OneLineRange(0, 1, 1)); const lineMatch2 = new Match(fileMatch1, ['bar'], new OneLineRange(0, 1, 1), new OneLineRange(2, 1, 1)); const lineMatch3 = new Match(fileMatch1, ['bar'], new OneLineRange(0, 1, 1), new OneLineRange(2, 1, 1)); assert(searchMatchComparer(fileMatch1, fileMatch2) < 0); assert(searchMatchComparer(fileMatch2, fileMatch1) > 0); assert(searchMatchComparer(fileMatch1, fileMatch1) === 0); assert(searchMatchComparer(fileMatch2, fileMatch3) < 0); assert(searchMatchComparer(lineMatch1, lineMatch2) < 0); assert(searchMatchComparer(lineMatch2, lineMatch1) > 0); assert(searchMatchComparer(lineMatch2, lineMatch3) === 0); }); test('Advanced Comparer', () => { const fileMatch1 = aFileMatch('/with/path/foo10'); const fileMatch2 = aFileMatch('/with/path2/foo1'); const fileMatch3 = aFileMatch('/with/path/bar.a'); const fileMatch4 = aFileMatch('/with/path/bar.b'); // By default, path < path2 assert(searchMatchComparer(fileMatch1, fileMatch2) < 0); // By filenames, foo10 > foo1 assert(searchMatchComparer(fileMatch1, fileMatch2, SearchSortOrder.FileNames) > 0); // By type, bar.a < bar.b assert(searchMatchComparer(fileMatch3, fileMatch4, SearchSortOrder.Type) < 0); }); test('Cross-type Comparer', () => { const searchResult = aSearchResult(); const folderMatch1 = aFolderMatch('/voo', 0, searchResult); const folderMatch2 = aFolderMatch('/with', 1, searchResult); const fileMatch1 = aFileMatch('/voo/foo.a', folderMatch1); const fileMatch2 = aFileMatch('/with/path.c', folderMatch2); const fileMatch3 = aFileMatch('/with/path/bar.b', folderMatch2); const lineMatch1 = new Match(fileMatch1, ['bar'], new OneLineRange(0, 1, 1), new OneLineRange(0, 1, 1)); const lineMatch2 = new Match(fileMatch1, ['bar'], new OneLineRange(0, 1, 1), new OneLineRange(2, 1, 1)); const lineMatch3 = new Match(fileMatch2, ['barfoo'], new OneLineRange(0, 1, 1), new OneLineRange(0, 1, 1)); const lineMatch4 = new Match(fileMatch2, ['fooooo'], new OneLineRange(0, 1, 1), new OneLineRange(2, 1, 1)); const lineMatch5 = new Match(fileMatch3, ['foobar'], new OneLineRange(0, 1, 1), new OneLineRange(2, 1, 1)); /*** * Structure would take the following form: * * folderMatch1 (voo) * > fileMatch1 (/foo.a) * >> lineMatch1 * >> lineMatch2 * folderMatch2 (with) * > fileMatch2 (/path.c) * >> lineMatch4 * >> lineMatch5 * > fileMatch3 (/path/bar.b) * >> lineMatch3 * */ // for these, refer to diagram above assert(searchComparer(fileMatch1, fileMatch3) < 0); assert(searchComparer(fileMatch2, fileMatch3) < 0); assert(searchComparer(folderMatch2, fileMatch2) < 0); assert(searchComparer(lineMatch4, lineMatch5) < 0); assert(searchComparer(lineMatch1, lineMatch3) < 0); assert(searchComparer(lineMatch2, folderMatch2) < 0); // travel up hierarchy and order of folders take precedence. "voo < with" in indices assert(searchComparer(fileMatch1, fileMatch3, SearchSortOrder.FileNames) < 0); // bar.b < path.c assert(searchComparer(fileMatch3, fileMatch2, SearchSortOrder.FileNames) < 0); // lineMatch4's parent is fileMatch2, "bar.b < path.c" assert(searchComparer(fileMatch3, lineMatch4, SearchSortOrder.FileNames) < 0); // bar.b < path.c assert(searchComparer(fileMatch3, fileMatch2, SearchSortOrder.Type) < 0); // lineMatch4's parent is fileMatch2, "bar.b < path.c" assert(searchComparer(fileMatch3, lineMatch4, SearchSortOrder.Type) < 0); }); function aFileMatch(path: string, parentFolder?: FolderMatch, ...lineMatches: ITextSearchMatch[]): FileMatch { const rawMatch: IFileMatch = { resource: URI.file('/' + path), results: lineMatches }; return instantiation.createInstance(FileMatch, { pattern: '' }, undefined, undefined, parentFolder ?? aFolderMatch('', 0), rawMatch, null); } function aFolderMatch(path: string, index: number, parent?: SearchResult): FolderMatch { const searchModel = instantiation.createInstance(SearchModel); return instantiation.createInstance(FolderMatch, createFileUriFromPathFromRoot(path), path, index, { type: QueryType.Text, folderQueries: [{ folder: createFileUriFromPathFromRoot() }], contentPattern: { pattern: '' } }, parent ?? aSearchResult().folderMatches()[0], searchModel, null); } function aSearchResult(): SearchResult { const searchModel = instantiation.createInstance(SearchModel); searchModel.searchResult.query = { type: QueryType.Text, folderQueries: [{ folder: createFileUriFromPathFromRoot() }], contentPattern: { pattern: '' } }; return searchModel.searchResult; } function stubModelService(instantiationService: TestInstantiationService): IModelService { instantiationService.stub(IThemeService, new TestThemeService()); const config = new TestConfigurationService(); config.setUserConfiguration('search', { searchOnType: true, experimental: { notebookSearch: false } }); instantiationService.stub(IConfigurationService, config); return instantiationService.createInstance(ModelService); } function stubNotebookEditorService(instantiationService: TestInstantiationService): INotebookEditorService { instantiationService.stub(IEditorGroupsService, new TestEditorGroupsService()); return instantiationService.createInstance(NotebookEditorWidgetService); } });
src/vs/workbench/contrib/search/test/browser/searchViewlet.test.ts
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.00017579703126102686, 0.00017060371465049684, 0.00016551115550100803, 0.00017076096264645457, 0.000002865172518795589 ]
{ "id": 8, "code_window": [ "\t\tif (i < uris.length - 1 && uris.length > 1) {\n", "\t\t\tsnippet.appendText(options?.separator ?? ' ');\n", "\t\t}\n", "\t});\n", "\treturn snippet;\n", "}\n", "\n", "function getMdPath(dir: vscode.Uri | undefined, file: vscode.Uri) {\n", "\tif (dir && dir.scheme === file.scheme && dir.authority === file.authority) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tlet label: string;\n", "\tif (insertedImageCount > 0 && insertedLinkCount > 0) {\n", "\t\tlabel = vscode.l10n.t('Insert Markdown images and links');\n", "\t} else if (insertedImageCount > 0) {\n", "\t\tlabel = insertedImageCount > 1\n", "\t\t\t? vscode.l10n.t('Insert Markdown images')\n", "\t\t\t: vscode.l10n.t('Insert Markdown image');\n", "\t} else {\n", "\t\tlabel = insertedLinkCount > 1\n", "\t\t\t? vscode.l10n.t('Insert Markdown links')\n", "\t\t\t: vscode.l10n.t('Insert Markdown link');\n", "\t}\n", "\n", "\treturn { snippet, label };\n" ], "file_path": "extensions/markdown-language-features/src/languageFeatures/copyFiles/dropIntoEditor.ts", "type": "replace", "edit_start_line_idx": 132 }
for(var i=0;i<9;i++){for(var j;j<i;j++){if(j+i<3)return i<j;}}
extensions/vscode-colorize-tests/test/colorize-fixtures/test6916.js
0
https://github.com/microsoft/vscode/commit/f6de066b4c454569e9d91b8a6937a75b62712c73
[ 0.0018281647935509682, 0.0018281647935509682, 0.0018281647935509682, 0.0018281647935509682, 0 ]
{ "id": 0, "code_window": [ " def fetch_result_sets(cls, db, datasource_type, force=False):\n", " return BaseEngineSpec.fetch_result_sets(\n", " db, datasource_type, force=force)\n", "\n", " @classmethod\n", " def progress(cls, logs):\n", " # 17/02/07 19:36:38 INFO ql.Driver: Total jobs = 5\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @classmethod\n", " def adjust_database_uri(cls, uri, selected_schema=None):\n", " if selected_schema:\n", " uri.database = selected_schema\n", " return uri\n", "\n" ], "file_path": "superset/db_engine_specs.py", "type": "add", "edit_start_line_idx": 652 }
import unittest from sqlalchemy.engine.url import make_url from superset.models.core import Database class DatabaseModelTestCase(unittest.TestCase): def test_database_schema_presto(self): sqlalchemy_uri = 'presto://presto.airbnb.io:8080/hive/default' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive/default', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) sqlalchemy_uri = 'presto://presto.airbnb.io:8080/hive' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) def test_database_schema_postgres(self): sqlalchemy_uri = 'postgresql+psycopg2://postgres.airbnb.io:5439/prod' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('prod', db) db = make_url(model.get_sqla_engine(schema='foo').url).database self.assertEquals('prod', db) def test_database_schema_hive(self): sqlalchemy_uri = 'hive://[email protected]:10000/hive/default' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive/default', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) def test_database_schema_mysql(self): sqlalchemy_uri = 'mysql://root@localhost/superset' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('superset', db) db = make_url(model.get_sqla_engine(schema='staging').url).database self.assertEquals('staging', db)
tests/model_tests.py
1
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.0008412231109105051, 0.00036593328695744276, 0.0001724796020425856, 0.00027936234255321324, 0.0002315971942152828 ]
{ "id": 0, "code_window": [ " def fetch_result_sets(cls, db, datasource_type, force=False):\n", " return BaseEngineSpec.fetch_result_sets(\n", " db, datasource_type, force=force)\n", "\n", " @classmethod\n", " def progress(cls, logs):\n", " # 17/02/07 19:36:38 INFO ql.Driver: Total jobs = 5\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @classmethod\n", " def adjust_database_uri(cls, uri, selected_schema=None):\n", " if selected_schema:\n", " uri.database = selected_schema\n", " return uri\n", "\n" ], "file_path": "superset/db_engine_specs.py", "type": "add", "edit_start_line_idx": 652 }
import React from 'react'; import Gravatar from 'react-gravatar'; import moment from 'moment'; import { Panel } from 'react-bootstrap'; const propTypes = { user: React.PropTypes.object.isRequired, }; const UserInfo = ({ user }) => ( <div> <a href="https://en.gravatar.com/"> <Gravatar email={user.email} width="100%" height="" alt="Profile picture provided by Gravatar" className="img-rounded" style={{ borderRadius: 15 }} /> </a> <hr /> <Panel> <h3> <strong>{user.firstName} {user.lastName}</strong> </h3> <h4 className="username"> <i className="fa fa-user-o" /> {user.username} </h4> <hr /> <p> <i className="fa fa-clock-o" /> joined {moment(user.createdOn, 'YYYYMMDD').fromNow()} </p> <p className="email"> <i className="fa fa-envelope-o" /> {user.email} </p> <p className="roles"> <i className="fa fa-lock" /> {Object.keys(user.roles).join(', ')} </p> <p> <i className="fa fa-key" />&nbsp; <span className="text-muted">id:</span>&nbsp; <span className="user-id">{user.userId}</span> </p> </Panel> </div> ); UserInfo.propTypes = propTypes; export default UserInfo;
superset/assets/javascripts/profile/components/UserInfo.jsx
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00017741360352374613, 0.0001766890927683562, 0.00017608137568458915, 0.00017668819054961205, 4.508607105435658e-7 ]
{ "id": 0, "code_window": [ " def fetch_result_sets(cls, db, datasource_type, force=False):\n", " return BaseEngineSpec.fetch_result_sets(\n", " db, datasource_type, force=force)\n", "\n", " @classmethod\n", " def progress(cls, logs):\n", " # 17/02/07 19:36:38 INFO ql.Driver: Total jobs = 5\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @classmethod\n", " def adjust_database_uri(cls, uri, selected_schema=None):\n", " if selected_schema:\n", " uri.database = selected_schema\n", " return uri\n", "\n" ], "file_path": "superset/db_engine_specs.py", "type": "add", "edit_start_line_idx": 652 }
import React, { PropTypes } from 'react'; import cx from 'classnames'; import URLShortLinkButton from './URLShortLinkButton'; import EmbedCodeButton from './EmbedCodeButton'; import DisplayQueryButton from './DisplayQueryButton'; const propTypes = { canDownload: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]).isRequired, slice: PropTypes.object, queryEndpoint: PropTypes.string, queryResponse: PropTypes.object, chartStatus: PropTypes.string, }; export default function ExploreActionButtons({ chartStatus, canDownload, slice, queryResponse, queryEndpoint }) { const exportToCSVClasses = cx('btn btn-default btn-sm', { 'disabled disabledButton': !canDownload, }); if (slice) { return ( <div className="btn-group results" role="group"> <URLShortLinkButton slice={slice} /> <EmbedCodeButton slice={slice} /> <a href={slice.data.json_endpoint} className="btn btn-default btn-sm" title="Export to .json" target="_blank" rel="noopener noreferrer" > <i className="fa fa-file-code-o" /> .json </a> <a href={slice.data.csv_endpoint} className={exportToCSVClasses} title="Export to .csv format" target="_blank" rel="noopener noreferrer" > <i className="fa fa-file-text-o" /> .csv </a> <DisplayQueryButton queryResponse={queryResponse} queryEndpoint={queryEndpoint} chartStatus={chartStatus} /> </div> ); } return ( <DisplayQueryButton queryEndpoint={queryEndpoint} /> ); } ExploreActionButtons.propTypes = propTypes;
superset/assets/javascripts/explorev2/components/ExploreActionButtons.jsx
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00017576952814124525, 0.00017251798999495804, 0.000164328288519755, 0.00017380347708240151, 0.000003882174041791586 ]
{ "id": 0, "code_window": [ " def fetch_result_sets(cls, db, datasource_type, force=False):\n", " return BaseEngineSpec.fetch_result_sets(\n", " db, datasource_type, force=force)\n", "\n", " @classmethod\n", " def progress(cls, logs):\n", " # 17/02/07 19:36:38 INFO ql.Driver: Total jobs = 5\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @classmethod\n", " def adjust_database_uri(cls, uri, selected_schema=None):\n", " if selected_schema:\n", " uri.database = selected_schema\n", " return uri\n", "\n" ], "file_path": "superset/db_engine_specs.py", "type": "add", "edit_start_line_idx": 652 }
{% extends "superset/basic.html" %} {% block tail_js %} {{ super() }} <script src="/static/assets/dist/index.entry.js"></script> {% endblock %}
superset/templates/superset/index.html
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00016964077076409012, 0.00016964077076409012, 0.00016964077076409012, 0.00016964077076409012, 0 ]
{ "id": 1, "code_window": [ " db = make_url(model.get_sqla_engine(schema='foo').url).database\n", " self.assertEquals('prod', db)\n", "\n", " def test_database_schema_hive(self):\n", " sqlalchemy_uri = 'hive://[email protected]:10000/hive/default'\n", " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n", " db = make_url(model.get_sqla_engine().url).database\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " sqlalchemy_uri = 'hive://[email protected]:10000/default?auth=NOSASL'\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 39 }
import unittest from sqlalchemy.engine.url import make_url from superset.models.core import Database class DatabaseModelTestCase(unittest.TestCase): def test_database_schema_presto(self): sqlalchemy_uri = 'presto://presto.airbnb.io:8080/hive/default' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive/default', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) sqlalchemy_uri = 'presto://presto.airbnb.io:8080/hive' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) def test_database_schema_postgres(self): sqlalchemy_uri = 'postgresql+psycopg2://postgres.airbnb.io:5439/prod' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('prod', db) db = make_url(model.get_sqla_engine(schema='foo').url).database self.assertEquals('prod', db) def test_database_schema_hive(self): sqlalchemy_uri = 'hive://[email protected]:10000/hive/default' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive/default', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) def test_database_schema_mysql(self): sqlalchemy_uri = 'mysql://root@localhost/superset' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('superset', db) db = make_url(model.get_sqla_engine(schema='staging').url).database self.assertEquals('staging', db)
tests/model_tests.py
1
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.9981082677841187, 0.48911237716674805, 0.0012544856872409582, 0.4834910035133362, 0.3403617739677429 ]
{ "id": 1, "code_window": [ " db = make_url(model.get_sqla_engine(schema='foo').url).database\n", " self.assertEquals('prod', db)\n", "\n", " def test_database_schema_hive(self):\n", " sqlalchemy_uri = 'hive://[email protected]:10000/hive/default'\n", " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n", " db = make_url(model.get_sqla_engine().url).database\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " sqlalchemy_uri = 'hive://[email protected]:10000/default?auth=NOSASL'\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 39 }
import React from 'react'; import { expect } from 'chai'; import { describe, it, beforeEach } from 'mocha'; import { shallow } from 'enzyme'; import { Panel } from 'react-bootstrap'; import { getFormDataFromControls, defaultControls } from '../../../../javascripts/explorev2/stores/store'; import { ControlPanelsContainer, } from '../../../../javascripts/explorev2/components/ControlPanelsContainer'; const defaultProps = { datasource_type: 'table', actions: {}, controls: defaultControls, form_data: getFormDataFromControls(defaultControls), isDatasourceMetaLoading: false, exploreState: {}, }; describe('ControlPanelsContainer', () => { let wrapper; beforeEach(() => { wrapper = shallow(<ControlPanelsContainer {...defaultProps} />); }); it('renders a Panel', () => { expect(wrapper.find(Panel)).to.have.lengthOf(1); }); });
superset/assets/spec/javascripts/explorev2/components/ControlPanelsContainer_spec.jsx
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.0001752910320647061, 0.00016997063357848674, 0.00016666152805555612, 0.0001689649943728, 0.0000033406920465495205 ]
{ "id": 1, "code_window": [ " db = make_url(model.get_sqla_engine(schema='foo').url).database\n", " self.assertEquals('prod', db)\n", "\n", " def test_database_schema_hive(self):\n", " sqlalchemy_uri = 'hive://[email protected]:10000/hive/default'\n", " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n", " db = make_url(model.get_sqla_engine().url).database\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " sqlalchemy_uri = 'hive://[email protected]:10000/default?auth=NOSASL'\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 39 }
Videos ====== Here is a collection of short videos showing different aspect of Superset. Quick Intro ''''''''''' This video demonstrates how Superset works at a high level, it shows how to navigate through datasets and dashboards that are already available. .. youtube:: https://www.youtube.com/watch?v=3Txm_nj_R7M Dashboard Creation '''''''''''''''''' This video walk you through the creation of a simple dashboard as a collection of data slices. - Coming soon! Dashboard Filtering ''''''''''''''''''' This video shows how to create dynamic filters on dashboards, how to immunize certain widgets from being affected by filters. - Coming soon! Customize CSS and dashboard themes '''''''''''''''''''''''''''''''''' A quick walkthrough on how to apply existing CSS templates, alter them and create new ones. - Coming soon! Slice Annotations ''''''''''''''''' A short video on how to annotate your charts, the markdown language and to toggle them on dashboards. - Coming soon! Adding a Table '''''''''''''' This videos shows you how to expose a new table in Superset, and how to define the semantics on how this can be accessed by others in the ``Explore`` and ``Dashboard`` views. - Coming soon! Define SQL Expressions '''''''''''''''''''''' A walkthrough on how to create your own derived dimensions and metrics. - Coming soon!
docs/videos.rst
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00017334071162622422, 0.00016879710892681032, 0.00016212261107284576, 0.00016967987176030874, 0.00000394319613405969 ]
{ "id": 1, "code_window": [ " db = make_url(model.get_sqla_engine(schema='foo').url).database\n", " self.assertEquals('prod', db)\n", "\n", " def test_database_schema_hive(self):\n", " sqlalchemy_uri = 'hive://[email protected]:10000/hive/default'\n", " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n", " db = make_url(model.get_sqla_engine().url).database\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " sqlalchemy_uri = 'hive://[email protected]:10000/default?auth=NOSASL'\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 39 }
[ignore: superset/assets/node_modules/**] [python: superset/**.py] [jinja2: superset/**/templates/**.html] encoding = utf-8
babel/babel.cfg
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00017537345411255956, 0.00017537345411255956, 0.00017537345411255956, 0.00017537345411255956, 0 ]
{ "id": 2, "code_window": [ " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n", " db = make_url(model.get_sqla_engine().url).database\n", " self.assertEquals('hive/default', db)\n", "\n", " db = make_url(model.get_sqla_engine(schema='core_db').url).database\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " self.assertEquals('default', db)\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 42 }
import unittest from sqlalchemy.engine.url import make_url from superset.models.core import Database class DatabaseModelTestCase(unittest.TestCase): def test_database_schema_presto(self): sqlalchemy_uri = 'presto://presto.airbnb.io:8080/hive/default' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive/default', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) sqlalchemy_uri = 'presto://presto.airbnb.io:8080/hive' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) def test_database_schema_postgres(self): sqlalchemy_uri = 'postgresql+psycopg2://postgres.airbnb.io:5439/prod' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('prod', db) db = make_url(model.get_sqla_engine(schema='foo').url).database self.assertEquals('prod', db) def test_database_schema_hive(self): sqlalchemy_uri = 'hive://[email protected]:10000/hive/default' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive/default', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) def test_database_schema_mysql(self): sqlalchemy_uri = 'mysql://root@localhost/superset' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('superset', db) db = make_url(model.get_sqla_engine(schema='staging').url).database self.assertEquals('staging', db)
tests/model_tests.py
1
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.9977325201034546, 0.8285501003265381, 0.002199317794293165, 0.9937462210655212, 0.3695790469646454 ]
{ "id": 2, "code_window": [ " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n", " db = make_url(model.get_sqla_engine().url).database\n", " self.assertEquals('hive/default', db)\n", "\n", " db = make_url(model.get_sqla_engine(schema='core_db').url).database\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " self.assertEquals('default', db)\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 42 }
try: import cPickle as pickle except ImportError: import pickle import mock from superset import app, results_backends from .base_tests import SupersetTestCase app.config['S3_CACHE_BUCKET'] = 'test-bucket' app.config['S3_CACHE_KEY_PREFIX'] = 'test-prefix/' class ResultsBackendsTests(SupersetTestCase): requires_examples = False @mock.patch('boto3.client') def setUp(self, mock_boto3_client): self.mock_boto3_client = mock_boto3_client self.mock_s3_client = mock.MagicMock() self.mock_boto3_client.return_value = self.mock_s3_client self.s3_cache = results_backends.S3Cache() self.s3_cache._key_exists = ResultsBackendsTests._mock_key_exists @staticmethod def _mock_download_fileobj(bucket, key, value_file): value_file.write(pickle.dumps('%s:%s' % (bucket, key))) @staticmethod def _mock_key_exists(key): return key == 'test-key' def test_s3_cache_initilization(self): self.mock_boto3_client.assert_called_with('s3') def test_s3_cache_set(self): result = self.s3_cache.set('test-key', 'test-value') self.assertTrue(result) self.mock_s3_client.upload_fileobj.assert_called_once() call_args = self.mock_s3_client.upload_fileobj.call_args_list[0][0] self.assertEquals(pickle.loads(call_args[0].getvalue()), 'test-value') self.assertEquals(call_args[1], 'test-bucket') self.assertEquals(call_args[2], 'test-prefix/test-key') def test_s3_cache_set_exception(self): self.mock_s3_client.upload_fileobj.side_effect = Exception('Something bad happened!') result = self.s3_cache.set('test-key', 'test-value') self.assertFalse(result) self.mock_s3_client.upload_fileobj.assert_called_once() def test_s3_cache_get_exists(self): self.mock_s3_client.download_fileobj.side_effect = ( ResultsBackendsTests._mock_download_fileobj) result = self.s3_cache.get('test-key') self.assertEquals(result, 'test-bucket:test-prefix/test-key') self.mock_s3_client.download_fileobj.assert_called_once() def test_s3_cache_get_does_not_exist(self): result = self.s3_cache.get('test-key2') self.assertEquals(result, None) self.assertFalse(self.mock_s3_client.download_fileobj.called) def test_s3_cache_get_exception(self): self.mock_s3_client.download_fileobj.side_effect = Exception('Something bad happened') result = self.s3_cache.get('test-key') self.assertEquals(result, None) self.mock_s3_client.download_fileobj.assert_called_once() def test_s3_cache_delete_exists(self): result = self.s3_cache.delete('test-key') self.assertTrue(result) self.mock_s3_client.delete_objects.assert_called_once_with( Bucket='test-bucket', Delete={'Objects': [{'Key': 'test-prefix/test-key'}]} ) def test_s3_cache_delete_does_not_exist(self): result = self.s3_cache.delete('test-key2') self.assertFalse(result) self.assertFalse(self.mock_s3_client.delete_objects.called) def test_s3_cache_delete_exception(self): self.mock_s3_client.delete_objects.side_effect = Exception('Something bad happened') result = self.s3_cache.delete('test-key') self.assertFalse(result) self.mock_s3_client.delete_objects.assert_called_once() def test_s3_cache_add_exists(self): result = self.s3_cache.add('test-key', 'test-value') self.assertFalse(result) self.assertFalse(self.mock_s3_client.upload_fileobj.called) def test_s3_cache_add_does_not_exist(self): result = self.s3_cache.add('test-key2', 'test-value') self.assertTrue(result) self.mock_s3_client.upload_fileobj.assert_called_once() call_args = self.mock_s3_client.upload_fileobj.call_args_list[0][0] self.assertEquals(pickle.loads(call_args[0].getvalue()), 'test-value') self.assertEquals(call_args[1], 'test-bucket') self.assertEquals(call_args[2], 'test-prefix/test-key2') def test_s3_cache_add_exception(self): self.mock_s3_client.upload_fileobj.side_effect = Exception('Something bad happened') result = self.s3_cache.add('test-key2', 'test-value') self.assertFalse(result) self.mock_s3_client.upload_fileobj.assert_called_once()
tests/results_backends_tests.py
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00017786974785849452, 0.00017468706937506795, 0.00016740562568884343, 0.00017576618120074272, 0.0000025437443582632113 ]
{ "id": 2, "code_window": [ " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n", " db = make_url(model.get_sqla_engine().url).database\n", " self.assertEquals('hive/default', db)\n", "\n", " db = make_url(model.get_sqla_engine(schema='core_db').url).database\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " self.assertEquals('default', db)\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 42 }
import React from 'react'; import AlertContainer from 'react-alert'; export default class AlertsWrapper extends React.PureComponent { render() { return ( <AlertContainer ref={(ref) => { global.notify = ref; }} offset={14} position="top right" theme="dark" time={5000} transition="fade" />); } }
superset/assets/javascripts/components/AlertsWrapper.jsx
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00017662264872342348, 0.00017587881302461028, 0.0001751349918777123, 0.00017587881302461028, 7.438284228555858e-7 ]
{ "id": 2, "code_window": [ " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n", " db = make_url(model.get_sqla_engine().url).database\n", " self.assertEquals('hive/default', db)\n", "\n", " db = make_url(model.get_sqla_engine(schema='core_db').url).database\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " self.assertEquals('default', db)\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 42 }
<?xml version="1.0" encoding="UTF-8"?> <svg width="210px" height="146px" viewBox="0 0 210 146" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 42 (36781) - http://www.bohemiancoding.com/sketch --> <title>Full Lockup Without Text@1x</title> <desc>Created with Sketch.</desc> <defs> <path d="M55.8666667,41.25 C64.4268817,50.85 73.137276,55.65 83.3494624,55.65 C100.019355,55.65 112.183871,43.95 112.183871,27.9 C112.183871,11.85 100.019355,0 83.3494624,0 C73.7379928,0 64.8774194,5.4 56.3172043,14.85 C47.9071685,5.25 38.8964158,0 28.8344086,0 C12.1645161,0 -2.84217094e-14,11.85 -2.84217094e-14,27.9 C-2.84217094e-14,43.95 12.1645161,55.65 28.8344086,55.65 C39.046595,55.65 47.0060932,50.85 55.8666667,41.25 Z" id="path-1"></path> <mask id="mask-2" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="-5" y="-5" width="122.183871" height="65.65"> <rect x="-5" y="-5" width="122.183871" height="65.65" fill="white"></rect> <use xlink:href="#path-1" fill="black"></use> </mask> </defs> <g id="Main" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="Superset" transform="translate(-177.000000, -466.000000)"> <g id="Full-Lockup-Without-Text" transform="translate(177.000000, 466.000000)"> <path d="M0.5,81.35 C9.06021505,81.35 15.5179211,85.1 15.5179211,95.3 L15.5179211,116.6 C15.5179211,136.4 26.4810036,145.7 44.6526882,145.7 L49.3082437,145.7 L49.3082437,130.55 L44.8028674,130.55 C37.444086,130.55 32.3379928,127.1 32.3379928,117.05 L32.3379928,92 C32.3379928,82.4 26.781362,75.5 17.1698925,73.1 C26.781362,70.55 32.3379928,63.8 32.3379928,54.2 L32.3379928,29 C32.3379928,18.95 37.444086,15.65 44.8028674,15.65 L49.3082437,15.65 L49.3082437,0.5 L44.6526882,0.5 C26.4810036,0.5 15.5179211,9.65 15.5179211,29.45 L15.5179211,50.75 C15.5179211,60.95 9.06021505,64.7 0.5,64.7 L0.5,81.35 Z" id="{-copy-4" fill="#484848"></path> <path d="M161.191756,81.35 C169.751971,81.35 176.209677,85.1 176.209677,95.3 L176.209677,116.6 C176.209677,136.4 187.17276,145.7 205.344444,145.7 L210,145.7 L210,130.55 L205.494624,130.55 C198.135842,130.55 193.029749,127.1 193.029749,117.05 L193.029749,92 C193.029749,82.4 187.473118,75.5 177.861649,73.1 C187.473118,70.55 193.029749,63.8 193.029749,54.2 L193.029749,29 C193.029749,18.95 198.135842,15.65 205.494624,15.65 L210,15.65 L210,0.5 L205.344444,0.5 C187.17276,0.5 176.209677,9.65 176.209677,29.45 L176.209677,50.75 C176.209677,60.95 169.751971,64.7 161.191756,64.7 L161.191756,81.35 Z" id="{-copy-5" fill="#484848" transform="translate(185.595878, 73.100000) rotate(-180.000000) translate(-185.595878, -73.100000) "></path> <path d="M105.366667,86.75 C96.5060932,96.35 88.546595,101.15 78.3344086,101.15 C61.6645161,101.15 49.5,89.45 49.5,73.4 C49.5,57.35 61.6645161,45.5 78.3344086,45.5 C88.3964158,45.5 97.4071685,50.75 105.817204,60.35 C114.377419,50.9 123.237993,45.5 132.849462,45.5 C149.519355,45.5 161.683871,57.35 161.683871,73.4 C161.683871,89.45 149.519355,101.15 132.849462,101.15 C122.637276,101.15 113.926882,96.35 105.366667,86.75 Z M78.634767,62.6 C71.5763441,62.6 67.3713262,67.4 67.3713262,73.55 C67.3713262,79.7 71.5763441,84.35 78.634767,84.35 C84.4917563,84.35 89.7480287,79.85 94.7039427,73.85 C89.4476703,67.4 84.6419355,62.6 78.634767,62.6 Z M132.549104,84.35 C126.692115,84.35 121.736201,79.7 116.479928,73.55 C121.88638,67.1 126.541935,62.6 132.549104,62.6 C139.607527,62.6 143.812545,67.4 143.812545,73.55 C143.812545,79.7 139.607527,84.35 132.549104,84.35 Z" id="∞" fill="#484848"></path> <rect id="Bottom" fill="#FFFFFF" transform="translate(117.815969, 86.222742) rotate(-320.000000) translate(-117.815969, -86.222742) " x="108.805216" y="73.9117829" width="18.0215054" height="24.6219184"></rect> <polygon id="Top" fill="#FFFFFF" transform="translate(93.488745, 61.141018) rotate(-320.000000) translate(-93.488745, -61.141018) " points="84.477992 50.894853 102.499497 50.894853 102.499497 71.3871824 84.5471936 70.9586997"></polygon> <g id="Group-10" transform="translate(49.500000, 45.500000)"> <g id="WORK-SPACE"> <path d="M55.8666667,41.25 C64.4268817,50.85 73.137276,55.65 83.3494624,55.65 C100.019355,55.65 112.183871,43.95 112.183871,27.9 C112.183871,11.85 100.019355,0 83.3494624,0 C73.7379928,0 64.8774194,5.4 56.3172043,14.85 C47.9071685,5.25 38.8964158,0 28.8344086,0 C12.1645161,0 -2.84217094e-14,11.85 -2.84217094e-14,27.9 C-2.84217094e-14,43.95 12.1645161,55.65 28.8344086,55.65 C39.046595,55.65 47.0060932,50.85 55.8666667,41.25 Z" id="∞-copy-2" fill="#484848"></path> <path d="M35.3031737,7.82736301 L54.6231734,7.82736301 C54.6231734,7.82736301 54.1382597,11.9130391 54.1201021,16.2068622 C54.1019446,20.5006853 53.079701,24.1223631 53.079701,24.1223631 L35.3031737,24.1223631 L35.3031737,7.82736301 Z" id="Path" fill="#00D1C1" transform="translate(44.963174, 15.974863) rotate(-50.000000) translate(-44.963174, -15.974863) "></path> <rect id="Path-Copy" fill="#00D1C1" transform="translate(67.518574, 40.130521) rotate(-50.000000) translate(-67.518574, -40.130521) " x="57.8585742" y="31.9830205" width="19.3199997" height="16.2950001"></rect> <path d="M29.134767,17.1 C35.1419355,17.1 39.9476703,21.9 45.2039427,28.35 C40.2480287,34.35 34.9917563,38.85 29.134767,38.85 C22.0763441,38.85 17.8713262,34.2 17.8713262,28.05 C17.8713262,21.9 22.0763441,17.1 29.134767,17.1 Z" id="Path" fill="#FFFFFF"></path> <path d="M83.0491039,38.85 C77.1921147,38.85 72.2362007,34.2 66.9799283,28.05 C72.3863799,21.6 77.0419355,17.1 83.0491039,17.1 C90.1075269,17.1 94.3125448,21.9 94.3125448,28.05 C94.3125448,34.2 90.1075269,38.85 83.0491039,38.85 Z" id="Path" fill="#FFFFFF"></path> </g> <use id="∞-copy-2" stroke="#FFFFFF" mask="url(#mask-2)" stroke-width="10" xlink:href="#path-1"></use> </g> </g> </g> </g> </svg>
superset/assets/branding/Full Lockup Without [email protected]
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.0009623111691325903, 0.0003980396140832454, 0.0001762587489793077, 0.0002267942763864994, 0.0003264975966885686 ]
{ "id": 3, "code_window": [ "\n", " db = make_url(model.get_sqla_engine(schema='core_db').url).database\n", " self.assertEquals('hive/core_db', db)\n", "\n", " def test_database_schema_mysql(self):\n", " sqlalchemy_uri = 'mysql://root@localhost/superset'\n", " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " self.assertEquals('core_db', db)\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 45 }
import unittest from sqlalchemy.engine.url import make_url from superset.models.core import Database class DatabaseModelTestCase(unittest.TestCase): def test_database_schema_presto(self): sqlalchemy_uri = 'presto://presto.airbnb.io:8080/hive/default' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive/default', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) sqlalchemy_uri = 'presto://presto.airbnb.io:8080/hive' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) def test_database_schema_postgres(self): sqlalchemy_uri = 'postgresql+psycopg2://postgres.airbnb.io:5439/prod' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('prod', db) db = make_url(model.get_sqla_engine(schema='foo').url).database self.assertEquals('prod', db) def test_database_schema_hive(self): sqlalchemy_uri = 'hive://[email protected]:10000/hive/default' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('hive/default', db) db = make_url(model.get_sqla_engine(schema='core_db').url).database self.assertEquals('hive/core_db', db) def test_database_schema_mysql(self): sqlalchemy_uri = 'mysql://root@localhost/superset' model = Database(sqlalchemy_uri=sqlalchemy_uri) db = make_url(model.get_sqla_engine().url).database self.assertEquals('superset', db) db = make_url(model.get_sqla_engine(schema='staging').url).database self.assertEquals('staging', db)
tests/model_tests.py
1
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.9974215030670166, 0.565923810005188, 0.004970002453774214, 0.642978310585022, 0.43804800510406494 ]
{ "id": 3, "code_window": [ "\n", " db = make_url(model.get_sqla_engine(schema='core_db').url).database\n", " self.assertEquals('hive/core_db', db)\n", "\n", " def test_database_schema_mysql(self):\n", " sqlalchemy_uri = 'mysql://root@localhost/superset'\n", " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " self.assertEquals('core_db', db)\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 45 }
import d3 from 'd3'; import 'datatables-bootstrap3-plugin/media/css/datatables-bootstrap3.css'; import 'datatables.net'; import dt from 'datatables.net-bs'; import { fixDataTableBodyHeight } from '../javascripts/modules/utils'; import { timeFormatFactory, formatDate } from '../javascripts/modules/dates'; import './table.css'; const $ = require('jquery'); dt(window, $); function tableVis(slice, payload) { const container = $(slice.selector); const fC = d3.format('0,000'); let timestampFormatter; const data = payload.data; const fd = slice.formData; // Removing metrics (aggregates) that are strings let metrics = fd.metrics || []; metrics = metrics.filter(m => !isNaN(data.records[0][m])); function col(c) { const arr = []; for (let i = 0; i < data.records.length; i += 1) { arr.push(data.records[i][c]); } return arr; } const maxes = {}; for (let i = 0; i < metrics.length; i += 1) { maxes[metrics[i]] = d3.max(col(metrics[i])); } if (fd.table_timestamp_format === 'smart_date') { timestampFormatter = formatDate; } else if (fd.table_timestamp_format !== undefined) { timestampFormatter = timeFormatFactory(fd.table_timestamp_format); } const div = d3.select(slice.selector); div.html(''); const table = div.append('table') .classed( 'dataframe dataframe table table-striped table-bordered ' + 'table-condensed table-hover dataTable no-footer', true) .attr('width', '100%'); table.append('thead').append('tr') .selectAll('th') .data(data.columns) .enter() .append('th') .text(function (d) { return d; }); table.append('tbody') .selectAll('tr') .data(data.records) .enter() .append('tr') .selectAll('td') .data(row => data.columns.map((c) => { const val = row[c]; let html; const isMetric = metrics.indexOf(c) >= 0; if (c === 'timestamp') { html = timestampFormatter(val); } if (typeof (val) === 'string') { html = `<span class="like-pre">${val}</span>`; } if (isMetric) { html = slice.d3format(c, val); } return { col: c, val, html, isMetric, }; })) .enter() .append('td') .style('background-image', function (d) { if (d.isMetric) { const perc = Math.round((d.val / maxes[d.col]) * 100); return ( `linear-gradient(to right, lightgrey, lightgrey ${perc}%, ` + `rgba(0,0,0,0) ${perc}%)` ); } return null; }) .attr('title', (d) => { if (!isNaN(d.val)) { return fC(d.val); } return null; }) .attr('data-sort', function (d) { return (d.isMetric) ? d.val : null; }) .on('click', function (d) { if (!d.isMetric && fd.table_filter) { const td = d3.select(this); if (td.classed('filtered')) { slice.removeFilter(d.col, [d.val]); d3.select(this).classed('filtered', false); } else { d3.select(this).classed('filtered', true); slice.addFilter(d.col, [d.val]); } } }) .style('cursor', function (d) { return (!d.isMetric) ? 'pointer' : ''; }) .html(d => d.html ? d.html : d.val); const height = slice.height(); let paging = false; let pageLength; if (fd.page_length && fd.page_length > 0) { paging = true; pageLength = parseInt(fd.page_length, 10); } const datatable = container.find('.dataTable').DataTable({ paging, pageLength, aaSorting: [], searching: fd.include_search, bInfo: false, scrollY: height + 'px', scrollCollapse: true, scrollX: true, }); fixDataTableBodyHeight( container.find('.dataTables_wrapper'), height); // Sorting table by main column if (metrics.length > 0) { const mainMetric = metrics[0]; datatable.column(data.columns.indexOf(mainMetric)).order('desc').draw(); } container.parents('.widget').find('.tooltip').remove(); } module.exports = tableVis;
superset/assets/visualizations/table.js
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00017722084885463119, 0.0001748200156725943, 0.00017189937352668494, 0.00017488611047156155, 0.000001479487423239334 ]
{ "id": 3, "code_window": [ "\n", " db = make_url(model.get_sqla_engine(schema='core_db').url).database\n", " self.assertEquals('hive/core_db', db)\n", "\n", " def test_database_schema_mysql(self):\n", " sqlalchemy_uri = 'mysql://root@localhost/superset'\n", " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " self.assertEquals('core_db', db)\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 45 }
/* eslint camelcase: 0 */ import controls from './controls'; import visTypes, { sectionsToRender } from './visTypes'; export function getFormDataFromControls(controlsState) { const formData = {}; Object.keys(controlsState).forEach((controlName) => { formData[controlName] = controlsState[controlName].value; }); return formData; } export function getControlNames(vizType, datasourceType) { const controlNames = []; sectionsToRender(vizType, datasourceType).forEach( section => section.controlSetRows.forEach( fsr => fsr.forEach( f => controlNames.push(f)))); return controlNames; } export function getControlsState(state, form_data) { /* * Gets a new controls object to put in the state. The controls object * is similar to the configuration control with only the controls * related to the current viz_type, materializes mapStateToProps functions, * adds value keys coming from form_data passed here. This can't be an action creator * just yet because it's used in both the explore and dashboard views. * */ // Getting a list of active control names for the current viz const formData = Object.assign({}, form_data); const vizType = formData.viz_type || 'table'; const controlNames = getControlNames(vizType, state.datasource.type); const viz = visTypes[vizType]; const controlOverrides = viz.controlOverrides || {}; const controlsState = {}; controlNames.forEach((k) => { const control = Object.assign({}, controls[k], controlOverrides[k]); if (control.mapStateToProps) { Object.assign(control, control.mapStateToProps(state)); delete control.mapStateToProps; } // If the value is not valid anymore based on choices, clear it if (control.type === 'SelectControl' && control.choices && k !== 'datasource' && formData[k]) { const choiceValues = control.choices.map(c => c[0]); if (control.multi && formData[k].length > 0 && choiceValues.indexOf(formData[k][0]) < 0) { delete formData[k]; } else if (!control.multi && !control.freeForm && choiceValues.indexOf(formData[k]) < 0) { delete formData[k]; } } // Removing invalid filters that point to a now inexisting column if (control.type === 'FilterControl' && control.choices) { if (!formData[k]) { formData[k] = []; } const choiceValues = control.choices.map(c => c[0]); formData[k] = formData[k].filter(flt => choiceValues.indexOf(flt.col) >= 0); } if (typeof control.default === 'function') { control.default = control.default(control); } control.value = formData[k] !== undefined ? formData[k] : control.default; controlsState[k] = control; }); return controlsState; } export function applyDefaultFormData(form_data) { const datasourceType = form_data.datasource.split('__')[1]; const vizType = form_data.viz_type || 'table'; const viz = visTypes[vizType]; const controlNames = getControlNames(vizType, datasourceType); const controlOverrides = viz.controlOverrides || {}; const formData = {}; controlNames.forEach((k) => { const control = Object.assign({}, controls[k]); if (controlOverrides[k]) { Object.assign(control, controlOverrides[k]); } if (form_data[k] === undefined) { if (typeof control.default === 'function') { formData[k] = control.default(controls[k]); } else { formData[k] = control.default; } } else { formData[k] = form_data[k]; } }); return formData; } export const autoQueryControls = [ 'datasource', 'viz_type', ]; const defaultControls = Object.assign({}, controls); Object.keys(controls).forEach((f) => { defaultControls[f].value = controls[f].default; }); const defaultState = { controls: defaultControls, form_data: getFormDataFromControls(defaultControls), }; export { defaultControls, defaultState };
superset/assets/javascripts/explorev2/stores/store.js
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00017718774324748665, 0.00017474307969678193, 0.00016806391067802906, 0.00017589361232239753, 0.0000027096828034700593 ]
{ "id": 3, "code_window": [ "\n", " db = make_url(model.get_sqla_engine(schema='core_db').url).database\n", " self.assertEquals('hive/core_db', db)\n", "\n", " def test_database_schema_mysql(self):\n", " sqlalchemy_uri = 'mysql://root@localhost/superset'\n", " model = Database(sqlalchemy_uri=sqlalchemy_uri)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " self.assertEquals('core_db', db)\n" ], "file_path": "tests/model_tests.py", "type": "replace", "edit_start_line_idx": 45 }
import { beforeEach, describe, it } from 'mocha'; import { expect } from 'chai'; import * as r from '../../../javascripts/SqlLab/reducers'; import * as actions from '../../../javascripts/SqlLab/actions'; import { alert, table, initialState } from './fixtures'; describe('sqlLabReducer', () => { describe('CLONE_QUERY_TO_NEW_TAB', () => { const testQuery = { sql: 'SELECT * FROM...', dbId: 1, id: 'flasj233' }; let newState = Object.assign({}, initialState, { queries: { [testQuery.id]: testQuery } }); newState = r.sqlLabReducer(newState, actions.cloneQueryToNewTab(testQuery)); it('should have at most one more tab', () => { expect(newState.queryEditors).have.length(2); }); it('should have the same SQL as the cloned query', () => { expect(newState.queryEditors[1].sql).to.equal(testQuery.sql); }); it('should prefix the new tab title with "Copy of"', () => { expect(newState.queryEditors[1].title).to.include('Copy of'); }); it('should push the cloned tab onto tab history stack', () => { expect(newState.tabHistory[1]).to.eq(newState.queryEditors[1].id); }); }); describe('Alerts', () => { const state = Object.assign({}, initialState); let newState; it('should add one alert', () => { newState = r.sqlLabReducer(state, actions.addAlert(alert)); expect(newState.alerts).to.have.lengthOf(1); }); it('should remove one alert', () => { newState = r.sqlLabReducer(newState, actions.removeAlert(newState.alerts[0])); expect(newState.alerts).to.have.lengthOf(0); }); }); describe('Query editors actions', () => { let newState; let defaultQueryEditor; let qe; beforeEach(() => { newState = Object.assign({}, initialState); defaultQueryEditor = newState.queryEditors[0]; qe = Object.assign({}, defaultQueryEditor); newState = r.sqlLabReducer(newState, actions.addQueryEditor(qe)); qe = newState.queryEditors[newState.queryEditors.length - 1]; }); it('should add a query editor', () => { expect(newState.queryEditors).to.have.lengthOf(2); }); it('should remove a query editor', () => { expect(newState.queryEditors).to.have.lengthOf(2); newState = r.sqlLabReducer(newState, actions.removeQueryEditor(qe)); expect(newState.queryEditors).to.have.lengthOf(1); }); it('should set q query editor active', () => { newState = r.sqlLabReducer(newState, actions.addQueryEditor(qe)); newState = r.sqlLabReducer(newState, actions.setActiveQueryEditor(defaultQueryEditor)); expect(newState.tabHistory[newState.tabHistory.length - 1]).equals(defaultQueryEditor.id); }); it('should not fail while setting DB', () => { const dbId = 9; newState = r.sqlLabReducer(newState, actions.queryEditorSetDb(qe, dbId)); expect(newState.queryEditors[1].dbId).to.equal(dbId); }); it('should not fail while setting schema', () => { const schema = 'foo'; newState = r.sqlLabReducer(newState, actions.queryEditorSetSchema(qe, schema)); expect(newState.queryEditors[1].schema).to.equal(schema); }); it('should not fail while setting autorun ', () => { newState = r.sqlLabReducer(newState, actions.queryEditorSetAutorun(qe, false)); expect(newState.queryEditors[1].autorun).to.equal(false); newState = r.sqlLabReducer(newState, actions.queryEditorSetAutorun(qe, true)); expect(newState.queryEditors[1].autorun).to.equal(true); }); it('should not fail while setting title', () => { const title = 'a new title'; newState = r.sqlLabReducer(newState, actions.queryEditorSetTitle(qe, title)); expect(newState.queryEditors[1].title).to.equal(title); }); it('should not fail while setting Sql', () => { const sql = 'SELECT nothing from dev_null'; newState = r.sqlLabReducer(newState, actions.queryEditorSetSql(qe, sql)); expect(newState.queryEditors[1].sql).to.equal(sql); }); it('should set selectedText', () => { const selectedText = 'TEST'; expect(newState.queryEditors[0].selectedText).to.equal(null); newState = r.sqlLabReducer( newState, actions.queryEditorSetSelectedText(newState.queryEditors[0], 'TEST')); expect(newState.queryEditors[0].selectedText).to.equal(selectedText); }); }); describe('Tables', () => { let newState; let newTable; beforeEach(() => { newTable = Object.assign({}, table); newState = r.sqlLabReducer(initialState, actions.mergeTable(newTable)); newTable = newState.tables[0]; }); it('should add a table', () => { // Testing that beforeEach actually added the table expect(newState.tables).to.have.lengthOf(1); }); it('should merge the table attributes', () => { // Merging the extra attribute newTable.extra = true; newState = r.sqlLabReducer(newState, actions.mergeTable(newTable)); expect(newState.tables).to.have.lengthOf(1); expect(newState.tables[0].extra).to.equal(true); }); it('should expand and collapse a table', () => { newState = r.sqlLabReducer(newState, actions.collapseTable(newTable)); expect(newState.tables[0].expanded).to.equal(false); newState = r.sqlLabReducer(newState, actions.expandTable(newTable)); expect(newState.tables[0].expanded).to.equal(true); }); it('should remove a table', () => { newState = r.sqlLabReducer(newState, actions.removeTable(newTable)); expect(newState.tables).to.have.lengthOf(0); }); }); describe('Run Query', () => { let newState; let query; let newQuery; beforeEach(() => { newState = Object.assign({}, initialState); newQuery = Object.assign({}, query); }); it('should start a query', () => { newState = r.sqlLabReducer(newState, actions.startQuery(newQuery)); expect(Object.keys(newState.queries)).to.have.lengthOf(1); }); it('should stop the query', () => { newState = r.sqlLabReducer(newState, actions.startQuery(newQuery)); newState = r.sqlLabReducer(newState, actions.stopQuery(newQuery)); const q = newState.queries[Object.keys(newState.queries)[0]]; expect(q.state).to.equal('stopped'); }); it('should remove a query', () => { newState = r.sqlLabReducer(newState, actions.startQuery(newQuery)); newState = r.sqlLabReducer(newState, actions.removeQuery(newQuery)); expect(Object.keys(newState.queries)).to.have.lengthOf(0); }); it('should refresh queries when polling returns empty', () => { newState = r.sqlLabReducer(newState, actions.refreshQueries({})); }); }); });
superset/assets/spec/javascripts/sqllab/reducers_spec.js
0
https://github.com/apache/superset/commit/91fe02cdc879097d517cddc06a8492536bc3b6ea
[ 0.00018970802193507552, 0.00017678207950666547, 0.00016984647663775831, 0.00017736692097969353, 0.000004296466158848489 ]
{ "id": 0, "code_window": [ "\trenderTemplate(container: HTMLElement): IExpressionTemplateData {\n", "\t\tconst expression = dom.append(container, $('.expression'));\n", "\t\tconst name = dom.append(expression, $('span.name'));\n", "\t\tconst value = dom.append(expression, $('span.value'));\n", "\t\tconst lazyButton = dom.append(expression, $('span.lazy-button'));\n", "\t\tlazyButton.classList.add(...Codicon.eye.classNamesArray);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/baseDebugView.ts", "type": "replace", "edit_start_line_idx": 159 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .codicon-debug-hint { cursor: pointer; } .codicon-debug-hint:not([class*='codicon-debug-breakpoint']):not([class*='codicon-debug-stackframe']) { opacity: 0.4 !important; } .inline-breakpoint-widget.codicon { display: flex !important; align-items: center; } .inline-breakpoint-widget.codicon-debug-breakpoint-disabled { opacity: 0.7; } .monaco-editor .inline-breakpoint-widget.line-start { left: -8px !important; } .monaco-editor .debug-breakpoint-placeholder { width: 0.9em; display: inline-flex; vertical-align: middle; margin-top: -1px; } .codicon-debug-breakpoint.codicon-debug-stackframe-focused::after, .codicon-debug-breakpoint.codicon-debug-stackframe::after { content: '\eb8a'; position: absolute; } .monaco-editor .debug-top-stack-frame-column { font: normal normal normal 16px/1 codicon; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; margin-left: 0; margin-right: 4px; margin-top: -1px; /* TODO @misolori: figure out a way to not use negative margin for alignment */ align-items: center; width: 0.9em; display: inline-flex; vertical-align: middle; } /* Do not push text with inline decoration when decoration on start of line */ .monaco-editor .debug-top-stack-frame-column.start-of-line { position: absolute; top: 50%; transform: translate(-17px, -50%); margin-top: 0px; /* TODO @misolori: figure out a way to not use negative margin for alignment */ } .monaco-editor .inline-breakpoint-widget { cursor: pointer; } .monaco-workbench .debug-view-content .monaco-list-row .monaco-tl-contents { overflow: hidden; text-overflow: ellipsis; } /* Expressions */ .monaco-workbench .debug-pane .monaco-list-row .expression, .monaco-workbench .debug-hover-widget .monaco-list-row .expression { font-size: 13px; overflow: hidden; text-overflow: ellipsis; font-family: var(--monaco-monospace-font); white-space: pre; } .monaco-workbench.mac .debug-pane .monaco-list-row .expression, .monaco-workbench.mac .debug-hover-widget .monaco-list-row .expression { font-size: 11px; } .monaco-workbench .monaco-list-row .expression .value { margin-left: 6px; } .monaco-workbench .monaco-list-row .expression .lazy-button { margin-left: 3px; } /* Links */ .monaco-workbench .monaco-list-row .expression .value a.link:hover { text-decoration: underline; } .monaco-workbench .monaco-list-row .expression .value a.link.pointer { cursor: pointer; } /* White color when element is selected and list is focused. White looks better on blue selection background. */ .monaco-workbench .monaco-list:focus .monaco-list-row.selected .expression .name, .monaco-workbench .monaco-list:focus .monaco-list-row.selected .expression .value { color: inherit; } .monaco-workbench .monaco-list-row .expression .name.virtual { opacity: 0.5; } .monaco-workbench .monaco-list-row .expression .name.internal { opacity: 0.5; } .monaco-workbench .monaco-list-row .expression .unavailable { font-style: italic; } .monaco-workbench .monaco-list-row .expression .lazy-button { display: none; border-radius: 5px; padding: 3px; } .monaco-workbench .monaco-list-row .expression.lazy .lazy-button { display: inline; } .monaco-workbench .monaco-list-row .expression.lazy .value { display: none; } .monaco-workbench .debug-inline-value { background-color: var(--vscode-editor-inlineValuesBackground); color: var(--vscode-editor-inlineValuesForeground); }
src/vs/workbench/contrib/debug/browser/media/debug.contribution.css
1
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.00017380528151988983, 0.00017070997273549438, 0.00016570142179261893, 0.00017137598479166627, 0.0000023832046736060875 ]
{ "id": 0, "code_window": [ "\trenderTemplate(container: HTMLElement): IExpressionTemplateData {\n", "\t\tconst expression = dom.append(container, $('.expression'));\n", "\t\tconst name = dom.append(expression, $('span.name'));\n", "\t\tconst value = dom.append(expression, $('span.value'));\n", "\t\tconst lazyButton = dom.append(expression, $('span.lazy-button'));\n", "\t\tlazyButton.classList.add(...Codicon.eye.classNamesArray);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/baseDebugView.ts", "type": "replace", "edit_start_line_idx": 159 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import './actions/expandAbbreviation';
src/vs/workbench/contrib/emmet/browser/emmet.contribution.ts
0
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.00017663191829342395, 0.00017663191829342395, 0.00017663191829342395, 0.00017663191829342395, 0 ]
{ "id": 0, "code_window": [ "\trenderTemplate(container: HTMLElement): IExpressionTemplateData {\n", "\t\tconst expression = dom.append(container, $('.expression'));\n", "\t\tconst name = dom.append(expression, $('span.name'));\n", "\t\tconst value = dom.append(expression, $('span.value'));\n", "\t\tconst lazyButton = dom.append(expression, $('span.lazy-button'));\n", "\t\tlazyButton.classList.add(...Codicon.eye.classNamesArray);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/baseDebugView.ts", "type": "replace", "edit_start_line_idx": 159 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { timeout } from 'vs/base/common/async'; import { Event } from 'vs/base/common/event'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { mock } from 'vs/base/test/common/mock'; import { runWithFakedTimers } from 'vs/base/test/common/timeTravelScheduler'; import { Range } from 'vs/editor/common/core/range'; import { CompletionItemKind, CompletionItemProvider } from 'vs/editor/common/languages'; import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker'; import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl'; import { SharedInlineCompletionCache } from 'vs/editor/contrib/inlineCompletions/browser/ghostTextModel'; import { SuggestWidgetPreviewModel } from 'vs/editor/contrib/inlineCompletions/browser/suggestWidgetPreviewModel'; import { GhostTextContext } from 'vs/editor/contrib/inlineCompletions/test/browser/utils'; import { SnippetController2 } from 'vs/editor/contrib/snippet/browser/snippetController2'; import { SuggestController } from 'vs/editor/contrib/suggest/browser/suggestController'; import { ISuggestMemoryService } from 'vs/editor/contrib/suggest/browser/suggestMemory'; import { ITestCodeEditor, TestCodeEditorInstantiationOptions, withAsyncTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor'; import { IMenu, IMenuService } from 'vs/platform/actions/common/actions'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { MockKeybindingService } from 'vs/platform/keybinding/test/common/mockKeybindingService'; import { ILogService, NullLogService } from 'vs/platform/log/common/log'; import { InMemoryStorageService, IStorageService } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils'; import assert = require('assert'); import { createTextModel } from 'vs/editor/test/common/testTextModel'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { rangeStartsWith } from 'vs/editor/contrib/inlineCompletions/browser/suggestWidgetInlineCompletionProvider'; import { LanguageFeaturesService } from 'vs/editor/common/services/languageFeaturesService'; import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures'; import { minimizeInlineCompletion } from 'vs/editor/contrib/inlineCompletions/browser/inlineCompletionToGhostText'; suite('Suggest Widget Model', () => { test('rangeStartsWith', () => { assert.strictEqual(rangeStartsWith(new Range(1, 1, 10, 5), new Range(1, 1, 1, 1)), true); assert.strictEqual(rangeStartsWith(new Range(1, 1, 10, 5), new Range(1, 1, 10, 5)), true); assert.strictEqual(rangeStartsWith(new Range(1, 1, 10, 5), new Range(1, 1, 10, 4)), true); assert.strictEqual(rangeStartsWith(new Range(1, 1, 10, 5), new Range(1, 1, 9, 6)), true); assert.strictEqual(rangeStartsWith(new Range(2, 1, 10, 5), new Range(1, 1, 10, 5)), false); assert.strictEqual(rangeStartsWith(new Range(1, 1, 10, 5), new Range(1, 1, 10, 6)), false); assert.strictEqual(rangeStartsWith(new Range(1, 1, 10, 5), new Range(1, 1, 11, 4)), false); }); test('Active', async () => { await withAsyncTestCodeEditorAndInlineCompletionsModel('', { fakeClock: true, provider, }, async ({ editor, editorViewModel, context, model }) => { let last: boolean | undefined = undefined; const history = new Array<boolean>(); model.onDidChange(() => { if (last !== model.isActive) { last = model.isActive; history.push(last); } }); context.keyboardType('h'); const suggestController = (editor.getContribution(SuggestController.ID) as SuggestController); suggestController.triggerSuggest(); await timeout(1000); assert.deepStrictEqual(history.splice(0), [false, true]); context.keyboardType('.'); await timeout(1000); // No flicker here assert.deepStrictEqual(history.splice(0), []); suggestController.cancelSuggestWidget(); await timeout(1000); assert.deepStrictEqual(history.splice(0), [false]); } ); }); test('Ghost Text', async () => { await withAsyncTestCodeEditorAndInlineCompletionsModel('', { fakeClock: true, provider, suggest: { preview: true } }, async ({ editor, editorViewModel, context, model }) => { context.keyboardType('h'); const suggestController = (editor.getContribution(SuggestController.ID) as SuggestController); suggestController.triggerSuggest(); await timeout(1000); assert.deepStrictEqual(context.getAndClearViewStates(), ['', 'h', 'h[ello]']); context.keyboardType('.'); await timeout(1000); assert.deepStrictEqual(context.getAndClearViewStates(), ['hello', 'hello.', 'hello.[hello]']); suggestController.cancelSuggestWidget(); await timeout(1000); assert.deepStrictEqual(context.getAndClearViewStates(), ['hello.']); } ); }); test('minimizeInlineCompletion', async () => { const model = createTextModel('fun'); const result = minimizeInlineCompletion(model, { range: new Range(1, 1, 1, 4), filterText: 'function', insertText: 'function', snippetInfo: undefined, additionalTextEdits: [], })!; assert.deepStrictEqual({ range: result.range.toString(), text: result.insertText }, { range: '[1,4 -> 1,4]', text: 'ction' }); model.dispose(); }); }); const provider: CompletionItemProvider = { triggerCharacters: ['.'], async provideCompletionItems(model, pos) { const word = model.getWordAtPosition(pos); const range = word ? { startLineNumber: 1, startColumn: word.startColumn, endLineNumber: 1, endColumn: word.endColumn } : Range.fromPositions(pos); return { suggestions: [{ insertText: 'hello', kind: CompletionItemKind.Text, label: 'hello', range, commitCharacters: ['.'], }] }; }, }; async function withAsyncTestCodeEditorAndInlineCompletionsModel( text: string, options: TestCodeEditorInstantiationOptions & { provider?: CompletionItemProvider; fakeClock?: boolean; serviceCollection?: never }, callback: (args: { editor: ITestCodeEditor; editorViewModel: ViewModel; model: SuggestWidgetPreviewModel; context: GhostTextContext }) => Promise<void> ): Promise<void> { await runWithFakedTimers({ useFakeTimers: options.fakeClock }, async () => { const disposableStore = new DisposableStore(); try { const serviceCollection = new ServiceCollection( [ITelemetryService, NullTelemetryService], [ILogService, new NullLogService()], [IStorageService, new InMemoryStorageService()], [IKeybindingService, new MockKeybindingService()], [IEditorWorkerService, new class extends mock<IEditorWorkerService>() { override computeWordRanges() { return Promise.resolve({}); } }], [ISuggestMemoryService, new class extends mock<ISuggestMemoryService>() { override memorize(): void { } override select(): number { return 0; } }], [IMenuService, new class extends mock<IMenuService>() { override createMenu() { return new class extends mock<IMenu>() { override onDidChange = Event.None; override dispose() { } }; } }], [ILabelService, new class extends mock<ILabelService>() { }], [IWorkspaceContextService, new class extends mock<IWorkspaceContextService>() { }], ); if (options.provider) { const languageFeaturesService = new LanguageFeaturesService(); serviceCollection.set(ILanguageFeaturesService, languageFeaturesService); const d = languageFeaturesService.completionProvider.register({ pattern: '**' }, options.provider); disposableStore.add(d); } await withAsyncTestCodeEditor(text, { ...options, serviceCollection }, async (editor, editorViewModel, instantiationService) => { editor.registerAndInstantiateContribution(SnippetController2.ID, SnippetController2); editor.registerAndInstantiateContribution(SuggestController.ID, SuggestController); const cache = disposableStore.add(new SharedInlineCompletionCache()); const model = instantiationService.createInstance(SuggestWidgetPreviewModel, editor, cache); const context = new GhostTextContext(model, editor); await callback({ editor, editorViewModel, model, context }); model.dispose(); }); } finally { disposableStore.dispose(); } }); }
src/vs/editor/contrib/inlineCompletions/test/browser/suggestWidgetModel.test.ts
0
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.00017720666073728353, 0.00017370926798321307, 0.0001684447779553011, 0.0001738062856020406, 0.0000023091206458047964 ]
{ "id": 0, "code_window": [ "\trenderTemplate(container: HTMLElement): IExpressionTemplateData {\n", "\t\tconst expression = dom.append(container, $('.expression'));\n", "\t\tconst name = dom.append(expression, $('span.name'));\n", "\t\tconst value = dom.append(expression, $('span.value'));\n", "\t\tconst lazyButton = dom.append(expression, $('span.lazy-button'));\n", "\t\tlazyButton.classList.add(...Codicon.eye.classNamesArray);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/baseDebugView.ts", "type": "replace", "edit_start_line_idx": 159 }
[ { "c": ":", "t": "source.css.scss entity.other.attribute-name.pseudo-class.css punctuation.definition.entity.css", "r": { "dark_plus": "entity.other.attribute-name.pseudo-class.css: #D7BA7D", "light_plus": "entity.other.attribute-name.pseudo-class.css: #800000", "dark_vs": "entity.other.attribute-name.pseudo-class.css: #D7BA7D", "light_vs": "entity.other.attribute-name.pseudo-class.css: #800000", "hc_black": "entity.other.attribute-name.pseudo-class.css: #D7BA7D", "hc_light": "entity.other.attribute-name.pseudo-class.css: #800000" } }, { "c": "root", "t": "source.css.scss entity.other.attribute-name.pseudo-class.css", "r": { "dark_plus": "entity.other.attribute-name.pseudo-class.css: #D7BA7D", "light_plus": "entity.other.attribute-name.pseudo-class.css: #800000", "dark_vs": "entity.other.attribute-name.pseudo-class.css: #D7BA7D", "light_vs": "entity.other.attribute-name.pseudo-class.css: #800000", "hc_black": "entity.other.attribute-name.pseudo-class.css: #D7BA7D", "hc_light": "entity.other.attribute-name.pseudo-class.css: #800000" } }, { "c": " ", "t": "source.css.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "{", "t": "source.css.scss meta.property-list.scss punctuation.section.property-list.begin.bracket.curly.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "--spacing-unit", "t": "source.css.scss meta.property-list.scss variable.scss", "r": { "dark_plus": "variable.scss: #9CDCFE", "light_plus": "variable.scss: #FF0000", "dark_vs": "variable.scss: #9CDCFE", "light_vs": "variable.scss: #FF0000", "hc_black": "variable.scss: #D4D4D4", "hc_light": "variable.scss: #264F78" } }, { "c": ":", "t": "source.css.scss meta.property-list.scss punctuation.separator.key-value.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "6", "t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css", "r": { "dark_plus": "constant.numeric: #B5CEA8", "light_plus": "constant.numeric: #098658", "dark_vs": "constant.numeric: #B5CEA8", "light_vs": "constant.numeric: #098658", "hc_black": "constant.numeric: #B5CEA8", "hc_light": "constant.numeric: #098658" } }, { "c": "px", "t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css keyword.other.unit.px.css", "r": { "dark_plus": "keyword.other.unit: #B5CEA8", "light_plus": "keyword.other.unit: #098658", "dark_vs": "keyword.other.unit: #B5CEA8", "light_vs": "keyword.other.unit: #098658", "hc_black": "keyword.other.unit: #B5CEA8", "hc_light": "keyword.other.unit: #098658" } }, { "c": ";", "t": "source.css.scss meta.property-list.scss punctuation.terminator.rule.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "--cell-padding", "t": "source.css.scss meta.property-list.scss variable.scss", "r": { "dark_plus": "variable.scss: #9CDCFE", "light_plus": "variable.scss: #FF0000", "dark_vs": "variable.scss: #9CDCFE", "light_vs": "variable.scss: #FF0000", "hc_black": "variable.scss: #D4D4D4", "hc_light": "variable.scss: #264F78" } }, { "c": ":", "t": "source.css.scss meta.property-list.scss punctuation.separator.key-value.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "(", "t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.definition.begin.bracket.round.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "4", "t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css", "r": { "dark_plus": "constant.numeric: #B5CEA8", "light_plus": "constant.numeric: #098658", "dark_vs": "constant.numeric: #B5CEA8", "light_vs": "constant.numeric: #098658", "hc_black": "constant.numeric: #B5CEA8", "hc_light": "constant.numeric: #098658" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss meta.property-value.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "*", "t": "source.css.scss meta.property-list.scss meta.property-value.scss keyword.operator.css", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4", "hc_light": "keyword.operator: #000000" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss meta.property-value.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "var", "t": "source.css.scss meta.property-list.scss meta.property-value.scss support.function.misc.scss", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "hc_light": "support.function: #795E26" } }, { "c": "(", "t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "--spacing-unit", "t": "source.css.scss meta.property-list.scss meta.property-value.scss variable.scss", "r": { "dark_plus": "variable.scss: #9CDCFE", "light_plus": "variable.scss: #FF0000", "dark_vs": "variable.scss: #9CDCFE", "light_vs": "variable.scss: #FF0000", "hc_black": "variable.scss: #D4D4D4", "hc_light": "variable.scss: #264F78" } }, { "c": ")", "t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": ")", "t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.definition.end.bracket.round.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": ";", "t": "source.css.scss meta.property-list.scss punctuation.terminator.rule.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "}", "t": "source.css.scss meta.property-list.scss punctuation.section.property-list.end.bracket.curly.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "body", "t": "source.css.scss entity.name.tag.css", "r": { "dark_plus": "entity.name.tag.css: #D7BA7D", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag.css: #D7BA7D", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag.css: #D7BA7D", "hc_light": "entity.name.tag: #800000" } }, { "c": " ", "t": "source.css.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "{", "t": "source.css.scss meta.property-list.scss punctuation.section.property-list.begin.bracket.curly.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "padding-left", "t": "source.css.scss meta.property-list.scss meta.property-name.scss support.type.property-name.css", "r": { "dark_plus": "support.type.property-name: #9CDCFE", "light_plus": "support.type.property-name: #FF0000", "dark_vs": "support.type.property-name: #9CDCFE", "light_vs": "support.type.property-name: #FF0000", "hc_black": "support.type.property-name: #D4D4D4", "hc_light": "support.type.property-name: #264F78" } }, { "c": ":", "t": "source.css.scss meta.property-list.scss punctuation.separator.key-value.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "calc", "t": "source.css.scss meta.property-list.scss meta.property-value.scss support.function.misc.scss", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "hc_light": "support.function: #795E26" } }, { "c": "(", "t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "4", "t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css", "r": { "dark_plus": "constant.numeric: #B5CEA8", "light_plus": "constant.numeric: #098658", "dark_vs": "constant.numeric: #B5CEA8", "light_vs": "constant.numeric: #098658", "hc_black": "constant.numeric: #B5CEA8", "hc_light": "constant.numeric: #098658" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss meta.property-value.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "*", "t": "source.css.scss meta.property-list.scss meta.property-value.scss keyword.operator.css", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4", "hc_light": "keyword.operator: #000000" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss meta.property-value.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "var", "t": "source.css.scss meta.property-list.scss meta.property-value.scss support.function.misc.scss", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "hc_light": "support.function: #795E26" } }, { "c": "(", "t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "--spacing-unit", "t": "source.css.scss meta.property-list.scss meta.property-value.scss variable.scss", "r": { "dark_plus": "variable.scss: #9CDCFE", "light_plus": "variable.scss: #FF0000", "dark_vs": "variable.scss: #9CDCFE", "light_vs": "variable.scss: #FF0000", "hc_black": "variable.scss: #D4D4D4", "hc_light": "variable.scss: #264F78" } }, { "c": ",", "t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.separator.delimiter.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": " ", "t": "source.css.scss meta.property-list.scss meta.property-value.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "5", "t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css", "r": { "dark_plus": "constant.numeric: #B5CEA8", "light_plus": "constant.numeric: #098658", "dark_vs": "constant.numeric: #B5CEA8", "light_vs": "constant.numeric: #098658", "hc_black": "constant.numeric: #B5CEA8", "hc_light": "constant.numeric: #098658" } }, { "c": "px", "t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css keyword.other.unit.px.css", "r": { "dark_plus": "keyword.other.unit: #B5CEA8", "light_plus": "keyword.other.unit: #098658", "dark_vs": "keyword.other.unit: #B5CEA8", "light_vs": "keyword.other.unit: #098658", "hc_black": "keyword.other.unit: #B5CEA8", "hc_light": "keyword.other.unit: #098658" } }, { "c": "))", "t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": ";", "t": "source.css.scss meta.property-list.scss punctuation.terminator.rule.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "}", "t": "source.css.scss meta.property-list.scss punctuation.section.property-list.end.bracket.curly.scss", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } } ]
extensions/vscode-colorize-tests/test/colorize-results/test-cssvariables_scss.json
0
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.00017772361752577126, 0.00017338349425699562, 0.00017081511032301933, 0.00017326751549262553, 0.0000013021397080592578 ]
{ "id": 1, "code_window": [ "\t\tconst lazyButton = dom.append(expression, $('span.lazy-button'));\n", "\t\tlazyButton.classList.add(...Codicon.eye.classNamesArray);\n", "\n", "\t\tconst label = new HighlightedLabel(name);\n", "\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst value = dom.append(expression, $('span.value'));\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/baseDebugView.ts", "type": "add", "edit_start_line_idx": 162 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { HighlightedLabel, IHighlight } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; import { IInputValidationOptions, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { Codicon } from 'vs/base/common/codicons'; import { createMatches, FuzzyScore } from 'vs/base/common/filters'; import { once } from 'vs/base/common/functional'; import { KeyCode } from 'vs/base/common/keyCodes'; import { DisposableStore, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { attachInputBoxStyler } from 'vs/platform/theme/common/styler'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector'; import { IDebugService, IExpression, IExpressionContainer } from 'vs/workbench/contrib/debug/common/debug'; import { Expression, ExpressionContainer, Variable } from 'vs/workbench/contrib/debug/common/debugModel'; import { ReplEvaluationResult } from 'vs/workbench/contrib/debug/common/replModel'; export const MAX_VALUE_RENDER_LENGTH_IN_VIEWLET = 1024; export const twistiePixels = 20; const booleanRegex = /^(true|false)$/i; const stringRegex = /^(['"]).*\1$/; const $ = dom.$; export interface IRenderValueOptions { showChanged?: boolean; maxValueLength?: number; showHover?: boolean; colorize?: boolean; linkDetector?: LinkDetector; } export interface IVariableTemplateData { expression: HTMLElement; name: HTMLElement; value: HTMLElement; label: HighlightedLabel; lazyButton: HTMLElement; } export function renderViewTree(container: HTMLElement): HTMLElement { const treeContainer = $('.'); treeContainer.classList.add('debug-view-content'); container.appendChild(treeContainer); return treeContainer; } export function renderExpressionValue(expressionOrValue: IExpressionContainer | string, container: HTMLElement, options: IRenderValueOptions): void { let value = typeof expressionOrValue === 'string' ? expressionOrValue : expressionOrValue.value; // remove stale classes container.className = 'value'; // when resolving expressions we represent errors from the server as a variable with name === null. if (value === null || ((expressionOrValue instanceof Expression || expressionOrValue instanceof Variable || expressionOrValue instanceof ReplEvaluationResult) && !expressionOrValue.available)) { container.classList.add('unavailable'); if (value !== Expression.DEFAULT_VALUE) { container.classList.add('error'); } } else if ((expressionOrValue instanceof ExpressionContainer) && options.showChanged && expressionOrValue.valueChanged && value !== Expression.DEFAULT_VALUE) { // value changed color has priority over other colors. container.className = 'value changed'; expressionOrValue.valueChanged = false; } if (options.colorize && typeof expressionOrValue !== 'string') { if (expressionOrValue.type === 'number' || expressionOrValue.type === 'boolean' || expressionOrValue.type === 'string') { container.classList.add(expressionOrValue.type); } else if (!isNaN(+value)) { container.classList.add('number'); } else if (booleanRegex.test(value)) { container.classList.add('boolean'); } else if (stringRegex.test(value)) { container.classList.add('string'); } } if (options.maxValueLength && value && value.length > options.maxValueLength) { value = value.substring(0, options.maxValueLength) + '...'; } if (!value) { value = ''; } if (options.linkDetector) { container.textContent = ''; const session = (expressionOrValue instanceof ExpressionContainer) ? expressionOrValue.getSession() : undefined; container.appendChild(options.linkDetector.linkify(value, false, session ? session.root : undefined)); } else { container.textContent = value; } if (options.showHover) { container.title = value || ''; } } export function renderVariable(variable: Variable, data: IVariableTemplateData, showChanged: boolean, highlights: IHighlight[], linkDetector?: LinkDetector): void { if (variable.available) { let text = variable.name; if (variable.value && typeof variable.name === 'string') { text += ':'; } data.label.set(text, highlights, variable.type ? variable.type : variable.name); data.name.classList.toggle('virtual', variable.presentationHint?.kind === 'virtual'); data.name.classList.toggle('internal', variable.presentationHint?.visibility === 'internal'); } else if (variable.value && typeof variable.name === 'string' && variable.name) { data.label.set(':'); } data.expression.classList.toggle('lazy', !!variable.presentationHint?.lazy); data.lazyButton.title = variable.presentationHint?.lazy ? variable.value : ''; renderExpressionValue(variable, data.value, { showChanged, maxValueLength: MAX_VALUE_RENDER_LENGTH_IN_VIEWLET, showHover: true, colorize: true, linkDetector }); } export interface IInputBoxOptions { initialValue: string; ariaLabel: string; placeholder?: string; validationOptions?: IInputValidationOptions; onFinish: (value: string, success: boolean) => void; } export interface IExpressionTemplateData { expression: HTMLElement; name: HTMLSpanElement; value: HTMLSpanElement; inputBoxContainer: HTMLElement; actionBar?: ActionBar; elementDisposable: IDisposable[]; templateDisposable: IDisposable; label: HighlightedLabel; lazyButton: HTMLElement; currentElement: IExpression | undefined; } export abstract class AbstractExpressionsRenderer implements ITreeRenderer<IExpression, FuzzyScore, IExpressionTemplateData> { constructor( @IDebugService protected debugService: IDebugService, @IContextViewService private readonly contextViewService: IContextViewService, @IThemeService private readonly themeService: IThemeService ) { } abstract get templateId(): string; renderTemplate(container: HTMLElement): IExpressionTemplateData { const expression = dom.append(container, $('.expression')); const name = dom.append(expression, $('span.name')); const value = dom.append(expression, $('span.value')); const lazyButton = dom.append(expression, $('span.lazy-button')); lazyButton.classList.add(...Codicon.eye.classNamesArray); const label = new HighlightedLabel(name); const inputBoxContainer = dom.append(expression, $('.inputBoxContainer')); const templateDisposable = new DisposableStore(); let actionBar: ActionBar | undefined; if (this.renderActionBar) { dom.append(expression, $('.span.actionbar-spacer')); actionBar = templateDisposable.add(new ActionBar(expression)); } const template: IExpressionTemplateData = { expression, name, value, label, inputBoxContainer, actionBar, elementDisposable: [], templateDisposable, lazyButton, currentElement: undefined }; templateDisposable.add(dom.addDisposableListener(lazyButton, dom.EventType.CLICK, () => { if (template.currentElement) { this.debugService.getViewModel().evaluateLazyExpression(template.currentElement); } })); return template; } renderElement(node: ITreeNode<IExpression, FuzzyScore>, index: number, data: IExpressionTemplateData): void { const { element } = node; data.currentElement = element; this.renderExpression(element, data, createMatches(node.filterData)); if (data.actionBar) { this.renderActionBar!(data.actionBar, element, data); } const selectedExpression = this.debugService.getViewModel().getSelectedExpression(); if (element === selectedExpression?.expression || (element instanceof Variable && element.errorMessage)) { const options = this.getInputBoxOptions(element, !!selectedExpression?.settingWatch); if (options) { data.elementDisposable.push(this.renderInputBox(data.name, data.value, data.inputBoxContainer, options)); } } } renderInputBox(nameElement: HTMLElement, valueElement: HTMLElement, inputBoxContainer: HTMLElement, options: IInputBoxOptions): IDisposable { nameElement.style.display = 'none'; valueElement.style.display = 'none'; inputBoxContainer.style.display = 'initial'; const inputBox = new InputBox(inputBoxContainer, this.contextViewService, options); const styler = attachInputBoxStyler(inputBox, this.themeService); inputBox.value = options.initialValue; inputBox.focus(); inputBox.select(); const done = once((success: boolean, finishEditing: boolean) => { nameElement.style.display = ''; valueElement.style.display = ''; inputBoxContainer.style.display = 'none'; const value = inputBox.value; dispose(toDispose); if (finishEditing) { this.debugService.getViewModel().setSelectedExpression(undefined, false); options.onFinish(value, success); } }); const toDispose = [ inputBox, dom.addStandardDisposableListener(inputBox.inputElement, dom.EventType.KEY_DOWN, (e: IKeyboardEvent) => { const isEscape = e.equals(KeyCode.Escape); const isEnter = e.equals(KeyCode.Enter); if (isEscape || isEnter) { e.preventDefault(); e.stopPropagation(); done(isEnter, true); } }), dom.addDisposableListener(inputBox.inputElement, dom.EventType.BLUR, () => { done(true, true); }), dom.addDisposableListener(inputBox.inputElement, dom.EventType.CLICK, e => { // Do not expand / collapse selected elements e.preventDefault(); e.stopPropagation(); }), styler ]; return toDisposable(() => { done(false, false); }); } protected abstract renderExpression(expression: IExpression, data: IExpressionTemplateData, highlights: IHighlight[]): void; protected abstract getInputBoxOptions(expression: IExpression, settingValue: boolean): IInputBoxOptions | undefined; protected renderActionBar?(actionBar: ActionBar, expression: IExpression, data: IExpressionTemplateData): void; disposeElement(node: ITreeNode<IExpression, FuzzyScore>, index: number, templateData: IExpressionTemplateData): void { dispose(templateData.elementDisposable); templateData.elementDisposable = []; } disposeTemplate(templateData: IExpressionTemplateData): void { dispose(templateData.elementDisposable); templateData.templateDisposable.dispose(); } }
src/vs/workbench/contrib/debug/browser/baseDebugView.ts
1
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.9984070658683777, 0.07494110614061356, 0.0001604995777597651, 0.00017179727728944272, 0.2609555423259735 ]
{ "id": 1, "code_window": [ "\t\tconst lazyButton = dom.append(expression, $('span.lazy-button'));\n", "\t\tlazyButton.classList.add(...Codicon.eye.classNamesArray);\n", "\n", "\t\tconst label = new HighlightedLabel(name);\n", "\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst value = dom.append(expression, $('span.value'));\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/baseDebugView.ts", "type": "add", "edit_start_line_idx": 162 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { parentOriginHash } from 'vs/workbench/browser/webview'; suite('parentOriginHash', () => { test('localhost 1', async () => { const hash = await parentOriginHash('http://localhost:9888', '123456'); assert.strictEqual(hash, '0fnsiac2jaup1t266qekgr7iuj4pnm31gf8r0h1o6k2lvvmfh6hk'); }); test('localhost 2', async () => { const hash = await parentOriginHash('http://localhost:9888', '123457'); assert.strictEqual(hash, '07shf01bmdfrghk96voldpletbh36vj7blnl4td8kdq1sej5kjqs'); }); test('localhost 3', async () => { const hash = await parentOriginHash('http://localhost:9887', '123456'); assert.strictEqual(hash, '1v1128i162q0nee9l89360sqan26u3pdnjrkke5ijd0sel8sbtqf'); }); });
src/vs/workbench/test/browser/webview.test.ts
0
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.00017677109281066805, 0.00017381682118866593, 0.00017158577975351363, 0.00017309362010564655, 0.0000021777884740004083 ]
{ "id": 1, "code_window": [ "\t\tconst lazyButton = dom.append(expression, $('span.lazy-button'));\n", "\t\tlazyButton.classList.add(...Codicon.eye.classNamesArray);\n", "\n", "\t\tconst label = new HighlightedLabel(name);\n", "\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst value = dom.append(expression, $('span.value'));\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/baseDebugView.ts", "type": "add", "edit_start_line_idx": 162 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IListService, WorkbenchList } from 'vs/platform/list/browser/listService'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { ITerminalGroupService, ITerminalInstance, ITerminalService, TerminalDataTransfers } from 'vs/workbench/contrib/terminal/browser/terminal'; import { localize } from 'vs/nls'; import * as DOM from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { MenuItemAction } from 'vs/platform/actions/common/actions'; import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { ITerminalBackend, TerminalCommandId } from 'vs/workbench/contrib/terminal/common/terminal'; import { TerminalLocation, TerminalSettingId } from 'vs/platform/terminal/common/terminal'; import { Codicon } from 'vs/base/common/codicons'; import { Action } from 'vs/base/common/actions'; import { MarkdownString } from 'vs/base/common/htmlContent'; import { TerminalDecorationsProvider } from 'vs/workbench/contrib/terminal/browser/terminalDecorationsProvider'; import { DEFAULT_LABELS_CONTAINER, IResourceLabel, ResourceLabels } from 'vs/workbench/browser/labels'; import { IDecorationsService } from 'vs/workbench/services/decorations/common/decorations'; import { IHoverAction, IHoverService } from 'vs/workbench/services/hover/browser/hover'; import Severity from 'vs/base/common/severity'; import { Disposable, DisposableStore, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { IListDragAndDrop, IListDragOverReaction, IListRenderer, ListDragOverEffect } from 'vs/base/browser/ui/list/list'; import { DataTransfers, IDragAndDropData } from 'vs/base/browser/dnd'; import { disposableTimeout } from 'vs/base/common/async'; import { ElementsDragAndDropData, NativeDragAndDropData } from 'vs/base/browser/ui/list/listView'; import { URI } from 'vs/base/common/uri'; import { getColorClass, getIconId, getUriClasses } from 'vs/workbench/contrib/terminal/browser/terminalIcon'; import { IEditableData } from 'vs/workbench/common/views'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { InputBox, MessageType } from 'vs/base/browser/ui/inputbox/inputBox'; import { once } from 'vs/base/common/functional'; import { attachInputBoxStyler } from 'vs/platform/theme/common/styler'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { KeyCode } from 'vs/base/common/keyCodes'; import { CodeDataTransfers, containsDragType } from 'vs/workbench/browser/dnd'; import { terminalStrings } from 'vs/workbench/contrib/terminal/common/terminalStrings'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { IProcessDetails } from 'vs/platform/terminal/common/terminalProcess'; import { TerminalContextKeys } from 'vs/workbench/contrib/terminal/common/terminalContextKey'; import { getTerminalResourcesFromDragEvent, parseTerminalUri } from 'vs/workbench/contrib/terminal/browser/terminalUri'; import { getShellIntegrationTooltip } from 'vs/workbench/contrib/terminal/browser/terminalTooltip'; const $ = DOM.$; export const enum TerminalTabsListSizes { TabHeight = 22, NarrowViewWidth = 46, WideViewMinimumWidth = 80, DefaultWidth = 120, MidpointViewWidth = (TerminalTabsListSizes.NarrowViewWidth + TerminalTabsListSizes.WideViewMinimumWidth) / 2, ActionbarMinimumWidth = 105, MaximumWidth = 500 } export class TerminalTabList extends WorkbenchList<ITerminalInstance> { private _decorationsProvider: TerminalDecorationsProvider | undefined; private _terminalTabsSingleSelectedContextKey: IContextKey<boolean>; private _isSplitContextKey: IContextKey<boolean>; constructor( container: HTMLElement, @IContextKeyService contextKeyService: IContextKeyService, @IListService listService: IListService, @IThemeService themeService: IThemeService, @IConfigurationService private readonly _configurationService: IConfigurationService, @IKeybindingService keybindingService: IKeybindingService, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, @IInstantiationService instantiationService: IInstantiationService, @IDecorationsService decorationsService: IDecorationsService, @IThemeService private readonly _themeService: IThemeService, @ILifecycleService lifecycleService: ILifecycleService, ) { super('TerminalTabsList', container, { getHeight: () => TerminalTabsListSizes.TabHeight, getTemplateId: () => 'terminal.tabs' }, [instantiationService.createInstance(TerminalTabsRenderer, container, instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER), () => this.getSelectedElements())], { horizontalScrolling: false, supportDynamicHeights: false, selectionNavigation: true, identityProvider: { getId: e => e?.instanceId }, accessibilityProvider: instantiationService.createInstance(TerminalTabsAccessibilityProvider), smoothScrolling: _configurationService.getValue<boolean>('workbench.list.smoothScrolling'), multipleSelectionSupport: true, additionalScrollHeight: TerminalTabsListSizes.TabHeight, dnd: instantiationService.createInstance(TerminalTabsDragAndDrop), openOnSingleClick: true }, contextKeyService, listService, themeService, _configurationService, keybindingService, ); const instanceDisposables: IDisposable[] = [ this._terminalGroupService.onDidChangeInstances(() => this.refresh()), this._terminalGroupService.onDidChangeGroups(() => this.refresh()), this._terminalGroupService.onDidShow(() => this.refresh()), this._terminalGroupService.onDidChangeInstanceCapability(() => this.refresh()), this._terminalService.onDidChangeInstanceTitle(() => this.refresh()), this._terminalService.onDidChangeInstanceIcon(() => this.refresh()), this._terminalService.onDidChangeInstancePrimaryStatus(() => this.refresh()), this._terminalService.onDidChangeConnectionState(() => this.refresh()), this._themeService.onDidColorThemeChange(() => this.refresh()), this._terminalGroupService.onDidChangeActiveInstance(e => { if (e) { const i = this._terminalGroupService.instances.indexOf(e); this.setSelection([i]); this.reveal(i); } this.refresh(); }) ]; // Dispose of instance listeners on shutdown to avoid extra work and so tabs don't disappear // briefly lifecycleService.onWillShutdown(e => { dispose(instanceDisposables); }); this.onMouseDblClick(async e => { const focus = this.getFocus(); if (focus.length === 0) { const instance = await this._terminalService.createTerminal({ location: TerminalLocation.Panel }); this._terminalGroupService.setActiveInstance(instance); await instance.focusWhenReady(); } if (this._getFocusMode() === 'doubleClick' && this.getFocus().length === 1) { e.element?.focus(true); } }); // on left click, if focus mode = single click, focus the element // unless multi-selection is in progress this.onMouseClick(async e => { if (e.browserEvent.altKey && e.element) { await this._terminalService.createTerminal({ location: { parentTerminal: e.element } }); } else if (this._getFocusMode() === 'singleClick') { if (this.getSelection().length <= 1) { e.element?.focus(true); } } }); // on right click, set the focus to that element // unless multi-selection is in progress this.onContextMenu(e => { if (!e.element) { this.setSelection([]); return; } const selection = this.getSelectedElements(); if (!selection || !selection.find(s => e.element === s)) { this.setFocus(e.index !== undefined ? [e.index] : []); } }); this._terminalTabsSingleSelectedContextKey = TerminalContextKeys.tabsSingularSelection.bindTo(contextKeyService); this._isSplitContextKey = TerminalContextKeys.splitTerminal.bindTo(contextKeyService); this.onDidChangeSelection(e => this._updateContextKey()); this.onDidChangeFocus(() => this._updateContextKey()); this.onDidOpen(async e => { const instance = e.element; if (!instance) { return; } this._terminalGroupService.setActiveInstance(instance); if (!e.editorOptions.preserveFocus) { await instance.focusWhenReady(); } }); if (!this._decorationsProvider) { this._decorationsProvider = instantiationService.createInstance(TerminalDecorationsProvider); decorationsService.registerDecorationsProvider(this._decorationsProvider); } this.refresh(); } private _getFocusMode(): 'singleClick' | 'doubleClick' { return this._configurationService.getValue<'singleClick' | 'doubleClick'>(TerminalSettingId.TabsFocusMode); } refresh(cancelEditing: boolean = true): void { if (cancelEditing && this._terminalService.isEditable(undefined)) { this.domFocus(); } this.splice(0, this.length, this._terminalGroupService.instances.slice()); } private _updateContextKey() { this._terminalTabsSingleSelectedContextKey.set(this.getSelectedElements().length === 1); const instance = this.getFocusedElements(); this._isSplitContextKey.set(instance.length > 0 && this._terminalGroupService.instanceIsSplit(instance[0])); } } class TerminalTabsRenderer implements IListRenderer<ITerminalInstance, ITerminalTabEntryTemplate> { templateId = 'terminal.tabs'; constructor( private readonly _container: HTMLElement, private readonly _labels: ResourceLabels, private readonly _getSelection: () => ITerminalInstance[], @IInstantiationService private readonly _instantiationService: IInstantiationService, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, @IHoverService private readonly _hoverService: IHoverService, @IConfigurationService private readonly _configurationService: IConfigurationService, @IKeybindingService private readonly _keybindingService: IKeybindingService, @IListService private readonly _listService: IListService, @IThemeService private readonly _themeService: IThemeService, @IContextViewService private readonly _contextViewService: IContextViewService ) { } renderTemplate(container: HTMLElement): ITerminalTabEntryTemplate { const element = DOM.append(container, $('.terminal-tabs-entry')); const context: { hoverActions?: IHoverAction[] } = {}; const label = this._labels.create(element, { supportHighlights: true, supportDescriptionHighlights: true, supportIcons: true, hoverDelegate: { delay: this._configurationService.getValue<number>('workbench.hover.delay'), showHover: options => { return this._hoverService.showHover({ ...options, actions: context.hoverActions, hideOnHover: true }); } } }); const actionsContainer = DOM.append(label.element, $('.actions')); const actionBar = new ActionBar(actionsContainer, { actionViewItemProvider: action => action instanceof MenuItemAction ? this._instantiationService.createInstance(MenuEntryActionViewItem, action, undefined) : undefined }); return { element, label, actionBar, context }; } shouldHideText(): boolean { return this._container ? this._container.clientWidth < TerminalTabsListSizes.MidpointViewWidth : false; } shouldHideActionBar(): boolean { return this._container ? this._container.clientWidth <= TerminalTabsListSizes.ActionbarMinimumWidth : false; } renderElement(instance: ITerminalInstance, index: number, template: ITerminalTabEntryTemplate): void { const hasText = !this.shouldHideText(); const group = this._terminalGroupService.getGroupForInstance(instance); if (!group) { throw new Error(`Could not find group for instance "${instance.instanceId}"`); } template.element.classList.toggle('has-text', hasText); template.element.classList.toggle('is-active', this._terminalGroupService.activeInstance === instance); let prefix: string = ''; if (group.terminalInstances.length > 1) { const terminalIndex = group.terminalInstances.indexOf(instance); if (terminalIndex === 0) { prefix = `┌ `; } else if (terminalIndex === group!.terminalInstances.length - 1) { prefix = `└ `; } else { prefix = `├ `; } } let statusString = ''; const statuses = instance.statusList.statuses; template.context.hoverActions = []; for (const status of statuses) { statusString += `\n\n---\n\n${status.icon ? `$(${status.icon?.id}) ` : ''}${status.tooltip || status.id}`; if (status.hoverActions) { template.context.hoverActions.push(...status.hoverActions); } } const shellIntegrationString = getShellIntegrationTooltip(instance, true); const iconId = getIconId(instance); const hasActionbar = !this.shouldHideActionBar(); let label: string = ''; if (!hasText) { const primaryStatus = instance.statusList.primary; // Don't show ignore severity if (primaryStatus && primaryStatus.severity > Severity.Ignore) { label = `${prefix}$(${primaryStatus.icon?.id || iconId})`; } else { label = `${prefix}$(${iconId})`; } } else { this.fillActionBar(instance, template); label = prefix; // Only add the title if the icon is set, this prevents the title jumping around for // example when launching with a ShellLaunchConfig.name and no icon if (instance.icon) { label += `$(${iconId}) ${instance.title}`; } } if (!hasActionbar) { template.actionBar.clear(); } if (!template.elementDisposables) { template.elementDisposables = new DisposableStore(); } // Kill terminal on middle click template.elementDisposables.add(DOM.addDisposableListener(template.element, DOM.EventType.AUXCLICK, e => { e.stopImmediatePropagation(); if (e.button === 1/*middle*/) { this._terminalService.safeDisposeTerminal(instance); } })); const extraClasses: string[] = []; const colorClass = getColorClass(instance); if (colorClass) { extraClasses.push(colorClass); } const uriClasses = getUriClasses(instance, this._themeService.getColorTheme().type); if (uriClasses) { extraClasses.push(...uriClasses); } template.label.setResource({ resource: instance.resource, name: label, description: hasText ? instance.description : undefined }, { fileDecorations: { colors: true, badges: hasText }, title: { markdown: new MarkdownString(instance.title + shellIntegrationString + statusString, { supportThemeIcons: true }), markdownNotSupportedFallback: undefined }, extraClasses }); const editableData = this._terminalService.getEditableData(instance); template.label.element.classList.toggle('editable-tab', !!editableData); if (editableData) { template.elementDisposables.add(this._renderInputBox(template.label.element.querySelector('.monaco-icon-label-container')!, instance, editableData)); template.actionBar.clear(); } } private _renderInputBox(container: HTMLElement, instance: ITerminalInstance, editableData: IEditableData): IDisposable { const value = instance.title || ''; const inputBox = new InputBox(container, this._contextViewService, { validationOptions: { validation: (value) => { const message = editableData.validationMessage(value); if (!message || message.severity !== Severity.Error) { return null; } return { content: message.content, formatContent: true, type: MessageType.ERROR }; } }, ariaLabel: localize('terminalInputAriaLabel', "Type terminal name. Press Enter to confirm or Escape to cancel.") }); const styler = attachInputBoxStyler(inputBox, this._themeService); inputBox.element.style.height = '22px'; inputBox.value = value; inputBox.focus(); inputBox.select({ start: 0, end: value.length }); const done = once((success: boolean, finishEditing: boolean) => { inputBox.element.style.display = 'none'; const value = inputBox.value; dispose(toDispose); inputBox.element.remove(); if (finishEditing) { editableData.onFinish(value, success); } }); const showInputBoxNotification = () => { if (inputBox.isInputValid()) { const message = editableData.validationMessage(inputBox.value); if (message) { inputBox.showMessage({ content: message.content, formatContent: true, type: message.severity === Severity.Info ? MessageType.INFO : message.severity === Severity.Warning ? MessageType.WARNING : MessageType.ERROR }); } else { inputBox.hideMessage(); } } }; showInputBoxNotification(); const toDispose = [ inputBox, DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: IKeyboardEvent) => { e.stopPropagation(); if (e.equals(KeyCode.Enter)) { done(inputBox.isInputValid(), true); } else if (e.equals(KeyCode.Escape)) { done(false, true); } }), DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_UP, (e: IKeyboardEvent) => { showInputBoxNotification(); }), DOM.addDisposableListener(inputBox.inputElement, DOM.EventType.BLUR, () => { done(inputBox.isInputValid(), true); }), styler ]; return toDisposable(() => { done(false, false); }); } disposeElement(instance: ITerminalInstance, index: number, templateData: ITerminalTabEntryTemplate): void { templateData.elementDisposables?.dispose(); templateData.elementDisposables = undefined; } disposeTemplate(templateData: ITerminalTabEntryTemplate): void { templateData.elementDisposables?.dispose(); templateData.elementDisposables = undefined; templateData.label.dispose(); } fillActionBar(instance: ITerminalInstance, template: ITerminalTabEntryTemplate): void { // If the instance is within the selection, split all selected const actions = [ new Action(TerminalCommandId.SplitInstance, terminalStrings.split.short, ThemeIcon.asClassName(Codicon.splitHorizontal), true, async () => { this._runForSelectionOrInstance(instance, async e => { this._terminalService.createTerminal({ location: { parentTerminal: e } }); }); }), new Action(TerminalCommandId.KillInstance, terminalStrings.kill.short, ThemeIcon.asClassName(Codicon.trashcan), true, async () => { this._runForSelectionOrInstance(instance, e => this._terminalService.safeDisposeTerminal(e)); }) ]; // TODO: Cache these in a way that will use the correct instance template.actionBar.clear(); for (const action of actions) { template.actionBar.push(action, { icon: true, label: false, keybinding: this._keybindingService.lookupKeybinding(action.id)?.getLabel() }); } } private _runForSelectionOrInstance(instance: ITerminalInstance, callback: (instance: ITerminalInstance) => void) { const selection = this._getSelection(); if (selection.includes(instance)) { for (const s of selection) { if (s) { callback(s); } } } else { callback(instance); } this._terminalGroupService.focusTabs(); this._listService.lastFocusedList?.focusNext(); } } interface ITerminalTabEntryTemplate { element: HTMLElement; label: IResourceLabel; actionBar: ActionBar; context: { hoverActions?: IHoverAction[]; }; elementDisposables?: DisposableStore; } class TerminalTabsAccessibilityProvider implements IListAccessibilityProvider<ITerminalInstance> { constructor( @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, ) { } getWidgetAriaLabel(): string { return localize('terminal.tabs', "Terminal tabs"); } getAriaLabel(instance: ITerminalInstance): string { let ariaLabel: string = ''; const tab = this._terminalGroupService.getGroupForInstance(instance); if (tab && tab.terminalInstances?.length > 1) { const terminalIndex = tab.terminalInstances.indexOf(instance); ariaLabel = localize({ key: 'splitTerminalAriaLabel', comment: [ `The terminal's ID`, `The terminal's title`, `The terminal's split number`, `The terminal group's total split number` ] }, "Terminal {0} {1}, split {2} of {3}", instance.instanceId, instance.title, terminalIndex + 1, tab.terminalInstances.length); } else { ariaLabel = localize({ key: 'terminalAriaLabel', comment: [ `The terminal's ID`, `The terminal's title` ] }, "Terminal {0} {1}", instance.instanceId, instance.title); } return ariaLabel; } } class TerminalTabsDragAndDrop implements IListDragAndDrop<ITerminalInstance> { private _autoFocusInstance: ITerminalInstance | undefined; private _autoFocusDisposable: IDisposable = Disposable.None; private _primaryBackend: ITerminalBackend | undefined; constructor( @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, ) { this._primaryBackend = this._terminalService.getPrimaryBackend(); } getDragURI(instance: ITerminalInstance): string | null { return instance.resource.toString(); } getDragLabel?(elements: ITerminalInstance[], originalEvent: DragEvent): string | undefined { return elements.length === 1 ? elements[0].title : undefined; } onDragLeave() { this._autoFocusInstance = undefined; this._autoFocusDisposable.dispose(); this._autoFocusDisposable = Disposable.None; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { if (!originalEvent.dataTransfer) { return; } const dndData: unknown = data.getData(); if (!Array.isArray(dndData)) { return; } // Attach terminals type to event const terminals: ITerminalInstance[] = dndData.filter(e => 'instanceId' in (e as any)); if (terminals.length > 0) { originalEvent.dataTransfer.setData(TerminalDataTransfers.Terminals, JSON.stringify(terminals.map(e => e.resource.toString()))); } } onDragOver(data: IDragAndDropData, targetInstance: ITerminalInstance | undefined, targetIndex: number | undefined, originalEvent: DragEvent): boolean | IListDragOverReaction { if (data instanceof NativeDragAndDropData) { if (!containsDragType(originalEvent, DataTransfers.FILES, DataTransfers.RESOURCES, TerminalDataTransfers.Terminals, CodeDataTransfers.FILES)) { return false; } } const didChangeAutoFocusInstance = this._autoFocusInstance !== targetInstance; if (didChangeAutoFocusInstance) { this._autoFocusDisposable.dispose(); this._autoFocusInstance = targetInstance; } if (!targetInstance && !containsDragType(originalEvent, TerminalDataTransfers.Terminals)) { return data instanceof ElementsDragAndDropData; } if (didChangeAutoFocusInstance && targetInstance) { this._autoFocusDisposable = disposableTimeout(() => { this._terminalService.setActiveInstance(targetInstance); this._autoFocusInstance = undefined; }, 500); } return { feedback: targetIndex ? [targetIndex] : undefined, accept: true, effect: ListDragOverEffect.Move }; } async drop(data: IDragAndDropData, targetInstance: ITerminalInstance | undefined, targetIndex: number | undefined, originalEvent: DragEvent): Promise<void> { this._autoFocusDisposable.dispose(); this._autoFocusInstance = undefined; let sourceInstances: ITerminalInstance[] | undefined; let promises: Promise<IProcessDetails | undefined>[] = []; const resources = getTerminalResourcesFromDragEvent(originalEvent); if (resources) { for (const uri of resources) { const instance = this._terminalService.getInstanceFromResource(uri); if (instance) { sourceInstances = [instance]; this._terminalService.moveToTerminalView(instance); } else if (this._primaryBackend) { const terminalIdentifier = parseTerminalUri(uri); if (terminalIdentifier.instanceId) { promises.push(this._primaryBackend.requestDetachInstance(terminalIdentifier.workspaceId, terminalIdentifier.instanceId)); } } } } if (promises.length) { let processes = await Promise.all(promises); processes = processes.filter(p => p !== undefined); let lastInstance: ITerminalInstance | undefined; for (const attachPersistentProcess of processes) { lastInstance = await this._terminalService.createTerminal({ config: { attachPersistentProcess } }); } if (lastInstance) { this._terminalService.setActiveInstance(lastInstance); } return; } if (sourceInstances === undefined) { if (!(data instanceof ElementsDragAndDropData)) { this._handleExternalDrop(targetInstance, originalEvent); return; } const draggedElement = data.getData(); if (!draggedElement || !Array.isArray(draggedElement)) { return; } sourceInstances = []; for (const e of draggedElement) { if ('instanceId' in e) { sourceInstances.push(e as ITerminalInstance); } } } if (!targetInstance) { this._terminalGroupService.moveGroupToEnd(sourceInstances[0]); return; } let focused = false; for (const instance of sourceInstances) { this._terminalGroupService.moveGroup(instance, targetInstance); if (!focused) { this._terminalService.setActiveInstance(instance); focused = true; } } } private async _handleExternalDrop(instance: ITerminalInstance | undefined, e: DragEvent) { if (!instance || !e.dataTransfer) { return; } // Check if files were dragged from the tree explorer let path: string | undefined; const rawResources = e.dataTransfer.getData(DataTransfers.RESOURCES); if (rawResources) { path = URI.parse(JSON.parse(rawResources)[0]).fsPath; } const rawCodeFiles = e.dataTransfer.getData(CodeDataTransfers.FILES); if (!path && rawCodeFiles) { path = URI.file(JSON.parse(rawCodeFiles)[0]).fsPath; } if (!path && e.dataTransfer.files.length > 0 && e.dataTransfer.files[0].path /* Electron only */) { // Check if the file was dragged from the filesystem path = URI.file(e.dataTransfer.files[0].path).fsPath; } if (!path) { return; } this._terminalService.setActiveInstance(instance); instance.focus(); await instance.sendPath(path, false); } }
src/vs/workbench/contrib/terminal/browser/terminalTabsList.ts
0
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.5269572138786316, 0.007464787922799587, 0.00016470084665343165, 0.00017176649998873472, 0.06122393161058426 ]
{ "id": 1, "code_window": [ "\t\tconst lazyButton = dom.append(expression, $('span.lazy-button'));\n", "\t\tlazyButton.classList.add(...Codicon.eye.classNamesArray);\n", "\n", "\t\tconst label = new HighlightedLabel(name);\n", "\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst value = dom.append(expression, $('span.value'));\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/baseDebugView.ts", "type": "add", "edit_start_line_idx": 162 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check 'use strict'; // Delete `VSCODE_CWD` very early even before // importing bootstrap files. We have seen // reports where `code .` would use the wrong // current working directory due to our variable // somehow escaping to the parent shell // (https://github.com/microsoft/vscode/issues/126399) delete process.env['VSCODE_CWD']; const bootstrap = require('./bootstrap'); const bootstrapNode = require('./bootstrap-node'); const product = require('../product.json'); // Avoid Monkey Patches from Application Insights bootstrap.avoidMonkeyPatchFromAppInsights(); // Enable portable support bootstrapNode.configurePortable(product); // Enable ASAR support bootstrap.enableASARSupport(); // Signal processes that we got launched as CLI process.env['VSCODE_CLI'] = '1'; // Load CLI through AMD loader require('./bootstrap-amd').load('vs/code/node/cli');
src/cli.js
0
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.00017662887694314122, 0.00017236825078725815, 0.00016850519750732929, 0.00017216945707332343, 0.000002961652626254363 ]
{ "id": 2, "code_window": [ "\n", ".monaco-workbench .monaco-list-row .expression.lazy .lazy-button {\n", "\tdisplay: inline;\n", "}\n", "\n", ".monaco-workbench .monaco-list-row .expression.lazy .value {\n", "\tdisplay: none;\n", "}\n", "\n", ".monaco-workbench .debug-inline-value {\n", "\tbackground-color: var(--vscode-editor-inlineValuesBackground);\n", "\tcolor: var(--vscode-editor-inlineValuesForeground);\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/media/debug.contribution.css", "type": "replace", "edit_start_line_idx": 132 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { HighlightedLabel, IHighlight } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; import { IInputValidationOptions, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { Codicon } from 'vs/base/common/codicons'; import { createMatches, FuzzyScore } from 'vs/base/common/filters'; import { once } from 'vs/base/common/functional'; import { KeyCode } from 'vs/base/common/keyCodes'; import { DisposableStore, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { attachInputBoxStyler } from 'vs/platform/theme/common/styler'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector'; import { IDebugService, IExpression, IExpressionContainer } from 'vs/workbench/contrib/debug/common/debug'; import { Expression, ExpressionContainer, Variable } from 'vs/workbench/contrib/debug/common/debugModel'; import { ReplEvaluationResult } from 'vs/workbench/contrib/debug/common/replModel'; export const MAX_VALUE_RENDER_LENGTH_IN_VIEWLET = 1024; export const twistiePixels = 20; const booleanRegex = /^(true|false)$/i; const stringRegex = /^(['"]).*\1$/; const $ = dom.$; export interface IRenderValueOptions { showChanged?: boolean; maxValueLength?: number; showHover?: boolean; colorize?: boolean; linkDetector?: LinkDetector; } export interface IVariableTemplateData { expression: HTMLElement; name: HTMLElement; value: HTMLElement; label: HighlightedLabel; lazyButton: HTMLElement; } export function renderViewTree(container: HTMLElement): HTMLElement { const treeContainer = $('.'); treeContainer.classList.add('debug-view-content'); container.appendChild(treeContainer); return treeContainer; } export function renderExpressionValue(expressionOrValue: IExpressionContainer | string, container: HTMLElement, options: IRenderValueOptions): void { let value = typeof expressionOrValue === 'string' ? expressionOrValue : expressionOrValue.value; // remove stale classes container.className = 'value'; // when resolving expressions we represent errors from the server as a variable with name === null. if (value === null || ((expressionOrValue instanceof Expression || expressionOrValue instanceof Variable || expressionOrValue instanceof ReplEvaluationResult) && !expressionOrValue.available)) { container.classList.add('unavailable'); if (value !== Expression.DEFAULT_VALUE) { container.classList.add('error'); } } else if ((expressionOrValue instanceof ExpressionContainer) && options.showChanged && expressionOrValue.valueChanged && value !== Expression.DEFAULT_VALUE) { // value changed color has priority over other colors. container.className = 'value changed'; expressionOrValue.valueChanged = false; } if (options.colorize && typeof expressionOrValue !== 'string') { if (expressionOrValue.type === 'number' || expressionOrValue.type === 'boolean' || expressionOrValue.type === 'string') { container.classList.add(expressionOrValue.type); } else if (!isNaN(+value)) { container.classList.add('number'); } else if (booleanRegex.test(value)) { container.classList.add('boolean'); } else if (stringRegex.test(value)) { container.classList.add('string'); } } if (options.maxValueLength && value && value.length > options.maxValueLength) { value = value.substring(0, options.maxValueLength) + '...'; } if (!value) { value = ''; } if (options.linkDetector) { container.textContent = ''; const session = (expressionOrValue instanceof ExpressionContainer) ? expressionOrValue.getSession() : undefined; container.appendChild(options.linkDetector.linkify(value, false, session ? session.root : undefined)); } else { container.textContent = value; } if (options.showHover) { container.title = value || ''; } } export function renderVariable(variable: Variable, data: IVariableTemplateData, showChanged: boolean, highlights: IHighlight[], linkDetector?: LinkDetector): void { if (variable.available) { let text = variable.name; if (variable.value && typeof variable.name === 'string') { text += ':'; } data.label.set(text, highlights, variable.type ? variable.type : variable.name); data.name.classList.toggle('virtual', variable.presentationHint?.kind === 'virtual'); data.name.classList.toggle('internal', variable.presentationHint?.visibility === 'internal'); } else if (variable.value && typeof variable.name === 'string' && variable.name) { data.label.set(':'); } data.expression.classList.toggle('lazy', !!variable.presentationHint?.lazy); data.lazyButton.title = variable.presentationHint?.lazy ? variable.value : ''; renderExpressionValue(variable, data.value, { showChanged, maxValueLength: MAX_VALUE_RENDER_LENGTH_IN_VIEWLET, showHover: true, colorize: true, linkDetector }); } export interface IInputBoxOptions { initialValue: string; ariaLabel: string; placeholder?: string; validationOptions?: IInputValidationOptions; onFinish: (value: string, success: boolean) => void; } export interface IExpressionTemplateData { expression: HTMLElement; name: HTMLSpanElement; value: HTMLSpanElement; inputBoxContainer: HTMLElement; actionBar?: ActionBar; elementDisposable: IDisposable[]; templateDisposable: IDisposable; label: HighlightedLabel; lazyButton: HTMLElement; currentElement: IExpression | undefined; } export abstract class AbstractExpressionsRenderer implements ITreeRenderer<IExpression, FuzzyScore, IExpressionTemplateData> { constructor( @IDebugService protected debugService: IDebugService, @IContextViewService private readonly contextViewService: IContextViewService, @IThemeService private readonly themeService: IThemeService ) { } abstract get templateId(): string; renderTemplate(container: HTMLElement): IExpressionTemplateData { const expression = dom.append(container, $('.expression')); const name = dom.append(expression, $('span.name')); const value = dom.append(expression, $('span.value')); const lazyButton = dom.append(expression, $('span.lazy-button')); lazyButton.classList.add(...Codicon.eye.classNamesArray); const label = new HighlightedLabel(name); const inputBoxContainer = dom.append(expression, $('.inputBoxContainer')); const templateDisposable = new DisposableStore(); let actionBar: ActionBar | undefined; if (this.renderActionBar) { dom.append(expression, $('.span.actionbar-spacer')); actionBar = templateDisposable.add(new ActionBar(expression)); } const template: IExpressionTemplateData = { expression, name, value, label, inputBoxContainer, actionBar, elementDisposable: [], templateDisposable, lazyButton, currentElement: undefined }; templateDisposable.add(dom.addDisposableListener(lazyButton, dom.EventType.CLICK, () => { if (template.currentElement) { this.debugService.getViewModel().evaluateLazyExpression(template.currentElement); } })); return template; } renderElement(node: ITreeNode<IExpression, FuzzyScore>, index: number, data: IExpressionTemplateData): void { const { element } = node; data.currentElement = element; this.renderExpression(element, data, createMatches(node.filterData)); if (data.actionBar) { this.renderActionBar!(data.actionBar, element, data); } const selectedExpression = this.debugService.getViewModel().getSelectedExpression(); if (element === selectedExpression?.expression || (element instanceof Variable && element.errorMessage)) { const options = this.getInputBoxOptions(element, !!selectedExpression?.settingWatch); if (options) { data.elementDisposable.push(this.renderInputBox(data.name, data.value, data.inputBoxContainer, options)); } } } renderInputBox(nameElement: HTMLElement, valueElement: HTMLElement, inputBoxContainer: HTMLElement, options: IInputBoxOptions): IDisposable { nameElement.style.display = 'none'; valueElement.style.display = 'none'; inputBoxContainer.style.display = 'initial'; const inputBox = new InputBox(inputBoxContainer, this.contextViewService, options); const styler = attachInputBoxStyler(inputBox, this.themeService); inputBox.value = options.initialValue; inputBox.focus(); inputBox.select(); const done = once((success: boolean, finishEditing: boolean) => { nameElement.style.display = ''; valueElement.style.display = ''; inputBoxContainer.style.display = 'none'; const value = inputBox.value; dispose(toDispose); if (finishEditing) { this.debugService.getViewModel().setSelectedExpression(undefined, false); options.onFinish(value, success); } }); const toDispose = [ inputBox, dom.addStandardDisposableListener(inputBox.inputElement, dom.EventType.KEY_DOWN, (e: IKeyboardEvent) => { const isEscape = e.equals(KeyCode.Escape); const isEnter = e.equals(KeyCode.Enter); if (isEscape || isEnter) { e.preventDefault(); e.stopPropagation(); done(isEnter, true); } }), dom.addDisposableListener(inputBox.inputElement, dom.EventType.BLUR, () => { done(true, true); }), dom.addDisposableListener(inputBox.inputElement, dom.EventType.CLICK, e => { // Do not expand / collapse selected elements e.preventDefault(); e.stopPropagation(); }), styler ]; return toDisposable(() => { done(false, false); }); } protected abstract renderExpression(expression: IExpression, data: IExpressionTemplateData, highlights: IHighlight[]): void; protected abstract getInputBoxOptions(expression: IExpression, settingValue: boolean): IInputBoxOptions | undefined; protected renderActionBar?(actionBar: ActionBar, expression: IExpression, data: IExpressionTemplateData): void; disposeElement(node: ITreeNode<IExpression, FuzzyScore>, index: number, templateData: IExpressionTemplateData): void { dispose(templateData.elementDisposable); templateData.elementDisposable = []; } disposeTemplate(templateData: IExpressionTemplateData): void { dispose(templateData.elementDisposable); templateData.templateDisposable.dispose(); } }
src/vs/workbench/contrib/debug/browser/baseDebugView.ts
1
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.0006616240134462714, 0.00019256120140198618, 0.00016272073844447732, 0.00016953566228039563, 0.00009371105261379853 ]
{ "id": 2, "code_window": [ "\n", ".monaco-workbench .monaco-list-row .expression.lazy .lazy-button {\n", "\tdisplay: inline;\n", "}\n", "\n", ".monaco-workbench .monaco-list-row .expression.lazy .value {\n", "\tdisplay: none;\n", "}\n", "\n", ".monaco-workbench .debug-inline-value {\n", "\tbackground-color: var(--vscode-editor-inlineValuesBackground);\n", "\tcolor: var(--vscode-editor-inlineValuesForeground);\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/media/debug.contribution.css", "type": "replace", "edit_start_line_idx": 132 }
test/** cgmanifest.json
extensions/csharp/.vscodeignore
0
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.00017421577649656683, 0.00017421577649656683, 0.00017421577649656683, 0.00017421577649656683, 0 ]
{ "id": 2, "code_window": [ "\n", ".monaco-workbench .monaco-list-row .expression.lazy .lazy-button {\n", "\tdisplay: inline;\n", "}\n", "\n", ".monaco-workbench .monaco-list-row .expression.lazy .value {\n", "\tdisplay: none;\n", "}\n", "\n", ".monaco-workbench .debug-inline-value {\n", "\tbackground-color: var(--vscode-editor-inlineValuesBackground);\n", "\tcolor: var(--vscode-editor-inlineValuesForeground);\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/media/debug.contribution.css", "type": "replace", "edit_start_line_idx": 132 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Event, Emitter } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ILogService } from 'vs/platform/log/common/log'; import { ITimelineService, TimelineChangeEvent, TimelineOptions, TimelineProvidersChangeEvent, TimelineProvider, TimelinePaneId } from './timeline'; import { IViewsService } from 'vs/workbench/common/views'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; export const TimelineHasProviderContext = new RawContextKey<boolean>('timelineHasProvider', false); export class TimelineService implements ITimelineService { declare readonly _serviceBrand: undefined; private readonly _onDidChangeProviders = new Emitter<TimelineProvidersChangeEvent>(); readonly onDidChangeProviders: Event<TimelineProvidersChangeEvent> = this._onDidChangeProviders.event; private readonly _onDidChangeTimeline = new Emitter<TimelineChangeEvent>(); readonly onDidChangeTimeline: Event<TimelineChangeEvent> = this._onDidChangeTimeline.event; private readonly _onDidChangeUri = new Emitter<URI>(); readonly onDidChangeUri: Event<URI> = this._onDidChangeUri.event; private readonly hasProviderContext: IContextKey<boolean>; private readonly providers = new Map<string, TimelineProvider>(); private readonly providerSubscriptions = new Map<string, IDisposable>(); constructor( @ILogService private readonly logService: ILogService, @IViewsService protected viewsService: IViewsService, @IConfigurationService protected configurationService: IConfigurationService, @IContextKeyService protected contextKeyService: IContextKeyService, ) { this.hasProviderContext = TimelineHasProviderContext.bindTo(this.contextKeyService); this.updateHasProviderContext(); } getSources() { return [...this.providers.values()].map(p => ({ id: p.id, label: p.label })); } getTimeline(id: string, uri: URI, options: TimelineOptions, tokenSource: CancellationTokenSource) { this.logService.trace(`TimelineService#getTimeline(${id}): uri=${uri.toString()}`); const provider = this.providers.get(id); if (provider === undefined) { return undefined; } if (typeof provider.scheme === 'string') { if (provider.scheme !== '*' && provider.scheme !== uri.scheme) { return undefined; } } else if (!provider.scheme.includes(uri.scheme)) { return undefined; } return { result: provider.provideTimeline(uri, options, tokenSource.token) .then(result => { if (result === undefined) { return undefined; } result.items = result.items.map(item => ({ ...item, source: provider.id })); result.items.sort((a, b) => (b.timestamp - a.timestamp) || b.source.localeCompare(a.source, undefined, { numeric: true, sensitivity: 'base' })); return result; }), options: options, source: provider.id, tokenSource: tokenSource, uri: uri }; } registerTimelineProvider(provider: TimelineProvider): IDisposable { this.logService.trace(`TimelineService#registerTimelineProvider: id=${provider.id}`); const id = provider.id; const existing = this.providers.get(id); if (existing) { // For now to deal with https://github.com/microsoft/vscode/issues/89553 allow any overwritting here (still will be blocked in the Extension Host) // TODO@eamodio: Ultimately will need to figure out a way to unregister providers when the Extension Host restarts/crashes // throw new Error(`Timeline Provider ${id} already exists.`); try { existing?.dispose(); } catch { } } this.providers.set(id, provider); this.updateHasProviderContext(); if (provider.onDidChange) { this.providerSubscriptions.set(id, provider.onDidChange(e => this._onDidChangeTimeline.fire(e))); } this._onDidChangeProviders.fire({ added: [id] }); return { dispose: () => { this.providers.delete(id); this._onDidChangeProviders.fire({ removed: [id] }); } }; } unregisterTimelineProvider(id: string): void { this.logService.trace(`TimelineService#unregisterTimelineProvider: id=${id}`); if (!this.providers.has(id)) { return; } this.providers.delete(id); this.providerSubscriptions.delete(id); this.updateHasProviderContext(); this._onDidChangeProviders.fire({ removed: [id] }); } setUri(uri: URI) { this.viewsService.openView(TimelinePaneId, true); this._onDidChangeUri.fire(uri); } private updateHasProviderContext() { this.hasProviderContext.set(this.providers.size !== 0); } }
src/vs/workbench/contrib/timeline/common/timelineService.ts
0
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.0001749207149259746, 0.00016983147361315787, 0.00016250474436674267, 0.00017076177755370736, 0.000003592547955122427 ]
{ "id": 2, "code_window": [ "\n", ".monaco-workbench .monaco-list-row .expression.lazy .lazy-button {\n", "\tdisplay: inline;\n", "}\n", "\n", ".monaco-workbench .monaco-list-row .expression.lazy .value {\n", "\tdisplay: none;\n", "}\n", "\n", ".monaco-workbench .debug-inline-value {\n", "\tbackground-color: var(--vscode-editor-inlineValuesBackground);\n", "\tcolor: var(--vscode-editor-inlineValuesForeground);\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/media/debug.contribution.css", "type": "replace", "edit_start_line_idx": 132 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module 'vscode' { // https://github.com/microsoft/vscode/issues/124024 @hediet @alexdima export interface InlineCompletionItemNew { /** * If set to `true`, unopened closing brackets are removed and unclosed opening brackets are closed. * Defaults to `false`. */ completeBracketPairs?: boolean; } export interface InlineCompletionItemProviderNew { // eslint-disable-next-line vscode-dts-provider-naming handleDidShowCompletionItem?(completionItem: InlineCompletionItemNew): void; } }
src/vscode-dts/vscode.proposed.inlineCompletionsAdditions.d.ts
0
https://github.com/microsoft/vscode/commit/f2e6fe3b863d076a36a69b410ad29cf6729cf777
[ 0.0001704855967545882, 0.00016767818306107074, 0.00016519219207111746, 0.0001673567749094218, 0.000002172941549360985 ]
{ "id": 0, "code_window": [ " addVariableCTA: Components.CallToActionCard.button('Add variable'),\n", " addVariableCTAV2: Components.CallToActionCard.buttonV2('Add variable'),\n", " newButton: 'Variable editor New variable button',\n", " table: 'Variable editor Table',\n", " tableRowNameFields: (variableName: string) => `Variable editor Table Name field ${variableName}`,\n", " tableRowDescriptionFields: (variableName: string) =>\n", " `Variable editor Table Description field ${variableName}`,\n", " tableRowArrowUpButtons: (variableName: string) => `Variable editor Table ArrowUp button ${variableName}`,\n", " tableRowArrowDownButtons: (variableName: string) => `Variable editor Table ArrowDown button ${variableName}`,\n", " tableRowDuplicateButtons: (variableName: string) => `Variable editor Table Duplicate button ${variableName}`,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " tableRowDefinitionFields: (variableName: string) => `Variable editor Table Definition field ${variableName}`,\n" ], "file_path": "packages/grafana-e2e-selectors/src/selectors/pages.ts", "type": "replace", "edit_start_line_idx": 116 }
import { css } from '@emotion/css'; import React, { ReactElement } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { reportInteraction } from '@grafana/runtime'; import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui'; import { isAdHoc } from '../guard'; import { VariableUsagesButton } from '../inspect/VariableUsagesButton'; import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils'; import { KeyedVariableIdentifier } from '../state/types'; import { VariableModel } from '../types'; import { toKeyedVariableIdentifier } from '../utils'; export interface VariableEditorListRowProps { index: number; variable: VariableModel; usageTree: VariableUsageTree[]; usagesNetwork: UsagesToNetwork[]; onEdit: (identifier: KeyedVariableIdentifier) => void; onDuplicate: (identifier: KeyedVariableIdentifier) => void; onDelete: (identifier: KeyedVariableIdentifier) => void; } export function VariableEditorListRow({ index, variable, usageTree, usagesNetwork, onEdit: propsOnEdit, onDuplicate: propsOnDuplicate, onDelete: propsOnDelete, }: VariableEditorListRowProps): ReactElement { const theme = useTheme2(); const styles = useStyles2(getStyles); const usages = getVariableUsages(variable.id, usageTree); const passed = usages > 0 || isAdHoc(variable); const identifier = toKeyedVariableIdentifier(variable); return ( <Draggable draggableId={JSON.stringify(identifier)} index={index}> {(provided, snapshot) => ( <tr ref={provided.innerRef} {...provided.draggableProps} style={{ userSelect: snapshot.isDragging ? 'none' : 'auto', background: snapshot.isDragging ? theme.colors.background.secondary : undefined, ...provided.draggableProps.style, }} > <td role="gridcell" className={styles.column}> <Button size="xs" fill="text" onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} className={styles.nameLink} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowNameFields(variable.name)} > {variable.name} </Button> </td> <td role="gridcell" className={styles.descriptionColumn} onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)} > {variable.description} </td> <td role="gridcell" className={styles.column}> <VariableCheckIndicator passed={passed} /> </td> <td role="gridcell" className={styles.column}> <VariableUsagesButton id={variable.id} isAdhoc={isAdHoc(variable)} usages={usagesNetwork} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Duplicate variable'); propsOnDuplicate(identifier); }} name="copy" tooltip="Duplicate variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDuplicateButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Delete variable'); propsOnDelete(identifier); }} name="trash-alt" tooltip="Remove variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowRemoveButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <div {...provided.dragHandleProps} className={styles.dragHandle}> <Icon name="draggabledots" size="lg" /> </div> </td> </tr> )} </Draggable> ); } interface VariableCheckIndicatorProps { passed: boolean; } function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement { const styles = useStyles2(getStyles); if (passed) { return ( <Icon name="check" className={styles.iconPassed} title="This variable is referenced by other variables or dashboard." /> ); } return ( <Icon name="exclamation-triangle" className={styles.iconFailed} title="This variable is not referenced by any variable or dashboard." /> ); } function getStyles(theme: GrafanaTheme2) { return { dragHandle: css` cursor: grab; `, column: css` width: 1%; `, nameLink: css` cursor: pointer; color: ${theme.colors.primary.text}; `, descriptionColumn: css` width: 100%; max-width: 200px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; white-space: nowrap; `, iconPassed: css` color: ${theme.v1.palette.greenBase}; `, iconFailed: css` color: ${theme.v1.palette.orange}; `, }; }
public/app/features/variables/editor/VariableEditorListRow.tsx
1
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.011412597261369228, 0.0016836491413414478, 0.00016423258057329804, 0.00017020624363794923, 0.003137947292998433 ]
{ "id": 0, "code_window": [ " addVariableCTA: Components.CallToActionCard.button('Add variable'),\n", " addVariableCTAV2: Components.CallToActionCard.buttonV2('Add variable'),\n", " newButton: 'Variable editor New variable button',\n", " table: 'Variable editor Table',\n", " tableRowNameFields: (variableName: string) => `Variable editor Table Name field ${variableName}`,\n", " tableRowDescriptionFields: (variableName: string) =>\n", " `Variable editor Table Description field ${variableName}`,\n", " tableRowArrowUpButtons: (variableName: string) => `Variable editor Table ArrowUp button ${variableName}`,\n", " tableRowArrowDownButtons: (variableName: string) => `Variable editor Table ArrowDown button ${variableName}`,\n", " tableRowDuplicateButtons: (variableName: string) => `Variable editor Table Duplicate button ${variableName}`,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " tableRowDefinitionFields: (variableName: string) => `Variable editor Table Definition field ${variableName}`,\n" ], "file_path": "packages/grafana-e2e-selectors/src/selectors/pages.ts", "type": "replace", "edit_start_line_idx": 116 }
import { Observable, of } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { AnnotationEvent, DataSourceApi } from '@grafana/data'; import { executeAnnotationQuery } from '../../../annotations/executeAnnotationQuery'; import { PanelModel } from '../../../dashboard/state'; import { AnnotationQueryRunner, AnnotationQueryRunnerOptions } from './types'; import { handleAnnotationQueryRunnerError } from './utils'; export class AnnotationsQueryRunner implements AnnotationQueryRunner { canRun(datasource?: DataSourceApi): boolean { if (!datasource) { return false; } return Boolean(!datasource.annotationQuery || datasource.annotations); } run({ annotation, datasource, dashboard, range }: AnnotationQueryRunnerOptions): Observable<AnnotationEvent[]> { if (!this.canRun(datasource)) { return of([]); } const panel: PanelModel = {} as unknown as PanelModel; // deliberate setting panel to empty object because executeAnnotationQuery shouldn't depend on panelModel return executeAnnotationQuery({ dashboard, range, panel }, datasource!, annotation).pipe( map((result) => { return result.events ?? []; }), catchError(handleAnnotationQueryRunnerError) ); } }
public/app/features/query/state/DashboardQueryRunner/AnnotationsQueryRunner.ts
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.0001735904806992039, 0.0001695292303338647, 0.00016518871416337788, 0.0001696688705123961, 0.000003058682068513008 ]
{ "id": 0, "code_window": [ " addVariableCTA: Components.CallToActionCard.button('Add variable'),\n", " addVariableCTAV2: Components.CallToActionCard.buttonV2('Add variable'),\n", " newButton: 'Variable editor New variable button',\n", " table: 'Variable editor Table',\n", " tableRowNameFields: (variableName: string) => `Variable editor Table Name field ${variableName}`,\n", " tableRowDescriptionFields: (variableName: string) =>\n", " `Variable editor Table Description field ${variableName}`,\n", " tableRowArrowUpButtons: (variableName: string) => `Variable editor Table ArrowUp button ${variableName}`,\n", " tableRowArrowDownButtons: (variableName: string) => `Variable editor Table ArrowDown button ${variableName}`,\n", " tableRowDuplicateButtons: (variableName: string) => `Variable editor Table Duplicate button ${variableName}`,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " tableRowDefinitionFields: (variableName: string) => `Variable editor Table Definition field ${variableName}`,\n" ], "file_path": "packages/grafana-e2e-selectors/src/selectors/pages.ts", "type": "replace", "edit_start_line_idx": 116 }
//go:build ignore // +build ignore //go:generate go run gen.go package main import ( "context" "fmt" "io/fs" "os" "path/filepath" "regexp" "sort" "strings" "cuelang.org/go/cue/errors" "github.com/grafana/codejen" "github.com/grafana/cuetsy" "github.com/grafana/kindsys" "github.com/grafana/grafana/pkg/codegen" "github.com/grafana/grafana/pkg/cuectx" ) func main() { if len(os.Args) > 1 { fmt.Fprintf(os.Stderr, "plugin thema code generator does not currently accept any arguments\n, got %q", os.Args) os.Exit(1) } // Core kinds composite code generator. Produces all generated code in // grafana/grafana that derives from core kinds. coreKindsGen := codejen.JennyListWithNamer(func(def kindsys.Kind) string { return def.Props().Common().MachineName }) // All the jennies that comprise the core kinds generator pipeline coreKindsGen.Append( &codegen.ResourceGoTypesJenny{}, &codegen.SubresourceGoTypesJenny{}, codegen.CoreKindJenny(cuectx.GoCoreKindParentPath, nil), codegen.BaseCoreRegistryJenny(filepath.Join("pkg", "registry", "corekind"), cuectx.GoCoreKindParentPath), codegen.LatestMajorsOrXJenny( cuectx.TSCoreKindParentPath, true, // forcing group so that we ignore the top level resource (for now) codegen.TSResourceJenny{}), codegen.TSVeneerIndexJenny(filepath.Join("packages", "grafana-schema", "src")), codegen.DocsJenny(filepath.Join("docs", "sources", "developers", "kinds", "core")), ) header := codegen.SlashHeaderMapper("kinds/gen.go") coreKindsGen.AddPostprocessors(header) cwd, err := os.Getwd() if err != nil { fmt.Fprintf(os.Stderr, "could not get working directory: %s", err) os.Exit(1) } groot := filepath.Dir(cwd) rt := cuectx.GrafanaThemaRuntime() var all []kindsys.Kind f := os.DirFS(filepath.Join(groot, cuectx.CoreDefParentPath)) kinddirs := elsedie(fs.ReadDir(f, "."))("error reading core kind fs root directory") for _, kinddir := range kinddirs { if !kinddir.IsDir() { continue } rel := filepath.Join(cuectx.CoreDefParentPath, kinddir.Name()) def, err := cuectx.LoadCoreKindDef(rel, rt.Context(), nil) if err != nil { die(fmt.Errorf("%s is not a valid kind: %s", rel, errors.Details(err, nil))) } if def.Properties.MachineName != kinddir.Name() { die(fmt.Errorf("%s: kind's machine name (%s) must equal parent dir name (%s)", rel, def.Properties.Name, kinddir.Name())) } all = append(all, elsedie(kindsys.BindCore(rt, def))(rel)) } sort.Slice(all, func(i, j int) bool { return nameFor(all[i].Props()) < nameFor(all[j].Props()) }) jfs, err := coreKindsGen.GenerateFS(all...) if err != nil { die(fmt.Errorf("core kinddirs codegen failed: %w", err)) } commfsys := elsedie(genCommon(filepath.Join(groot, "pkg", "kindsys")))("common schemas failed") commfsys = elsedie(commfsys.Map(header))("failed gen header on common fsys") if err = jfs.Merge(commfsys); err != nil { die(err) } if _, set := os.LookupEnv("CODEGEN_VERIFY"); set { if err = jfs.Verify(context.Background(), groot); err != nil { die(fmt.Errorf("generated code is out of sync with inputs:\n%s\nrun `make gen-cue` to regenerate", err)) } } else if err = jfs.Write(context.Background(), groot); err != nil { die(fmt.Errorf("error while writing generated code to disk:\n%s", err)) } } func nameFor(m kindsys.SomeKindProperties) string { switch x := m.(type) { case kindsys.CoreProperties: return x.Name case kindsys.CustomProperties: return x.Name case kindsys.ComposableProperties: return x.Name default: // unreachable so long as all the possibilities in KindProperties have switch branches panic("unreachable") } } type dummyCommonJenny struct{} func genCommon(kp string) (*codejen.FS, error) { fsys := codejen.NewFS() // kp := filepath.Join("pkg", "kindsys") path := filepath.Join("packages", "grafana-schema", "src", "common") // Grab all the common_* files from kindsys and load them in dfsys := os.DirFS(kp) matches := elsedie(fs.Glob(dfsys, "common_*.cue"))("could not glob kindsys cue files") for _, fname := range matches { fpath := filepath.Join(path, strings.TrimPrefix(fname, "common_")) fpath = fpath[:len(fpath)-4] + "_gen.cue" data := elsedie(fs.ReadFile(dfsys, fname))("error reading " + fname) _ = fsys.Add(*codejen.NewFile(fpath, data, dummyCommonJenny{})) } fsys = elsedie(fsys.Map(packageMapper))("failed remapping fs") v, err := cuectx.BuildGrafanaInstance(nil, path, "", nil) if err != nil { return nil, err } b := elsedie(cuetsy.Generate(v, cuetsy.Config{ Export: true, }))("failed to generate common schema TS") _ = fsys.Add(*codejen.NewFile(filepath.Join(path, "common.gen.ts"), b, dummyCommonJenny{})) return fsys, nil } func (j dummyCommonJenny) JennyName() string { return "CommonSchemaJenny" } func (j dummyCommonJenny) Generate(dummy any) ([]codejen.File, error) { return nil, nil } var pkgReplace = regexp.MustCompile("^package kindsys") func packageMapper(f codejen.File) (codejen.File, error) { f.Data = pkgReplace.ReplaceAllLiteral(f.Data, []byte("package common")) return f, nil } func elsedie[T any](t T, err error) func(msg string) T { if err != nil { return func(msg string) T { fmt.Fprintf(os.Stderr, "%s: %s\n", msg, err) os.Exit(1) return t } } return func(msg string) T { return t } } func die(err error) { fmt.Fprint(os.Stderr, err, "\n") os.Exit(1) }
kinds/gen.go
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017533601203467697, 0.00016993057215586305, 0.00016563554527238011, 0.00017054723866749555, 0.0000028016481792292325 ]
{ "id": 0, "code_window": [ " addVariableCTA: Components.CallToActionCard.button('Add variable'),\n", " addVariableCTAV2: Components.CallToActionCard.buttonV2('Add variable'),\n", " newButton: 'Variable editor New variable button',\n", " table: 'Variable editor Table',\n", " tableRowNameFields: (variableName: string) => `Variable editor Table Name field ${variableName}`,\n", " tableRowDescriptionFields: (variableName: string) =>\n", " `Variable editor Table Description field ${variableName}`,\n", " tableRowArrowUpButtons: (variableName: string) => `Variable editor Table ArrowUp button ${variableName}`,\n", " tableRowArrowDownButtons: (variableName: string) => `Variable editor Table ArrowDown button ${variableName}`,\n", " tableRowDuplicateButtons: (variableName: string) => `Variable editor Table Duplicate button ${variableName}`,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " tableRowDefinitionFields: (variableName: string) => `Variable editor Table Definition field ${variableName}`,\n" ], "file_path": "packages/grafana-e2e-selectors/src/selectors/pages.ts", "type": "replace", "edit_start_line_idx": 116 }
package sqlstash import ( "context" "database/sql" "encoding/json" "fmt" "strconv" "strings" "time" "github.com/grafana/grafana/pkg/infra/appcontext" "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/slugify" "github.com/grafana/grafana/pkg/services/grpcserver" "github.com/grafana/grafana/pkg/services/sqlstore/session" "github.com/grafana/grafana/pkg/services/store" "github.com/grafana/grafana/pkg/services/store/entity" "github.com/grafana/grafana/pkg/services/store/kind" "github.com/grafana/grafana/pkg/services/store/resolver" "github.com/grafana/grafana/pkg/setting" ) // Make sure we implement both store + admin var _ entity.EntityStoreServer = &sqlEntityServer{} var _ entity.EntityStoreAdminServer = &sqlEntityServer{} func ProvideSQLEntityServer(db db.DB, cfg *setting.Cfg, grpcServerProvider grpcserver.Provider, kinds kind.KindRegistry, resolver resolver.EntityReferenceResolver) entity.EntityStoreServer { entityServer := &sqlEntityServer{ sess: db.GetSqlxSession(), log: log.New("sql-entity-server"), kinds: kinds, resolver: resolver, } entity.RegisterEntityStoreServer(grpcServerProvider.GetServer(), entityServer) return entityServer } type sqlEntityServer struct { log log.Logger sess *session.SessionDB kinds kind.KindRegistry resolver resolver.EntityReferenceResolver } func getReadSelect(r *entity.ReadEntityRequest) string { fields := []string{ "tenant_id", "kind", "uid", "folder", // GRN + folder "version", "size", "etag", "errors", // errors are always returned "created_at", "created_by", "updated_at", "updated_by", "origin", "origin_key", "origin_ts"} if r.WithBody { fields = append(fields, `body`) } if r.WithSummary { fields = append(fields, "name", "slug", "description", "labels", "fields") } return "SELECT " + strings.Join(fields, ",") + " FROM entity WHERE " } func (s *sqlEntityServer) rowToReadEntityResponse(ctx context.Context, rows *sql.Rows, r *entity.ReadEntityRequest) (*entity.Entity, error) { raw := &entity.Entity{ GRN: &entity.GRN{}, Origin: &entity.EntityOriginInfo{}, } summaryjson := &summarySupport{} args := []interface{}{ &raw.GRN.TenantId, &raw.GRN.Kind, &raw.GRN.UID, &raw.Folder, &raw.Version, &raw.Size, &raw.ETag, &summaryjson.errors, &raw.CreatedAt, &raw.CreatedBy, &raw.UpdatedAt, &raw.UpdatedBy, &raw.Origin.Source, &raw.Origin.Key, &raw.Origin.Time, } if r.WithBody { args = append(args, &raw.Body) } if r.WithSummary { args = append(args, &summaryjson.name, &summaryjson.slug, &summaryjson.description, &summaryjson.labels, &summaryjson.fields) } err := rows.Scan(args...) if err != nil { return nil, err } if raw.Origin.Source == "" { raw.Origin = nil } if r.WithSummary || summaryjson.errors != nil { summary, err := summaryjson.toEntitySummary() if err != nil { return nil, err } js, err := json.Marshal(summary) if err != nil { return nil, err } raw.SummaryJson = js } return raw, nil } func (s *sqlEntityServer) validateGRN(ctx context.Context, grn *entity.GRN) (*entity.GRN, error) { if grn == nil { return nil, fmt.Errorf("missing GRN") } user, err := appcontext.User(ctx) if err != nil { return nil, err } if grn.TenantId == 0 { grn.TenantId = user.OrgID } else if grn.TenantId != user.OrgID { return nil, fmt.Errorf("tenant ID does not match userID") } if grn.Kind == "" { return nil, fmt.Errorf("GRN missing kind") } if grn.UID == "" { return nil, fmt.Errorf("GRN missing UID") } if len(grn.UID) > 40 { return nil, fmt.Errorf("GRN UID is too long (>40)") } if strings.ContainsAny(grn.UID, "/#$@?") { return nil, fmt.Errorf("invalid character in GRN") } return grn, nil } func (s *sqlEntityServer) Read(ctx context.Context, r *entity.ReadEntityRequest) (*entity.Entity, error) { if r.Version != "" { return s.readFromHistory(ctx, r) } grn, err := s.validateGRN(ctx, r.GRN) if err != nil { return nil, err } args := []interface{}{grn.ToGRNString()} where := "grn=?" rows, err := s.sess.Query(ctx, getReadSelect(r)+where, args...) if err != nil { return nil, err } defer func() { _ = rows.Close() }() if !rows.Next() { return &entity.Entity{}, nil } return s.rowToReadEntityResponse(ctx, rows, r) } func (s *sqlEntityServer) readFromHistory(ctx context.Context, r *entity.ReadEntityRequest) (*entity.Entity, error) { grn, err := s.validateGRN(ctx, r.GRN) if err != nil { return nil, err } oid := grn.ToGRNString() fields := []string{ "body", "size", "etag", "updated_at", "updated_by", } rows, err := s.sess.Query(ctx, "SELECT "+strings.Join(fields, ",")+ " FROM entity_history WHERE grn=? AND version=?", oid, r.Version) if err != nil { return nil, err } defer func() { _ = rows.Close() }() // Version or key not found if !rows.Next() { return &entity.Entity{}, nil } raw := &entity.Entity{ GRN: r.GRN, } err = rows.Scan(&raw.Body, &raw.Size, &raw.ETag, &raw.UpdatedAt, &raw.UpdatedBy) if err != nil { return nil, err } // For versioned files, the created+updated are the same raw.CreatedAt = raw.UpdatedAt raw.CreatedBy = raw.UpdatedBy raw.Version = r.Version // from the query // Dynamically create the summary if r.WithSummary { builder := s.kinds.GetSummaryBuilder(r.GRN.Kind) if builder != nil { val, out, err := builder(ctx, r.GRN.UID, raw.Body) if err == nil { raw.Body = out // cleaned up raw.SummaryJson, err = json.Marshal(val) if err != nil { return nil, err } } } } // Clear the body if not requested if !r.WithBody { raw.Body = nil } return raw, err } func (s *sqlEntityServer) BatchRead(ctx context.Context, b *entity.BatchReadEntityRequest) (*entity.BatchReadEntityResponse, error) { if len(b.Batch) < 1 { return nil, fmt.Errorf("missing querires") } first := b.Batch[0] args := []interface{}{} constraints := []string{} for _, r := range b.Batch { if r.WithBody != first.WithBody || r.WithSummary != first.WithSummary { return nil, fmt.Errorf("requests must want the same things") } grn, err := s.validateGRN(ctx, r.GRN) if err != nil { return nil, err } where := "grn=?" args = append(args, grn.ToGRNString()) if r.Version != "" { return nil, fmt.Errorf("version not supported for batch read (yet?)") } constraints = append(constraints, where) } req := b.Batch[0] query := getReadSelect(req) + strings.Join(constraints, " OR ") rows, err := s.sess.Query(ctx, query, args...) if err != nil { return nil, err } defer func() { _ = rows.Close() }() // TODO? make sure the results are in order? rsp := &entity.BatchReadEntityResponse{} for rows.Next() { r, err := s.rowToReadEntityResponse(ctx, rows, req) if err != nil { return nil, err } rsp.Results = append(rsp.Results, r) } return rsp, nil } func (s *sqlEntityServer) Write(ctx context.Context, r *entity.WriteEntityRequest) (*entity.WriteEntityResponse, error) { return s.AdminWrite(ctx, entity.ToAdminWriteEntityRequest(r)) } //nolint:gocyclo func (s *sqlEntityServer) AdminWrite(ctx context.Context, r *entity.AdminWriteEntityRequest) (*entity.WriteEntityResponse, error) { grn, err := s.validateGRN(ctx, r.GRN) if err != nil { return nil, err } oid := grn.ToGRNString() timestamp := time.Now().UnixMilli() createdAt := r.CreatedAt createdBy := r.CreatedBy updatedAt := r.UpdatedAt updatedBy := r.UpdatedBy if updatedBy == "" { modifier, err := appcontext.User(ctx) if err != nil { return nil, err } if modifier == nil { return nil, fmt.Errorf("can not find user in context") } updatedBy = store.GetUserIDString(modifier) } if updatedAt < 1000 { updatedAt = timestamp } summary, body, err := s.prepare(ctx, r) if err != nil { return nil, err } etag := createContentsHash(body) rsp := &entity.WriteEntityResponse{ GRN: grn, Status: entity.WriteEntityResponse_CREATED, // Will be changed if not true } origin := r.Origin if origin == nil { origin = &entity.EntityOriginInfo{} } err = s.sess.WithTransaction(ctx, func(tx *session.SessionTx) error { var versionInfo *entity.EntityVersionInfo isUpdate := false if r.ClearHistory { // Optionally keep the original creation time information if createdAt < 1000 || createdBy == "" { err = s.fillCreationInfo(ctx, tx, oid, &createdAt, &createdBy) if err != nil { return err } } _, err = doDelete(ctx, tx, grn) if err != nil { return err } versionInfo = &entity.EntityVersionInfo{} } else { versionInfo, err = s.selectForUpdate(ctx, tx, oid) if err != nil { return err } } // Same entity if versionInfo.ETag == etag { rsp.Entity = versionInfo rsp.Status = entity.WriteEntityResponse_UNCHANGED return nil } // Optimistic locking if r.PreviousVersion != "" { if r.PreviousVersion != versionInfo.Version { return fmt.Errorf("optimistic lock failed") } } // Set the comment on this write versionInfo.Comment = r.Comment if r.Version == "" { if versionInfo.Version == "" { versionInfo.Version = "1" } else { // Increment the version i, _ := strconv.ParseInt(versionInfo.Version, 0, 64) if i < 1 { i = timestamp } versionInfo.Version = fmt.Sprintf("%d", i+1) isUpdate = true } } else { versionInfo.Version = r.Version } if isUpdate { // Clear the labels+refs if _, err := tx.Exec(ctx, "DELETE FROM entity_labels WHERE grn=? OR parent_grn=?", oid, oid); err != nil { return err } if _, err := tx.Exec(ctx, "DELETE FROM entity_ref WHERE grn=? OR parent_grn=?", oid, oid); err != nil { return err } if _, err := tx.Exec(ctx, "DELETE FROM entity_nested WHERE parent_grn=?", oid); err != nil { return err } } // 1. Add the `entity_history` values versionInfo.Size = int64(len(body)) versionInfo.ETag = etag versionInfo.UpdatedAt = updatedAt versionInfo.UpdatedBy = updatedBy _, err = tx.Exec(ctx, `INSERT INTO entity_history (`+ "grn, version, message, "+ "size, body, etag, "+ "updated_at, updated_by) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", oid, versionInfo.Version, versionInfo.Comment, versionInfo.Size, body, versionInfo.ETag, updatedAt, versionInfo.UpdatedBy, ) if err != nil { return err } // 5. Add/update the main `entity` table rsp.Entity = versionInfo if isUpdate { rsp.Status = entity.WriteEntityResponse_UPDATED _, err = tx.Exec(ctx, "UPDATE entity SET "+ "body=?, size=?, etag=?, version=?, "+ "updated_at=?, updated_by=?,"+ "name=?, description=?,"+ "labels=?, fields=?, errors=?, "+ "origin=?, origin_key=?, origin_ts=? "+ "WHERE grn=?", body, versionInfo.Size, etag, versionInfo.Version, updatedAt, versionInfo.UpdatedBy, summary.model.Name, summary.model.Description, summary.labels, summary.fields, summary.errors, origin.Source, origin.Key, timestamp, oid, ) } else { if createdAt < 1000 { createdAt = updatedAt } if createdBy == "" { createdBy = updatedBy } _, err = tx.Exec(ctx, "INSERT INTO entity ("+ "grn, tenant_id, kind, uid, folder, "+ "size, body, etag, version, "+ "updated_at, updated_by, created_at, created_by, "+ "name, description, slug, "+ "labels, fields, errors, "+ "origin, origin_key, origin_ts) "+ "VALUES (?, ?, ?, ?, ?, "+ " ?, ?, ?, ?, "+ " ?, ?, ?, ?, "+ " ?, ?, ?, "+ " ?, ?, ?, "+ " ?, ?, ?)", oid, grn.TenantId, grn.Kind, grn.UID, r.Folder, versionInfo.Size, body, etag, versionInfo.Version, updatedAt, createdBy, createdAt, createdBy, summary.model.Name, summary.model.Description, summary.model.Slug, summary.labels, summary.fields, summary.errors, origin.Source, origin.Key, origin.Time, ) } if err == nil && entity.StandardKindFolder == r.GRN.Kind { err = updateFolderTree(ctx, tx, grn.TenantId) } if err == nil { summary.folder = r.Folder summary.parent_grn = grn return s.writeSearchInfo(ctx, tx, oid, summary) } return err }) rsp.SummaryJson = summary.marshaled if err != nil { rsp.Status = entity.WriteEntityResponse_ERROR } return rsp, err } func (s *sqlEntityServer) fillCreationInfo(ctx context.Context, tx *session.SessionTx, grn string, createdAt *int64, createdBy *string) error { if *createdAt > 1000 { ignore := int64(0) createdAt = &ignore } if *createdBy == "" { ignore := "" createdBy = &ignore } rows, err := tx.Query(ctx, "SELECT created_at,created_by FROM entity WHERE grn=?", grn) if err != nil { return err } if rows.Next() { err = rows.Scan(&createdAt, &createdBy) } errClose := rows.Close() if err != nil { return err } return errClose } func (s *sqlEntityServer) selectForUpdate(ctx context.Context, tx *session.SessionTx, grn string) (*entity.EntityVersionInfo, error) { q := "SELECT etag,version,updated_at,size FROM entity WHERE grn=?" if false { // TODO, MYSQL/PosgreSQL can lock the row " FOR UPDATE" q += " FOR UPDATE" } rows, err := tx.Query(ctx, q, grn) if err != nil { return nil, err } current := &entity.EntityVersionInfo{} if rows.Next() { err = rows.Scan(&current.ETag, &current.Version, &current.UpdatedAt, &current.Size) } errClose := rows.Close() if err != nil { return nil, err } return current, errClose } func (s *sqlEntityServer) writeSearchInfo( ctx context.Context, tx *session.SessionTx, grn string, summary *summarySupport, ) error { parent_grn := summary.getParentGRN() // Add the labels rows for k, v := range summary.model.Labels { _, err := tx.Exec(ctx, `INSERT INTO entity_labels `+ "(grn, label, value, parent_grn) "+ `VALUES (?, ?, ?, ?)`, grn, k, v, parent_grn, ) if err != nil { return err } } // Resolve references for _, ref := range summary.model.References { resolved, err := s.resolver.Resolve(ctx, ref) if err != nil { return err } _, err = tx.Exec(ctx, `INSERT INTO entity_ref (`+ "grn, parent_grn, family, type, id, "+ "resolved_ok, resolved_to, resolved_warning, resolved_time) "+ `VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, grn, parent_grn, ref.Family, ref.Type, ref.Identifier, resolved.OK, resolved.Key, resolved.Warning, resolved.Timestamp, ) if err != nil { return err } } // Traverse entities and insert refs if summary.model.Nested != nil { for _, childModel := range summary.model.Nested { grn = (&entity.GRN{ TenantId: summary.parent_grn.TenantId, Kind: childModel.Kind, UID: childModel.UID, // append??? }).ToGRNString() child, err := newSummarySupport(childModel) if err != nil { return err } child.isNested = true child.folder = summary.folder child.parent_grn = summary.parent_grn parent_grn := child.getParentGRN() _, err = tx.Exec(ctx, "INSERT INTO entity_nested ("+ "parent_grn, grn, "+ "tenant_id, kind, uid, folder, "+ "name, description, "+ "labels, fields, errors) "+ "VALUES (?, ?,"+ " ?, ?, ?, ?,"+ " ?, ?,"+ " ?, ?, ?)", *parent_grn, grn, summary.parent_grn.TenantId, childModel.Kind, childModel.UID, summary.folder, child.name, child.description, child.labels, child.fields, child.errors, ) if err != nil { return err } err = s.writeSearchInfo(ctx, tx, grn, child) if err != nil { return err } } } return nil } func (s *sqlEntityServer) prepare(ctx context.Context, r *entity.AdminWriteEntityRequest) (*summarySupport, []byte, error) { grn := r.GRN builder := s.kinds.GetSummaryBuilder(grn.Kind) if builder == nil { return nil, nil, fmt.Errorf("unsupported kind") } summary, body, err := builder(ctx, grn.UID, r.Body) if err != nil { return nil, nil, err } // Update a summary based on the name (unless the root suggested one) if summary.Slug == "" { t := summary.Name if t == "" { t = r.GRN.UID } summary.Slug = slugify.Slugify(t) } summaryjson, err := newSummarySupport(summary) if err != nil { return nil, nil, err } return summaryjson, body, nil } func (s *sqlEntityServer) Delete(ctx context.Context, r *entity.DeleteEntityRequest) (*entity.DeleteEntityResponse, error) { grn, err := s.validateGRN(ctx, r.GRN) if err != nil { return nil, err } rsp := &entity.DeleteEntityResponse{} err = s.sess.WithTransaction(ctx, func(tx *session.SessionTx) error { rsp.OK, err = doDelete(ctx, tx, grn) return err }) return rsp, err } func doDelete(ctx context.Context, tx *session.SessionTx, grn *entity.GRN) (bool, error) { str := grn.ToGRNString() results, err := tx.Exec(ctx, "DELETE FROM entity WHERE grn=?", str) if err != nil { return false, err } rows, err := results.RowsAffected() if err != nil { return false, err } // TODO: keep history? would need current version bump, and the "write" would have to get from history _, err = tx.Exec(ctx, "DELETE FROM entity_history WHERE grn=?", str) if err != nil { return false, err } _, err = tx.Exec(ctx, "DELETE FROM entity_labels WHERE grn=? OR parent_grn=?", str, str) if err != nil { return false, err } _, err = tx.Exec(ctx, "DELETE FROM entity_ref WHERE grn=? OR parent_grn=?", str, str) if err != nil { return false, err } _, err = tx.Exec(ctx, "DELETE FROM entity_nested WHERE parent_grn=?", str) if err != nil { return false, err } if grn.Kind == entity.StandardKindFolder { err = updateFolderTree(ctx, tx, grn.TenantId) } return rows > 0, err } func (s *sqlEntityServer) History(ctx context.Context, r *entity.EntityHistoryRequest) (*entity.EntityHistoryResponse, error) { grn, err := s.validateGRN(ctx, r.GRN) if err != nil { return nil, err } oid := grn.ToGRNString() page := "" args := []interface{}{oid} if r.NextPageToken != "" { // args = append(args, r.NextPageToken) // TODO, need to get time from the version // page = "AND updated <= ?" return nil, fmt.Errorf("next page not supported yet") } query := "SELECT version,size,etag,updated_at,updated_by,message \n" + " FROM entity_history \n" + " WHERE grn=? " + page + "\n" + " ORDER BY updated_at DESC LIMIT 100" rows, err := s.sess.Query(ctx, query, args...) if err != nil { return nil, err } defer func() { _ = rows.Close() }() rsp := &entity.EntityHistoryResponse{ GRN: r.GRN, } for rows.Next() { v := &entity.EntityVersionInfo{} err := rows.Scan(&v.Version, &v.Size, &v.ETag, &v.UpdatedAt, &v.UpdatedBy, &v.Comment) if err != nil { return nil, err } rsp.Versions = append(rsp.Versions, v) } return rsp, err } func (s *sqlEntityServer) Search(ctx context.Context, r *entity.EntitySearchRequest) (*entity.EntitySearchResponse, error) { user, err := appcontext.User(ctx) if err != nil { return nil, err } if user == nil { return nil, fmt.Errorf("missing user in context") } if r.NextPageToken != "" || len(r.Sort) > 0 { return nil, fmt.Errorf("not yet supported") } fields := []string{ "grn", "tenant_id", "kind", "uid", "version", "folder", "slug", "errors", // errors are always returned "size", "updated_at", "updated_by", "name", "description", // basic summary } if r.WithBody { fields = append(fields, "body") } if r.WithLabels { fields = append(fields, "labels") } if r.WithFields { fields = append(fields, "fields") } entityQuery := selectQuery{ fields: fields, from: "entity", // the table args: []interface{}{}, limit: r.Limit, oneExtra: true, // request one more than the limit (and show next token if it exists) } entityQuery.addWhere("tenant_id", user.OrgID) if len(r.Kind) > 0 { entityQuery.addWhereIn("kind", r.Kind) } // Folder UID or OID? if r.Folder != "" { entityQuery.addWhere("folder", r.Folder) } if len(r.Labels) > 0 { var args []interface{} var conditions []string for labelKey, labelValue := range r.Labels { args = append(args, labelKey) args = append(args, labelValue) conditions = append(conditions, "(label = ? AND value = ?)") } joinedConditions := strings.Join(conditions, " OR ") query := "SELECT grn FROM entity_labels WHERE " + joinedConditions + " GROUP BY grn HAVING COUNT(label) = ?" args = append(args, len(r.Labels)) entityQuery.addWhereInSubquery("grn", query, args) } query, args := entityQuery.toQuery() rows, err := s.sess.Query(ctx, query, args...) if err != nil { return nil, err } defer func() { _ = rows.Close() }() oid := "" rsp := &entity.EntitySearchResponse{} for rows.Next() { result := &entity.EntitySearchResult{ GRN: &entity.GRN{}, } summaryjson := summarySupport{} args := []interface{}{ &oid, &result.GRN.TenantId, &result.GRN.Kind, &result.GRN.UID, &result.Version, &result.Folder, &result.Slug, &summaryjson.errors, &result.Size, &result.UpdatedAt, &result.UpdatedBy, &result.Name, &summaryjson.description, } if r.WithBody { args = append(args, &result.Body) } if r.WithLabels { args = append(args, &summaryjson.labels) } if r.WithFields { args = append(args, &summaryjson.fields) } err = rows.Scan(args...) if err != nil { return rsp, err } // found one more than requested if int64(len(rsp.Results)) >= entityQuery.limit { // TODO? should this encode start+offset? rsp.NextPageToken = oid break } if summaryjson.description != nil { result.Description = *summaryjson.description } if summaryjson.labels != nil { b := []byte(*summaryjson.labels) err = json.Unmarshal(b, &result.Labels) if err != nil { return rsp, err } } if summaryjson.fields != nil { result.FieldsJson = []byte(*summaryjson.fields) } if summaryjson.errors != nil { result.ErrorJson = []byte(*summaryjson.errors) } rsp.Results = append(rsp.Results, result) } return rsp, err } func (s *sqlEntityServer) Watch(*entity.EntityWatchRequest, entity.EntityStore_WatchServer) error { return fmt.Errorf("unimplemented") }
pkg/services/store/entity/sqlstash/sql_storage_server.go
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017323432257398963, 0.0001684822200331837, 0.0001629068865440786, 0.0001684452872723341, 0.0000022624349185207393 ]
{ "id": 1, "code_window": [ " >\n", " <thead>\n", " <tr>\n", " <th>Variable</th>\n", " <th>Description</th>\n", " <th colSpan={5} />\n", " </tr>\n", " </thead>\n", " <DragDropContext onDragEnd={onDragEnd}>\n", " <Droppable droppableId=\"variables-list\" direction=\"vertical\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <th>Definition</th>\n" ], "file_path": "public/app/features/variables/editor/VariableEditorList.tsx", "type": "replace", "edit_start_line_idx": 61 }
import { css } from '@emotion/css'; import React, { ReactElement } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { reportInteraction } from '@grafana/runtime'; import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui'; import { isAdHoc } from '../guard'; import { VariableUsagesButton } from '../inspect/VariableUsagesButton'; import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils'; import { KeyedVariableIdentifier } from '../state/types'; import { VariableModel } from '../types'; import { toKeyedVariableIdentifier } from '../utils'; export interface VariableEditorListRowProps { index: number; variable: VariableModel; usageTree: VariableUsageTree[]; usagesNetwork: UsagesToNetwork[]; onEdit: (identifier: KeyedVariableIdentifier) => void; onDuplicate: (identifier: KeyedVariableIdentifier) => void; onDelete: (identifier: KeyedVariableIdentifier) => void; } export function VariableEditorListRow({ index, variable, usageTree, usagesNetwork, onEdit: propsOnEdit, onDuplicate: propsOnDuplicate, onDelete: propsOnDelete, }: VariableEditorListRowProps): ReactElement { const theme = useTheme2(); const styles = useStyles2(getStyles); const usages = getVariableUsages(variable.id, usageTree); const passed = usages > 0 || isAdHoc(variable); const identifier = toKeyedVariableIdentifier(variable); return ( <Draggable draggableId={JSON.stringify(identifier)} index={index}> {(provided, snapshot) => ( <tr ref={provided.innerRef} {...provided.draggableProps} style={{ userSelect: snapshot.isDragging ? 'none' : 'auto', background: snapshot.isDragging ? theme.colors.background.secondary : undefined, ...provided.draggableProps.style, }} > <td role="gridcell" className={styles.column}> <Button size="xs" fill="text" onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} className={styles.nameLink} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowNameFields(variable.name)} > {variable.name} </Button> </td> <td role="gridcell" className={styles.descriptionColumn} onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)} > {variable.description} </td> <td role="gridcell" className={styles.column}> <VariableCheckIndicator passed={passed} /> </td> <td role="gridcell" className={styles.column}> <VariableUsagesButton id={variable.id} isAdhoc={isAdHoc(variable)} usages={usagesNetwork} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Duplicate variable'); propsOnDuplicate(identifier); }} name="copy" tooltip="Duplicate variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDuplicateButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Delete variable'); propsOnDelete(identifier); }} name="trash-alt" tooltip="Remove variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowRemoveButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <div {...provided.dragHandleProps} className={styles.dragHandle}> <Icon name="draggabledots" size="lg" /> </div> </td> </tr> )} </Draggable> ); } interface VariableCheckIndicatorProps { passed: boolean; } function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement { const styles = useStyles2(getStyles); if (passed) { return ( <Icon name="check" className={styles.iconPassed} title="This variable is referenced by other variables or dashboard." /> ); } return ( <Icon name="exclamation-triangle" className={styles.iconFailed} title="This variable is not referenced by any variable or dashboard." /> ); } function getStyles(theme: GrafanaTheme2) { return { dragHandle: css` cursor: grab; `, column: css` width: 1%; `, nameLink: css` cursor: pointer; color: ${theme.colors.primary.text}; `, descriptionColumn: css` width: 100%; max-width: 200px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; white-space: nowrap; `, iconPassed: css` color: ${theme.v1.palette.greenBase}; `, iconFailed: css` color: ${theme.v1.palette.orange}; `, }; }
public/app/features/variables/editor/VariableEditorListRow.tsx
1
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.007574939634650946, 0.0006337978411465883, 0.00016501759819220752, 0.00017682957695797086, 0.0016886260127648711 ]
{ "id": 1, "code_window": [ " >\n", " <thead>\n", " <tr>\n", " <th>Variable</th>\n", " <th>Description</th>\n", " <th colSpan={5} />\n", " </tr>\n", " </thead>\n", " <DragDropContext onDragEnd={onDragEnd}>\n", " <Droppable droppableId=\"variables-list\" direction=\"vertical\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <th>Definition</th>\n" ], "file_path": "public/app/features/variables/editor/VariableEditorList.tsx", "type": "replace", "edit_start_line_idx": 61 }
#! /usr/bin/env bash # chkconfig: 2345 80 05 # description: Grafana web server & backend # processname: grafana # config: /etc/grafana/grafana.ini # pidfile: /var/run/grafana.pid ### BEGIN INIT INFO # Provides: grafana # Required-Start: $all # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start grafana at boot time ### END INIT INFO # tested on # 1. New lsb that define start-stop-daemon # 3. Centos with initscripts package installed PATH=/bin:/usr/bin:/sbin:/usr/sbin NAME=grafana-server DESC="Grafana Server" DEFAULT=/etc/sysconfig/$NAME GRAFANA_USER=grafana GRAFANA_GROUP=grafana GRAFANA_HOME=/usr/share/grafana CONF_DIR=/etc/grafana WORK_DIR=$GRAFANA_HOME DATA_DIR=/var/lib/grafana PLUGINS_DIR=/var/lib/grafana/plugins LOG_DIR=/var/log/grafana CONF_FILE=$CONF_DIR/grafana.ini PROVISIONING_CFG_DIR=$CONF_DIR/provisioning MAX_OPEN_FILES=10000 PID_FILE=/var/run/$NAME.pid DAEMON=$GRAFANA_HOME/bin/grafana if [ ! -x $DAEMON ]; then echo "Program not installed or not executable" exit 5 fi # # init.d / servicectl compatibility (openSUSE) # if [ -f /etc/rc.status ]; then . /etc/rc.status rc_reset fi # # Source function library. # if [ -f /etc/rc.d/init.d/functions ]; then . /etc/rc.d/init.d/functions fi # overwrite settings from default file if [ -f "$DEFAULT" ]; then . "$DEFAULT" fi DAEMON_OPTS="server --pidfile=${PID_FILE} --config=${CONF_FILE} --packaging=rpm cfg:default.paths.provisioning=$PROVISIONING_CFG_DIR cfg:default.paths.data=${DATA_DIR} cfg:default.paths.logs=${LOG_DIR} cfg:default.paths.plugins=${PLUGINS_DIR}" function isRunning() { status -p $PID_FILE $NAME > /dev/null 2>&1 } function checkUser() { if [ `id -u` -ne 0 ]; then echo "You need root privileges to run this script" exit 4 fi } case "$1" in start) checkUser isRunning if [ $? -eq 0 ]; then echo "Already running." exit 0 fi # Prepare environment mkdir -p "$LOG_DIR" "$DATA_DIR" && chown "$GRAFANA_USER":"$GRAFANA_GROUP" "$LOG_DIR" "$DATA_DIR" touch "$PID_FILE" && chown "$GRAFANA_USER":"$GRAFANA_GROUP" "$PID_FILE" if [ -n "$MAX_OPEN_FILES" ]; then ulimit -n $MAX_OPEN_FILES fi # Start Daemon cd $GRAFANA_HOME action $"Starting $DESC: ..." su -s /bin/sh -c "nohup ${DAEMON} ${DAEMON_OPTS} >> /dev/null 3>&1 &" $GRAFANA_USER 2> /dev/null return=$? if [ $return -eq 0 ] then sleep 1 # check if pid file has been written to if ! [[ -s $PID_FILE ]]; then echo "FAILED" exit 1 fi i=0 timeout=10 # Wait for the process to be properly started before exiting until { cat "$PID_FILE" | xargs kill -0; } >/dev/null 2>&1 do sleep 1 i=$(($i + 1)) if [ $i -gt $timeout ]; then echo "FAILED" exit 1 fi done fi exit $return ;; stop) checkUser echo -n "Stopping $DESC: ..." if [ -f "$PID_FILE" ]; then killproc -p $PID_FILE -d 20 $NAME if [ $? -eq 1 ]; then echo "$DESC is not running but pid file exists, cleaning up" elif [ $? -eq 3 ]; then PID="`cat $PID_FILE`" echo "Failed to stop $DESC (pid $PID)" exit 1 fi rm -f "$PID_FILE" echo "" exit 0 else echo "(not running)" fi exit 0 ;; status) status -p $PID_FILE $NAME exit $? ;; restart|force-reload) if [ -f "$PID_FILE" ]; then $0 stop sleep 1 fi $0 start ;; *) echo "Usage: $0 {start|stop|restart|force-reload|status}" exit 3 ;; esac
packaging/rpm/init.d/grafana-server
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017620112339500338, 0.0001713578385533765, 0.00016481443890370429, 0.00017211602244060487, 0.000003598209332267288 ]
{ "id": 1, "code_window": [ " >\n", " <thead>\n", " <tr>\n", " <th>Variable</th>\n", " <th>Description</th>\n", " <th colSpan={5} />\n", " </tr>\n", " </thead>\n", " <DragDropContext onDragEnd={onDragEnd}>\n", " <Droppable droppableId=\"variables-list\" direction=\"vertical\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <th>Definition</th>\n" ], "file_path": "public/app/features/variables/editor/VariableEditorList.tsx", "type": "replace", "edit_start_line_idx": 61 }
{ "name": "Google Cloud Monitoring", "type": "datasource", "id": "stackdriver", "category": "cloud", "metrics": true, "alerting": true, "annotations": true, "backend": true, "includes": [ { "type": "dashboard", "name": "Data Processing Monitoring", "path": "dashboards/dataprocessing-monitoring.json" }, { "type": "dashboard", "name": "Cloud Functions Monitoring", "path": "dashboards/cloudfunctions-monitoring.json" }, { "type": "dashboard", "name": "GCE VM Instance Monitoring", "path": "dashboards/gce-vm-instance-monitoring.json" }, { "type": "dashboard", "name": "GKE Prometheus Pod/Node Monitoring", "path": "dashboards/gke-prometheus-pod-node-monitoring.json" }, { "type": "dashboard", "name": "Firewall Insights Monitoring", "path": "dashboards/firewall-insight-monitoring.json" }, { "type": "dashboard", "name": "GCE Network Monitoring", "path": "dashboards/gce-network-monitoring.json" }, { "type": "dashboard", "name": "HTTP/S LB Backend Services", "path": "dashboards/https-lb-backend-services-monitoring.json" }, { "type": "dashboard", "name": "HTTP/S Load Balancer Monitoring", "path": "dashboards/https-loadbalancer-monitoring.json" }, { "type": "dashboard", "name": "Network TCP Load Balancer Monitoring", "path": "dashboards/network-tcp-loadbalancer-monitoring.json" }, { "type": "dashboard", "name": "MicroService Monitoring", "path": "dashboards/micro-service-monitoring.json" }, { "type": "dashboard", "name": "Cloud Storage Monitoring", "path": "dashboards/cloud-storage-monitoring.json" }, { "type": "dashboard", "name": "Cloud SQL Monitoring", "path": "dashboards/cloudsql-monitoring.json" }, { "type": "dashboard", "name": "Cloud SQL(MySQL) Monitoring", "path": "dashboards/cloudsql-mysql-monitoring.json" } ], "queryOptions": { "maxDataPoints": true, "cacheTimeout": true }, "info": { "description": "Data source for Google's monitoring service (formerly named Stackdriver)", "version": "1.0.0", "logos": { "small": "img/cloud_monitoring_logo.svg", "large": "img/cloud_monitoring_logo.svg" }, "author": { "name": "Grafana Labs", "url": "https://grafana.com" } } }
public/app/plugins/datasource/cloud-monitoring/plugin.json
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017336981545668095, 0.00017113426292780787, 0.00016891717677935958, 0.0001710037759039551, 0.0000014824292975390563 ]
{ "id": 1, "code_window": [ " >\n", " <thead>\n", " <tr>\n", " <th>Variable</th>\n", " <th>Description</th>\n", " <th colSpan={5} />\n", " </tr>\n", " </thead>\n", " <DragDropContext onDragEnd={onDragEnd}>\n", " <Droppable droppableId=\"variables-list\" direction=\"vertical\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <th>Definition</th>\n" ], "file_path": "public/app/features/variables/editor/VariableEditorList.tsx", "type": "replace", "edit_start_line_idx": 61 }
import { css } from '@emotion/css'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { Alert, LinkButton, useStyles2 } from '@grafana/ui'; import { ROUTES } from '../../constants'; const getStyles = (theme: GrafanaTheme2) => ({ alertContent: css` display: flex; flex-direction: row; padding: 0; justify-content: space-between; align-items: center; `, alertParagraph: css` margin: 0 ${theme.spacing(1)} 0 0; line-height: ${theme.spacing(theme.components.height.sm)}; `, }); export function ConnectionsRedirectNotice() { const styles = useStyles2(getStyles); return ( <Alert severity="warning" title=""> <div className={styles.alertContent}> <p className={styles.alertParagraph}> Data sources have a new home! You can discover new data sources or manage existing ones in the new Connections page, accessible from the main menu. </p> <LinkButton aria-label="Link to Connections" icon="arrow-right" href={ROUTES.DataSources} fill="text"> Go to connections </LinkButton> </div> </Alert> ); }
public/app/features/connections/components/ConnectionsRedirectNotice/ConnectionsRedirectNotice.tsx
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017877532809507102, 0.00017536216182634234, 0.00017179088899865746, 0.0001754412369336933, 0.0000029261436793603934 ]
{ "id": 2, "code_window": [ "import { GrafanaTheme2 } from '@grafana/data';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { reportInteraction } from '@grafana/runtime';\n", "import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui';\n", "\n", "import { isAdHoc } from '../guard';\n", "import { VariableUsagesButton } from '../inspect/VariableUsagesButton';\n", "import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils';\n", "import { KeyedVariableIdentifier } from '../state/types';\n", "import { VariableModel } from '../types';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { hasOptions, isAdHoc, isQuery } from '../guard';\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import { Components } from './components'; /** * Selectors grouped/defined in Pages * * @alpha */ export const Pages = { Login: { url: '/login', username: 'Username input field', password: 'Password input field', submit: 'Login button', skip: 'Skip change password button', }, Home: { url: '/', }, DataSource: { name: 'Data source settings page name input field', delete: 'Data source settings page Delete button', readOnly: 'Data source settings page read only message', saveAndTest: 'data-testid Data source settings page Save and Test button', alert: 'Data source settings page Alert', }, DataSources: { url: '/datasources', dataSources: (dataSourceName: string) => `Data source list item ${dataSourceName}`, }, EditDataSource: { url: (dataSourceUid: string) => `/datasources/edit/${dataSourceUid}`, settings: 'Datasource settings page basic settings', }, AddDataSource: { url: '/datasources/new', /** @deprecated Use dataSourcePluginsV2 */ dataSourcePlugins: (pluginName: string) => `Data source plugin item ${pluginName}`, dataSourcePluginsV2: (pluginName: string) => `Add new data source ${pluginName}`, }, ConfirmModal: { delete: 'data-testid Confirm Modal Danger Button', }, AddDashboard: { url: '/dashboard/new', itemButton: (title: string) => `data-testid ${title}`, addNewPanel: 'Add new panel', addNewRow: 'Add new row', addNewPanelLibrary: 'Add new panel from panel library', }, Dashboard: { url: (uid: string) => `/d/${uid}`, DashNav: { /** * @deprecated use navV2 from Grafana 8.3 instead */ nav: 'Dashboard navigation', navV2: 'data-testid Dashboard navigation', publicDashboardTag: 'data-testid public dashboard tag', }, SubMenu: { submenu: 'Dashboard submenu', submenuItem: 'data-testid template variable', submenuItemLabels: (item: string) => `data-testid Dashboard template variables submenu Label ${item}`, submenuItemValueDropDownValueLinkTexts: (item: string) => `data-testid Dashboard template variables Variable Value DropDown value link text ${item}`, submenuItemValueDropDownDropDown: 'Variable options', submenuItemValueDropDownOptionTexts: (item: string) => `data-testid Dashboard template variables Variable Value DropDown option text ${item}`, Annotations: { annotationsWrapper: 'data-testid annotation-wrapper', annotationLabel: (label: string) => `data-testid Dashboard annotations submenu Label ${label}`, annotationToggle: (label: string) => `data-testid Dashboard annotations submenu Toggle ${label}`, }, }, Settings: { Actions: { close: 'data-testid dashboard-settings-close', }, General: { deleteDashBoard: 'Dashboard settings page delete dashboard button', sectionItems: (item: string) => `Dashboard settings section item ${item}`, saveDashBoard: 'Dashboard settings aside actions Save button', saveAsDashBoard: 'Dashboard settings aside actions Save As button', /** * @deprecated use components.TimeZonePicker.containerV2 from Grafana 8.3 instead */ timezone: 'Time zone picker select container', title: 'Tab General', }, Annotations: { List: { /** * @deprecated use addAnnotationCTAV2 from Grafana 8.3 instead */ addAnnotationCTA: Components.CallToActionCard.button('Add annotation query'), addAnnotationCTAV2: Components.CallToActionCard.buttonV2('Add annotation query'), }, Settings: { name: 'Annotations settings name input', }, NewAnnotation: { panelFilterSelect: 'data-testid annotations-panel-filter', showInLabel: 'show-in-label', previewInDashboard: 'data-testid annotations-preview', }, }, Variables: { List: { /** * @deprecated use addVariableCTAV2 from Grafana 8.3 instead */ addVariableCTA: Components.CallToActionCard.button('Add variable'), addVariableCTAV2: Components.CallToActionCard.buttonV2('Add variable'), newButton: 'Variable editor New variable button', table: 'Variable editor Table', tableRowNameFields: (variableName: string) => `Variable editor Table Name field ${variableName}`, tableRowDescriptionFields: (variableName: string) => `Variable editor Table Description field ${variableName}`, tableRowArrowUpButtons: (variableName: string) => `Variable editor Table ArrowUp button ${variableName}`, tableRowArrowDownButtons: (variableName: string) => `Variable editor Table ArrowDown button ${variableName}`, tableRowDuplicateButtons: (variableName: string) => `Variable editor Table Duplicate button ${variableName}`, tableRowRemoveButtons: (variableName: string) => `Variable editor Table Remove button ${variableName}`, }, Edit: { General: { headerLink: 'Variable editor Header link', modeLabelNew: 'Variable editor Header mode New', /** * @deprecated */ modeLabelEdit: 'Variable editor Header mode Edit', generalNameInput: 'Variable editor Form Name field', generalNameInputV2: 'data-testid Variable editor Form Name field', generalTypeSelect: 'Variable editor Form Type select', generalTypeSelectV2: 'data-testid Variable editor Form Type select', generalLabelInput: 'Variable editor Form Label field', generalLabelInputV2: 'data-testid Variable editor Form Label field', generalHideSelect: 'Variable editor Form Hide select', generalHideSelectV2: 'data-testid Variable editor Form Hide select', selectionOptionsMultiSwitch: 'Variable editor Form Multi switch', selectionOptionsIncludeAllSwitch: 'Variable editor Form IncludeAll switch', selectionOptionsCustomAllInput: 'Variable editor Form IncludeAll field', selectionOptionsCustomAllInputV2: 'data-testid Variable editor Form IncludeAll field', previewOfValuesOption: 'Variable editor Preview of Values option', submitButton: 'Variable editor Submit button', applyButton: 'data-testid Variable editor Apply button', }, QueryVariable: { queryOptionsDataSourceSelect: Components.DataSourcePicker.container, queryOptionsRefreshSelect: 'Variable editor Form Query Refresh select', queryOptionsRefreshSelectV2: 'data-testid Variable editor Form Query Refresh select', queryOptionsRegExInput: 'Variable editor Form Query RegEx field', queryOptionsRegExInputV2: 'data-testid Variable editor Form Query RegEx field', queryOptionsSortSelect: 'Variable editor Form Query Sort select', queryOptionsSortSelectV2: 'data-testid Variable editor Form Query Sort select', queryOptionsQueryInput: 'Variable editor Form Default Variable Query Editor textarea', valueGroupsTagsEnabledSwitch: 'Variable editor Form Query UseTags switch', valueGroupsTagsTagsQueryInput: 'Variable editor Form Query TagsQuery field', valueGroupsTagsTagsValuesQueryInput: 'Variable editor Form Query TagsValuesQuery field', }, ConstantVariable: { constantOptionsQueryInput: 'Variable editor Form Constant Query field', constantOptionsQueryInputV2: 'data-testid Variable editor Form Constant Query field', }, DatasourceVariable: { datasourceSelect: 'data-testid datasource variable datasource type', }, TextBoxVariable: { textBoxOptionsQueryInput: 'Variable editor Form TextBox Query field', textBoxOptionsQueryInputV2: 'data-testid Variable editor Form TextBox Query field', }, CustomVariable: { customValueInput: 'data-testid custom-variable-input', }, IntervalVariable: { intervalsValueInput: 'data-testid interval variable intervals input', }, }, }, }, Annotations: { marker: 'data-testid annotation-marker', }, }, Dashboards: { url: '/dashboards', /** * @deprecated use components.Search.dashboardItem from Grafana 8.3 instead */ dashboards: (title: string) => `Dashboard search item ${title}`, }, SaveDashboardAsModal: { newName: 'Save dashboard title field', save: 'Save dashboard button', }, SaveDashboardModal: { save: 'Dashboard settings Save Dashboard Modal Save button', saveVariables: 'Dashboard settings Save Dashboard Modal Save variables checkbox', saveTimerange: 'Dashboard settings Save Dashboard Modal Save timerange checkbox', }, SharePanelModal: { linkToRenderedImage: 'Link to rendered image', }, ShareDashboardModal: { shareButton: 'Share dashboard or panel', PublicDashboard: { Tab: 'Tab Public dashboard', WillBePublicCheckbox: 'data-testid public dashboard will be public checkbox', LimitedDSCheckbox: 'data-testid public dashboard limited datasources checkbox', CostIncreaseCheckbox: 'data-testid public dashboard cost may increase checkbox', PauseSwitch: 'data-testid public dashboard pause switch', EnableAnnotationsSwitch: 'data-testid public dashboard on off switch for annotations', CreateButton: 'data-testid public dashboard create button', DeleteButton: 'data-testid public dashboard delete button', CopyUrlInput: 'data-testid public dashboard copy url input', CopyUrlButton: 'data-testid public dashboard copy url button', TemplateVariablesWarningAlert: 'data-testid public dashboard disabled template variables alert', UnsupportedDataSourcesWarningAlert: 'data-testid public dashboard unsupported data sources alert', NoUpsertPermissionsWarningAlert: 'data-testid public dashboard no upsert permissions alert', EnableTimeRangeSwitch: 'data-testid public dashboard on off switch for time range', EmailSharingConfiguration: { Container: 'data-testid email sharing config container', ShareType: 'data-testid public dashboard share type', EmailSharingInput: 'data-testid public dashboard email sharing input', EmailSharingInviteButton: 'data-testid public dashboard email sharing invite button', EmailSharingList: 'data-testid public dashboard email sharing list', DeleteEmail: 'data-testid public dashboard delete email button', ReshareLink: 'data-testid public dashboard reshare link button', }, }, }, PublicDashboard: { page: 'public-dashboard-page', NotAvailable: { container: 'public-dashboard-not-available', title: 'public-dashboard-title', pausedDescription: 'public-dashboard-paused-description', }, }, RequestViewAccess: { form: 'request-view-access-form', recipientInput: 'request-view-access-recipient-input', submitButton: 'request-view-access-submit-button', }, Explore: { url: '/explore', General: { container: 'data-testid Explore', graph: 'Explore Graph', table: 'Explore Table', scrollView: 'data-testid explorer scroll view', }, }, SoloPanel: { url: (page: string) => `/d-solo/${page}`, }, PluginsList: { page: 'Plugins list page', list: 'Plugins list', listItem: 'Plugins list item', signatureErrorNotice: 'Unsigned plugins notice', }, PluginPage: { page: 'Plugin page', signatureInfo: 'Plugin signature info', disabledInfo: 'Plugin disabled info', }, PlaylistForm: { name: 'Playlist name', interval: 'Playlist interval', itemDelete: 'Delete playlist item', }, BrowseDashbards: { table: { row: (uid: string) => `data-testid ${uid} row`, checkbox: (uid: string) => `data-testid ${uid} checkbox`, }, }, Search: { url: '/?search=openn', FolderView: { url: '/?search=open&layout=folders', }, }, PublicDashboards: { ListItem: { linkButton: 'public-dashboard-link-button', configButton: 'public-dashboard-configuration-button', trashcanButton: 'public-dashboard-remove-button', pauseSwitch: 'data-testid public dashboard pause switch', }, }, UserListPage: { tabs: { allUsers: 'data-testid all-users-tab', orgUsers: 'data-testid org-users-tab', publicDashboardsUsers: 'data-testid public-dashboards-users-tab', users: 'data-testid users-tab', }, org: { url: '/org/users', }, admin: { url: '/admin/users', }, publicDashboards: { container: 'data-testid public-dashboards-users-list', }, UserListAdminPage: { container: 'data-testid user-list-admin-page', }, UsersListPage: { container: 'data-testid users-list-page', }, UsersListPublicDashboardsPage: { container: 'data-testid users-list-public-dashboards-page', DashboardsListModal: { listItem: (uid: string) => `data-testid dashboards-list-item-${uid}`, }, }, }, };
packages/grafana-e2e-selectors/src/selectors/pages.ts
1
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017818259948398918, 0.00017324612417723984, 0.00016646331641823053, 0.0001730023795971647, 0.0000030609969599026954 ]
{ "id": 2, "code_window": [ "import { GrafanaTheme2 } from '@grafana/data';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { reportInteraction } from '@grafana/runtime';\n", "import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui';\n", "\n", "import { isAdHoc } from '../guard';\n", "import { VariableUsagesButton } from '../inspect/VariableUsagesButton';\n", "import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils';\n", "import { KeyedVariableIdentifier } from '../state/types';\n", "import { VariableModel } from '../types';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { hasOptions, isAdHoc, isQuery } from '../guard';\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
package grn import ( "fmt" "strconv" "strings" ) // Grafana resource name. See also: // https://github.com/grafana/grafana/blob/main/pkg/services/store/entity/entity.proto#L6 // NOTE: This structure/format is still under active development and is subject to change type GRN struct { // TenantID contains the ID of the tenant (in hosted grafana) or // organization (in other environments) the resource belongs to. This field // may be omitted for global Grafana resources which are not associated with // an organization. TenantID int64 // The kind of resource being identified, for e.g. "dashboard" or "user". // The caller is responsible for validating the value. ResourceKind string // ResourceIdentifier is used by the underlying service to identify the // resource. ResourceIdentifier string // GRN can not be extended _ interface{} } // ParseStr attempts to parse a string into a GRN. It returns an error if the // given string does not match the GRN format, but does not validate the values. func ParseStr(str string) (GRN, error) { ret := GRN{} parts := strings.Split(str, ":") if len(parts) != 3 { return ret, ErrInvalidGRN.Errorf("%q is not a complete GRN", str) } if parts[0] != "grn" { return ret, ErrInvalidGRN.Errorf("%q does not look like a GRN", str) } // split the final segment into Kind and ID. This only splits after the // first occurrence of "/"; a ResourceIdentifier may contain "/" kind, id, found := strings.Cut(parts[2], "/") if !found { // missing "/" return ret, ErrInvalidGRN.Errorf("invalid resource identifier in GRN %q", str) } ret.ResourceIdentifier = id ret.ResourceKind = kind if parts[1] != "" { tID, err := strconv.ParseInt(parts[1], 10, 64) if err != nil { return ret, ErrInvalidGRN.Errorf("ID segment cannot be converted to an integer") } else { ret.TenantID = tID } } return ret, nil } // MustParseStr is a wrapper around ParseStr that panics if the given input is // not a valid GRN. This is intended for use in tests. func MustParseStr(str string) GRN { grn, err := ParseStr(str) if err != nil { panic("bad grn!") } return grn } // String returns a string representation of a grn in the format // grn:tenantID:kind/resourceIdentifier func (g *GRN) String() string { return fmt.Sprintf("grn:%d:%s/%s", g.TenantID, g.ResourceKind, g.ResourceIdentifier) }
pkg/infra/grn/grn.go
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.000188791862456128, 0.0001748757786117494, 0.0001683593582129106, 0.0001744499895721674, 0.000005642667474603513 ]
{ "id": 2, "code_window": [ "import { GrafanaTheme2 } from '@grafana/data';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { reportInteraction } from '@grafana/runtime';\n", "import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui';\n", "\n", "import { isAdHoc } from '../guard';\n", "import { VariableUsagesButton } from '../inspect/VariableUsagesButton';\n", "import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils';\n", "import { KeyedVariableIdentifier } from '../state/types';\n", "import { VariableModel } from '../types';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { hasOptions, isAdHoc, isQuery } from '../guard';\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import { cloneDeep, find, isEmpty } from 'lodash'; import { merge, Observable, of } from 'rxjs'; import { CoreApp, DataFrame, DataQueryRequest, DataQueryResponse, DataSourceInstanceSettings, DataSourceWithLogsContextSupport, LoadingState, LogRowContextOptions, LogRowModel, ScopedVars, } from '@grafana/data'; import { DataSourceWithBackend } from '@grafana/runtime'; import { getTimeSrv, TimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv'; import { CloudWatchAnnotationSupport } from './annotationSupport'; import { DEFAULT_METRICS_QUERY, getDefaultLogsQuery } from './defaultQueries'; import { isCloudWatchAnnotationQuery, isCloudWatchLogsQuery, isCloudWatchMetricsQuery } from './guards'; import { CloudWatchLogsLanguageProvider } from './language/cloudwatch-logs/CloudWatchLogsLanguageProvider'; import { SQLCompletionItemProvider } from './language/cloudwatch-sql/completion/CompletionItemProvider'; import { MetricMathCompletionItemProvider } from './language/metric-math/completion/CompletionItemProvider'; import { CloudWatchAnnotationQueryRunner } from './query-runner/CloudWatchAnnotationQueryRunner'; import { CloudWatchLogsQueryRunner } from './query-runner/CloudWatchLogsQueryRunner'; import { CloudWatchMetricsQueryRunner } from './query-runner/CloudWatchMetricsQueryRunner'; import { ResourcesAPI } from './resources/ResourcesAPI'; import { CloudWatchAnnotationQuery, CloudWatchJsonData, CloudWatchLogsQuery, CloudWatchMetricsQuery, CloudWatchQuery, } from './types'; import { CloudWatchVariableSupport } from './variables'; export class CloudWatchDatasource extends DataSourceWithBackend<CloudWatchQuery, CloudWatchJsonData> implements DataSourceWithLogsContextSupport<CloudWatchLogsQuery> { defaultRegion?: string; languageProvider: CloudWatchLogsLanguageProvider; sqlCompletionItemProvider: SQLCompletionItemProvider; metricMathCompletionItemProvider: MetricMathCompletionItemProvider; defaultLogGroups?: string[]; type = 'cloudwatch'; private metricsQueryRunner: CloudWatchMetricsQueryRunner; private annotationQueryRunner: CloudWatchAnnotationQueryRunner; logsQueryRunner: CloudWatchLogsQueryRunner; resources: ResourcesAPI; constructor( private instanceSettings: DataSourceInstanceSettings<CloudWatchJsonData>, readonly templateSrv: TemplateSrv = getTemplateSrv(), timeSrv: TimeSrv = getTimeSrv() ) { super(instanceSettings); this.defaultRegion = instanceSettings.jsonData.defaultRegion; this.resources = new ResourcesAPI(instanceSettings, templateSrv); this.languageProvider = new CloudWatchLogsLanguageProvider(this); this.sqlCompletionItemProvider = new SQLCompletionItemProvider(this.resources, this.templateSrv); this.metricMathCompletionItemProvider = new MetricMathCompletionItemProvider(this.resources, this.templateSrv); this.metricsQueryRunner = new CloudWatchMetricsQueryRunner(instanceSettings, templateSrv); this.logsQueryRunner = new CloudWatchLogsQueryRunner(instanceSettings, templateSrv, timeSrv); this.annotationQueryRunner = new CloudWatchAnnotationQueryRunner(instanceSettings, templateSrv); this.variables = new CloudWatchVariableSupport(this.resources); this.annotations = CloudWatchAnnotationSupport; } filterQuery(query: CloudWatchQuery) { return query.hide !== true || (isCloudWatchMetricsQuery(query) && query.id !== ''); } query(options: DataQueryRequest<CloudWatchQuery>): Observable<DataQueryResponse> { options = cloneDeep(options); let queries = options.targets.filter(this.filterQuery); const logQueries: CloudWatchLogsQuery[] = []; const metricsQueries: CloudWatchMetricsQuery[] = []; const annotationQueries: CloudWatchAnnotationQuery[] = []; queries.forEach((query) => { if (isCloudWatchAnnotationQuery(query)) { annotationQueries.push(query); } else if (isCloudWatchLogsQuery(query)) { logQueries.push(query); } else { metricsQueries.push(query); } }); const dataQueryResponses: Array<Observable<DataQueryResponse>> = []; if (logQueries.length) { dataQueryResponses.push(this.logsQueryRunner.handleLogQueries(logQueries, options)); } if (metricsQueries.length) { dataQueryResponses.push(this.metricsQueryRunner.handleMetricQueries(metricsQueries, options)); } if (annotationQueries.length) { dataQueryResponses.push(this.annotationQueryRunner.handleAnnotationQuery(annotationQueries, options)); } // No valid targets, return the empty result to save a round trip. if (isEmpty(dataQueryResponses)) { return of({ data: [], state: LoadingState.Done, }); } return merge(...dataQueryResponses); } interpolateVariablesInQueries(queries: CloudWatchQuery[], scopedVars: ScopedVars): CloudWatchQuery[] { if (!queries.length) { return queries; } return queries.map((query) => ({ ...query, region: this.metricsQueryRunner.replaceVariableAndDisplayWarningIfMulti( this.getActualRegion(query.region), scopedVars ), ...(isCloudWatchMetricsQuery(query) && this.metricsQueryRunner.interpolateMetricsQueryVariables(query, scopedVars)), })); } getLogRowContext = async ( row: LogRowModel, context?: LogRowContextOptions, query?: CloudWatchLogsQuery ): Promise<{ data: DataFrame[] }> => { return this.logsQueryRunner.getLogRowContext(row, context, query); }; targetContainsTemplate(target: any) { return ( this.templateSrv.containsTemplate(target.region) || this.templateSrv.containsTemplate(target.namespace) || this.templateSrv.containsTemplate(target.metricName) || this.templateSrv.containsTemplate(target.expression!) || target.logGroupNames?.some((logGroup: string) => this.templateSrv.containsTemplate(logGroup)) || find(target.dimensions, (v, k) => this.templateSrv.containsTemplate(k) || this.templateSrv.containsTemplate(v)) ); } showContextToggle() { return true; } getQueryDisplayText(query: CloudWatchQuery) { if (isCloudWatchLogsQuery(query)) { return query.expression ?? ''; } else { return JSON.stringify(query); } } // public getVariables() { return this.resources.getVariables(); } getActualRegion(region?: string) { if (region === 'default' || region === undefined || region === '') { return this.defaultRegion ?? ''; } return region; } getDefaultQuery(_: CoreApp): Partial<CloudWatchQuery> { return { ...getDefaultLogsQuery(this.instanceSettings.jsonData.logGroups, this.instanceSettings.jsonData.defaultLogGroups), ...DEFAULT_METRICS_QUERY, }; } }
public/app/plugins/datasource/cloudwatch/datasource.ts
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017812621081247926, 0.00017431925516575575, 0.00016630798927508295, 0.00017516205844003707, 0.0000027272230909147765 ]
{ "id": 2, "code_window": [ "import { GrafanaTheme2 } from '@grafana/data';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { reportInteraction } from '@grafana/runtime';\n", "import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui';\n", "\n", "import { isAdHoc } from '../guard';\n", "import { VariableUsagesButton } from '../inspect/VariableUsagesButton';\n", "import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils';\n", "import { KeyedVariableIdentifier } from '../state/types';\n", "import { VariableModel } from '../types';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { hasOptions, isAdHoc, isQuery } from '../guard';\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import React from 'react'; import { AnnotationQuery } from '@grafana/data'; import { EditorField, EditorRow } from '@grafana/experimental'; import { Input } from '@grafana/ui'; import { ElasticsearchQuery } from '../../types'; import { ElasticQueryEditorProps, ElasticSearchQueryField } from './index'; type Props = ElasticQueryEditorProps & { annotation?: AnnotationQuery<ElasticsearchQuery>; onAnnotationChange?: (annotation: AnnotationQuery<ElasticsearchQuery>) => void; }; export function ElasticsearchAnnotationsQueryEditor(props: Props) { const annotation = props.annotation!; const onAnnotationChange = props.onAnnotationChange!; return ( <> <div className="gf-form-group"> <ElasticSearchQueryField value={annotation.target?.query} onChange={(query) => { const currentTarget = annotation.target ?? { refId: 'annotation_query' }; const newTarget = { ...currentTarget, query, }; onAnnotationChange({ ...annotation, target: newTarget, }); }} /> </div> <div className="gf-form-group"> <h6>Field mappings</h6> <EditorRow> <EditorField label="Time"> <Input type="text" placeholder="@timestamp" value={annotation.timeField} onChange={(e) => { onAnnotationChange({ ...annotation, timeField: e.currentTarget.value, }); }} /> </EditorField> <EditorField label="Time End"> <Input type="text" value={annotation.timeEndField} onChange={(e) => { onAnnotationChange({ ...annotation, timeEndField: e.currentTarget.value, }); }} /> </EditorField> <EditorField label="Text"> <Input type="text" value={annotation.textField} onChange={(e) => { onAnnotationChange({ ...annotation, textField: e.currentTarget.value, }); }} /> </EditorField> <EditorField label="Tags"> <Input type="text" placeholder="tags" value={annotation.tagsField} onChange={(e) => { onAnnotationChange({ ...annotation, tagsField: e.currentTarget.value, }); }} /> </EditorField> </EditorRow> </div> </> ); }
public/app/plugins/datasource/elasticsearch/components/QueryEditor/AnnotationQueryEditor.tsx
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.0001778164878487587, 0.00017504619609098881, 0.00016765417240094393, 0.0001755364064592868, 0.000002776434030238306 ]
{ "id": 3, "code_window": [ " onDuplicate: propsOnDuplicate,\n", " onDelete: propsOnDelete,\n", "}: VariableEditorListRowProps): ReactElement {\n", " const theme = useTheme2();\n", " const styles = useStyles2(getStyles);\n", " const usages = getVariableUsages(variable.id, usageTree);\n", " const passed = usages > 0 || isAdHoc(variable);\n", " const identifier = toKeyedVariableIdentifier(variable);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const definition = getDefinition(variable);\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "add", "edit_start_line_idx": 37 }
import { css } from '@emotion/css'; import React, { ReactElement } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { reportInteraction } from '@grafana/runtime'; import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui'; import { isAdHoc } from '../guard'; import { VariableUsagesButton } from '../inspect/VariableUsagesButton'; import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils'; import { KeyedVariableIdentifier } from '../state/types'; import { VariableModel } from '../types'; import { toKeyedVariableIdentifier } from '../utils'; export interface VariableEditorListRowProps { index: number; variable: VariableModel; usageTree: VariableUsageTree[]; usagesNetwork: UsagesToNetwork[]; onEdit: (identifier: KeyedVariableIdentifier) => void; onDuplicate: (identifier: KeyedVariableIdentifier) => void; onDelete: (identifier: KeyedVariableIdentifier) => void; } export function VariableEditorListRow({ index, variable, usageTree, usagesNetwork, onEdit: propsOnEdit, onDuplicate: propsOnDuplicate, onDelete: propsOnDelete, }: VariableEditorListRowProps): ReactElement { const theme = useTheme2(); const styles = useStyles2(getStyles); const usages = getVariableUsages(variable.id, usageTree); const passed = usages > 0 || isAdHoc(variable); const identifier = toKeyedVariableIdentifier(variable); return ( <Draggable draggableId={JSON.stringify(identifier)} index={index}> {(provided, snapshot) => ( <tr ref={provided.innerRef} {...provided.draggableProps} style={{ userSelect: snapshot.isDragging ? 'none' : 'auto', background: snapshot.isDragging ? theme.colors.background.secondary : undefined, ...provided.draggableProps.style, }} > <td role="gridcell" className={styles.column}> <Button size="xs" fill="text" onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} className={styles.nameLink} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowNameFields(variable.name)} > {variable.name} </Button> </td> <td role="gridcell" className={styles.descriptionColumn} onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)} > {variable.description} </td> <td role="gridcell" className={styles.column}> <VariableCheckIndicator passed={passed} /> </td> <td role="gridcell" className={styles.column}> <VariableUsagesButton id={variable.id} isAdhoc={isAdHoc(variable)} usages={usagesNetwork} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Duplicate variable'); propsOnDuplicate(identifier); }} name="copy" tooltip="Duplicate variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDuplicateButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Delete variable'); propsOnDelete(identifier); }} name="trash-alt" tooltip="Remove variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowRemoveButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <div {...provided.dragHandleProps} className={styles.dragHandle}> <Icon name="draggabledots" size="lg" /> </div> </td> </tr> )} </Draggable> ); } interface VariableCheckIndicatorProps { passed: boolean; } function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement { const styles = useStyles2(getStyles); if (passed) { return ( <Icon name="check" className={styles.iconPassed} title="This variable is referenced by other variables or dashboard." /> ); } return ( <Icon name="exclamation-triangle" className={styles.iconFailed} title="This variable is not referenced by any variable or dashboard." /> ); } function getStyles(theme: GrafanaTheme2) { return { dragHandle: css` cursor: grab; `, column: css` width: 1%; `, nameLink: css` cursor: pointer; color: ${theme.colors.primary.text}; `, descriptionColumn: css` width: 100%; max-width: 200px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; white-space: nowrap; `, iconPassed: css` color: ${theme.v1.palette.greenBase}; `, iconFailed: css` color: ${theme.v1.palette.orange}; `, }; }
public/app/features/variables/editor/VariableEditorListRow.tsx
1
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.998968243598938, 0.7116539478302002, 0.00017694916459731758, 0.9815360903739929, 0.44020602107048035 ]
{ "id": 3, "code_window": [ " onDuplicate: propsOnDuplicate,\n", " onDelete: propsOnDelete,\n", "}: VariableEditorListRowProps): ReactElement {\n", " const theme = useTheme2();\n", " const styles = useStyles2(getStyles);\n", " const usages = getVariableUsages(variable.id, usageTree);\n", " const passed = usages > 0 || isAdHoc(variable);\n", " const identifier = toKeyedVariableIdentifier(variable);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const definition = getDefinition(variable);\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "add", "edit_start_line_idx": 37 }
import createMockDatasource from './__mocks__/datasource'; import { migrateQuery, migrateStringQueriesToObjectQueries } from './grafanaTemplateVariableFns'; import { AzureMonitorQuery, AzureQueryType } from './types'; describe('migrateStringQueriesToObjectQueries', () => { const expectedMigrations: Array<{ input: string; output: AzureMonitorQuery }> = [ { input: 'Subscriptions()', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'SubscriptionsQuery', rawQuery: 'Subscriptions()' }, subscription: 'defaultSubscriptionId', }, }, { input: 'ResourceGroups()', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'ResourceGroupsQuery', rawQuery: 'ResourceGroups()', subscription: 'defaultSubscriptionId', }, subscription: 'defaultSubscriptionId', }, }, { input: 'ResourceGroups(subId)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'ResourceGroupsQuery', rawQuery: 'ResourceGroups(subId)', subscription: 'subId', }, subscription: 'defaultSubscriptionId', }, }, { input: 'Namespaces(rg)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamespaceQuery', rawQuery: 'Namespaces(rg)', subscription: 'defaultSubscriptionId', resourceGroup: 'rg', }, subscription: 'defaultSubscriptionId', }, }, { input: 'Namespaces(subId, rg)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamespaceQuery', rawQuery: 'Namespaces(subId, rg)', subscription: 'subId', resourceGroup: 'rg', }, subscription: 'defaultSubscriptionId', }, }, { input: 'ResourceNames(rg, md)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'ResourceNamesQuery', rawQuery: 'ResourceNames(rg, md)', subscription: 'defaultSubscriptionId', resourceGroup: 'rg', metricNamespace: 'md', }, subscription: 'defaultSubscriptionId', }, }, { input: 'ResourceNames(subId, rg, md)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'ResourceNamesQuery', rawQuery: 'ResourceNames(subId, rg, md)', subscription: 'subId', resourceGroup: 'rg', metricNamespace: 'md', }, subscription: 'defaultSubscriptionId', }, }, { input: 'MetricNamespace(rg, md, rn)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamespaceQuery', rawQuery: 'MetricNamespace(rg, md, rn)', subscription: 'defaultSubscriptionId', resourceGroup: 'rg', metricNamespace: 'md', resourceName: 'rn', }, subscription: 'defaultSubscriptionId', }, }, { input: 'MetricNamespace(subId, rg, md, rn)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamespaceQuery', rawQuery: 'MetricNamespace(subId, rg, md, rn)', subscription: 'subId', resourceGroup: 'rg', metricNamespace: 'md', resourceName: 'rn', }, subscription: 'defaultSubscriptionId', }, }, { input: 'MetricNames(rg, md, rn, mn)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamesQuery', rawQuery: 'MetricNames(rg, md, rn, mn)', subscription: 'defaultSubscriptionId', resourceGroup: 'rg', metricNamespace: 'md', resourceName: 'rn', }, subscription: 'defaultSubscriptionId', }, }, { input: 'MetricNames(subId, rg, md, rn, mn)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamesQuery', rawQuery: 'MetricNames(subId, rg, md, rn, mn)', subscription: 'subId', resourceGroup: 'rg', metricNamespace: 'md', resourceName: 'rn', }, subscription: 'defaultSubscriptionId', }, }, { input: 'AppInsightsMetricNames()', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'AppInsightsMetricNameQuery', rawQuery: 'AppInsightsMetricNames()', }, subscription: 'defaultSubscriptionId', }, }, { input: 'AppInsightsGroupBys(mn)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'AppInsightsGroupByQuery', rawQuery: 'AppInsightsGroupBys(mn)', metricName: 'mn', }, subscription: 'defaultSubscriptionId', }, }, { input: 'workspaces()', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'WorkspacesQuery', rawQuery: 'workspaces()', subscription: 'defaultSubscriptionId', }, subscription: 'defaultSubscriptionId', }, }, { input: 'workspaces(subId)', output: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'WorkspacesQuery', rawQuery: 'workspaces(subId)', subscription: 'subId', }, subscription: 'defaultSubscriptionId', }, }, { input: 'some kind of kql query', output: { refId: 'A', queryType: AzureQueryType.LogAnalytics, azureLogAnalytics: { query: 'some kind of kql query', resources: [], }, subscription: 'defaultSubscriptionId', }, }, ]; it('successfully converts all old string queries into formatted query objects', async () => { return expectedMigrations.map(async ({ input, output }) => { const datasource = createMockDatasource({ azureMonitorDatasource: { defaultSubscriptionId: 'defaultSubscriptionId', }, }); const actual = await migrateStringQueriesToObjectQueries(input, { datasource }); expect(actual).toEqual(output); }); }); }); describe('migrateStringQueriesToObjectQueries', () => { const expectedMigrations: Array<{ input: AzureMonitorQuery; output: AzureMonitorQuery }> = [ { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'SubscriptionsQuery', rawQuery: 'Subscriptions()' }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.SubscriptionsQuery, }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'ResourceGroupsQuery', rawQuery: 'ResourceGroups()', subscription: 'defaultSubscriptionId', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.ResourceGroupsQuery, subscription: 'defaultSubscriptionId', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'ResourceGroupsQuery', rawQuery: 'ResourceGroups(subId)', subscription: 'subId', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.ResourceGroupsQuery, subscription: 'subId', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamespaceQuery', rawQuery: 'Namespaces(rg)', subscription: 'defaultSubscriptionId', resourceGroup: 'rg', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.NamespacesQuery, subscription: 'defaultSubscriptionId', resourceGroup: 'rg', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamespaceQuery', rawQuery: 'Namespaces(subId, rg)', subscription: 'subId', resourceGroup: 'rg', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.NamespacesQuery, subscription: 'subId', resourceGroup: 'rg', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'ResourceNamesQuery', rawQuery: 'ResourceNames(rg, md)', subscription: 'defaultSubscriptionId', resourceGroup: 'rg', metricNamespace: 'md', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.ResourceNamesQuery, subscription: 'defaultSubscriptionId', resourceGroup: 'rg', namespace: 'md', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'ResourceNamesQuery', rawQuery: 'ResourceNames(subId, rg, md)', subscription: 'subId', resourceGroup: 'rg', metricNamespace: 'md', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.ResourceNamesQuery, subscription: 'subId', resourceGroup: 'rg', namespace: 'md', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamespaceQuery', rawQuery: 'MetricNamespace(rg, md, rn)', subscription: 'defaultSubscriptionId', resourceGroup: 'rg', metricNamespace: 'md', resourceName: 'rn', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.NamespacesQuery, subscription: 'defaultSubscriptionId', resourceGroup: 'rg', namespace: 'md', resource: 'rn', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamespaceQuery', rawQuery: 'MetricNamespace(subId, rg, md, rn)', subscription: 'subId', resourceGroup: 'rg', metricNamespace: 'md', resourceName: 'rn', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.NamespacesQuery, subscription: 'subId', resourceGroup: 'rg', namespace: 'md', resource: 'rn', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamesQuery', rawQuery: 'MetricNames(rg, md, rn, mn)', subscription: 'defaultSubscriptionId', resourceGroup: 'rg', metricNamespace: 'md', resourceName: 'rn', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.MetricNamesQuery, subscription: 'defaultSubscriptionId', resourceGroup: 'rg', namespace: 'md', resource: 'rn', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'MetricNamesQuery', rawQuery: 'MetricNames(subId, rg, md, rn, mn)', subscription: 'subId', resourceGroup: 'rg', metricNamespace: 'md', resourceName: 'rn', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.MetricNamesQuery, subscription: 'subId', resourceGroup: 'rg', namespace: 'md', resource: 'rn', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'WorkspacesQuery', rawQuery: 'workspaces()', subscription: 'defaultSubscriptionId', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.WorkspacesQuery, subscription: 'defaultSubscriptionId', }, }, { input: { refId: 'A', queryType: AzureQueryType.GrafanaTemplateVariableFn, grafanaTemplateVariableFn: { kind: 'WorkspacesQuery', rawQuery: 'workspaces(subId)', subscription: 'subId', }, subscription: 'defaultSubscriptionId', }, output: { refId: 'A', queryType: AzureQueryType.WorkspacesQuery, subscription: 'subId', }, }, ]; it('successfully converts all old variable functions into formatted predefined queries', async () => { return expectedMigrations.map(async ({ input, output }) => { const datasource = createMockDatasource({ azureMonitorDatasource: { defaultSubscriptionId: 'defaultSubscriptionId', }, }); const actual = await migrateQuery(input, { datasource }); expect(actual).toMatchObject(output); }); }); });
public/app/plugins/datasource/azuremonitor/grafanaTemplateVariables.test.ts
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017759756883606315, 0.00017244891205336899, 0.00016568861610721797, 0.0001726688351482153, 0.0000030004682685103035 ]
{ "id": 3, "code_window": [ " onDuplicate: propsOnDuplicate,\n", " onDelete: propsOnDelete,\n", "}: VariableEditorListRowProps): ReactElement {\n", " const theme = useTheme2();\n", " const styles = useStyles2(getStyles);\n", " const usages = getVariableUsages(variable.id, usageTree);\n", " const passed = usages > 0 || isAdHoc(variable);\n", " const identifier = toKeyedVariableIdentifier(variable);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const definition = getDefinition(variable);\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "add", "edit_start_line_idx": 37 }
import { css } from '@emotion/css'; import React, { memo, PropsWithChildren } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { useStyles2 } from '../../../themes'; const getStyles = (theme: GrafanaTheme2) => { return { text: css` font-size: ${theme.typography.size.md}; font-weight: ${theme.typography.fontWeightMedium}; color: ${theme.colors.text.primary}; margin: 0; display: flex; `, }; }; export const TimePickerTitle = memo<PropsWithChildren<{}>>(({ children }) => { const styles = useStyles2(getStyles); return <h3 className={styles.text}>{children}</h3>; }); TimePickerTitle.displayName = 'TimePickerTitle';
packages/grafana-ui/src/components/DateTimePickers/TimeRangePicker/TimePickerTitle.tsx
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.9899285435676575, 0.6509056687355042, 0.001743339584209025, 0.9610452055931091, 0.45917853713035583 ]
{ "id": 3, "code_window": [ " onDuplicate: propsOnDuplicate,\n", " onDelete: propsOnDelete,\n", "}: VariableEditorListRowProps): ReactElement {\n", " const theme = useTheme2();\n", " const styles = useStyles2(getStyles);\n", " const usages = getVariableUsages(variable.id, usageTree);\n", " const passed = usages > 0 || isAdHoc(variable);\n", " const identifier = toKeyedVariableIdentifier(variable);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const definition = getDefinition(variable);\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "add", "edit_start_line_idx": 37 }
// 🌟 This was machine generated. Do not edit. 🌟 // // Frame[0] { // "typeVersion": [ // 0, // 0 // ] // } // Name: // Dimensions: 4 Fields by 2 Rows // +-------------------------+-------------------------------+----------------+---------------------+ // | Name: __labels | Name: Time | Name: Line | Name: TS | // | Labels: | Labels: | Labels: | Labels: | // | Type: []json.RawMessage | Type: []time.Time | Type: []string | Type: []string | // +-------------------------+-------------------------------+----------------+---------------------+ // | {"label1":"value1"} | 2022-06-17 06:49:51 +0000 UTC | text1 | 1655448591000000000 | // | {"label2":"value2"} | 2022-06-17 06:49:52 +0000 UTC | text2 | 1655448592000000000 | // +-------------------------+-------------------------------+----------------+---------------------+ // // // 🌟 This was machine generated. Do not edit. 🌟 { "status": 200, "frames": [ { "schema": { "meta": { "typeVersion": [ 0, 0 ] }, "fields": [ { "name": "__labels", "type": "other", "typeInfo": { "frame": "json.RawMessage" } }, { "name": "Time", "type": "time", "typeInfo": { "frame": "time.Time" } }, { "name": "Line", "type": "string", "typeInfo": { "frame": "string" } }, { "name": "TS", "type": "string", "typeInfo": { "frame": "string" } } ] }, "data": { "values": [ [ { "label1": "value1" }, { "label2": "value2" } ], [ 1655448591000, 1655448592000 ], [ "text1", "text2" ], [ "1655448591000000000", "1655448592000000000" ] ] } } ] }
pkg/util/converter/testdata/loki-streams-c-wide-frame.jsonc
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017696840222924948, 0.00017257913714274764, 0.0001662740542087704, 0.00017294407007284462, 0.000003016521532117622 ]
{ "id": 4, "code_window": [ " </Button>\n", " </td>\n", " <td\n", " role=\"gridcell\"\n", " className={styles.descriptionColumn}\n", " onClick={(event) => {\n", " event.preventDefault();\n", " propsOnEdit(identifier);\n", " }}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " className={styles.definitionColumn}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 69 }
import { css } from '@emotion/css'; import React, { ReactElement } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { reportInteraction } from '@grafana/runtime'; import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui'; import { isAdHoc } from '../guard'; import { VariableUsagesButton } from '../inspect/VariableUsagesButton'; import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils'; import { KeyedVariableIdentifier } from '../state/types'; import { VariableModel } from '../types'; import { toKeyedVariableIdentifier } from '../utils'; export interface VariableEditorListRowProps { index: number; variable: VariableModel; usageTree: VariableUsageTree[]; usagesNetwork: UsagesToNetwork[]; onEdit: (identifier: KeyedVariableIdentifier) => void; onDuplicate: (identifier: KeyedVariableIdentifier) => void; onDelete: (identifier: KeyedVariableIdentifier) => void; } export function VariableEditorListRow({ index, variable, usageTree, usagesNetwork, onEdit: propsOnEdit, onDuplicate: propsOnDuplicate, onDelete: propsOnDelete, }: VariableEditorListRowProps): ReactElement { const theme = useTheme2(); const styles = useStyles2(getStyles); const usages = getVariableUsages(variable.id, usageTree); const passed = usages > 0 || isAdHoc(variable); const identifier = toKeyedVariableIdentifier(variable); return ( <Draggable draggableId={JSON.stringify(identifier)} index={index}> {(provided, snapshot) => ( <tr ref={provided.innerRef} {...provided.draggableProps} style={{ userSelect: snapshot.isDragging ? 'none' : 'auto', background: snapshot.isDragging ? theme.colors.background.secondary : undefined, ...provided.draggableProps.style, }} > <td role="gridcell" className={styles.column}> <Button size="xs" fill="text" onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} className={styles.nameLink} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowNameFields(variable.name)} > {variable.name} </Button> </td> <td role="gridcell" className={styles.descriptionColumn} onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)} > {variable.description} </td> <td role="gridcell" className={styles.column}> <VariableCheckIndicator passed={passed} /> </td> <td role="gridcell" className={styles.column}> <VariableUsagesButton id={variable.id} isAdhoc={isAdHoc(variable)} usages={usagesNetwork} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Duplicate variable'); propsOnDuplicate(identifier); }} name="copy" tooltip="Duplicate variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDuplicateButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Delete variable'); propsOnDelete(identifier); }} name="trash-alt" tooltip="Remove variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowRemoveButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <div {...provided.dragHandleProps} className={styles.dragHandle}> <Icon name="draggabledots" size="lg" /> </div> </td> </tr> )} </Draggable> ); } interface VariableCheckIndicatorProps { passed: boolean; } function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement { const styles = useStyles2(getStyles); if (passed) { return ( <Icon name="check" className={styles.iconPassed} title="This variable is referenced by other variables or dashboard." /> ); } return ( <Icon name="exclamation-triangle" className={styles.iconFailed} title="This variable is not referenced by any variable or dashboard." /> ); } function getStyles(theme: GrafanaTheme2) { return { dragHandle: css` cursor: grab; `, column: css` width: 1%; `, nameLink: css` cursor: pointer; color: ${theme.colors.primary.text}; `, descriptionColumn: css` width: 100%; max-width: 200px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; white-space: nowrap; `, iconPassed: css` color: ${theme.v1.palette.greenBase}; `, iconFailed: css` color: ${theme.v1.palette.orange}; `, }; }
public/app/features/variables/editor/VariableEditorListRow.tsx
1
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.22112946212291718, 0.023334909230470657, 0.00016421740292571485, 0.0008746418170630932, 0.054716818034648895 ]
{ "id": 4, "code_window": [ " </Button>\n", " </td>\n", " <td\n", " role=\"gridcell\"\n", " className={styles.descriptionColumn}\n", " onClick={(event) => {\n", " event.preventDefault();\n", " propsOnEdit(identifier);\n", " }}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " className={styles.definitionColumn}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 69 }
{ "stable": "10.0.0", "testing": "10.0.0" }
latest.json
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017135606321971864, 0.00017135606321971864, 0.00017135606321971864, 0.00017135606321971864, 0 ]
{ "id": 4, "code_window": [ " </Button>\n", " </td>\n", " <td\n", " role=\"gridcell\"\n", " className={styles.descriptionColumn}\n", " onClick={(event) => {\n", " event.preventDefault();\n", " propsOnEdit(identifier);\n", " }}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " className={styles.definitionColumn}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 69 }
--- title: Build a logs data source plugin --- # Build a logs data source plugin Grafana data source plugins support metrics, logs, and other data types. The steps to build a logs data source plugin are largely the same as for a metrics data source, but there are a few differences which we will explain in this guide. ## Before you begin This guide assumes that you're already familiar with how to [Build a data source plugin](/tutorials/build-a-data-source-plugin/) for metrics. We recommend that you review this material before continuing. ## Add logs support to your data source To add logs support to an existing data source, you need to: 1. Enable logs support 1. Construct the log data When these steps are done, then you can improve the user experience with one or more [optional features](#enhance-your-logs-data-source-plugin-with-optional-features). ### Step 1: Enable logs support Tell Grafana that your data source plugin can return log data, by adding `"logs": true` to the [plugin.json]({{< relref "metadata/" >}}) file. ```json { "logs": true } ``` ### Step 2: Construct the log data As it does with metrics data, Grafana expects your plugin to return log data as a [data frame]({{< relref "data-frames/" >}}). To return log data, return a data frame with at least one time field and one text field from the data source's `query` method. **Example:** ```ts const frame = new MutableDataFrame({ refId: query.refId, fields: [ { name: 'time', type: FieldType.time }, { name: 'content', type: FieldType.string }, ], }); frame.add({ time: 1589189388597, content: 'user registered' }); frame.add({ time: 1589189406480, content: 'user logged in' }); ``` That's all you need to start returning log data from your data source. Go ahead and try it out in [Explore]({{< relref "../../explore/" >}}) or by adding a [Logs panel]({{< relref "../../panels-visualizations/visualizations/logs/" >}}). Congratulations, you just wrote your first logs data source plugin! Next, let's look at a couple of features that can further improve the experience for the user. ## Enhance your logs data source plugin with optional features Add visualization type hints, labels, and other optional features to logs. ### Add a preferred visualization type hint to the data frame To make sure Grafana recognizes data as logs and shows logs visualization automatically in Explore, set `meta.preferredVisualisationType` to `'logs'` in the returned data frame. See [Selecting preferred visualisation section]({{< relref "add-support-for-explore-queries/#selecting-preferred-visualisation" >}}) **Example:** ```ts const frame = new MutableDataFrame({ refId: query.refId, meta: { preferredVisualisationType: 'logs', }, fields: [ { name: 'time', type: FieldType.time }, { name: 'content', type: FieldType.string }, ], }); ``` ### Add labels to your logs Many log systems let you query logs based on metadata, or _labels_, to help filter log lines. Add labels to a stream of logs by setting the `labels` property on the Field. **Example**: ```ts const frame = new MutableDataFrame({ refId: query.refId, fields: [ { name: 'time', type: FieldType.time }, { name: 'content', type: FieldType.string, labels: { filename: 'file.txt' } }, ], }); frame.add({ time: 1589189388597, content: 'user registered' }); frame.add({ time: 1589189406480, content: 'user logged in' }); ``` ### Extract detected fields from your logs Add additional information about each log line by supplying more data frame fields. If a data frame has more than one text field, then Grafana assumes the first field in the data frame to be the actual log line. Grafana treats subsequent text fields as [detected fields]({{< relref "../../explore/#labels-and-detected-fields" >}}). Any number of custom fields can be added to your data frame; Grafana comes with two dedicated fields: `levels` and `id`. #### Levels To set the level for each log line, add a `level` field. **Example:** ```ts const frame = new MutableDataFrame({ refId: query.refId, fields: [ { name: 'time', type: FieldType.time }, { name: 'content', type: FieldType.string, labels: { filename: 'file.txt' } }, { name: 'level', type: FieldType.string }, ], }); frame.add({ time: 1589189388597, content: 'user registered', level: 'info' }); frame.add({ time: 1589189406480, content: 'unknown error', level: 'error' }); ``` #### 'id' for assigning unique identifiers to log lines By default, Grafana offers basic support for deduplicating log lines. You can improve the support by adding an `id` field to explicitly assign identifiers to each log line. **Example:** ```ts const frame = new MutableDataFrame({ refId: query.refId, fields: [ { name: 'time', type: FieldType.time }, { name: 'content', type: FieldType.string, labels: { filename: 'file.txt' } }, { name: 'level', type: FieldType.string }, { name: 'id', type: FieldType.string }, ], }); frame.add({ time: 1589189388597, content: 'user registered', level: 'info', id: 'd3b07384d113edec49eaa6238ad5ff00' }); frame.add({ time: 1589189406480, content: 'unknown error', level: 'error', id: 'c157a79031e1c40f85931829bc5fc552' }); ```
docs/sources/developers/plugins/build-a-logs-data-source-plugin.md
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.0001756999990902841, 0.00016931751451920718, 0.0001612813794054091, 0.00017041084356606007, 0.000004260752120899269 ]
{ "id": 4, "code_window": [ " </Button>\n", " </td>\n", " <td\n", " role=\"gridcell\"\n", " className={styles.descriptionColumn}\n", " onClick={(event) => {\n", " event.preventDefault();\n", " propsOnEdit(identifier);\n", " }}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " className={styles.definitionColumn}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 69 }
export interface AzureLogAnalyticsMetadata { functions: AzureLogAnalyticsMetadataFunction[]; resourceTypes: AzureLogAnalyticsMetadataResourceType[]; tables: AzureLogAnalyticsMetadataTable[]; solutions: AzureLogAnalyticsMetadataSolution[]; workspaces: AzureLogAnalyticsMetadataWorkspace[]; categories: AzureLogAnalyticsMetadataCategory[]; } export interface AzureLogAnalyticsMetadataCategory { id: string; displayName: string; related: AzureLogAnalyticsMetadataCategoryRelated; } export interface AzureLogAnalyticsMetadataCategoryRelated { tables: string[]; functions?: string[]; } export interface AzureLogAnalyticsMetadataFunction { id: string; name: string; displayName?: string; description: string; body: string; parameters?: string; related: AzureLogAnalyticsMetadataFunctionRelated; } export interface AzureLogAnalyticsMetadataFunctionRelated { solutions: string[]; categories?: string[]; tables: string[]; } export interface AzureLogAnalyticsMetadataResourceType { id: string; type: string; displayName: string; description: string; related: AzureLogAnalyticsMetadataResourceTypeRelated; } export interface AzureLogAnalyticsMetadataResourceTypeRelated { tables: string[]; workspaces: string[]; } export interface AzureLogAnalyticsMetadataSolution { id: string; name: string; related: AzureLogAnalyticsMetadataSolutionRelated; } export interface AzureLogAnalyticsMetadataSolutionRelated { tables: string[]; functions: string[]; workspaces: string[]; } export interface AzureLogAnalyticsMetadataTable { id: string; name: string; description?: string; timespanColumn: string; columns: AzureLogAnalyticsMetadataColumn[]; related: AzureLogAnalyticsMetadataTableRelated; isTroubleshootingAllowed?: boolean; hasData?: boolean; } export interface AzureLogAnalyticsMetadataColumn { name: string; type: string; description?: string; isPreferredFacet?: boolean; } export interface AzureLogAnalyticsMetadataTableRelated { categories?: string[]; solutions: string[]; functions?: string[]; } export interface AzureLogAnalyticsMetadataWorkspace { id: string; resourceId: string; name: string; region: string; related: AzureLogAnalyticsMetadataWorkspaceRelated; } export interface AzureLogAnalyticsMetadataWorkspaceRelated { solutions: string[]; }
public/app/plugins/datasource/azuremonitor/types/logAnalyticsMetadata.ts
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.0008528075413778424, 0.00025598338106647134, 0.00016225360741373152, 0.00017064987332560122, 0.00020591956854332238 ]
{ "id": 5, "code_window": [ " onClick={(event) => {\n", " event.preventDefault();\n", " propsOnEdit(identifier);\n", " }}\n", " aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDefinitionFields(variable.name)}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 74 }
import { css } from '@emotion/css'; import React, { ReactElement } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { reportInteraction } from '@grafana/runtime'; import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui'; import { isAdHoc } from '../guard'; import { VariableUsagesButton } from '../inspect/VariableUsagesButton'; import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils'; import { KeyedVariableIdentifier } from '../state/types'; import { VariableModel } from '../types'; import { toKeyedVariableIdentifier } from '../utils'; export interface VariableEditorListRowProps { index: number; variable: VariableModel; usageTree: VariableUsageTree[]; usagesNetwork: UsagesToNetwork[]; onEdit: (identifier: KeyedVariableIdentifier) => void; onDuplicate: (identifier: KeyedVariableIdentifier) => void; onDelete: (identifier: KeyedVariableIdentifier) => void; } export function VariableEditorListRow({ index, variable, usageTree, usagesNetwork, onEdit: propsOnEdit, onDuplicate: propsOnDuplicate, onDelete: propsOnDelete, }: VariableEditorListRowProps): ReactElement { const theme = useTheme2(); const styles = useStyles2(getStyles); const usages = getVariableUsages(variable.id, usageTree); const passed = usages > 0 || isAdHoc(variable); const identifier = toKeyedVariableIdentifier(variable); return ( <Draggable draggableId={JSON.stringify(identifier)} index={index}> {(provided, snapshot) => ( <tr ref={provided.innerRef} {...provided.draggableProps} style={{ userSelect: snapshot.isDragging ? 'none' : 'auto', background: snapshot.isDragging ? theme.colors.background.secondary : undefined, ...provided.draggableProps.style, }} > <td role="gridcell" className={styles.column}> <Button size="xs" fill="text" onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} className={styles.nameLink} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowNameFields(variable.name)} > {variable.name} </Button> </td> <td role="gridcell" className={styles.descriptionColumn} onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)} > {variable.description} </td> <td role="gridcell" className={styles.column}> <VariableCheckIndicator passed={passed} /> </td> <td role="gridcell" className={styles.column}> <VariableUsagesButton id={variable.id} isAdhoc={isAdHoc(variable)} usages={usagesNetwork} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Duplicate variable'); propsOnDuplicate(identifier); }} name="copy" tooltip="Duplicate variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDuplicateButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Delete variable'); propsOnDelete(identifier); }} name="trash-alt" tooltip="Remove variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowRemoveButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <div {...provided.dragHandleProps} className={styles.dragHandle}> <Icon name="draggabledots" size="lg" /> </div> </td> </tr> )} </Draggable> ); } interface VariableCheckIndicatorProps { passed: boolean; } function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement { const styles = useStyles2(getStyles); if (passed) { return ( <Icon name="check" className={styles.iconPassed} title="This variable is referenced by other variables or dashboard." /> ); } return ( <Icon name="exclamation-triangle" className={styles.iconFailed} title="This variable is not referenced by any variable or dashboard." /> ); } function getStyles(theme: GrafanaTheme2) { return { dragHandle: css` cursor: grab; `, column: css` width: 1%; `, nameLink: css` cursor: pointer; color: ${theme.colors.primary.text}; `, descriptionColumn: css` width: 100%; max-width: 200px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; white-space: nowrap; `, iconPassed: css` color: ${theme.v1.palette.greenBase}; `, iconFailed: css` color: ${theme.v1.palette.orange}; `, }; }
public/app/features/variables/editor/VariableEditorListRow.tsx
1
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.9958464503288269, 0.11362234503030777, 0.00016388420772273093, 0.0011999233392998576, 0.3118378520011902 ]
{ "id": 5, "code_window": [ " onClick={(event) => {\n", " event.preventDefault();\n", " propsOnEdit(identifier);\n", " }}\n", " aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDefinitionFields(variable.name)}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 74 }
{ "compilerOptions": { "declarationDir": "./compiled", "emitDeclarationOnly": true, "isolatedModules": true, "rootDirs": ["."], "types": ["cypress"] }, "exclude": ["dist/**/*"], "extends": "@grafana/tsconfig", "include": ["src/**/*.ts", "cypress/support/index.d.ts"] }
packages/grafana-e2e/tsconfig.json
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017453002510592341, 0.0001725009933579713, 0.0001704719616100192, 0.0001725009933579713, 0.0000020290317479521036 ]
{ "id": 5, "code_window": [ " onClick={(event) => {\n", " event.preventDefault();\n", " propsOnEdit(identifier);\n", " }}\n", " aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDefinitionFields(variable.name)}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 74 }
#!/bin/bash blocks_dir=docker/blocks docker_dir=docker template_dir=templates grafana_config_file=conf.tmp grafana_config=config compose_header_file=docker/compose_header.yml compose_file=docker-compose.yaml env_file=.env if [ "$#" == 0 ]; then blocks=`ls $blocks_dir` if [ -z "$blocks" ]; then echo "No Blocks available in $blocks_dir" else echo "Available Blocks:" for block in $blocks; do echo " $block" done fi exit 0 fi for file in $grafana_config_file $compose_file $env_file; do if [ -e $file ]; then echo "Deleting $file" rm $file fi done echo "Adding Compose header to $compose_file" cat $compose_header_file >> $compose_file for dir in $@; do current_dir=$blocks_dir/$dir if [ ! -d "$current_dir" ]; then echo "$current_dir is not a directory" exit 1 fi if [ -e $current_dir/$grafana_config ]; then echo "Adding $current_dir/$grafana_config to $grafana_config_file" cat $current_dir/$grafana_config >> $grafana_config_file echo "" >> $grafana_config_file fi if [ -e $current_dir/$compose_file ]; then echo "Adding $current_dir/$compose_file to $compose_file" cat $current_dir/$compose_file >> $compose_file echo "" >> $compose_file fi if [ -e $current_dir/$env_file ]; then echo "Adding $current_dir/$env_file to .env" cat $current_dir/$env_file >> .env echo "" >> .env fi done
devenv/create_docker_compose.sh
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017495673091616482, 0.00017288092931266874, 0.0001707465562503785, 0.0001729355863062665, 0.0000015137271702769795 ]
{ "id": 5, "code_window": [ " onClick={(event) => {\n", " event.preventDefault();\n", " propsOnEdit(identifier);\n", " }}\n", " aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDefinitionFields(variable.name)}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 74 }
import { language, languageConfiguration } from './lang'; export const languageDefinition = { id: 'parca', extensions: ['.parca'], aliases: ['parca'], mimetypes: [], def: { language, languageConfiguration, }, };
public/app/plugins/datasource/parca/lang/index.ts
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017551648488733917, 0.00017174406093545258, 0.00016797165153548121, 0.00017174406093545258, 0.00000377241667592898 ]
{ "id": 6, "code_window": [ " >\n", " {variable.description}\n", " </td>\n", "\n", " <td role=\"gridcell\" className={styles.column}>\n", " <VariableCheckIndicator passed={passed} />\n", " </td>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {definition}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 76 }
import { css } from '@emotion/css'; import React, { ReactElement } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { reportInteraction } from '@grafana/runtime'; import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui'; import { isAdHoc } from '../guard'; import { VariableUsagesButton } from '../inspect/VariableUsagesButton'; import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils'; import { KeyedVariableIdentifier } from '../state/types'; import { VariableModel } from '../types'; import { toKeyedVariableIdentifier } from '../utils'; export interface VariableEditorListRowProps { index: number; variable: VariableModel; usageTree: VariableUsageTree[]; usagesNetwork: UsagesToNetwork[]; onEdit: (identifier: KeyedVariableIdentifier) => void; onDuplicate: (identifier: KeyedVariableIdentifier) => void; onDelete: (identifier: KeyedVariableIdentifier) => void; } export function VariableEditorListRow({ index, variable, usageTree, usagesNetwork, onEdit: propsOnEdit, onDuplicate: propsOnDuplicate, onDelete: propsOnDelete, }: VariableEditorListRowProps): ReactElement { const theme = useTheme2(); const styles = useStyles2(getStyles); const usages = getVariableUsages(variable.id, usageTree); const passed = usages > 0 || isAdHoc(variable); const identifier = toKeyedVariableIdentifier(variable); return ( <Draggable draggableId={JSON.stringify(identifier)} index={index}> {(provided, snapshot) => ( <tr ref={provided.innerRef} {...provided.draggableProps} style={{ userSelect: snapshot.isDragging ? 'none' : 'auto', background: snapshot.isDragging ? theme.colors.background.secondary : undefined, ...provided.draggableProps.style, }} > <td role="gridcell" className={styles.column}> <Button size="xs" fill="text" onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} className={styles.nameLink} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowNameFields(variable.name)} > {variable.name} </Button> </td> <td role="gridcell" className={styles.descriptionColumn} onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)} > {variable.description} </td> <td role="gridcell" className={styles.column}> <VariableCheckIndicator passed={passed} /> </td> <td role="gridcell" className={styles.column}> <VariableUsagesButton id={variable.id} isAdhoc={isAdHoc(variable)} usages={usagesNetwork} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Duplicate variable'); propsOnDuplicate(identifier); }} name="copy" tooltip="Duplicate variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDuplicateButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Delete variable'); propsOnDelete(identifier); }} name="trash-alt" tooltip="Remove variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowRemoveButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <div {...provided.dragHandleProps} className={styles.dragHandle}> <Icon name="draggabledots" size="lg" /> </div> </td> </tr> )} </Draggable> ); } interface VariableCheckIndicatorProps { passed: boolean; } function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement { const styles = useStyles2(getStyles); if (passed) { return ( <Icon name="check" className={styles.iconPassed} title="This variable is referenced by other variables or dashboard." /> ); } return ( <Icon name="exclamation-triangle" className={styles.iconFailed} title="This variable is not referenced by any variable or dashboard." /> ); } function getStyles(theme: GrafanaTheme2) { return { dragHandle: css` cursor: grab; `, column: css` width: 1%; `, nameLink: css` cursor: pointer; color: ${theme.colors.primary.text}; `, descriptionColumn: css` width: 100%; max-width: 200px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; white-space: nowrap; `, iconPassed: css` color: ${theme.v1.palette.greenBase}; `, iconFailed: css` color: ${theme.v1.palette.orange}; `, }; }
public/app/features/variables/editor/VariableEditorListRow.tsx
1
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.9923486709594727, 0.10453654825687408, 0.00016566208796575665, 0.0018122328910976648, 0.28893566131591797 ]
{ "id": 6, "code_window": [ " >\n", " {variable.description}\n", " </td>\n", "\n", " <td role=\"gridcell\" className={styles.column}>\n", " <VariableCheckIndicator passed={passed} />\n", " </td>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {definition}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 76 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M21,18.3V5.7c0.6-0.3,1-1,1-1.7c0-1.1-0.9-2-2-2c-0.7,0-1.4,0.4-1.7,1H5.7C5.4,2.4,4.7,2,4,2C2.9,2,2,2.9,2,4c0,0.7,0.4,1.4,1,1.7v12.6c-0.6,0.3-1,1-1,1.7c0,1.1,0.9,2,2,2c0.7,0,1.4-0.4,1.7-1h12.6c0.3,0.6,1,1,1.7,1c1.1,0,2-0.9,2-2C22,19.3,21.6,18.6,21,18.3z M19,18.3c-0.3,0.2-0.5,0.4-0.7,0.7H5.7c-0.2-0.3-0.4-0.5-0.7-0.7V5.7C5.3,5.5,5.5,5.3,5.7,5h12.6c0.2,0.3,0.4,0.5,0.7,0.7V18.3z M14,9V8c0-0.6-0.4-1-1-1H8C7.4,7,7,7.4,7,8v5c0,0.6,0.4,1,1,1h1v-3c0-1.1,0.9-2,2-2H14z M16,10h-5c-0.6,0-1,0.4-1,1v5c0,0.6,0.4,1,1,1h5c0.6,0,1-0.4,1-1v-5C17,10.4,16.6,10,16,10z"/></svg>
public/img/icons/solid/object-group.svg
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.0002332886215299368, 0.0002332886215299368, 0.0002332886215299368, 0.0002332886215299368, 0 ]
{ "id": 6, "code_window": [ " >\n", " {variable.description}\n", " </td>\n", "\n", " <td role=\"gridcell\" className={styles.column}>\n", " <VariableCheckIndicator passed={passed} />\n", " </td>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {definition}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 76 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9.29,13.29,4,18.59V17a1,1,0,0,0-2,0v4a1,1,0,0,0,.08.38,1,1,0,0,0,.54.54A1,1,0,0,0,3,22H7a1,1,0,0,0,0-2H5.41l5.3-5.29a1,1,0,0,0-1.42-1.42ZM5.41,4H7A1,1,0,0,0,7,2H3a1,1,0,0,0-.38.08,1,1,0,0,0-.54.54A1,1,0,0,0,2,3V7A1,1,0,0,0,4,7V5.41l5.29,5.3a1,1,0,0,0,1.42,0,1,1,0,0,0,0-1.42ZM21,16a1,1,0,0,0-1,1v1.59l-5.29-5.3a1,1,0,0,0-1.42,1.42L18.59,20H17a1,1,0,0,0,0,2h4a1,1,0,0,0,.38-.08,1,1,0,0,0,.54-.54A1,1,0,0,0,22,21V17A1,1,0,0,0,21,16Zm.92-13.38a1,1,0,0,0-.54-.54A1,1,0,0,0,21,2H17a1,1,0,0,0,0,2h1.59l-5.3,5.29a1,1,0,0,0,0,1.42,1,1,0,0,0,1.42,0L20,5.41V7a1,1,0,0,0,2,0V3A1,1,0,0,0,21.92,2.62Z"/></svg>
public/img/icons/unicons/expand-arrows-alt.svg
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00016917975153774023, 0.00016917975153774023, 0.00016917975153774023, 0.00016917975153774023, 0 ]
{ "id": 6, "code_window": [ " >\n", " {variable.description}\n", " </td>\n", "\n", " <td role=\"gridcell\" className={styles.column}>\n", " <VariableCheckIndicator passed={passed} />\n", " </td>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {definition}\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 76 }
// reset font file paths so storybook loads them based on // staticDirs defined in packages/grafana-ui/.storybook/main.ts $font-file-path: './public/fonts'; $fa-font-path: $font-file-path; @import '../../../public/sass/grafana.light.scss';
packages/grafana-ui/.storybook/grafana.light.scss
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017049518646672368, 0.00017049518646672368, 0.00017049518646672368, 0.00017049518646672368, 0 ]
{ "id": 7, "code_window": [ " );\n", "}\n", "\n", "interface VariableCheckIndicatorProps {\n", " passed: boolean;\n", "}\n", "\n", "function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "function getDefinition(model: VariableModel): string {\n", " let definition = '';\n", " if (isQuery(model)) {\n", " if (model.definition) {\n", " definition = model.definition;\n", " } else if (typeof model.query === 'string') {\n", " definition = model.query;\n", " }\n", " } else if (hasOptions(model)) {\n", " definition = model.query;\n", " }\n", "\n", " return definition;\n", "}\n", "\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "add", "edit_start_line_idx": 123 }
import { css } from '@emotion/css'; import React, { ReactElement } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { reportInteraction } from '@grafana/runtime'; import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui'; import { isAdHoc } from '../guard'; import { VariableUsagesButton } from '../inspect/VariableUsagesButton'; import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils'; import { KeyedVariableIdentifier } from '../state/types'; import { VariableModel } from '../types'; import { toKeyedVariableIdentifier } from '../utils'; export interface VariableEditorListRowProps { index: number; variable: VariableModel; usageTree: VariableUsageTree[]; usagesNetwork: UsagesToNetwork[]; onEdit: (identifier: KeyedVariableIdentifier) => void; onDuplicate: (identifier: KeyedVariableIdentifier) => void; onDelete: (identifier: KeyedVariableIdentifier) => void; } export function VariableEditorListRow({ index, variable, usageTree, usagesNetwork, onEdit: propsOnEdit, onDuplicate: propsOnDuplicate, onDelete: propsOnDelete, }: VariableEditorListRowProps): ReactElement { const theme = useTheme2(); const styles = useStyles2(getStyles); const usages = getVariableUsages(variable.id, usageTree); const passed = usages > 0 || isAdHoc(variable); const identifier = toKeyedVariableIdentifier(variable); return ( <Draggable draggableId={JSON.stringify(identifier)} index={index}> {(provided, snapshot) => ( <tr ref={provided.innerRef} {...provided.draggableProps} style={{ userSelect: snapshot.isDragging ? 'none' : 'auto', background: snapshot.isDragging ? theme.colors.background.secondary : undefined, ...provided.draggableProps.style, }} > <td role="gridcell" className={styles.column}> <Button size="xs" fill="text" onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} className={styles.nameLink} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowNameFields(variable.name)} > {variable.name} </Button> </td> <td role="gridcell" className={styles.descriptionColumn} onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)} > {variable.description} </td> <td role="gridcell" className={styles.column}> <VariableCheckIndicator passed={passed} /> </td> <td role="gridcell" className={styles.column}> <VariableUsagesButton id={variable.id} isAdhoc={isAdHoc(variable)} usages={usagesNetwork} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Duplicate variable'); propsOnDuplicate(identifier); }} name="copy" tooltip="Duplicate variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDuplicateButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Delete variable'); propsOnDelete(identifier); }} name="trash-alt" tooltip="Remove variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowRemoveButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <div {...provided.dragHandleProps} className={styles.dragHandle}> <Icon name="draggabledots" size="lg" /> </div> </td> </tr> )} </Draggable> ); } interface VariableCheckIndicatorProps { passed: boolean; } function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement { const styles = useStyles2(getStyles); if (passed) { return ( <Icon name="check" className={styles.iconPassed} title="This variable is referenced by other variables or dashboard." /> ); } return ( <Icon name="exclamation-triangle" className={styles.iconFailed} title="This variable is not referenced by any variable or dashboard." /> ); } function getStyles(theme: GrafanaTheme2) { return { dragHandle: css` cursor: grab; `, column: css` width: 1%; `, nameLink: css` cursor: pointer; color: ${theme.colors.primary.text}; `, descriptionColumn: css` width: 100%; max-width: 200px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; white-space: nowrap; `, iconPassed: css` color: ${theme.v1.palette.greenBase}; `, iconFailed: css` color: ${theme.v1.palette.orange}; `, }; }
public/app/features/variables/editor/VariableEditorListRow.tsx
1
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.9991638660430908, 0.11269121617078781, 0.00016466222587041557, 0.00017461505194660276, 0.3120529353618622 ]
{ "id": 7, "code_window": [ " );\n", "}\n", "\n", "interface VariableCheckIndicatorProps {\n", " passed: boolean;\n", "}\n", "\n", "function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "function getDefinition(model: VariableModel): string {\n", " let definition = '';\n", " if (isQuery(model)) {\n", " if (model.definition) {\n", " definition = model.definition;\n", " } else if (typeof model.query === 'string') {\n", " definition = model.query;\n", " }\n", " } else if (hasOptions(model)) {\n", " definition = model.query;\n", " }\n", "\n", " return definition;\n", "}\n", "\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "add", "edit_start_line_idx": 123 }
import { css, cx } from '@emotion/css'; import React from 'react'; import { selectors } from '@grafana/e2e-selectors'; import { useStyles2 } from '../../themes'; import { Icon } from '../Icon/Icon'; import { Tooltip } from '../Tooltip/Tooltip'; /** * @internal */ export type LoadingIndicatorProps = { loading: boolean; onCancel: () => void; }; /** * @internal */ export const LoadingIndicator = ({ onCancel, loading }: LoadingIndicatorProps) => { const styles = useStyles2(getStyles); if (!loading) { return null; } return ( <Tooltip content="Cancel query"> <Icon className={cx('spin-clockwise', { [styles.clickable]: !!onCancel })} name="sync" size="sm" onClick={onCancel} aria-label={selectors.components.LoadingIndicator.icon} /> </Tooltip> ); }; const getStyles = () => { return { clickable: css({ cursor: 'pointer', }), }; };
packages/grafana-ui/src/components/PanelChrome/LoadingIndicator.tsx
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.009606684558093548, 0.0031755012460052967, 0.0001687201438471675, 0.0001745796180330217, 0.0038749792147427797 ]
{ "id": 7, "code_window": [ " );\n", "}\n", "\n", "interface VariableCheckIndicatorProps {\n", " passed: boolean;\n", "}\n", "\n", "function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "function getDefinition(model: VariableModel): string {\n", " let definition = '';\n", " if (isQuery(model)) {\n", " if (model.definition) {\n", " definition = model.definition;\n", " } else if (typeof model.query === 'string') {\n", " definition = model.query;\n", " }\n", " } else if (hasOptions(model)) {\n", " definition = model.query;\n", " }\n", "\n", " return definition;\n", "}\n", "\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "add", "edit_start_line_idx": 123 }
import React from 'react'; import { PanelPlugin } from '@grafana/data'; import { config, DataSourcePicker } from '@grafana/runtime'; import { TagsInput } from '@grafana/ui'; import { FolderPicker } from 'app/core/components/Select/FolderPicker'; import { ALL_FOLDER, GENERAL_FOLDER, ReadonlyFolderPicker, } from 'app/core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker'; import { PermissionLevelString } from 'app/types'; import { AlertList } from './AlertList'; import { alertListPanelMigrationHandler } from './AlertListMigrationHandler'; import { GroupBy } from './GroupByWithLoading'; import { UnifiedAlertList } from './UnifiedAlertList'; import { AlertListSuggestionsSupplier } from './suggestions'; import { AlertListOptions, GroupMode, ShowOption, SortOrder, UnifiedAlertListOptions, ViewMode } from './types'; function showIfCurrentState(options: AlertListOptions) { return options.showOptions === ShowOption.Current; } const alertList = new PanelPlugin<AlertListOptions>(AlertList) .setPanelOptions((builder) => { builder .addSelect({ name: 'Show', path: 'showOptions', settings: { options: [ { label: 'Current state', value: ShowOption.Current }, { label: 'Recent state changes', value: ShowOption.RecentChanges }, ], }, defaultValue: ShowOption.Current, category: ['Options'], }) .addNumberInput({ name: 'Max items', path: 'maxItems', defaultValue: 10, category: ['Options'], }) .addSelect({ name: 'Sort order', path: 'sortOrder', settings: { options: [ { label: 'Alphabetical (asc)', value: SortOrder.AlphaAsc }, { label: 'Alphabetical (desc)', value: SortOrder.AlphaDesc }, { label: 'Importance', value: SortOrder.Importance }, { label: 'Time (asc)', value: SortOrder.TimeAsc }, { label: 'Time (desc)', value: SortOrder.TimeDesc }, ], }, defaultValue: SortOrder.AlphaAsc, category: ['Options'], }) .addBooleanSwitch({ path: 'dashboardAlerts', name: 'Alerts from this dashboard', defaultValue: false, category: ['Options'], }) .addTextInput({ path: 'alertName', name: 'Alert name', defaultValue: '', category: ['Filter'], showIf: showIfCurrentState, }) .addTextInput({ path: 'dashboardTitle', name: 'Dashboard title', defaultValue: '', category: ['Filter'], showIf: showIfCurrentState, }) .addCustomEditor({ path: 'folderId', name: 'Folder', id: 'folderId', defaultValue: null, editor: function RenderFolderPicker({ value, onChange }) { return ( <ReadonlyFolderPicker initialFolderId={value} onChange={(folder) => onChange(folder?.id)} extraFolders={[ALL_FOLDER, GENERAL_FOLDER]} /> ); }, category: ['Filter'], showIf: showIfCurrentState, }) .addCustomEditor({ id: 'tags', path: 'tags', name: 'Tags', description: '', defaultValue: [], editor(props) { return <TagsInput tags={props.value} onChange={props.onChange} />; }, category: ['Filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.ok', name: 'Ok', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.paused', name: 'Paused', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.no_data', name: 'No data', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.execution_error', name: 'Execution error', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.alerting', name: 'Alerting', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.pending', name: 'Pending', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }); }) .setMigrationHandler(alertListPanelMigrationHandler) .setSuggestionsSupplier(new AlertListSuggestionsSupplier()); const unifiedAlertList = new PanelPlugin<UnifiedAlertListOptions>(UnifiedAlertList).setPanelOptions((builder) => { builder .addRadio({ path: 'viewMode', name: 'View mode', description: 'Toggle between list view and stat view', defaultValue: ViewMode.List, settings: { options: [ { label: 'List', value: ViewMode.List }, { label: 'Stat', value: ViewMode.Stat }, ], }, category: ['Options'], }) .addRadio({ path: 'groupMode', name: 'Group mode', description: 'How alert instances should be grouped', defaultValue: GroupMode.Default, settings: { options: [ { value: GroupMode.Default, label: 'Default grouping' }, { value: GroupMode.Custom, label: 'Custom grouping' }, ], }, category: ['Options'], }) .addCustomEditor({ path: 'groupBy', name: 'Group by', description: 'Filter alerts using label querying', id: 'groupBy', defaultValue: [], showIf: (options) => options.groupMode === GroupMode.Custom, category: ['Options'], editor: (props) => { return ( <GroupBy id={props.id ?? 'groupBy'} defaultValue={props.value.map((value: string) => ({ label: value, value }))} onChange={props.onChange} /> ); }, }) .addNumberInput({ name: 'Max items', path: 'maxItems', description: 'Maximum alerts to display', defaultValue: 20, category: ['Options'], }) .addSelect({ name: 'Sort order', path: 'sortOrder', description: 'Sort order of alerts and alert instances', settings: { options: [ { label: 'Alphabetical (asc)', value: SortOrder.AlphaAsc }, { label: 'Alphabetical (desc)', value: SortOrder.AlphaDesc }, { label: 'Importance', value: SortOrder.Importance }, { label: 'Time (asc)', value: SortOrder.TimeAsc }, { label: 'Time (desc)', value: SortOrder.TimeDesc }, ], }, defaultValue: SortOrder.AlphaAsc, category: ['Options'], }) .addBooleanSwitch({ path: 'dashboardAlerts', name: 'Alerts from this dashboard', description: 'Show alerts from this dashboard', defaultValue: false, category: ['Options'], }) .addTextInput({ path: 'alertName', name: 'Alert name', description: 'Filter for alerts containing this text', defaultValue: '', category: ['Filter'], }) .addTextInput({ path: 'alertInstanceLabelFilter', name: 'Alert instance label', description: 'Filter alert instances using label querying, ex: {severity="critical", instance=~"cluster-us-.+"}', defaultValue: '', category: ['Filter'], }) .addCustomEditor({ path: 'folder', name: 'Folder', description: 'Filter for alerts in the selected folder (only for Grafana alerts)', id: 'folder', defaultValue: null, editor: function RenderFolderPicker(props) { return ( <FolderPicker enableReset={true} showRoot={false} allowEmpty={true} initialTitle={props.value?.title} initialFolderUid={props.value?.uid} permissionLevel={PermissionLevelString.View} onClear={() => props.onChange('')} {...props} /> ); }, category: ['Filter'], }) .addCustomEditor({ path: 'datasource', name: 'Datasource', description: 'Filter alerts from selected datasource', id: 'datasource', defaultValue: null, editor: function RenderDatasourcePicker(props) { return ( <DataSourcePicker {...props} type={['prometheus', 'loki', 'grafana']} noDefault current={props.value} onChange={(ds) => props.onChange(ds.name)} onClear={() => props.onChange(null)} /> ); }, category: ['Filter'], }) .addBooleanSwitch({ path: 'stateFilter.firing', name: 'Alerting / Firing', defaultValue: true, category: ['Alert state filter'], }) .addBooleanSwitch({ path: 'stateFilter.pending', name: 'Pending', defaultValue: true, category: ['Alert state filter'], }) .addBooleanSwitch({ path: 'stateFilter.noData', name: 'No Data', defaultValue: false, category: ['Alert state filter'], }) .addBooleanSwitch({ path: 'stateFilter.normal', name: 'Normal', defaultValue: false, category: ['Alert state filter'], }) .addBooleanSwitch({ path: 'stateFilter.error', name: 'Error', defaultValue: true, category: ['Alert state filter'], }); }); export const plugin = config.unifiedAlertingEnabled ? unifiedAlertList : alertList;
public/app/plugins/panel/alertlist/module.tsx
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00021724158432334661, 0.00017495776410214603, 0.0001687388139544055, 0.00017314695287495852, 0.000008724411600269377 ]
{ "id": 7, "code_window": [ " );\n", "}\n", "\n", "interface VariableCheckIndicatorProps {\n", " passed: boolean;\n", "}\n", "\n", "function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "function getDefinition(model: VariableModel): string {\n", " let definition = '';\n", " if (isQuery(model)) {\n", " if (model.definition) {\n", " definition = model.definition;\n", " } else if (typeof model.query === 'string') {\n", " definition = model.query;\n", " }\n", " } else if (hasOptions(model)) {\n", " definition = model.query;\n", " }\n", "\n", " return definition;\n", "}\n", "\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "add", "edit_start_line_idx": 123 }
import { isNumber, isFinite, escape } from 'lodash'; import { DecimalCount, formattedValueToString, getValueFormat, stringToJsRegex, ValueFormatter } from '@grafana/data'; function matchSeriesOverride(aliasOrRegex: string, seriesAlias: string) { if (!aliasOrRegex) { return false; } if (aliasOrRegex[0] === '/') { const regex = stringToJsRegex(aliasOrRegex); return seriesAlias.match(regex) != null; } return aliasOrRegex === seriesAlias; } function translateFillOption(fill: number) { return fill === 0 ? 0.001 : fill / 10; } function getFillGradient(amount: number) { if (!amount) { return null; } return { colors: [{ opacity: 0.0 }, { opacity: amount / 10 }], }; } /** * Calculate decimals for legend and update values for each series. * @param data series data * @param panel * @param height */ export function updateLegendValues(data: TimeSeries[], panel: any, height: number) { for (let i = 0; i < data.length; i++) { const series = data[i]; const yaxes = panel.yaxes; const seriesYAxis = series.yaxis || 1; const axis = yaxes[seriesYAxis - 1]; const formatter = getValueFormat(axis.format); // decimal override if (isNumber(panel.decimals)) { series.updateLegendValues(formatter, panel.decimals); } else if (isNumber(axis.decimals)) { series.updateLegendValues(formatter, axis.decimals + 1); } else { series.updateLegendValues(formatter, null); } } } /** * @deprecated: This class should not be used in new panels * * Use DataFrame and helpers instead */ export default class TimeSeries { datapoints: any; id: string; // Represents index of original data frame in the quey response dataFrameIndex: number; // Represents index of field in the data frame fieldIndex: number; label: string; alias: string; aliasEscaped: string; color?: string; valueFormater: any; stats: any; legend: boolean; hideTooltip?: boolean; allIsNull?: boolean; allIsZero?: boolean; decimals: DecimalCount; hasMsResolution: boolean; isOutsideRange?: boolean; lines: any; hiddenSeries?: boolean; dashes: any; bars: any; points: any; yaxis: any; zindex: any; stack: any; nullPointMode: any; fillBelowTo: any; transform: any; flotpairs: any; unit: any; constructor(opts: any) { this.datapoints = opts.datapoints; this.label = opts.alias; this.id = opts.alias; this.alias = opts.alias; this.aliasEscaped = escape(opts.alias); this.color = opts.color; this.bars = { fillColor: opts.color }; this.valueFormater = getValueFormat('none'); this.stats = {}; this.legend = true; this.unit = opts.unit; this.dataFrameIndex = opts.dataFrameIndex; this.fieldIndex = opts.fieldIndex; this.hasMsResolution = this.isMsResolutionNeeded(); } applySeriesOverrides(overrides: any[]) { this.lines = {}; this.dashes = { dashLength: [], }; this.points = {}; this.yaxis = 1; this.zindex = 0; this.nullPointMode = null; delete this.stack; delete this.bars.show; for (let i = 0; i < overrides.length; i++) { const override = overrides[i]; if (!matchSeriesOverride(override.alias, this.alias)) { continue; } if (override.lines !== void 0) { this.lines.show = override.lines; } if (override.dashes !== void 0) { this.dashes.show = override.dashes; this.lines.lineWidth = 0; } if (override.points !== void 0) { this.points.show = override.points; } if (override.bars !== void 0) { this.bars.show = override.bars; } if (override.fill !== void 0) { this.lines.fill = translateFillOption(override.fill); } if (override.fillGradient !== void 0) { this.lines.fillColor = getFillGradient(override.fillGradient); } if (override.stack !== void 0) { this.stack = override.stack; } if (override.linewidth !== void 0) { this.lines.lineWidth = this.dashes.show ? 0 : override.linewidth; this.dashes.lineWidth = override.linewidth; } if (override.dashLength !== void 0) { this.dashes.dashLength[0] = override.dashLength; } if (override.spaceLength !== void 0) { this.dashes.dashLength[1] = override.spaceLength; } if (override.nullPointMode !== void 0) { this.nullPointMode = override.nullPointMode; } if (override.pointradius !== void 0) { this.points.radius = override.pointradius; } if (override.steppedLine !== void 0) { this.lines.steps = override.steppedLine; } if (override.zindex !== void 0) { this.zindex = override.zindex; } if (override.fillBelowTo !== void 0) { this.fillBelowTo = override.fillBelowTo; } if (override.color !== void 0) { this.setColor(override.color); } if (override.transform !== void 0) { this.transform = override.transform; } if (override.legend !== void 0) { this.legend = override.legend; } if (override.hideTooltip !== void 0) { this.hideTooltip = override.hideTooltip; } if (override.yaxis !== void 0) { this.yaxis = override.yaxis; } if (override.hiddenSeries !== void 0) { this.hiddenSeries = override.hiddenSeries; } } } getFlotPairs(fillStyle: string) { const result = []; this.stats.total = 0; this.stats.max = -Number.MAX_VALUE; this.stats.min = Number.MAX_VALUE; this.stats.logmin = Number.MAX_VALUE; this.stats.avg = null; this.stats.current = null; this.stats.first = null; this.stats.delta = 0; this.stats.diff = null; this.stats.diffperc = 0; this.stats.range = null; this.stats.timeStep = Number.MAX_VALUE; this.allIsNull = true; this.allIsZero = true; const ignoreNulls = fillStyle === 'connected'; const nullAsZero = fillStyle === 'null as zero'; let currentTime; let currentValue; let nonNulls = 0; let previousTime; let previousValue = 0; let previousDeltaUp = true; for (let i = 0; i < this.datapoints.length; i++) { currentValue = this.datapoints[i][0]; currentTime = this.datapoints[i][1]; // Due to missing values we could have different timeStep all along the series // so we have to find the minimum one (could occur with aggregators such as ZimSum) if (previousTime !== undefined) { const timeStep = currentTime - previousTime; if (timeStep < this.stats.timeStep) { this.stats.timeStep = timeStep; } } previousTime = currentTime; if (currentValue === null) { if (ignoreNulls) { continue; } if (nullAsZero) { currentValue = 0; } } if (currentValue !== null) { if (isNumber(currentValue)) { this.stats.total += currentValue; this.allIsNull = false; nonNulls++; } if (currentValue > this.stats.max) { this.stats.max = currentValue; } if (currentValue < this.stats.min) { this.stats.min = currentValue; } if (this.stats.first === null) { this.stats.first = currentValue; } else { if (previousValue > currentValue) { // counter reset previousDeltaUp = false; if (i === this.datapoints.length - 1) { // reset on last this.stats.delta += currentValue; } } else { if (previousDeltaUp) { this.stats.delta += currentValue - previousValue; // normal increment } else { this.stats.delta += currentValue; // account for counter reset } previousDeltaUp = true; } } previousValue = currentValue; if (currentValue < this.stats.logmin && currentValue > 0) { this.stats.logmin = currentValue; } if (currentValue !== 0) { this.allIsZero = false; } } result.push([currentTime, currentValue]); } if (this.stats.max === -Number.MAX_VALUE) { this.stats.max = null; } if (this.stats.min === Number.MAX_VALUE) { this.stats.min = null; } if (result.length && !this.allIsNull) { this.stats.avg = this.stats.total / nonNulls; this.stats.current = result[result.length - 1][1]; if (this.stats.current === null && result.length > 1) { this.stats.current = result[result.length - 2][1]; } } if (this.stats.max !== null && this.stats.min !== null) { this.stats.range = this.stats.max - this.stats.min; } if (this.stats.current !== null && this.stats.first !== null) { this.stats.diff = this.stats.current - this.stats.first; this.stats.diffperc = this.stats.diff / this.stats.first; } this.stats.count = result.length; return result; } updateLegendValues(formater: ValueFormatter, decimals: DecimalCount) { this.valueFormater = formater; this.decimals = decimals; } formatValue(value: number | null) { if (!isFinite(value)) { value = null; // Prevent NaN formatting } return formattedValueToString(this.valueFormater(value, this.decimals)); } isMsResolutionNeeded() { for (let i = 0; i < this.datapoints.length; i++) { if (this.datapoints[i][1] !== null && this.datapoints[i][1] !== undefined) { const timestamp = this.datapoints[i][1].toString(); if (timestamp.length === 13 && timestamp % 1000 !== 0) { return true; } } } return false; } hideFromLegend(options: any) { if (options.hideEmpty && this.allIsNull) { return true; } // ignore series excluded via override if (!this.legend) { return true; } // ignore zero series if (options.hideZero && this.allIsZero) { return true; } return false; } setColor(color: string) { this.color = color; this.bars.fillColor = color; } }
public/app/core/time_series2.ts
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00018210578127764165, 0.00017134375229943544, 0.00016433550626970828, 0.0001718123530736193, 0.000003003756319230888 ]
{ "id": 8, "code_window": [ " nameLink: css`\n", " cursor: pointer;\n", " color: ${theme.colors.primary.text};\n", " `,\n", " descriptionColumn: css`\n", " width: 100%;\n", " max-width: 200px;\n", " cursor: pointer;\n", " overflow: hidden;\n", " text-overflow: ellipsis;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " definitionColumn: css`\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 160 }
import { css } from '@emotion/css'; import React, { ReactElement } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { reportInteraction } from '@grafana/runtime'; import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui'; import { isAdHoc } from '../guard'; import { VariableUsagesButton } from '../inspect/VariableUsagesButton'; import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils'; import { KeyedVariableIdentifier } from '../state/types'; import { VariableModel } from '../types'; import { toKeyedVariableIdentifier } from '../utils'; export interface VariableEditorListRowProps { index: number; variable: VariableModel; usageTree: VariableUsageTree[]; usagesNetwork: UsagesToNetwork[]; onEdit: (identifier: KeyedVariableIdentifier) => void; onDuplicate: (identifier: KeyedVariableIdentifier) => void; onDelete: (identifier: KeyedVariableIdentifier) => void; } export function VariableEditorListRow({ index, variable, usageTree, usagesNetwork, onEdit: propsOnEdit, onDuplicate: propsOnDuplicate, onDelete: propsOnDelete, }: VariableEditorListRowProps): ReactElement { const theme = useTheme2(); const styles = useStyles2(getStyles); const usages = getVariableUsages(variable.id, usageTree); const passed = usages > 0 || isAdHoc(variable); const identifier = toKeyedVariableIdentifier(variable); return ( <Draggable draggableId={JSON.stringify(identifier)} index={index}> {(provided, snapshot) => ( <tr ref={provided.innerRef} {...provided.draggableProps} style={{ userSelect: snapshot.isDragging ? 'none' : 'auto', background: snapshot.isDragging ? theme.colors.background.secondary : undefined, ...provided.draggableProps.style, }} > <td role="gridcell" className={styles.column}> <Button size="xs" fill="text" onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} className={styles.nameLink} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowNameFields(variable.name)} > {variable.name} </Button> </td> <td role="gridcell" className={styles.descriptionColumn} onClick={(event) => { event.preventDefault(); propsOnEdit(identifier); }} aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDescriptionFields(variable.name)} > {variable.description} </td> <td role="gridcell" className={styles.column}> <VariableCheckIndicator passed={passed} /> </td> <td role="gridcell" className={styles.column}> <VariableUsagesButton id={variable.id} isAdhoc={isAdHoc(variable)} usages={usagesNetwork} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Duplicate variable'); propsOnDuplicate(identifier); }} name="copy" tooltip="Duplicate variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDuplicateButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <IconButton onClick={(event) => { event.preventDefault(); reportInteraction('Delete variable'); propsOnDelete(identifier); }} name="trash-alt" tooltip="Remove variable" aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowRemoveButtons(variable.name)} /> </td> <td role="gridcell" className={styles.column}> <div {...provided.dragHandleProps} className={styles.dragHandle}> <Icon name="draggabledots" size="lg" /> </div> </td> </tr> )} </Draggable> ); } interface VariableCheckIndicatorProps { passed: boolean; } function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement { const styles = useStyles2(getStyles); if (passed) { return ( <Icon name="check" className={styles.iconPassed} title="This variable is referenced by other variables or dashboard." /> ); } return ( <Icon name="exclamation-triangle" className={styles.iconFailed} title="This variable is not referenced by any variable or dashboard." /> ); } function getStyles(theme: GrafanaTheme2) { return { dragHandle: css` cursor: grab; `, column: css` width: 1%; `, nameLink: css` cursor: pointer; color: ${theme.colors.primary.text}; `, descriptionColumn: css` width: 100%; max-width: 200px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; white-space: nowrap; `, iconPassed: css` color: ${theme.v1.palette.greenBase}; `, iconFailed: css` color: ${theme.v1.palette.orange}; `, }; }
public/app/features/variables/editor/VariableEditorListRow.tsx
1
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.9938981533050537, 0.11063728481531143, 0.00016552978195250034, 0.00017500038666184992, 0.31187137961387634 ]
{ "id": 8, "code_window": [ " nameLink: css`\n", " cursor: pointer;\n", " color: ${theme.colors.primary.text};\n", " `,\n", " descriptionColumn: css`\n", " width: 100%;\n", " max-width: 200px;\n", " cursor: pointer;\n", " overflow: hidden;\n", " text-overflow: ellipsis;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " definitionColumn: css`\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 160 }
package state import ( "context" "fmt" "math/rand" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/infra/log/logtest" "github.com/grafana/grafana/pkg/services/ngalert/eval" ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models" "github.com/grafana/grafana/pkg/util" ) // Not for parallel tests. type CountingImageService struct { Called int } func (c *CountingImageService) NewImage(_ context.Context, _ *ngmodels.AlertRule) (*ngmodels.Image, error) { c.Called += 1 return &ngmodels.Image{ Token: fmt.Sprint(rand.Int()), }, nil } func TestStateIsStale(t *testing.T) { now := time.Now() intervalSeconds := rand.Int63n(10) + 5 testCases := []struct { name string lastEvaluation time.Time expectedResult bool }{ { name: "false if last evaluation is now", lastEvaluation: now, expectedResult: false, }, { name: "false if last evaluation is 1 interval before now", lastEvaluation: now.Add(-time.Duration(intervalSeconds)), expectedResult: false, }, { name: "false if last evaluation is little less than 2 interval before now", lastEvaluation: now.Add(-time.Duration(intervalSeconds) * time.Second * 2).Add(100 * time.Millisecond), expectedResult: false, }, { name: "true if last evaluation is 2 intervals from now", lastEvaluation: now.Add(-time.Duration(intervalSeconds) * time.Second * 2), expectedResult: true, }, { name: "true if last evaluation is 3 intervals from now", lastEvaluation: now.Add(-time.Duration(intervalSeconds) * time.Second * 3), expectedResult: true, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.expectedResult, stateIsStale(now, tc.lastEvaluation, intervalSeconds)) }) } } func TestManager_saveAlertStates(t *testing.T) { type stateWithReason struct { State eval.State Reason string } create := func(s eval.State, r string) stateWithReason { return stateWithReason{ State: s, Reason: r, } } allStates := [...]stateWithReason{ create(eval.Normal, ""), create(eval.Normal, eval.NoData.String()), create(eval.Normal, eval.Error.String()), create(eval.Normal, util.GenerateShortUID()), create(eval.Alerting, ""), create(eval.Pending, ""), create(eval.NoData, ""), create(eval.Error, ""), } transitionToKey := map[ngmodels.AlertInstanceKey]StateTransition{} transitions := make([]StateTransition, 0) for _, fromState := range allStates { for i, toState := range allStates { tr := StateTransition{ State: &State{ State: toState.State, StateReason: toState.Reason, Labels: ngmodels.GenerateAlertLabels(5, fmt.Sprintf("%d--", i)), }, PreviousState: fromState.State, PreviousStateReason: fromState.Reason, } key, err := tr.GetAlertInstanceKey() require.NoError(t, err) transitionToKey[key] = tr transitions = append(transitions, tr) } } t.Run("should save all transitions if doNotSaveNormalState is false", func(t *testing.T) { st := &FakeInstanceStore{} m := Manager{instanceStore: st, doNotSaveNormalState: false} m.saveAlertStates(context.Background(), &logtest.Fake{}, transitions...) savedKeys := map[ngmodels.AlertInstanceKey]ngmodels.AlertInstance{} for _, op := range st.RecordedOps { saved := op.(ngmodels.AlertInstance) savedKeys[saved.AlertInstanceKey] = saved } assert.Len(t, transitionToKey, len(savedKeys)) for key, tr := range transitionToKey { assert.Containsf(t, savedKeys, key, "state %s (%s) was not saved but should be", tr.State.State, tr.StateReason) } }) t.Run("should not save Normal->Normal if doNotSaveNormalState is true", func(t *testing.T) { st := &FakeInstanceStore{} m := Manager{instanceStore: st, doNotSaveNormalState: true} m.saveAlertStates(context.Background(), &logtest.Fake{}, transitions...) savedKeys := map[ngmodels.AlertInstanceKey]ngmodels.AlertInstance{} for _, op := range st.RecordedOps { saved := op.(ngmodels.AlertInstance) savedKeys[saved.AlertInstanceKey] = saved } for key, tr := range transitionToKey { if tr.State.State == eval.Normal && tr.StateReason == "" && tr.PreviousState == eval.Normal && tr.PreviousStateReason == "" { continue } assert.Containsf(t, savedKeys, key, "state %s (%s) was not saved but should be", tr.State.State, tr.StateReason) } }) }
pkg/services/ngalert/state/manager_private_test.go
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.0001774394913809374, 0.0001737420097924769, 0.00016616706852801144, 0.0001739045837894082, 0.000002930873733930639 ]
{ "id": 8, "code_window": [ " nameLink: css`\n", " cursor: pointer;\n", " color: ${theme.colors.primary.text};\n", " `,\n", " descriptionColumn: css`\n", " width: 100%;\n", " max-width: 200px;\n", " cursor: pointer;\n", " overflow: hidden;\n", " text-overflow: ellipsis;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " definitionColumn: css`\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 160 }
export function isLogLineJSON(line: string): boolean { let parsed; try { parsed = JSON.parse(line); } catch (error) {} // The JSON parser should only be used for log lines that are valid serialized JSON objects. return typeof parsed === 'object'; } // This matches: // first a label from start of the string or first white space, then any word chars until "=" // second either an empty quotes, or anything that starts with quote and ends with unescaped quote, // or any non whitespace chars that do not start with quote const LOGFMT_REGEXP = /(?:^|\s)([\w\(\)\[\]\{\}]+)=(""|(?:".*?[^\\]"|[^"\s]\S*))/; export function isLogLineLogfmt(line: string): boolean { return LOGFMT_REGEXP.test(line); } export function isLogLinePacked(line: string): boolean { let parsed; try { parsed = JSON.parse(line); return parsed.hasOwnProperty('_entry'); } catch (error) { return false; } }
public/app/plugins/datasource/loki/lineParser.ts
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017462807591073215, 0.00017173164815176278, 0.0001682779984548688, 0.00017228892829734832, 0.000002622184410938644 ]
{ "id": 8, "code_window": [ " nameLink: css`\n", " cursor: pointer;\n", " color: ${theme.colors.primary.text};\n", " `,\n", " descriptionColumn: css`\n", " width: 100%;\n", " max-width: 200px;\n", " cursor: pointer;\n", " overflow: hidden;\n", " text-overflow: ellipsis;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " definitionColumn: css`\n" ], "file_path": "public/app/features/variables/editor/VariableEditorListRow.tsx", "type": "replace", "edit_start_line_idx": 160 }
import { queryMetricTree } from './metricTree'; describe('MetricTree', () => { it('queryMetric tree return right tree nodes', () => { const nodes = queryMetricTree('*'); expect(nodes[0].children[0].name).toBe('AA'); expect(nodes[0].children[1].name).toBe('AB'); }); it('queryMetric tree return right tree nodes', () => { const nodes = queryMetricTree('A.AB.ABC.*'); expect(nodes[0].name).toBe('ABCA'); }); it('queryMetric tree supports glob paths', () => { const nodes = queryMetricTree('A.{AB,AC}.*').map((i) => i.name); expect(nodes).toEqual(expect.arrayContaining(['ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC'])); }); it('queryMetric tree supports wildcard matching', () => { const nodes = queryMetricTree('A.AB.AB*').map((i) => i.name); expect(nodes).toEqual(expect.arrayContaining(['ABA', 'ABB', 'ABC'])); }); });
public/app/plugins/datasource/testdata/metricTree.test.ts
0
https://github.com/grafana/grafana/commit/b60b43640f59b2fc0627736d9abe1820cb0814ed
[ 0.00017643565661273897, 0.0001757625286700204, 0.0001747808128129691, 0.0001760711456881836, 7.099558274603623e-7 ]
{ "id": 0, "code_window": [ " if (controller.current === null) {\n", " controller.current = cancelToken();\n", " }\n", " useEffect(() => {\n", " return () => {\n", " // when unmount cancel the axios request\n", " controller.current.abort();\n", " };\n", " }, []);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/admin/admin/src/hooks/useFetchClient/index.js", "type": "replace", "edit_start_line_idx": 17 }
import React, { useEffect, useState, useRef, useReducer } from 'react'; import { useIntl } from 'react-intl'; import { SettingsPageTitle, useFocusWhenNavigate, Form, useOverlayBlocker, useNotification, useTracking, useGuidedTour, useRBAC, } from '@strapi/helper-plugin'; import { Main } from '@strapi/design-system/Main'; import { Formik } from 'formik'; import { get as getProperty } from 'lodash'; import { useRouteMatch, useHistory } from 'react-router-dom'; import { useQuery } from 'react-query'; import { useFetchClient } from '../../../../../hooks'; import { formatAPIErrors } from '../../../../../utils'; import { schema } from './utils'; import LoadingView from './components/LoadingView'; import FormHead from './components/FormHead'; import FormBody from './components/FormBody'; import adminPermissions from '../../../../../permissions'; import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions'; import init from './init'; import reducer, { initialState } from './reducer'; const MSG_ERROR_NAME_TAKEN = 'Name already taken'; const ApiTokenCreateView = () => { const { get, post, put } = useFetchClient(); useFocusWhenNavigate(); const { formatMessage } = useIntl(); const { lockApp, unlockApp } = useOverlayBlocker(); const toggleNotification = useNotification(); const history = useHistory(); const [apiToken, setApiToken] = useState( history.location.state?.apiToken.accessKey ? { ...history.location.state.apiToken, } : null ); const { trackUsage } = useTracking(); const trackUsageRef = useRef(trackUsage); const { setCurrentStep } = useGuidedTour(); const { allowedActions: { canCreate, canUpdate, canRegenerate }, } = useRBAC(adminPermissions.settings['api-tokens']); const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {})); const { params: { id }, } = useRouteMatch('/settings/api-tokens/:id'); const isCreating = id === 'create'; useQuery( 'content-api-permissions', async () => { const [permissions, routes] = await Promise.all( ['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => { const { data } = await get(url); return data.data; }) ); dispatch({ type: 'UPDATE_PERMISSIONS_LAYOUT', value: permissions, }); dispatch({ type: 'UPDATE_ROUTES', value: routes, }); if (apiToken) { if (apiToken?.type === 'read-only') { dispatch({ type: 'ON_CHANGE_READ_ONLY', }); } if (apiToken?.type === 'full-access') { dispatch({ type: 'SELECT_ALL_ACTIONS', }); } if (apiToken?.type === 'custom') { dispatch({ type: 'UPDATE_PERMISSIONS', value: apiToken?.permissions, }); } } }, { onError() { toggleNotification({ type: 'warning', message: { id: 'notification.error', defaultMessage: 'An error occured' }, }); }, } ); useEffect(() => { trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList'); }, [isCreating]); const { status } = useQuery( ['api-token', id], async () => { const { data: { data }, } = await get(`/admin/api-tokens/${id}`); setApiToken({ ...data, }); if (data?.type === 'read-only') { dispatch({ type: 'ON_CHANGE_READ_ONLY', }); } if (data?.type === 'full-access') { dispatch({ type: 'SELECT_ALL_ACTIONS', }); } if (data?.type === 'custom') { dispatch({ type: 'UPDATE_PERMISSIONS', value: data?.permissions, }); } return data; }, { enabled: !isCreating && !apiToken, onError() { toggleNotification({ type: 'warning', message: { id: 'notification.error', defaultMessage: 'An error occured' }, }); }, } ); const handleSubmit = async (body, actions) => { trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken'); lockApp(); const lifespanVal = body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0' ? parseInt(body.lifespan, 10) : null; try { const { data: { data: response }, } = isCreating ? await post(`/admin/api-tokens`, { ...body, lifespan: lifespanVal, permissions: body.type === 'custom' ? state.selectedActions : null, }) : await put(`/admin/api-tokens/${id}`, { name: body.name, description: body.description, type: body.type, permissions: body.type === 'custom' ? state.selectedActions : null, }); if (isCreating) { history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response }); setCurrentStep('apiTokens.success'); } unlockApp(); setApiToken({ ...response, }); toggleNotification({ type: 'success', message: isCreating ? formatMessage({ id: 'notification.success.tokencreated', defaultMessage: 'API Token successfully created', }) : formatMessage({ id: 'notification.success.tokenedited', defaultMessage: 'API Token successfully edited', }), }); trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', { type: apiToken.type, }); } catch (err) { const errors = formatAPIErrors(err.response.data); actions.setErrors(errors); if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) { toggleNotification({ type: 'warning', message: getProperty( err, 'response.data.message', 'notification.error.tokennamenotunique' ), }); } else { toggleNotification({ type: 'warning', message: getProperty(err, 'response.data.message', 'notification.error'), }); } unlockApp(); } }; const [hasChangedPermissions, setHasChangedPermissions] = useState(false); const handleChangeCheckbox = ({ target: { value } }) => { setHasChangedPermissions(true); dispatch({ type: 'ON_CHANGE', value, }); }; const handleChangeSelectAllCheckbox = ({ target: { value } }) => { setHasChangedPermissions(true); dispatch({ type: 'SELECT_ALL_IN_PERMISSION', value, }); }; const setSelectedAction = ({ target: { value } }) => { dispatch({ type: 'SET_SELECTED_ACTION', value, }); }; const providerValue = { ...state, onChange: handleChangeCheckbox, onChangeSelectAll: handleChangeSelectAllCheckbox, setSelectedAction, }; const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating); const isLoading = !isCreating && !apiToken && status !== 'success'; if (isLoading) { return <LoadingView apiTokenName={apiToken?.name} />; } return ( <ApiTokenPermissionsContextProvider value={providerValue}> <Main> <SettingsPageTitle name="API Tokens" /> <Formik validationSchema={schema} validateOnChange={false} initialValues={{ name: apiToken?.name || '', description: apiToken?.description || '', type: apiToken?.type, lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan, }} enableReinitialize onSubmit={(body, actions) => handleSubmit(body, actions)} > {({ errors, handleChange, isSubmitting, values, setFieldValue }) => { if (hasChangedPermissions && values?.type !== 'custom') { setFieldValue('type', 'custom'); } return ( <Form> <FormHead apiToken={apiToken} setApiToken={setApiToken} canEditInputs={canEditInputs} canRegenerate={canRegenerate} isSubmitting={isSubmitting} /> <FormBody apiToken={apiToken} errors={errors} onChange={handleChange} canEditInputs={canEditInputs} isCreating={isCreating} values={values} onDispatch={dispatch} setHasChangedPermissions={setHasChangedPermissions} /> </Form> ); }} </Formik> </Main> </ApiTokenPermissionsContextProvider> ); }; export default ApiTokenCreateView;
packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js
1
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.0015379969263449311, 0.00021885555179324, 0.00016411532124038786, 0.00017050464521162212, 0.00023883284302428365 ]
{ "id": 0, "code_window": [ " if (controller.current === null) {\n", " controller.current = cancelToken();\n", " }\n", " useEffect(() => {\n", " return () => {\n", " // when unmount cancel the axios request\n", " controller.current.abort();\n", " };\n", " }, []);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/admin/admin/src/hooks/useFetchClient/index.js", "type": "replace", "edit_start_line_idx": 17 }
'use strict'; const { createTestBuilder } = require('../../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../../test/helpers/strapi'); const { createAuthRequest } = require('../../../../../../test/helpers/request'); const builder = createTestBuilder(); let strapi; let rq; const ct = { displayName: 'withjson', singularName: 'withjson', pluralName: 'withjsons', attributes: { field: { type: 'json', }, }, }; describe('Test type json', () => { beforeAll(async () => { await builder.addContentType(ct).build(); strapi = await createStrapiInstance(); rq = await createAuthRequest({ strapi }); }); afterAll(async () => { await strapi.destroy(); await builder.cleanup(); }); test('Create entry with value input JSON', async () => { const inputValue = { key: 'value', }; const res = await rq.post('/content-manager/collection-types/api::withjson.withjson', { body: { field: inputValue, }, }); expect(res.statusCode).toBe(200); expect(res.body).toMatchObject({ field: inputValue, }); }); test('Create entry with array value input JSON', async () => { const inputValue = [ { key: 'value', }, { key: 'value', }, ]; const res = await rq.post('/content-manager/collection-types/api::withjson.withjson', { body: { field: inputValue, }, }); expect(res.statusCode).toBe(200); expect(res.body).toMatchObject({ field: inputValue, }); }); test('Reading entry, returns correct value', async () => { const res = await rq.get('/content-manager/collection-types/api::withjson.withjson'); expect(res.statusCode).toBe(200); expect(res.body.pagination).toBeDefined(); expect(Array.isArray(res.body.results)).toBe(true); res.body.results.forEach((entry) => { expect(entry.field).toBeDefined(); expect(entry.field).not.toBeNull(); expect(typeof entry.field).toBe('object'); }); }); test.todo('Throw when input is not a nested object'); test('Updating entry sets the right value and format', async () => { const res = await rq.post('/content-manager/collection-types/api::withjson.withjson', { body: { field: { key: 'value', }, }, }); const updateRes = await rq.put( `/content-manager/collection-types/api::withjson.withjson/${res.body.id}`, { body: { field: { newKey: 'newVal', }, }, } ); expect(updateRes.statusCode).toBe(200); expect(updateRes.body).toMatchObject({ id: res.body.id, field: { newKey: 'newVal' }, }); }); });
packages/core/content-manager/server/tests/fields/json.test.api.js
0
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.00017544769798405468, 0.00017219799337908626, 0.0001650328777031973, 0.0001731019001454115, 0.000003133798372800811 ]
{ "id": 0, "code_window": [ " if (controller.current === null) {\n", " controller.current = cancelToken();\n", " }\n", " useEffect(() => {\n", " return () => {\n", " // when unmount cancel the axios request\n", " controller.current.abort();\n", " };\n", " }, []);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/admin/admin/src/hooks/useFetchClient/index.js", "type": "replace", "edit_start_line_idx": 17 }
import React, { useState, useRef, useEffect } from 'react'; import styled from 'styled-components'; import { PropTypes } from 'prop-types'; import { useIntl } from 'react-intl'; import { Box } from '@strapi/design-system/Box'; import { Flex } from '@strapi/design-system/Flex'; import { Stack } from '@strapi/design-system/Stack'; import { Typography } from '@strapi/design-system/Typography'; import { SimpleMenu, MenuItem } from '@strapi/design-system/SimpleMenu'; import { IconButton } from '@strapi/design-system/IconButton'; import Plus from '@strapi/icons/Plus'; import DraggableCard from './DraggableCard'; import { getTrad } from '../../../utils'; const FlexWrapper = styled(Box)` flex: ${({ size }) => size}; `; const ScrollableContainer = styled(FlexWrapper)` overflow-x: scroll; overflow-y: hidden; `; const SelectContainer = styled(FlexWrapper)` max-width: ${32 / 16}rem; `; const SortDisplayedFields = ({ displayedFields, listRemainingFields, metadatas, onAddField, onClickEditField, onMoveField, onRemoveField, }) => { const { formatMessage } = useIntl(); const [isDraggingSibling, setIsDraggingSibling] = useState(false); const [lastAction, setLastAction] = useState(null); const scrollableContainerRef = useRef(); function handleAddField(...args) { setLastAction('add'); onAddField(...args); } function handleRemoveField(...args) { setLastAction('remove'); onRemoveField(...args); } useEffect(() => { if (lastAction === 'add' && scrollableContainerRef?.current) { scrollableContainerRef.current.scrollLeft = scrollableContainerRef.current.scrollWidth; } }, [displayedFields, lastAction]); return ( <> <Box paddingBottom={4}> <Typography variant="delta" as="h2"> {formatMessage({ id: getTrad('containers.SettingPage.view'), defaultMessage: 'View', })} </Typography> </Box> <Flex paddingTop={4} paddingLeft={4} paddingRight={4} borderColor="neutral300" borderStyle="dashed" borderWidth="1px" hasRadius > <ScrollableContainer size="1" paddingBottom={4} ref={scrollableContainerRef}> <Stack horizontal spacing={3}> {displayedFields.map((field, index) => ( <DraggableCard key={field} index={index} isDraggingSibling={isDraggingSibling} onMoveField={onMoveField} onClickEditField={onClickEditField} onRemoveField={(e) => handleRemoveField(e, index)} name={field} labelField={metadatas[field].list.label || field} setIsDraggingSibling={setIsDraggingSibling} /> ))} </Stack> </ScrollableContainer> <SelectContainer size="auto" paddingBottom={4}> <SimpleMenu label={formatMessage({ id: getTrad('components.FieldSelect.label'), defaultMessage: 'Add a field', })} as={IconButton} icon={<Plus />} disabled={listRemainingFields.length <= 0} data-testid="add-field" > {listRemainingFields.map((field) => ( <MenuItem key={field} onClick={() => handleAddField(field)}> {metadatas[field].list.label || field} </MenuItem> ))} </SimpleMenu> </SelectContainer> </Flex> </> ); }; SortDisplayedFields.propTypes = { displayedFields: PropTypes.array.isRequired, listRemainingFields: PropTypes.array.isRequired, metadatas: PropTypes.objectOf( PropTypes.shape({ list: PropTypes.shape({ label: PropTypes.string, }), }) ).isRequired, onAddField: PropTypes.func.isRequired, onClickEditField: PropTypes.func.isRequired, onMoveField: PropTypes.func.isRequired, onRemoveField: PropTypes.func.isRequired, }; export default SortDisplayedFields;
packages/core/admin/admin/src/content-manager/pages/ListSettingsView/components/SortDisplayedFields.js
0
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.0024606932420283556, 0.00039079406997188926, 0.00016811616660561413, 0.00017445249250158668, 0.0006062163156457245 ]
{ "id": 0, "code_window": [ " if (controller.current === null) {\n", " controller.current = cancelToken();\n", " }\n", " useEffect(() => {\n", " return () => {\n", " // when unmount cancel the axios request\n", " controller.current.abort();\n", " };\n", " }, []);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/admin/admin/src/hooks/useFetchClient/index.js", "type": "replace", "edit_start_line_idx": 17 }
'use strict'; const createContentAPI = require('../content-api'); describe('Content API - Permissions', () => { const bindToContentAPI = (action) => { Object.assign(action, { [Symbol.for('__type__')]: ['content-api'] }); return action; }; describe('Get Actions Map', () => { test('When no API are defined, it should return an empty object', () => { global.strapi = {}; const contentAPI = createContentAPI(global.strapi); const actionsMap = contentAPI.permissions.getActionsMap(); expect(actionsMap).toEqual({}); }); test('When no controller are defined for an API, it should ignore the API', () => { global.strapi = { api: { foo: {}, bar: {}, }, }; const contentAPI = createContentAPI(global.strapi); const actionsMap = contentAPI.permissions.getActionsMap(); expect(actionsMap).toEqual({}); }); test(`Do not register controller if they're not bound to the content API`, () => { const actionC = () => {}; Object.assign(actionC, { [Symbol.for('__type__')]: ['admin-api'] }); global.strapi = { api: { foo: { controllers: { controllerA: { actionA: bindToContentAPI(() => {}), actionB() {}, actionC, }, }, }, }, }; const contentAPI = createContentAPI(global.strapi); const actionsMap = contentAPI.permissions.getActionsMap(); expect(actionsMap).toEqual({ 'api::foo': { controllers: { controllerA: ['actionA'] } }, }); }); test('Creates and populate a map of actions from APIs and plugins', () => { global.strapi = { api: { foo: { controllers: { controllerA: { actionA: bindToContentAPI(() => {}), actionB: bindToContentAPI(() => {}), }, }, }, bar: { controllers: { controllerA: { actionA: bindToContentAPI(() => {}), actionB: bindToContentAPI(() => {}), }, }, }, foobar: { controllers: { controllerA: { actionA: bindToContentAPI(() => {}), actionB: bindToContentAPI(() => {}), }, controllerB: { actionC: bindToContentAPI(() => {}), actionD: bindToContentAPI(() => {}), }, }, }, }, plugins: { foo: { controllers: { controllerA: { actionA: bindToContentAPI(() => {}), actionB: bindToContentAPI(() => {}), }, }, }, bar: { controllers: { controllerA: { actionA: bindToContentAPI(() => {}), actionB: bindToContentAPI(() => {}), }, }, }, }, }; const contentAPI = createContentAPI(global.strapi); const actionsMap = contentAPI.permissions.getActionsMap(); expect(actionsMap).toEqual({ 'api::foo': { controllers: { controllerA: ['actionA', 'actionB'] } }, 'api::bar': { controllers: { controllerA: ['actionA', 'actionB'] } }, 'api::foobar': { controllers: { controllerA: ['actionA', 'actionB'], controllerB: ['actionC', 'actionD'], }, }, 'plugin::foo': { controllers: { controllerA: ['actionA', 'actionB'] } }, 'plugin::bar': { controllers: { controllerA: ['actionA', 'actionB'] } }, }); }); }); describe('Register Actions', () => { beforeEach(() => { global.strapi = { api: { foo: { controllers: { controllerA: { actionA: bindToContentAPI(() => {}), actionB: bindToContentAPI(() => {}), }, controllerB: { actionC: bindToContentAPI(() => {}), actionD: bindToContentAPI(() => {}), }, }, }, }, plugins: { foo: { controllers: { controllerA: { actionA: bindToContentAPI(() => {}), }, }, }, }, }; }); test('The action provider should holds every action from APIs and plugins', async () => { const contentAPI = createContentAPI(global.strapi); await contentAPI.permissions.registerActions(); const values = contentAPI.permissions.providers.action.values(); expect(values).toEqual([ { uid: 'api::foo.controllerA.actionA', api: 'api::foo', controller: 'controllerA', action: 'actionA', }, { uid: 'api::foo.controllerA.actionB', api: 'api::foo', controller: 'controllerA', action: 'actionB', }, { uid: 'api::foo.controllerB.actionC', api: 'api::foo', controller: 'controllerB', action: 'actionC', }, { uid: 'api::foo.controllerB.actionD', api: 'api::foo', controller: 'controllerB', action: 'actionD', }, { uid: 'plugin::foo.controllerA.actionA', api: 'plugin::foo', controller: 'controllerA', action: 'actionA', }, ]); }); test('Call registerActions twice should throw a duplicate error', async () => { const contentAPI = createContentAPI(global.strapi); await contentAPI.permissions.registerActions(); expect(() => contentAPI.permissions.registerActions()).rejects.toThrowError( 'Duplicated item key: api::foo.controllerA.actionA' ); }); }); describe('Providers', () => { test('You should not be able to register action once strapi is loaded', () => { global.strapi.isLoaded = true; const contentAPI = createContentAPI(global.strapi); // Actions expect(() => contentAPI.permissions.providers.action.register('foo', {}) ).rejects.toThrowError(`You can't register new actions outside the bootstrap function.`); // Conditions expect(() => contentAPI.permissions.providers.condition.register({ name: 'myCondition' }) ).rejects.toThrowError(`You can't register new conditions outside the bootstrap function.`); // Register Actions expect(() => contentAPI.permissions.registerActions()).rejects.toThrowError( `You can't register new actions outside the bootstrap function.` ); }); }); describe('Engine', () => { test('Engine warns when registering an unknown action', async () => { global.strapi = { log: { debug: jest.fn(), }, }; const contentAPI = createContentAPI(); const ability = await contentAPI.permissions.engine.generateAbility([{ action: 'foo' }]); expect(ability.rules).toHaveLength(0); expect(global.strapi.log.debug).toHaveBeenCalledWith( `Unknown action "foo" supplied when registering a new permission` ); }); test('Engine filter out invalid action when generating an ability', async () => { global.strapi = { log: { debug: jest.fn(), }, api: { foo: { controllers: { bar: { foobar: bindToContentAPI(() => {}) }, }, }, }, }; const contentAPI = createContentAPI(global.strapi); await contentAPI.permissions.registerActions(); const ability = await contentAPI.permissions.engine.generateAbility([ { action: 'foo' }, { action: 'api::foo.bar.foobar' }, ]); expect(ability.rules).toHaveLength(1); expect(ability.rules).toEqual([ { action: 'api::foo.bar.foobar', subject: 'all', }, ]); expect(global.strapi.log.debug).toHaveBeenCalledTimes(1); expect(global.strapi.log.debug).toHaveBeenCalledWith( `Unknown action "foo" supplied when registering a new permission` ); }); }); });
packages/core/strapi/lib/services/__tests__/content-api-permissions.test.js
0
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.00026365704252384603, 0.00017666240455582738, 0.00016370553930755705, 0.00017104884318541735, 0.000020174056771793403 ]
{ "id": 1, "code_window": [ " useGuidedTour,\n", " useRBAC,\n", "} from '@strapi/helper-plugin';\n", "import { Main } from '@strapi/design-system/Main';\n", "import { Formik } from 'formik';\n", "import { get as getProperty } from 'lodash';\n", "import { useRouteMatch, useHistory } from 'react-router-dom';\n", "import { useQuery } from 'react-query';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "import { get } from 'lodash';\n" ], "file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js", "type": "replace", "edit_start_line_idx": 14 }
import React, { useEffect, useState, useRef, useReducer } from 'react'; import { useIntl } from 'react-intl'; import { SettingsPageTitle, useFocusWhenNavigate, Form, useOverlayBlocker, useNotification, useTracking, useGuidedTour, useRBAC, } from '@strapi/helper-plugin'; import { Main } from '@strapi/design-system/Main'; import { Formik } from 'formik'; import { get as getProperty } from 'lodash'; import { useRouteMatch, useHistory } from 'react-router-dom'; import { useQuery } from 'react-query'; import { useFetchClient } from '../../../../../hooks'; import { formatAPIErrors } from '../../../../../utils'; import { schema } from './utils'; import LoadingView from './components/LoadingView'; import FormHead from './components/FormHead'; import FormBody from './components/FormBody'; import adminPermissions from '../../../../../permissions'; import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions'; import init from './init'; import reducer, { initialState } from './reducer'; const MSG_ERROR_NAME_TAKEN = 'Name already taken'; const ApiTokenCreateView = () => { const { get, post, put } = useFetchClient(); useFocusWhenNavigate(); const { formatMessage } = useIntl(); const { lockApp, unlockApp } = useOverlayBlocker(); const toggleNotification = useNotification(); const history = useHistory(); const [apiToken, setApiToken] = useState( history.location.state?.apiToken.accessKey ? { ...history.location.state.apiToken, } : null ); const { trackUsage } = useTracking(); const trackUsageRef = useRef(trackUsage); const { setCurrentStep } = useGuidedTour(); const { allowedActions: { canCreate, canUpdate, canRegenerate }, } = useRBAC(adminPermissions.settings['api-tokens']); const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {})); const { params: { id }, } = useRouteMatch('/settings/api-tokens/:id'); const isCreating = id === 'create'; useQuery( 'content-api-permissions', async () => { const [permissions, routes] = await Promise.all( ['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => { const { data } = await get(url); return data.data; }) ); dispatch({ type: 'UPDATE_PERMISSIONS_LAYOUT', value: permissions, }); dispatch({ type: 'UPDATE_ROUTES', value: routes, }); if (apiToken) { if (apiToken?.type === 'read-only') { dispatch({ type: 'ON_CHANGE_READ_ONLY', }); } if (apiToken?.type === 'full-access') { dispatch({ type: 'SELECT_ALL_ACTIONS', }); } if (apiToken?.type === 'custom') { dispatch({ type: 'UPDATE_PERMISSIONS', value: apiToken?.permissions, }); } } }, { onError() { toggleNotification({ type: 'warning', message: { id: 'notification.error', defaultMessage: 'An error occured' }, }); }, } ); useEffect(() => { trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList'); }, [isCreating]); const { status } = useQuery( ['api-token', id], async () => { const { data: { data }, } = await get(`/admin/api-tokens/${id}`); setApiToken({ ...data, }); if (data?.type === 'read-only') { dispatch({ type: 'ON_CHANGE_READ_ONLY', }); } if (data?.type === 'full-access') { dispatch({ type: 'SELECT_ALL_ACTIONS', }); } if (data?.type === 'custom') { dispatch({ type: 'UPDATE_PERMISSIONS', value: data?.permissions, }); } return data; }, { enabled: !isCreating && !apiToken, onError() { toggleNotification({ type: 'warning', message: { id: 'notification.error', defaultMessage: 'An error occured' }, }); }, } ); const handleSubmit = async (body, actions) => { trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken'); lockApp(); const lifespanVal = body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0' ? parseInt(body.lifespan, 10) : null; try { const { data: { data: response }, } = isCreating ? await post(`/admin/api-tokens`, { ...body, lifespan: lifespanVal, permissions: body.type === 'custom' ? state.selectedActions : null, }) : await put(`/admin/api-tokens/${id}`, { name: body.name, description: body.description, type: body.type, permissions: body.type === 'custom' ? state.selectedActions : null, }); if (isCreating) { history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response }); setCurrentStep('apiTokens.success'); } unlockApp(); setApiToken({ ...response, }); toggleNotification({ type: 'success', message: isCreating ? formatMessage({ id: 'notification.success.tokencreated', defaultMessage: 'API Token successfully created', }) : formatMessage({ id: 'notification.success.tokenedited', defaultMessage: 'API Token successfully edited', }), }); trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', { type: apiToken.type, }); } catch (err) { const errors = formatAPIErrors(err.response.data); actions.setErrors(errors); if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) { toggleNotification({ type: 'warning', message: getProperty( err, 'response.data.message', 'notification.error.tokennamenotunique' ), }); } else { toggleNotification({ type: 'warning', message: getProperty(err, 'response.data.message', 'notification.error'), }); } unlockApp(); } }; const [hasChangedPermissions, setHasChangedPermissions] = useState(false); const handleChangeCheckbox = ({ target: { value } }) => { setHasChangedPermissions(true); dispatch({ type: 'ON_CHANGE', value, }); }; const handleChangeSelectAllCheckbox = ({ target: { value } }) => { setHasChangedPermissions(true); dispatch({ type: 'SELECT_ALL_IN_PERMISSION', value, }); }; const setSelectedAction = ({ target: { value } }) => { dispatch({ type: 'SET_SELECTED_ACTION', value, }); }; const providerValue = { ...state, onChange: handleChangeCheckbox, onChangeSelectAll: handleChangeSelectAllCheckbox, setSelectedAction, }; const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating); const isLoading = !isCreating && !apiToken && status !== 'success'; if (isLoading) { return <LoadingView apiTokenName={apiToken?.name} />; } return ( <ApiTokenPermissionsContextProvider value={providerValue}> <Main> <SettingsPageTitle name="API Tokens" /> <Formik validationSchema={schema} validateOnChange={false} initialValues={{ name: apiToken?.name || '', description: apiToken?.description || '', type: apiToken?.type, lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan, }} enableReinitialize onSubmit={(body, actions) => handleSubmit(body, actions)} > {({ errors, handleChange, isSubmitting, values, setFieldValue }) => { if (hasChangedPermissions && values?.type !== 'custom') { setFieldValue('type', 'custom'); } return ( <Form> <FormHead apiToken={apiToken} setApiToken={setApiToken} canEditInputs={canEditInputs} canRegenerate={canRegenerate} isSubmitting={isSubmitting} /> <FormBody apiToken={apiToken} errors={errors} onChange={handleChange} canEditInputs={canEditInputs} isCreating={isCreating} values={values} onDispatch={dispatch} setHasChangedPermissions={setHasChangedPermissions} /> </Form> ); }} </Formik> </Main> </ApiTokenPermissionsContextProvider> ); }; export default ApiTokenCreateView;
packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js
1
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.7855797410011292, 0.04390682280063629, 0.00016204950225073844, 0.0001735853438731283, 0.16909970343112946 ]
{ "id": 1, "code_window": [ " useGuidedTour,\n", " useRBAC,\n", "} from '@strapi/helper-plugin';\n", "import { Main } from '@strapi/design-system/Main';\n", "import { Formik } from 'formik';\n", "import { get as getProperty } from 'lodash';\n", "import { useRouteMatch, useHistory } from 'react-router-dom';\n", "import { useQuery } from 'react-query';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "import { get } from 'lodash';\n" ], "file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js", "type": "replace", "edit_start_line_idx": 14 }
/** * * Wrapper * */ import styled from 'styled-components'; import { Box } from '@strapi/design-system/Box'; const BoxWrapper = styled(Box)` position: relative; `; export default BoxWrapper;
packages/core/content-type-builder/admin/src/components/ListRow/BoxWrapper.js
0
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.00017586626927368343, 0.0001712511875666678, 0.00016663609130773693, 0.0001712511875666678, 0.000004615088982973248 ]
{ "id": 1, "code_window": [ " useGuidedTour,\n", " useRBAC,\n", "} from '@strapi/helper-plugin';\n", "import { Main } from '@strapi/design-system/Main';\n", "import { Formik } from 'formik';\n", "import { get as getProperty } from 'lodash';\n", "import { useRouteMatch, useHistory } from 'react-router-dom';\n", "import { useQuery } from 'react-query';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "import { get } from 'lodash';\n" ], "file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js", "type": "replace", "edit_start_line_idx": 14 }
'use strict'; module.exports = (path) => { let tmpPath = path; if (typeof tmpPath !== 'string') throw new Error('admin.url must be a string'); if (tmpPath === '' || tmpPath === '/') return '/'; if (tmpPath[0] !== '/') tmpPath = `/${tmpPath}`; if (tmpPath[tmpPath.length - 1] !== '/') tmpPath += '/'; return tmpPath; };
packages/core/strapi/lib/utils/addSlash.js
0
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.0001756196143105626, 0.00017291746917180717, 0.0001702153094811365, 0.00017291746917180717, 0.000002702152414713055 ]
{ "id": 1, "code_window": [ " useGuidedTour,\n", " useRBAC,\n", "} from '@strapi/helper-plugin';\n", "import { Main } from '@strapi/design-system/Main';\n", "import { Formik } from 'formik';\n", "import { get as getProperty } from 'lodash';\n", "import { useRouteMatch, useHistory } from 'react-router-dom';\n", "import { useQuery } from 'react-query';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "import { get } from 'lodash';\n" ], "file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js", "type": "replace", "edit_start_line_idx": 14 }
'use strict'; module.exports = { ...require('./search'), ...require('./order-by'), ...require('./join'), ...require('./populate'), ...require('./where'), ...require('./transform'), };
packages/core/database/lib/query/helpers/index.js
0
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.00017479233792982996, 0.00017395519535057247, 0.0001731180673232302, 0.00017395519535057247, 8.371353032998741e-7 ]
{ "id": 2, "code_window": [ "import { useRouteMatch, useHistory } from 'react-router-dom';\n", "import { useQuery } from 'react-query';\n", "import { useFetchClient } from '../../../../../hooks';\n", "import { formatAPIErrors } from '../../../../../utils';\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js", "type": "replace", "edit_start_line_idx": 17 }
import { auth } from '@strapi/helper-plugin'; import { getFetchClient } from '../getFetchClient'; const token = 'coolToken'; auth.getToken = jest.fn().mockReturnValue(token); auth.clearAppStorage = jest.fn().mockReturnValue(token); process.env.STRAPI_ADMIN_BACKEND_URL = 'http://localhost:1337'; describe('ADMIN | utils | getFetchClient', () => { it('should return the 4 HTTP methods to call GET, POST, PUT and DELETE apis', () => { const response = getFetchClient(); expect(response).toHaveProperty('get'); expect(response).toHaveProperty('post'); expect(response).toHaveProperty('put'); expect(response).toHaveProperty('delete'); }); it('should contain the headers config values and the data when we try to reach an unknown API', async () => { const response = getFetchClient(); try { await response.get('/test'); } catch (err) { const { headers } = err.config; expect(headers.Authorization).toContain(`Bearer ${token}`); expect(headers.Accept).toBe('application/json'); } }); it('should contain the headers config values and the data when we try to reach an API without authorization and run the interceptor', async () => { const response = getFetchClient(); try { await response.get('/admin/information'); } catch (err) { expect(err.response.status).toBe(401); expect(auth.clearAppStorage).toHaveBeenCalledTimes(1); } }); it('should respond with status 200 to a known API and create the instance with the correct base URL', async () => { const response = getFetchClient(); const getData = await response.get('/admin/project-type'); expect(getData.status).toBe(200); expect(getData.request.responseURL).toContain(process.env.STRAPI_ADMIN_BACKEND_URL); }); });
packages/core/admin/admin/src/utils/tests/getFetchClient.test.js
1
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.00019594148034229875, 0.00017528214084450155, 0.00016460211190860718, 0.00017085160652641207, 0.000011363894373062067 ]
{ "id": 2, "code_window": [ "import { useRouteMatch, useHistory } from 'react-router-dom';\n", "import { useQuery } from 'react-query';\n", "import { useFetchClient } from '../../../../../hooks';\n", "import { formatAPIErrors } from '../../../../../utils';\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js", "type": "replace", "edit_start_line_idx": 17 }
'use strict'; const createExtension = require('./extension'); module.exports = createExtension;
packages/plugins/graphql/server/services/extension/index.js
0
https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688
[ 0.00017111717897932976, 0.00017111717897932976, 0.00017111717897932976, 0.00017111717897932976, 0 ]