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": 1, "code_window": [ "\tpublic setShowBorder(showBorder: boolean): void {\n", "\t\tthis.withBorder = showBorder;\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n", "\t\treturn this.entry ? this.entry.getLabel() : super.getLabel();\n", "\t}\n", "\n", "\tpublic getMeta(): string {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic getPrefix(): string {\n", "\t\treturn this.entry ? this.entry.getPrefix() : super.getPrefix();\n", "\t}\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 211 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!vs/languages/css/common/css-hover'; import nls = require('vs/nls'); import Platform = require('vs/platform/platform'); import modesExtensions = require('vs/editor/common/modes/modesRegistry'); import ConfigurationRegistry = require('vs/platform/configuration/common/configurationRegistry'); import lintRules = require('vs/languages/css/common/services/lintRules'); modesExtensions.registerMode({ id: 'css', extensions: ['.css'], aliases: ['CSS', 'css'], mimetypes: ['text/css'], moduleId: 'vs/languages/css/common/css', ctorName: 'CSSMode' }); var configurationRegistry = <ConfigurationRegistry.IConfigurationRegistry>Platform.Registry.as(ConfigurationRegistry.Extensions.Configuration); configurationRegistry.registerConfiguration({ 'id': 'css', 'order': 20, 'title': nls.localize('cssConfigurationTitle', "CSS configuration"), 'allOf': [{ 'title': nls.localize('lint', "Controls CSS validation and problem severities."), 'properties': lintRules.getConfigurationProperties('css') }] });
src/vs/languages/css/common/css.contribution.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017955416115000844, 0.00017633941024541855, 0.00017405538528691977, 0.00017587403999641538, 0.0000020773686628672294 ]
{ "id": 1, "code_window": [ "\tpublic setShowBorder(showBorder: boolean): void {\n", "\t\tthis.withBorder = showBorder;\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n", "\t\treturn this.entry ? this.entry.getLabel() : super.getLabel();\n", "\t}\n", "\n", "\tpublic getMeta(): string {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic getPrefix(): string {\n", "\t\treturn this.entry ? this.entry.getPrefix() : super.getPrefix();\n", "\t}\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 211 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {TPromise} from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import env = require('vs/base/common/flags'); import {MainThreadService as CommonMainThreadService} from 'vs/platform/thread/common/mainThreadService'; import pluginsIPC = require('vs/platform/plugins/common/ipcRemoteCom'); import remote = require('vs/base/common/remote'); import marshalling = require('vs/base/common/marshalling'); import json = require('vs/base/common/json'); import strings = require('vs/base/common/strings'); import objects = require('vs/base/common/objects'); import uri from 'vs/base/common/uri'; import errors = require('vs/base/common/errors'); import {SyncDescriptor0} from 'vs/platform/instantiation/common/descriptors'; import {IMessageService, Severity} from 'vs/platform/message/common/message'; import {IWorkspaceContextService, IConfiguration} from 'vs/platform/workspace/common/workspace'; import {IWindowService} from 'vs/workbench/services/window/electron-browser/windowService'; import ports = require('vs/base/node/ports'); import cp = require('child_process'); import ipc = require('ipc'); export const PLUGIN_LOG_BROADCAST_CHANNEL = 'vscode:pluginLog'; export const PLUGIN_ATTACH_BROADCAST_CHANNEL = 'vscode:pluginAttach'; // Enable to see detailed message communication between window and plugin host const logPluginHostCommunication = false; export interface ILogEntry { type: string; severity: string; arguments: any; } export class MainThreadService extends CommonMainThreadService { private pluginHostProcessManager: PluginHostProcessManager; private remoteCom: pluginsIPC.IPluginsIPC; constructor(contextService: IWorkspaceContextService, messageService: IMessageService, windowService: IWindowService) { super(contextService, 'vs/editor/common/worker/editorWorkerServer'); this.pluginHostProcessManager = new PluginHostProcessManager(contextService, messageService, windowService); let logCommunication = logPluginHostCommunication || contextService.getConfiguration().env.logPluginHostCommunication; // Message: Window --> Plugin Host this.remoteCom = pluginsIPC.create((msg) => { if (logCommunication) { console.log('%c[Window \u2192 Plugin]%c[len: ' + strings.pad(msg.length, 5, ' ') + ']', 'color: darkgreen', 'color: grey', JSON.parse(msg)); } this.pluginHostProcessManager.postMessage(msg); }); // Message: Plugin Host --> Window this.pluginHostProcessManager.startPluginHostProcess((msg) => { if (logCommunication) { console.log('%c[Plugin \u2192 Window]%c[len: ' + strings.pad(msg.length, 5, ' ') + ']', 'color: darkgreen', 'color: grey', JSON.parse(msg)); } this.remoteCom.handle(msg) }); this.remoteCom.registerBigHandler(this); } public dispose(): void { this.pluginHostProcessManager.terminate(); } protected _registerAndInstantiatePluginHostActor<T>(id: string, descriptor: SyncDescriptor0<T>): T { return this._getOrCreateProxyInstance(this.remoteCom, id, descriptor); } } class PluginHostProcessManager { private messageService: IMessageService; private contextService: IWorkspaceContextService; private windowService: IWindowService; private initializePluginHostProcess: TPromise<cp.ChildProcess>; private pluginHostProcessHandle: cp.ChildProcess; private initializeTimer: number; private lastPluginHostError: string; private unsentMessages: any[]; private terminating: boolean; private isPluginDevelopmentHost: boolean; constructor(contextService: IWorkspaceContextService, messageService: IMessageService, windowService: IWindowService) { this.messageService = messageService; this.contextService = contextService; this.windowService = windowService; // handle plugin host lifecycle a bit special when we know we are developing an extension that runs inside this.isPluginDevelopmentHost = !!this.contextService.getConfiguration().env.pluginDevelopmentPath; this.unsentMessages = []; } public startPluginHostProcess(onPluginHostMessage: (msg: any) => void): void { let config = this.contextService.getConfiguration(); let isDev = !config.env.isBuilt || !!config.env.pluginDevelopmentPath; let isTestingFromCli = !!config.env.pluginTestsPath && !config.env.debugBrkPluginHost; let opts: any = { env: objects.mixin(objects.clone(process.env), { AMD_ENTRYPOINT: 'vs/workbench/node/pluginHostProcess', PIPE_LOGGING: 'true', VERBOSE_LOGGING: true }) }; // Help in case we fail to start it if (isDev) { this.initializeTimer = setTimeout(() => { const msg = config.env.debugBrkPluginHost ? nls.localize('pluginHostProcess.startupFailDebug', "Plugin host did not start in 10 seconds, it might be stopped on the first line and needs a debugger to continue.") : nls.localize('pluginHostProcess.startupFail', "Plugin host did not start in 10 seconds, that might be a problem."); this.messageService.show(Severity.Warning, msg); }, 10000); } // Initialize plugin host process with hand shakes this.initializePluginHostProcess = new TPromise<cp.ChildProcess>((c, e) => { // Resolve additional execution args (e.g. debug) return this.resolveDebugPort(config, (port) => { if (port) { opts.execArgv = ['--nolazy', (config.env.debugBrkPluginHost ? '--debug-brk=' : '--debug=') + port]; } // Run Plugin Host as fork of current process this.pluginHostProcessHandle = cp.fork(uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=pluginHost'], opts); // Notify debugger that we are ready to attach to the process if we run a development plugin if (config.env.pluginDevelopmentPath && port) { this.windowService.broadcast({ channel: PLUGIN_ATTACH_BROADCAST_CHANNEL, payload: { port: port } }, config.env.pluginDevelopmentPath /* target */); } // Messages from Plugin host this.pluginHostProcessHandle.on('message', (msg) => { // 1) Host is ready to receive messages, initialize it if (msg === 'ready') { if (this.initializeTimer) { window.clearTimeout(this.initializeTimer); } let initPayload = marshalling.serialize({ parentPid: process.pid, contextService: { workspace: this.contextService.getWorkspace(), configuration: this.contextService.getConfiguration(), options: this.contextService.getOptions() }, }); this.pluginHostProcessHandle.send(initPayload); } // 2) Host is initialized else if (msg === 'initialized') { this.unsentMessages.forEach(m => this.postMessage(m)); this.unsentMessages = []; c(this.pluginHostProcessHandle); } // Support logging from plugin host else if (msg && (<ILogEntry>msg).type === '__$console') { let logEntry:ILogEntry = msg; let args = []; try { let parsed = JSON.parse(logEntry.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(logEntry.arguments); } // If the first argument is a string, check for % which indicates that the message // uses substitution for variables. In this case, we cannot just inject our colored // [Plugin Host] to the front because it breaks substitution. let consoleArgs = []; if (typeof args[0] === 'string' && args[0].indexOf('%') >= 0) { consoleArgs = [`%c[Plugin Host]%c ${args[0]}`, 'color: blue', 'color: black', ...args.slice(1)]; } else { consoleArgs = ['%c[Plugin Host]', 'color: blue', ...args]; } // Send to local console unless we run tests from cli if (!isTestingFromCli) { console[logEntry.severity].apply(console, consoleArgs); } // Log on main side if running tests from cli if (isTestingFromCli) { ipc.send('vscode:log', logEntry); } // Broadcast to other windows if we are in development mode else if (isDev) { this.windowService.broadcast({ channel: PLUGIN_LOG_BROADCAST_CHANNEL, payload: logEntry }, config.env.pluginDevelopmentPath /* target */); } } // Any other message goes to the callback else { onPluginHostMessage(msg); } }); // Lifecycle let onExit = () => this.terminate(); process.once('exit', onExit); this.pluginHostProcessHandle.on('error', (err) => { let errorMessage = errors.toErrorMessage(err); if (errorMessage === this.lastPluginHostError) { return; // prevent error spam } this.lastPluginHostError = errorMessage; this.messageService.show(Severity.Error, nls.localize('pluginHostProcess.error', "Error from the plugin host: {0}", errorMessage)); }); this.pluginHostProcessHandle.on('exit', (code: any, signal: any) => { process.removeListener('exit', onExit); if (!this.terminating) { // Unexpected termination if (!this.isPluginDevelopmentHost) { this.messageService.show(Severity.Error, nls.localize('pluginHostProcess.crash', "Plugin host terminated unexpectedly. Please restart VSCode to recover.")); console.error('Plugin host terminated unexpectedly. Code: ', code, ' Signal: ', signal); } // Expected development plugin termination: When the plugin host goes down we also shutdown the window else if (!isTestingFromCli) { this.windowService.getWindow().close(); } // When CLI testing make sure to exit with proper exit code else { ipc.send('vscode:exit', code); } } }); }); }, () => this.terminate()); } private resolveDebugPort(config: IConfiguration, clb: (port: number) => void): void { // Check for a free debugging port if (typeof config.env.debugPluginHostPort === 'number') { return ports.findFreePort(config.env.debugPluginHostPort, 10 /* try 10 ports */, (port) => { if (!port) { console.warn('%c[Plugin Host] %cCould not find a free port for debugging', 'color: blue', 'color: black'); return clb(void 0); } if (port !== config.env.debugPluginHostPort) { console.warn('%c[Plugin Host] %cProvided debugging port ' + config.env.debugPluginHostPort + ' is not free, using ' + port + ' instead.', 'color: blue', 'color: black'); } if (config.env.debugBrkPluginHost) { console.warn('%c[Plugin Host] %cSTOPPED on first line for debugging on port ' + port, 'color: blue', 'color: black'); } else { console.info('%c[Plugin Host] %cdebugger listening on port ' + port, 'color: blue', 'color: black'); } return clb(port); }); } // Nothing to do here else { return clb(void 0); } } public postMessage(msg: any): void { if (this.initializePluginHostProcess) { this.initializePluginHostProcess.done(p => p.send(msg)); } else { this.unsentMessages.push(msg); } } public terminate(): void { this.terminating = true; if (this.pluginHostProcessHandle) { this.pluginHostProcessHandle.kill(); } } }
src/vs/workbench/services/thread/electron-browser/threadService.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00020591745851561427, 0.00017142496653832495, 0.00016411438991781324, 0.0001702793233562261, 0.000007052096407278441 ]
{ "id": 2, "code_window": [ "export interface IQuickOpenEntryTemplateData {\n", "\tcontainer: HTMLElement;\n", "\ticon: HTMLSpanElement;\n", "\tlabel: HighlightedLabel.HighlightedLabel;\n", "\tmeta: HTMLSpanElement;\n", "\tdescription: HighlightedLabel.HighlightedLabel;\n", "\tactionBar: ActionBar.ActionBar;\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprefix: HTMLSpanElement;\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 301 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import WinJS = require('vs/base/common/winjs.base'); import Types = require('vs/base/common/types'); import URI from 'vs/base/common/uri'; import Tree = require('vs/base/parts/tree/common/tree'); import {IQuickNavigateConfiguration, IModel, IDataSource, IFilter, IRenderer, IRunner, Mode} from './quickOpen'; import ActionsRenderer = require('vs/base/parts/tree/browser/actionsRenderer'); import Actions = require('vs/base/common/actions'); import {compareAnything} from 'vs/base/common/comparers'; import ActionBar = require('vs/base/browser/ui/actionbar/actionbar'); import TreeDefaults = require('vs/base/parts/tree/browser/treeDefaults'); import HighlightedLabel = require('vs/base/browser/ui/highlightedlabel/highlightedLabel'); import DOM = require('vs/base/browser/dom'); export interface IContext { event: any; quickNavigateConfiguration: IQuickNavigateConfiguration; } export interface IHighlight { start: number; end: number; } let IDS = 0; export class QuickOpenEntry { private id: string; private labelHighlights: IHighlight[]; private descriptionHighlights: IHighlight[]; private hidden: boolean; constructor(highlights: IHighlight[] = []) { this.id = (IDS++).toString(); this.labelHighlights = highlights; this.descriptionHighlights = []; } /** * A unique identifier for the entry */ public getId(): string { return this.id; } /** * The label of the entry to identify it from others in the list */ public getLabel(): string { return null; } /** * Meta information about the entry that is optional and can be shown to the right of the label */ public getMeta(): string { return null; } /** * The icon of the entry to identify it from others in the list */ public getIcon(): string { return null; } /** * A secondary description that is optional and can be shown right to the label */ public getDescription(): string { return null; } /** * A resource for this entry. Resource URIs can be used to compare different kinds of entries and group * them together. */ public getResource(): URI { return null; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public isHidden(): boolean { return this.hidden; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public setHidden(hidden: boolean): void { this.hidden = hidden; } /** * Allows to set highlight ranges that should show up for the entry label and optionally description if set. */ public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.labelHighlights = labelHighlights; this.descriptionHighlights = descriptionHighlights; } /** * Allows to return highlight ranges that should show up for the entry label and description. */ public getHighlights(): [IHighlight[] /* Label */, IHighlight[] /* Description */] { return [this.labelHighlights, this.descriptionHighlights]; } /** * Called when the entry is selected for opening. Returns a boolean value indicating if an action was performed or not. * The mode parameter gives an indication if the element is previewed (using arrow keys) or opened. * * The context parameter provides additional context information how the run was triggered. */ public run(mode: Mode, context: IContext): boolean { return false; } /** * A good default sort implementation for quick open entries */ public static compare(elementA: QuickOpenEntry, elementB: QuickOpenEntry, lookFor: string): number { // Give matches with label highlights higher priority over // those with only description highlights const labelHighlightsA = elementA.getHighlights()[0] || []; const labelHighlightsB = elementB.getHighlights()[0] || []; if (labelHighlightsA.length && !labelHighlightsB.length) { return -1; } else if (!labelHighlightsA.length && labelHighlightsB.length) { return 1; } // Sort by name/path let nameA = elementA.getLabel(); let nameB = elementB.getLabel(); if (nameA === nameB) { let resourceA = elementA.getResource(); let resourceB = elementB.getResource(); if (resourceA && resourceB) { nameA = elementA.getResource().fsPath; nameB = elementB.getResource().fsPath; } } return compareAnything(nameA, nameB, lookFor); } } export class QuickOpenEntryItem extends QuickOpenEntry { /** * Must return the height as being used by the render function. */ public getHeight(): number { return 0; } /** * Allows to present the quick open entry in a custom way inside the tree. */ public render(tree: Tree.ITree, container: HTMLElement, previousCleanupFn: Tree.IElementCallback): Tree.IElementCallback { return null; } } export class QuickOpenEntryGroup extends QuickOpenEntry { private entry: QuickOpenEntry; private groupLabel: string; private withBorder: boolean; constructor(entry?: QuickOpenEntry, groupLabel?: string, withBorder?: boolean) { super(); this.entry = entry; this.groupLabel = groupLabel; this.withBorder = withBorder; } /** * The label of the group or null if none. */ public getGroupLabel(): string { return this.groupLabel; } public setGroupLabel(groupLabel: string): void { this.groupLabel = groupLabel; } /** * Whether to show a border on top of the group entry or not. */ public showBorder(): boolean { return this.withBorder; } public setShowBorder(showBorder: boolean): void { this.withBorder = showBorder; } public getLabel(): string { return this.entry ? this.entry.getLabel() : super.getLabel(); } public getMeta(): string { return this.entry ? this.entry.getMeta() : super.getMeta(); } public getResource(): URI { return this.entry ? this.entry.getResource() : super.getResource(); } public getIcon(): string { return this.entry ? this.entry.getIcon() : super.getIcon(); } public getDescription(): string { return this.entry ? this.entry.getDescription() : super.getDescription(); } public getEntry(): QuickOpenEntry { return this.entry; } public getHighlights(): [IHighlight[], IHighlight[]] { return this.entry ? this.entry.getHighlights() : super.getHighlights(); } public isHidden(): boolean { return this.entry ? this.entry.isHidden() : super.isHidden(); } public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.entry ? this.entry.setHighlights(labelHighlights, descriptionHighlights) : super.setHighlights(labelHighlights, descriptionHighlights); } public setHidden(hidden: boolean): void { this.entry ? this.entry.setHidden(hidden) : super.setHidden(hidden); } public run(mode: Mode, context: IContext): boolean { return this.entry ? this.entry.run(mode, context) : super.run(mode, context); } } const templateEntry = 'quickOpenEntry'; const templateEntryGroup = 'quickOpenEntryGroup'; const templateEntryItem = 'quickOpenEntryItem'; class EntryItemRenderer extends TreeDefaults.LegacyRenderer { public getTemplateId(tree: Tree.ITree, element: any): string { return templateEntryItem; } protected render(tree: Tree.ITree, element: any, container: HTMLElement, previousCleanupFn?: Tree.IElementCallback): Tree.IElementCallback { if (element instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>element).render(tree, container, previousCleanupFn); } return super.render(tree, element, container, previousCleanupFn); } } class NoActionProvider implements ActionsRenderer.IActionProvider { public hasActions(tree: Tree.ITree, element: any): boolean { return false; } public getActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public hasSecondaryActions(tree: Tree.ITree, element: any): boolean { return false; } public getSecondaryActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public getActionItem(tree: Tree.ITree, element: any, action: Actions.Action): ActionBar.IActionItem { return null; } } export interface IQuickOpenEntryTemplateData { container: HTMLElement; icon: HTMLSpanElement; label: HighlightedLabel.HighlightedLabel; meta: HTMLSpanElement; description: HighlightedLabel.HighlightedLabel; actionBar: ActionBar.ActionBar; } export interface IQuickOpenEntryGroupTemplateData extends IQuickOpenEntryTemplateData { group: HTMLDivElement; } class Renderer implements IRenderer<QuickOpenEntry> { private actionProvider: ActionsRenderer.IActionProvider; private actionRunner: Actions.IActionRunner; private entryItemRenderer: EntryItemRenderer; constructor(actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider(), actionRunner: Actions.IActionRunner = null) { this.actionProvider = actionProvider; this.actionRunner = actionRunner; this.entryItemRenderer = new EntryItemRenderer(); } public getHeight(entry: QuickOpenEntry): number { if (entry instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>entry).getHeight(); } return 24; } public getTemplateId(entry: QuickOpenEntry): string { if (entry instanceof QuickOpenEntryItem) { return templateEntryItem; } if (entry instanceof QuickOpenEntryGroup) { return templateEntryGroup; } return templateEntry; } public renderTemplate(templateId: string, container: HTMLElement): IQuickOpenEntryGroupTemplateData { // Entry Item if (templateId === templateEntryItem) { return this.entryItemRenderer.renderTemplate(null, templateId, container); } // Entry Group let group: HTMLDivElement; if (templateId === templateEntryGroup) { group = document.createElement('div'); DOM.addClass(group, 'results-group'); container.appendChild(group); } // Action Bar DOM.addClass(container, 'actions'); let entryContainer = document.createElement('div'); DOM.addClass(entryContainer, 'sub-content'); container.appendChild(entryContainer); let actionBarContainer = document.createElement('div'); DOM.addClass(actionBarContainer, 'primary-action-bar'); container.appendChild(actionBarContainer); let actionBar = new ActionBar.ActionBar(actionBarContainer, { actionRunner: this.actionRunner }); // Entry let entry = document.createElement('div'); DOM.addClass(entry, 'quick-open-entry'); entryContainer.appendChild(entry); // Icon let icon = document.createElement('span'); entry.appendChild(icon); // Label let label = new HighlightedLabel.HighlightedLabel(entry); // Meta let meta = document.createElement('span'); entry.appendChild(meta); DOM.addClass(meta, 'quick-open-entry-meta'); // Description let descriptionContainer = document.createElement('span'); entry.appendChild(descriptionContainer); DOM.addClass(descriptionContainer, 'quick-open-entry-description'); let description = new HighlightedLabel.HighlightedLabel(descriptionContainer); return { container: container, icon: icon, label: label, meta: meta, description: description, group: group, actionBar: actionBar }; } public renderElement(entry: QuickOpenEntry, templateId: string, templateData: any): void { // Entry Item if (templateId === templateEntryItem) { this.entryItemRenderer.renderElement(null, entry, templateId, <TreeDefaults.ILegacyTemplateData>templateData); return; } let data: IQuickOpenEntryTemplateData = templateData; // Action Bar if (this.actionProvider.hasActions(null, entry)) { DOM.addClass(data.container, 'has-actions'); } else { DOM.removeClass(data.container, 'has-actions'); } data.actionBar.context = entry; // make sure the context is the current element this.actionProvider.getActions(null, entry).then((actions) => { // TODO@Ben this will not work anymore as soon as quick open has more actions // but as long as there is only one are ok if (data.actionBar.isEmpty() && actions && actions.length > 0) { data.actionBar.push(actions, { icon: true, label: false }); } else if (!data.actionBar.isEmpty() && (!actions || actions.length === 0)) { data.actionBar.clear(); } }); // Entry group if (entry instanceof QuickOpenEntryGroup) { let group = <QuickOpenEntryGroup>entry; // Border if (group.showBorder()) { DOM.addClass(data.container, 'results-group-separator'); } else { DOM.removeClass(data.container, 'results-group-separator'); } // Group Label let groupLabel = group.getGroupLabel() || ''; (<IQuickOpenEntryGroupTemplateData>templateData).group.textContent = groupLabel; } // Normal Entry if (entry instanceof QuickOpenEntry) { let highlights = entry.getHighlights(); // Icon let iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : ''; data.icon.className = iconClass; // Label let labelHighlights = highlights[0]; data.label.set(entry.getLabel() || '', labelHighlights || []); // Meta let metaLabel = entry.getMeta() || ''; data.meta.textContent = metaLabel; // Description let descriptionHighlights = highlights[1]; data.description.set(entry.getDescription() || '', descriptionHighlights || []); } } public disposeTemplate(templateId: string, templateData: any): void { if (templateId === templateEntryItem) { this.entryItemRenderer.disposeTemplate(null, templateId, templateData); } } } export class QuickOpenModel implements IModel<QuickOpenEntry>, IDataSource<QuickOpenEntry>, IFilter<QuickOpenEntry>, IRunner<QuickOpenEntry> { private _entries: QuickOpenEntry[]; private _dataSource: IDataSource<QuickOpenEntry>; private _renderer: IRenderer<QuickOpenEntry>; private _filter: IFilter<QuickOpenEntry>; private _runner: IRunner<QuickOpenEntry>; constructor(entries: QuickOpenEntry[] = [], actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider()) { this._entries = entries; this._dataSource = this; this._renderer = new Renderer(actionProvider); this._filter = this; this._runner = this; } public get entries() { return this._entries; } public get dataSource() { return this._dataSource; } public get renderer() { return this._renderer; } public get filter() { return this._filter; } public get runner() { return this._runner; } public set entries(entries: QuickOpenEntry[]) { this._entries = entries; } /** * Adds entries that should show up in the quick open viewer. */ public addEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = this._entries.concat(entries); } } /** * Set the entries that should show up in the quick open viewer. */ public setEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = entries; } } /** * Get the entries that should show up in the quick open viewer. * * @visibleOnly optional parameter to only return visible entries */ public getEntries(visibleOnly?: boolean): QuickOpenEntry[] { if (visibleOnly) { return this._entries.filter((e) => !e.isHidden()); } return this._entries; } getId(entry: QuickOpenEntry): string { return entry.getId(); } getLabel(entry: QuickOpenEntry): string { return entry.getLabel(); } isVisible<T>(entry: QuickOpenEntry): boolean { return !entry.isHidden(); } run(entry: QuickOpenEntry, mode: Mode, context: IContext): boolean { return entry.run(mode, context); } }
src/vs/base/parts/quickopen/browser/quickOpenModel.ts
1
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.9991948008537292, 0.08910969644784927, 0.00016406134818680584, 0.00020202604355290532, 0.2757326066493988 ]
{ "id": 2, "code_window": [ "export interface IQuickOpenEntryTemplateData {\n", "\tcontainer: HTMLElement;\n", "\ticon: HTMLSpanElement;\n", "\tlabel: HighlightedLabel.HighlightedLabel;\n", "\tmeta: HTMLSpanElement;\n", "\tdescription: HighlightedLabel.HighlightedLabel;\n", "\tactionBar: ActionBar.ActionBar;\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprefix: HTMLSpanElement;\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 301 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Promise } from 'vs/base/common/winjs.base'; import { isFunction } from 'vs/base/common/types'; import { ActionBar, IActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { ITree, IRenderer, IFilter, IDataSource } from 'vs/base/parts/tree/common/tree'; import { IModel } from './quickOpen'; export interface IModelProvider { getModel<T>(): IModel<T>; } export class DataSource implements IDataSource { private modelProvider: IModelProvider; constructor(model: IModel<any>); constructor(modelProvider: IModelProvider); constructor(arg: any) { this.modelProvider = isFunction(arg.getModel) ? arg : { getModel: () => arg }; } getId(tree: ITree, element: any): string { if (!element) { return null; } const model = this.modelProvider.getModel(); return model === element ? '__root__' : model.dataSource.getId(element); } hasChildren(tree: ITree, element: any): boolean { const model = this.modelProvider.getModel(); return model && model === element && model.entries.length > 0; } getChildren(tree: ITree, element: any): Promise { const model = this.modelProvider.getModel(); return Promise.as(model === element ? model.entries : []); } getParent(tree: ITree, element: any): Promise { return Promise.as(null); } } export class Filter implements IFilter { constructor(private modelProvider: IModelProvider) { } isVisible(tree: ITree, element: any): boolean { const model = this.modelProvider.getModel(); if (!model.filter) { return true; } return model.filter.isVisible(element); } } export class Renderer implements IRenderer { constructor(private modelProvider: IModelProvider) { } getHeight(tree: ITree, element: any): number { const model = this.modelProvider.getModel(); return model.renderer.getHeight(element); } getTemplateId(tree: ITree, element: any): string { const model = this.modelProvider.getModel(); return model.renderer.getTemplateId(element); } renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any { const model = this.modelProvider.getModel(); return model.renderer.renderTemplate(templateId, container); } renderElement(tree: ITree, element: any, templateId: string, templateData: any): void { const model = this.modelProvider.getModel(); model.renderer.renderElement(element, templateId, templateData); } disposeTemplate(tree: ITree, templateId: string, templateData: any): void { const model = this.modelProvider.getModel(); model.renderer.disposeTemplate(templateId, templateData); } }
src/vs/base/parts/quickopen/browser/quickOpenViewer.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017720210598781705, 0.00017002371896523982, 0.00016270275227725506, 0.00016997568309307098, 0.000003973258571932092 ]
{ "id": 2, "code_window": [ "export interface IQuickOpenEntryTemplateData {\n", "\tcontainer: HTMLElement;\n", "\ticon: HTMLSpanElement;\n", "\tlabel: HighlightedLabel.HighlightedLabel;\n", "\tmeta: HTMLSpanElement;\n", "\tdescription: HighlightedLabel.HighlightedLabel;\n", "\tactionBar: ActionBar.ActionBar;\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprefix: HTMLSpanElement;\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 301 }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>fileTypes</key> <array> <string>ini</string> <string>conf</string> </array> <key>keyEquivalent</key> <string>^~I</string> <key>name</key> <string>Ini</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>(^[ \t]+)?(?=#)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.whitespace.comment.leading.ini</string> </dict> </dict> <key>end</key> <string>(?!\G)</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>#</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.comment.ini</string> </dict> </dict> <key>end</key> <string>\n</string> <key>name</key> <string>comment.line.number-sign.ini</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(^[ \t]+)?(?=;)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.whitespace.comment.leading.ini</string> </dict> </dict> <key>end</key> <string>(?!\G)</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>;</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.comment.ini</string> </dict> </dict> <key>end</key> <string>\n</string> <key>name</key> <string>comment.line.semicolon.ini</string> </dict> </array> </dict> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.other.definition.ini</string> </dict> <key>2</key> <dict> <key>name</key> <string>punctuation.separator.key-value.ini</string> </dict> </dict> <key>match</key> <string>\b([a-zA-Z0-9_.-]+)\b\s*(=)</string> </dict> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.entity.ini</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.entity.ini</string> </dict> </dict> <key>match</key> <string>^(\[)(.*?)(\])</string> <key>name</key> <string>entity.name.section.group-title.ini</string> </dict> <dict> <key>begin</key> <string>'</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.ini</string> </dict> </dict> <key>end</key> <string>'</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.ini</string> </dict> </dict> <key>name</key> <string>string.quoted.single.ini</string> <key>patterns</key> <array> <dict> <key>match</key> <string>\\.</string> <key>name</key> <string>constant.character.escape.ini</string> </dict> </array> </dict> <dict> <key>begin</key> <string>"</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.ini</string> </dict> </dict> <key>end</key> <string>"</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.ini</string> </dict> </dict> <key>name</key> <string>string.quoted.double.ini</string> </dict> </array> <key>scopeName</key> <string>source.ini</string> <key>uuid</key> <string>77DC23B6-8A90-11D9-BAA4-000A9584EC8C</string> </dict> </plist>
extensions/ini/syntaxes/Ini.plist
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017837536870501935, 0.0001738143473630771, 0.00017097267846111208, 0.00017394886526744813, 0.0000016955663113549235 ]
{ "id": 2, "code_window": [ "export interface IQuickOpenEntryTemplateData {\n", "\tcontainer: HTMLElement;\n", "\ticon: HTMLSpanElement;\n", "\tlabel: HighlightedLabel.HighlightedLabel;\n", "\tmeta: HTMLSpanElement;\n", "\tdescription: HighlightedLabel.HighlightedLabel;\n", "\tactionBar: ActionBar.ActionBar;\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprefix: HTMLSpanElement;\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 301 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.method, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.function, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.constructor, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.variable, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.class, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.interface, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.module, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.property, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.enum, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.string, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.rule, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.file, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.array, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.number, .monaco-workbench .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.boolean { background-image: url('symbol-sprite.svg'); background-repeat: no-repeat; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.method, .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.function, .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.constructor { background-position: 0 -4px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.variable { background-position: -22px -4px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.class { background-position: -43px -3px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.interface { background-position: -63px -4px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.module { background-position: -82px -4px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.property { background-position: -102px -3px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.enum { background-position: -122px -3px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.string { background-position: -202px -3px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.rule { background-position: -242px -4px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.file { background-position: -262px -4px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.array { background-position: -302px -4px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.number { background-position: -322px -4px; } .monaco-workbench.vs .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.boolean { background-position: -343px -4px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.method, .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.function, .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.constructor { background-position: 0 -24px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.variable { background-position: -22px -24px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.class { background-position: -43px -23px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.interface { background-position: -63px -24px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.module { background-position: -82px -24px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.property { background-position: -102px -23px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.string { background-position: -202px -23px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.enum { background-position: -122px -23px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.rule { background-position: -242px -24px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.file { background-position: -262px -24px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.array { background-position: -302px -24px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.number { background-position: -322px -24px; } .monaco-workbench.vs-dark .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.boolean { background-position: -342px -24px; } /* High Contrast Theming */ .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.method, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.function, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.constructor, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.variable, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.class, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.interface, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.module, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.property, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.enum, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.string, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.rule, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.file, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.array, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.number, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.boolean { background: none; display: inline; } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.method:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.function:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.constructor:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.variable:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.class:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.interface:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.module:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.property:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.enum:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.string:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.rule:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.file:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.array:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.number:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.boolean:before { height: 16px; width: 16px; display: inline-block; } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.method:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.function:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.constructor:before { content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZmlsbD0iI0IxODBENyIgZD0iTTUuNSAzbC00LjUgMi44NTd2NC4yODVsNC41IDIuODU4IDQuNS0yLjg1N3YtNC4yODZsLTQuNS0yLjg1N3ptLS41IDguNDk4bC0zLTEuOTA1di0yLjgxNmwzIDEuOTA1djIuODE2em0tMi4zNTgtNS40OThsMi44NTgtMS44MTUgMi44NTggMS44MTUtMi44NTggMS44MTUtMi44NTgtMS44MTV6bTYuMzU4IDMuNTkzbC0zIDEuOTA1di0yLjgxNWwzLTEuOTA1djIuODE1eiIvPjwvc3ZnPg=="); margin-left: 2px; } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.field:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.variable:before { content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZmlsbD0iIzc1QkVGRiIgZD0iTTEgNnY0bDQgMiA2LTN2LTRsLTQtMi02IDN6bTQgMWwtMi0xIDQtMiAyIDEtNCAyeiIvPjwvc3ZnPg=="); margin-left: 2px; } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.class:before { content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBvbHlnb24gZmlsbD0iI0U4QUI1MyIgcG9pbnRzPSIxMS45OTgsMTEuMDAyIDksMTEgOSw3IDExLDcgMTAsOCAxMiwxMCAxNSw3IDEzLDUgMTIsNiA3LDYgOSw0IDYsMSAxLDYgNCw5IDYsNyA4LDcgOCwxMiAxMSwxMiAxMCwxMyAxMiwxNSAxNSwxMiAxMywxMCIvPjwvc3ZnPg=="); } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.interface:before { content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZmlsbD0iIzc1QkVGRiIgZD0iTTExLjUgNGMtMS43NTkgMC0zLjIwNCAxLjMwOC0zLjQ0OSAzaC0zLjEyMmMtLjIyMy0uODYxLS45OTgtMS41LTEuOTI5LTEuNS0xLjEwNCAwLTIgLjg5NS0yIDIgMCAxLjEwNC44OTYgMiAyIDIgLjkzMSAwIDEuNzA2LS42MzkgMS45MjktMS41aDMuMTIyYy4yNDUgMS42OTEgMS42OSAzIDMuNDQ5IDMgMS45MyAwIDMuNS0xLjU3IDMuNS0zLjUgMC0xLjkzMS0xLjU3LTMuNS0zLjUtMy41em0wIDVjLS44MjcgMC0xLjUtLjY3NC0xLjUtMS41IDAtLjgyOC42NzMtMS41IDEuNS0xLjVzMS41LjY3MiAxLjUgMS41YzAgLjgyNi0uNjczIDEuNS0xLjUgMS41eiIvPjwvc3ZnPg=="); } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.module:before { content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZmlsbD0iI0M1QzVDNSIgZD0iTTkgMTF2LTFjMC0uODM0LjQ5Ni0xLjczOCAxLTItLjUwNC0uMjctMS0xLjE2OC0xLTJ2LTFjMC0uODQtLjU4NC0xLTEtMXYtMWMyLjA4MyAwIDIgMS4xNjYgMiAydjFjMCAuOTY5LjcwMy45OCAxIDF2MmMtLjMyMi4wMi0xIC4wNTMtMSAxdjFjMCAuODM0LjA4MyAyLTIgMnYtMWMuODMzIDAgMS0xIDEtMXptLTYgMHYtMWMwLS44MzQtLjQ5Ni0xLjczOC0xLTIgLjUwNC0uMjcgMS0xLjE2OCAxLTJ2LTFjMC0uODQuNTg0LTEgMS0xdi0xYy0yLjA4MyAwLTIgMS4xNjYtMiAydjFjMCAuOTY5LS43MDMuOTgtMSAxdjJjLjMyMi4wMiAxIC4wNTMgMSAxdjFjMCAuODM0LS4wODMgMiAyIDJ2LTFjLS44MzMgMC0xLTEtMS0xeiIvPjwvc3ZnPg=="); margin-left: 2px; } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.property:before { content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZmlsbD0iI0M1QzVDNSIgZD0iTTEyLjA5IDQuMzU5bC0yLjY0MSAyLjY0MS0yLTIgMi42NDEtMi42NDFjLS41MDItLjIyNi0xLjA1NS0uMzU5LTEuNjQxLS4zNTktMi4yMDkgMC00IDEuNzkxLTQgNCAwIC41ODYuMTMzIDEuMTM5LjM1OSAxLjY0bC0zLjM1OSAzLjM2cy0xIDEgMCAyaDJsMy4zNTktMy4zNmMuNTAzLjIyNiAxLjA1NS4zNiAxLjY0MS4zNiAyLjIwOSAwIDQtMS43OTEgNC00IDAtLjU4Ni0uMTMzLTEuMTM5LS4zNTktMS42NDF6Ii8+PC9zdmc+"); margin-left: 1px; } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.value:before, .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.enum:before { content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PGcgZmlsbD0iIzc1QkVGRiI+PHBhdGggZD0iTTEyIDNoLTRsLTEgMXYyaDV2MWgtMnYxaDJsMS0xdi0zbC0xLTF6bTAgMmgtNHYtMWg0djF6TTMgMTJoNnYtNWgtNnY1em0xLTNoNHYxaC00di0xeiIvPjwvZz48L3N2Zz4="); } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.rule:before { content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMiIgaGVpZ2h0PSIxMiI+PHBhdGggZmlsbD0iI0M1QzVDNSIgZD0iTTEwIDVoLTh2LTJoOHYyem0wIDFoLTZ2MWg2di0xem0wIDJoLTZ2MWg2di0xeiIvPjwvc3ZnPg=="); } .monaco-workbench.hc-black .quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.file:before { content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZmlsbD0iI0M1QzVDNSIgZD0iTTkuNjc2IDJoLTYuNjc2djEyaDEwdi05bC0zLjMyNC0zem0yLjMyNCAxMWgtOHYtMTBoNXYzaDN2N3oiLz48L3N2Zz4="); }
src/vs/workbench/parts/quickopen/browser/media/gotoSymbolHandler.css
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.004910305608063936, 0.0006027042982168496, 0.0001640629197936505, 0.00016767176566645503, 0.001178242266178131 ]
{ "id": 3, "code_window": [ "\t\tlet icon = document.createElement('span');\n", "\t\tentry.appendChild(icon);\n", "\n", "\t\t// Label\n", "\t\tlet label = new HighlightedLabel.HighlightedLabel(entry);\n", "\n", "\t\t// Meta\n", "\t\tlet meta = document.createElement('span');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// Prefix\n", "\t\tlet prefix = document.createElement('span');\n", "\t\tentry.appendChild(prefix);\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 382 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import WinJS = require('vs/base/common/winjs.base'); import Types = require('vs/base/common/types'); import URI from 'vs/base/common/uri'; import Tree = require('vs/base/parts/tree/common/tree'); import {IQuickNavigateConfiguration, IModel, IDataSource, IFilter, IRenderer, IRunner, Mode} from './quickOpen'; import ActionsRenderer = require('vs/base/parts/tree/browser/actionsRenderer'); import Actions = require('vs/base/common/actions'); import {compareAnything} from 'vs/base/common/comparers'; import ActionBar = require('vs/base/browser/ui/actionbar/actionbar'); import TreeDefaults = require('vs/base/parts/tree/browser/treeDefaults'); import HighlightedLabel = require('vs/base/browser/ui/highlightedlabel/highlightedLabel'); import DOM = require('vs/base/browser/dom'); export interface IContext { event: any; quickNavigateConfiguration: IQuickNavigateConfiguration; } export interface IHighlight { start: number; end: number; } let IDS = 0; export class QuickOpenEntry { private id: string; private labelHighlights: IHighlight[]; private descriptionHighlights: IHighlight[]; private hidden: boolean; constructor(highlights: IHighlight[] = []) { this.id = (IDS++).toString(); this.labelHighlights = highlights; this.descriptionHighlights = []; } /** * A unique identifier for the entry */ public getId(): string { return this.id; } /** * The label of the entry to identify it from others in the list */ public getLabel(): string { return null; } /** * Meta information about the entry that is optional and can be shown to the right of the label */ public getMeta(): string { return null; } /** * The icon of the entry to identify it from others in the list */ public getIcon(): string { return null; } /** * A secondary description that is optional and can be shown right to the label */ public getDescription(): string { return null; } /** * A resource for this entry. Resource URIs can be used to compare different kinds of entries and group * them together. */ public getResource(): URI { return null; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public isHidden(): boolean { return this.hidden; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public setHidden(hidden: boolean): void { this.hidden = hidden; } /** * Allows to set highlight ranges that should show up for the entry label and optionally description if set. */ public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.labelHighlights = labelHighlights; this.descriptionHighlights = descriptionHighlights; } /** * Allows to return highlight ranges that should show up for the entry label and description. */ public getHighlights(): [IHighlight[] /* Label */, IHighlight[] /* Description */] { return [this.labelHighlights, this.descriptionHighlights]; } /** * Called when the entry is selected for opening. Returns a boolean value indicating if an action was performed or not. * The mode parameter gives an indication if the element is previewed (using arrow keys) or opened. * * The context parameter provides additional context information how the run was triggered. */ public run(mode: Mode, context: IContext): boolean { return false; } /** * A good default sort implementation for quick open entries */ public static compare(elementA: QuickOpenEntry, elementB: QuickOpenEntry, lookFor: string): number { // Give matches with label highlights higher priority over // those with only description highlights const labelHighlightsA = elementA.getHighlights()[0] || []; const labelHighlightsB = elementB.getHighlights()[0] || []; if (labelHighlightsA.length && !labelHighlightsB.length) { return -1; } else if (!labelHighlightsA.length && labelHighlightsB.length) { return 1; } // Sort by name/path let nameA = elementA.getLabel(); let nameB = elementB.getLabel(); if (nameA === nameB) { let resourceA = elementA.getResource(); let resourceB = elementB.getResource(); if (resourceA && resourceB) { nameA = elementA.getResource().fsPath; nameB = elementB.getResource().fsPath; } } return compareAnything(nameA, nameB, lookFor); } } export class QuickOpenEntryItem extends QuickOpenEntry { /** * Must return the height as being used by the render function. */ public getHeight(): number { return 0; } /** * Allows to present the quick open entry in a custom way inside the tree. */ public render(tree: Tree.ITree, container: HTMLElement, previousCleanupFn: Tree.IElementCallback): Tree.IElementCallback { return null; } } export class QuickOpenEntryGroup extends QuickOpenEntry { private entry: QuickOpenEntry; private groupLabel: string; private withBorder: boolean; constructor(entry?: QuickOpenEntry, groupLabel?: string, withBorder?: boolean) { super(); this.entry = entry; this.groupLabel = groupLabel; this.withBorder = withBorder; } /** * The label of the group or null if none. */ public getGroupLabel(): string { return this.groupLabel; } public setGroupLabel(groupLabel: string): void { this.groupLabel = groupLabel; } /** * Whether to show a border on top of the group entry or not. */ public showBorder(): boolean { return this.withBorder; } public setShowBorder(showBorder: boolean): void { this.withBorder = showBorder; } public getLabel(): string { return this.entry ? this.entry.getLabel() : super.getLabel(); } public getMeta(): string { return this.entry ? this.entry.getMeta() : super.getMeta(); } public getResource(): URI { return this.entry ? this.entry.getResource() : super.getResource(); } public getIcon(): string { return this.entry ? this.entry.getIcon() : super.getIcon(); } public getDescription(): string { return this.entry ? this.entry.getDescription() : super.getDescription(); } public getEntry(): QuickOpenEntry { return this.entry; } public getHighlights(): [IHighlight[], IHighlight[]] { return this.entry ? this.entry.getHighlights() : super.getHighlights(); } public isHidden(): boolean { return this.entry ? this.entry.isHidden() : super.isHidden(); } public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.entry ? this.entry.setHighlights(labelHighlights, descriptionHighlights) : super.setHighlights(labelHighlights, descriptionHighlights); } public setHidden(hidden: boolean): void { this.entry ? this.entry.setHidden(hidden) : super.setHidden(hidden); } public run(mode: Mode, context: IContext): boolean { return this.entry ? this.entry.run(mode, context) : super.run(mode, context); } } const templateEntry = 'quickOpenEntry'; const templateEntryGroup = 'quickOpenEntryGroup'; const templateEntryItem = 'quickOpenEntryItem'; class EntryItemRenderer extends TreeDefaults.LegacyRenderer { public getTemplateId(tree: Tree.ITree, element: any): string { return templateEntryItem; } protected render(tree: Tree.ITree, element: any, container: HTMLElement, previousCleanupFn?: Tree.IElementCallback): Tree.IElementCallback { if (element instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>element).render(tree, container, previousCleanupFn); } return super.render(tree, element, container, previousCleanupFn); } } class NoActionProvider implements ActionsRenderer.IActionProvider { public hasActions(tree: Tree.ITree, element: any): boolean { return false; } public getActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public hasSecondaryActions(tree: Tree.ITree, element: any): boolean { return false; } public getSecondaryActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public getActionItem(tree: Tree.ITree, element: any, action: Actions.Action): ActionBar.IActionItem { return null; } } export interface IQuickOpenEntryTemplateData { container: HTMLElement; icon: HTMLSpanElement; label: HighlightedLabel.HighlightedLabel; meta: HTMLSpanElement; description: HighlightedLabel.HighlightedLabel; actionBar: ActionBar.ActionBar; } export interface IQuickOpenEntryGroupTemplateData extends IQuickOpenEntryTemplateData { group: HTMLDivElement; } class Renderer implements IRenderer<QuickOpenEntry> { private actionProvider: ActionsRenderer.IActionProvider; private actionRunner: Actions.IActionRunner; private entryItemRenderer: EntryItemRenderer; constructor(actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider(), actionRunner: Actions.IActionRunner = null) { this.actionProvider = actionProvider; this.actionRunner = actionRunner; this.entryItemRenderer = new EntryItemRenderer(); } public getHeight(entry: QuickOpenEntry): number { if (entry instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>entry).getHeight(); } return 24; } public getTemplateId(entry: QuickOpenEntry): string { if (entry instanceof QuickOpenEntryItem) { return templateEntryItem; } if (entry instanceof QuickOpenEntryGroup) { return templateEntryGroup; } return templateEntry; } public renderTemplate(templateId: string, container: HTMLElement): IQuickOpenEntryGroupTemplateData { // Entry Item if (templateId === templateEntryItem) { return this.entryItemRenderer.renderTemplate(null, templateId, container); } // Entry Group let group: HTMLDivElement; if (templateId === templateEntryGroup) { group = document.createElement('div'); DOM.addClass(group, 'results-group'); container.appendChild(group); } // Action Bar DOM.addClass(container, 'actions'); let entryContainer = document.createElement('div'); DOM.addClass(entryContainer, 'sub-content'); container.appendChild(entryContainer); let actionBarContainer = document.createElement('div'); DOM.addClass(actionBarContainer, 'primary-action-bar'); container.appendChild(actionBarContainer); let actionBar = new ActionBar.ActionBar(actionBarContainer, { actionRunner: this.actionRunner }); // Entry let entry = document.createElement('div'); DOM.addClass(entry, 'quick-open-entry'); entryContainer.appendChild(entry); // Icon let icon = document.createElement('span'); entry.appendChild(icon); // Label let label = new HighlightedLabel.HighlightedLabel(entry); // Meta let meta = document.createElement('span'); entry.appendChild(meta); DOM.addClass(meta, 'quick-open-entry-meta'); // Description let descriptionContainer = document.createElement('span'); entry.appendChild(descriptionContainer); DOM.addClass(descriptionContainer, 'quick-open-entry-description'); let description = new HighlightedLabel.HighlightedLabel(descriptionContainer); return { container: container, icon: icon, label: label, meta: meta, description: description, group: group, actionBar: actionBar }; } public renderElement(entry: QuickOpenEntry, templateId: string, templateData: any): void { // Entry Item if (templateId === templateEntryItem) { this.entryItemRenderer.renderElement(null, entry, templateId, <TreeDefaults.ILegacyTemplateData>templateData); return; } let data: IQuickOpenEntryTemplateData = templateData; // Action Bar if (this.actionProvider.hasActions(null, entry)) { DOM.addClass(data.container, 'has-actions'); } else { DOM.removeClass(data.container, 'has-actions'); } data.actionBar.context = entry; // make sure the context is the current element this.actionProvider.getActions(null, entry).then((actions) => { // TODO@Ben this will not work anymore as soon as quick open has more actions // but as long as there is only one are ok if (data.actionBar.isEmpty() && actions && actions.length > 0) { data.actionBar.push(actions, { icon: true, label: false }); } else if (!data.actionBar.isEmpty() && (!actions || actions.length === 0)) { data.actionBar.clear(); } }); // Entry group if (entry instanceof QuickOpenEntryGroup) { let group = <QuickOpenEntryGroup>entry; // Border if (group.showBorder()) { DOM.addClass(data.container, 'results-group-separator'); } else { DOM.removeClass(data.container, 'results-group-separator'); } // Group Label let groupLabel = group.getGroupLabel() || ''; (<IQuickOpenEntryGroupTemplateData>templateData).group.textContent = groupLabel; } // Normal Entry if (entry instanceof QuickOpenEntry) { let highlights = entry.getHighlights(); // Icon let iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : ''; data.icon.className = iconClass; // Label let labelHighlights = highlights[0]; data.label.set(entry.getLabel() || '', labelHighlights || []); // Meta let metaLabel = entry.getMeta() || ''; data.meta.textContent = metaLabel; // Description let descriptionHighlights = highlights[1]; data.description.set(entry.getDescription() || '', descriptionHighlights || []); } } public disposeTemplate(templateId: string, templateData: any): void { if (templateId === templateEntryItem) { this.entryItemRenderer.disposeTemplate(null, templateId, templateData); } } } export class QuickOpenModel implements IModel<QuickOpenEntry>, IDataSource<QuickOpenEntry>, IFilter<QuickOpenEntry>, IRunner<QuickOpenEntry> { private _entries: QuickOpenEntry[]; private _dataSource: IDataSource<QuickOpenEntry>; private _renderer: IRenderer<QuickOpenEntry>; private _filter: IFilter<QuickOpenEntry>; private _runner: IRunner<QuickOpenEntry>; constructor(entries: QuickOpenEntry[] = [], actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider()) { this._entries = entries; this._dataSource = this; this._renderer = new Renderer(actionProvider); this._filter = this; this._runner = this; } public get entries() { return this._entries; } public get dataSource() { return this._dataSource; } public get renderer() { return this._renderer; } public get filter() { return this._filter; } public get runner() { return this._runner; } public set entries(entries: QuickOpenEntry[]) { this._entries = entries; } /** * Adds entries that should show up in the quick open viewer. */ public addEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = this._entries.concat(entries); } } /** * Set the entries that should show up in the quick open viewer. */ public setEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = entries; } } /** * Get the entries that should show up in the quick open viewer. * * @visibleOnly optional parameter to only return visible entries */ public getEntries(visibleOnly?: boolean): QuickOpenEntry[] { if (visibleOnly) { return this._entries.filter((e) => !e.isHidden()); } return this._entries; } getId(entry: QuickOpenEntry): string { return entry.getId(); } getLabel(entry: QuickOpenEntry): string { return entry.getLabel(); } isVisible<T>(entry: QuickOpenEntry): boolean { return !entry.isHidden(); } run(entry: QuickOpenEntry, mode: Mode, context: IContext): boolean { return entry.run(mode, context); } }
src/vs/base/parts/quickopen/browser/quickOpenModel.ts
1
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.9982253909111023, 0.054264046251773834, 0.00016387671348638833, 0.00017021526582539082, 0.22390638291835785 ]
{ "id": 3, "code_window": [ "\t\tlet icon = document.createElement('span');\n", "\t\tentry.appendChild(icon);\n", "\n", "\t\t// Label\n", "\t\tlet label = new HighlightedLabel.HighlightedLabel(entry);\n", "\n", "\t\t// Meta\n", "\t\tlet meta = document.createElement('span');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// Prefix\n", "\t\tlet prefix = document.createElement('span');\n", "\t\tentry.appendChild(prefix);\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 382 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define([ 'vs/editor/browser/widget/codeEditorWidget', 'vs/editor/browser/widget/diffEditorWidget', 'vs/editor/contrib/clipboard/browser/clipboard', 'vs/editor/contrib/codelens/browser/codelens', 'vs/editor/contrib/color/browser/color', 'vs/editor/contrib/comment/common/comment', 'vs/editor/contrib/contextmenu/browser/contextmenu', 'vs/editor/contrib/diffNavigator/common/diffNavigator', 'vs/editor/contrib/find/browser/find', 'vs/editor/contrib/format/common/formatActions', 'vs/editor/contrib/goToDeclaration/browser/goToDeclaration', 'vs/editor/contrib/gotoError/browser/gotoError', 'vs/editor/contrib/hover/browser/hover', 'vs/editor/contrib/inPlaceReplace/common/inPlaceReplace', 'vs/editor/contrib/iPadShowKeyboard/browser/iPadShowKeyboard', 'vs/editor/contrib/linesOperations/common/linesOperations', 'vs/editor/contrib/links/browser/links', 'vs/editor/contrib/multicursor/common/multicursor', 'vs/editor/contrib/outlineMarker/browser/outlineMarker', 'vs/editor/contrib/parameterHints/browser/parameterHints', 'vs/editor/contrib/quickFix/browser/quickFix', 'vs/editor/contrib/referenceSearch/browser/referenceSearch', 'vs/editor/contrib/rename/browser/rename', 'vs/editor/contrib/rename/browser/rename2', 'vs/editor/contrib/smartSelect/common/smartSelect', 'vs/editor/contrib/smartSelect/common/jumpToBracket', 'vs/editor/contrib/snippet/common/snippet', 'vs/editor/contrib/snippet/browser/snippet', 'vs/editor/contrib/suggest/browser/suggest', 'vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode', 'vs/editor/contrib/wordHighlighter/common/wordHighlighter', 'vs/editor/contrib/workerStatusReporter/browser/workerStatusReporter', 'vs/editor/contrib/defineKeybinding/browser/defineKeybinding', // include these in the editor bundle because they are widely used by many languages 'vs/editor/common/languages.common' ], function() { 'use strict'; });
src/vs/editor/browser/editor.all.js
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017362143262289464, 0.00017024020780809224, 0.00016904914809856564, 0.00016959435015451163, 0.0000017137081158580258 ]
{ "id": 3, "code_window": [ "\t\tlet icon = document.createElement('span');\n", "\t\tentry.appendChild(icon);\n", "\n", "\t\t// Label\n", "\t\tlet label = new HighlightedLabel.HighlightedLabel(entry);\n", "\n", "\t\t// Meta\n", "\t\tlet meta = document.createElement('span');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// Prefix\n", "\t\tlet prefix = document.createElement('span');\n", "\t\tentry.appendChild(prefix);\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 382 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IStringDictionary, INumberDictionary } from 'vs/base/common/collections'; import URI from 'vs/base/common/uri'; import { EventEmitter } from 'vs/base/common/eventEmitter'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IModelService } from 'vs/editor/common/services/modelService'; import { ILineMatcher, createLineMatcher, ProblemMatcher, FileLocationKind, ProblemMatch, ApplyToKind, WatchingPattern, getResource } from 'vs/platform/markers/common/problemMatcher'; import { IMarkerService, IMarkerData, MarkerType, IResourceMarker, IMarker, MarkerStatistics } from 'vs/platform/markers/common/markers'; export namespace ProblemCollectorEvents { export let WatchingBeginDetected: string = 'watchingBeginDetected'; export let WatchingEndDetected: string = 'watchingEndDetected'; } export interface IProblemMatcher { processLine(line:string):void; } export class AbstractProblemCollector extends EventEmitter implements IDisposable { private matchers: INumberDictionary<ILineMatcher[]>; private activeMatcher : ILineMatcher; private _numberOfMatches: number; private buffer: string[]; private bufferLength: number; private openModels: IStringDictionary<boolean>; private modelListeners: IDisposable[]; constructor(problemMatchers: ProblemMatcher[], private modelService: IModelService) { super(); this.matchers = Object.create(null); this.bufferLength = 1; problemMatchers.map(elem => createLineMatcher(elem)).forEach((matcher) => { let length = matcher.matchLength; if (length > this.bufferLength) { this.bufferLength = length; } let value = this.matchers[length]; if (!value) { value = []; this.matchers[length] = value; } value.push(matcher); }); this.buffer = []; this.activeMatcher = null; this.openModels = Object.create(null); this.modelListeners = []; this.modelService.onModelAdded.add((model) => { this.openModels[model.getAssociatedResource().toString()] = true; }, this, this.modelListeners); this.modelService.onModelRemoved.add((model) => { delete this.openModels[model.getAssociatedResource().toString()]; }, this, this.modelListeners); this.modelService.getModels().forEach(model => this.openModels[model.getAssociatedResource().toString()] = true); } public dispose() { this.modelListeners.forEach(disposable => disposable.dispose()); } public get numberOfMatches(): number { return this._numberOfMatches; } protected tryFindMarker(line: string): ProblemMatch { let result: ProblemMatch = null; if (this.activeMatcher) { result = this.activeMatcher.next(line); if (result) { this._numberOfMatches++; return result; } this.clearBuffer(); this.activeMatcher = null; } if (this.buffer.length < this.bufferLength) { this.buffer.push(line); } else { let end = this.buffer.length - 1; for (let i = 0; i < end; i++) { this.buffer[i] = this.buffer[i + 1]; } this.buffer[end] = line; } result = this.tryMatchers(); if (result) { this.clearBuffer(); } return result; } protected isOpen(resource: URI): boolean { return !!this.openModels[resource.toString()]; } protected shouldApplyMatch(result: ProblemMatch): boolean { switch(result.description.applyTo) { case ApplyToKind.allDocuments: return true; case ApplyToKind.openDocuments: return this.openModels[result.resource.toString()] case ApplyToKind.closedDocuments: return !this.openModels[result.resource.toString()] default: return true; } } private tryMatchers(): ProblemMatch { this.activeMatcher = null; let length = this.buffer.length; for (let startIndex = 0; startIndex < length; startIndex++) { let candidates = this.matchers[length - startIndex]; if (!candidates) { continue; } for (let i = 0; i < candidates.length; i++) { let matcher = candidates[i]; let result = matcher.handle(this.buffer, startIndex); if (result.match) { this._numberOfMatches++; if (result.continue) { this.activeMatcher = matcher; } return result.match; } } } return null; } private clearBuffer(): void { if (this.buffer.length > 0) { this.buffer = []; } } } export enum ProblemHandlingStrategy { Clean } export class StartStopProblemCollector extends AbstractProblemCollector implements IProblemMatcher { private owners: string[]; private markerService: IMarkerService; private strategy: ProblemHandlingStrategy; // Global state private currentResourcesWithMarkers: IStringDictionary<URI[]>; private reportedResourcesWithMarkers: IStringDictionary<IStringDictionary<URI>>; // Current State private currentResource: URI = null; private currentResourceAsString: string = null; private markers: IStringDictionary<IMarkerData[]> = Object.create(null); constructor(problemMatchers: ProblemMatcher[], markerService:IMarkerService, modelService: IModelService, strategy: ProblemHandlingStrategy = ProblemHandlingStrategy.Clean) { super(problemMatchers, modelService); let ownerSet:{ [key:string]:boolean; } = Object.create(null); problemMatchers.forEach(description => ownerSet[description.owner] = true); this.owners = Object.keys(ownerSet); this.markerService = markerService; this.strategy = strategy; this.currentResourcesWithMarkers = Object.create(null); this.reportedResourcesWithMarkers = Object.create(null); this.owners.forEach((owner) => { this.currentResourcesWithMarkers[owner] = this.markerService.read({owner: owner}).map(m => m.resource); this.reportedResourcesWithMarkers[owner] = Object.create(null); }); this.currentResource = null; this.currentResourceAsString = null; this.markers = Object.create(null); } public processLine(line:string):void { let markerMatch = this.tryFindMarker(line); if (!markerMatch) { return; } let owner = markerMatch.description.owner; let resource = markerMatch.resource; let resourceAsString = resource.toString(); let shouldApplyMatch = this.shouldApplyMatch(markerMatch); if (shouldApplyMatch) { if (this.currentResourceAsString !== resourceAsString) { if (this.currentResource) { Object.keys(this.markers).forEach((owner) => { this.markerService.changeOne(owner, this.currentResource, this.markers[owner]); }); this.markers = Object.create(null); } this.reportedResourcesWithMarkers[owner][resourceAsString] = resource; this.currentResource = resource; this.currentResourceAsString = resourceAsString; } let markerData = this.markers[owner]; if (!markerData) { markerData = []; this.markers[owner] = markerData; } markerData.push(markerMatch.marker); } else { this.reportedResourcesWithMarkers[owner][resourceAsString] = resource; } } public done(): void { if (this.currentResource) { Object.keys(this.markers).forEach((owner) => { this.markerService.changeOne(owner, this.currentResource, this.markers[owner]); }); } if (this.strategy === ProblemHandlingStrategy.Clean) { Object.keys(this.currentResourcesWithMarkers).forEach((owner) => { let toRemove:URI[] = []; let withMarkers = this.reportedResourcesWithMarkers[owner]; this.currentResourcesWithMarkers[owner].forEach((resource) => { if (!withMarkers[resource.toString()]) { toRemove.push(resource); } }); this.markerService.remove(owner, toRemove); }); } this.currentResource = null; this.currentResourceAsString = null; this.markers = Object.create(null); } } interface OwnedWatchingPattern { problemMatcher: ProblemMatcher; pattern: WatchingPattern; } export class WatchingProblemCollector extends AbstractProblemCollector implements IProblemMatcher { private problemMatchers: ProblemMatcher[]; private watchingBeginsPatterns: OwnedWatchingPattern[]; private watchingEndsPatterns: OwnedWatchingPattern[]; private markerService: IMarkerService; // Current State private currentResource: URI; private currentResourceAsString: string; private markers: IStringDictionary<IMarkerData[]>; // Cleaning state private ignoreOpenByOwner: IStringDictionary<boolean>; private resourcesToClean: IStringDictionary<IStringDictionary<URI>>; constructor(problemMatchers: ProblemMatcher[], markerService: IMarkerService, modelService: IModelService) { super(problemMatchers, modelService); this.problemMatchers = problemMatchers; this.markerService = markerService; this.resetCurrentResource(); this.resourcesToClean = Object.create(null); this.ignoreOpenByOwner = Object.create(null); this.watchingBeginsPatterns = []; this.watchingEndsPatterns = []; this.problemMatchers.forEach(matcher => { if (matcher.watching) { this.watchingBeginsPatterns.push({ problemMatcher: matcher, pattern: matcher.watching.beginsPattern }); this.watchingEndsPatterns.push({ problemMatcher: matcher, pattern: matcher.watching.endsPattern }); } }) } public aboutToStart(): void { this.problemMatchers.forEach(matcher => { if (matcher.watching && matcher.watching.activeOnStart) { this.emit(ProblemCollectorEvents.WatchingBeginDetected, {}); this.recordResourcesToClean(matcher.owner); } let value: boolean = this.ignoreOpenByOwner[matcher.owner]; if (!value) { this.ignoreOpenByOwner[matcher.owner] = (matcher.applyTo === ApplyToKind.closedDocuments); } else { let newValue = value && (matcher.applyTo === ApplyToKind.closedDocuments); if (newValue != value) { this.ignoreOpenByOwner[matcher.owner] = newValue; } } }) } public processLine(line: string): void { if (this.tryBegin(line) || this.tryFinish(line)) { return; } let markerMatch = this.tryFindMarker(line); if (!markerMatch) { return; } let resource = markerMatch.resource; let owner = markerMatch.description.owner; let resourceAsString = resource.toString(); let shouldApplyMatch = this.shouldApplyMatch(markerMatch); if (shouldApplyMatch) { if (this.currentResourceAsString !== resourceAsString) { this.removeResourceToClean(owner, resourceAsString); if (this.currentResource) { this.deliverMarkersForCurrentResource(); } this.currentResource = resource; this.currentResourceAsString = resourceAsString; } let markerData = this.markers[owner]; if (!markerData) { markerData = []; this.markers[owner] = markerData; } markerData.push(markerMatch.marker); } else { this.removeResourceToClean(owner, resourceAsString); } } public forceDelivery(): void { this.deliverMarkersForCurrentResource(false); Object.keys(this.resourcesToClean).forEach((owner) => { this.cleanMarkers(owner, false); }); this.resourcesToClean = Object.create(null); } private tryBegin(line: string): boolean { let result = false; for (let i = 0; i < this.watchingBeginsPatterns.length; i++) { let beginMatcher = this.watchingBeginsPatterns[i]; let matches = beginMatcher.pattern.regexp.exec(line); if (matches) { this.emit(ProblemCollectorEvents.WatchingBeginDetected, {}); result = true; let owner = beginMatcher.problemMatcher.owner; if (matches[1]) { let resource = getResource(matches[1], beginMatcher.problemMatcher); if (this.currentResourceAsString && this.currentResourceAsString === resource.toString()) { this.resetCurrentResource(); } this.recordResourceToClean(owner, resource); } else { this.recordResourcesToClean(owner); this.resetCurrentResource(); } } } return result; } private tryFinish(line: string): boolean { let result = false; for (let i = 0; i < this.watchingEndsPatterns.length; i++) { let endMatcher = this.watchingEndsPatterns[i]; let matches = endMatcher.pattern.regexp.exec(line); if (matches) { this.emit(ProblemCollectorEvents.WatchingEndDetected, {}); result = true; let owner = endMatcher.problemMatcher.owner; this.cleanMarkers(owner); this.deliverMarkersForCurrentResource(); } } return result; } private recordResourcesToClean(owner: string): void { let resourceSetToClean = this.getResourceSetToClean(owner); this.markerService.read({ owner: owner }).forEach(marker => resourceSetToClean[marker.resource.toString()] = marker.resource); } private recordResourceToClean(owner: string, resource: URI): void { this.getResourceSetToClean(owner)[resource.toString()] = resource; } private removeResourceToClean(owner: string, resource: string): void { let resourceSet = this.resourcesToClean[owner]; if (resourceSet) { delete resourceSet[resource]; } } private cleanMarkers(owner: string, remove: boolean = true): void { let resourceSet = this.resourcesToClean[owner]; if (resourceSet) { let toClean = Object.keys(resourceSet).map(key => resourceSet[key]).filter(resource => { return this.ignoreOpenByOwner[owner] && !this.isOpen(resource); }); this.markerService.remove(owner, toClean); if (remove) { delete this.resourcesToClean[owner]; } } } private deliverMarkersForCurrentResource(resetCurrentResource: boolean = true): void { if (this.currentResource) { Object.keys(this.markers).forEach((owner) => { this.markerService.changeOne(owner, this.currentResource, this.markers[owner]); }); } if (resetCurrentResource) { this.resetCurrentResource(); } } private getResourceSetToClean(owner: string): IStringDictionary<URI> { let result = this.resourcesToClean[owner]; if (!result) { result = Object.create(null); this.resourcesToClean[owner] = result; } return result; } private resetCurrentResource(): void { this.currentResource = null; this.currentResourceAsString = null; this.markers = Object.create(null); } }
src/vs/workbench/parts/tasks/common/problemCollectors.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.0001761878520483151, 0.00017222852329723537, 0.00016742892330512404, 0.0001724467147141695, 0.0000024453299829474417 ]
{ "id": 3, "code_window": [ "\t\tlet icon = document.createElement('span');\n", "\t\tentry.appendChild(icon);\n", "\n", "\t\t// Label\n", "\t\tlet label = new HighlightedLabel.HighlightedLabel(entry);\n", "\n", "\t\t// Meta\n", "\t\tlet meta = document.createElement('span');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// Prefix\n", "\t\tlet prefix = document.createElement('span');\n", "\t\tentry.appendChild(prefix);\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 382 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" enable-background="new 0 0 16 16" height="16" width="16"><path fill="#1E1E1E" d="M16 2.6L13.4 0H6v6H0v10h10v-6h6z"/><g fill="#75BEFF"><path d="M5 7h1v2H5zM11 1h1v2h-1zM13 1v3H9V1H7v5h.4L10 8.6V9h5V3zM7 10H3V7H1v8h8V9L7 7z"/></g></svg>
src/vs/workbench/parts/files/browser/media/saveall_inverse.svg
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00016839565068949014, 0.00016839565068949014, 0.00016839565068949014, 0.00016839565068949014, 0 ]
{ "id": 4, "code_window": [ "\n", "\t\treturn {\n", "\t\t\tcontainer: container,\n", "\t\t\ticon: icon,\n", "\t\t\tlabel: label,\n", "\t\t\tmeta: meta,\n", "\t\t\tdescription: description,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tprefix: prefix,\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 399 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {Registry} from 'vs/platform/platform'; import filters = require('vs/base/common/filters'); import strings = require('vs/base/common/strings'); import types = require('vs/base/common/types'); import paths = require('vs/base/common/paths'); import URI from 'vs/base/common/uri'; import {EventType} from 'vs/base/common/events'; import comparers = require('vs/base/common/comparers'); import {Mode, IContext} from 'vs/base/parts/quickopen/browser/quickOpen'; import {QuickOpenEntry, QuickOpenModel, IHighlight} from 'vs/base/parts/quickopen/browser/quickOpenModel'; import {EditorInput, getUntitledOrFileResource} from 'vs/workbench/common/editor'; import {IEditorRegistry, Extensions} from 'vs/workbench/browser/parts/editor/baseEditor'; import {EditorQuickOpenEntry} from 'vs/workbench/browser/quickopen'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; const MAX_ENTRIES = 200; export class EditorHistoryEntry extends EditorQuickOpenEntry { private input: EditorInput; private model: EditorHistoryModel; private resource: URI; constructor( editorService: IWorkbenchEditorService, private contextService: IWorkspaceContextService, input: EditorInput, labelHighlights: IHighlight[], descriptionHighlights: IHighlight[], model: EditorHistoryModel ) { super(editorService); this.input = input; this.model = model; let resource = getUntitledOrFileResource(input); if (resource) { this.resource = resource; } else { let inputWithResource: { getResource(): URI } = <any>input; if (types.isFunction(inputWithResource.getResource)) { this.resource = inputWithResource.getResource(); } } this.setHighlights(labelHighlights, descriptionHighlights); } public clone(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): EditorHistoryEntry { return new EditorHistoryEntry(this.editorService, this.contextService, this.input, labelHighlights, descriptionHighlights, this.model); } public getLabel(): string { let status = this.input.getStatus(); if (status && status.decoration) { return status.decoration + ' ' + this.input.getName(); } return this.input.getName(); } public getDescription(): string { return this.input.getDescription(); } public getResource(): URI { return this.resource; } public getInput(): EditorInput { return this.input; } public matches(input: EditorInput): boolean { return this.input.matches(input); } public run(mode: Mode, context: IContext): boolean { if (mode === Mode.OPEN) { let event = context.event; let sideBySide = !context.quickNavigateConfiguration && (event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey)))); this.editorService.openEditor(this.input, null, sideBySide).done(() => { // Automatically clean up stale history entries when the input can not be opened if (!this.input.matches(this.editorService.getActiveEditorInput())) { this.model.remove(this.input); } }); return true; } return false; } } interface ISerializedEditorInput { id: string; value: string; } export class EditorHistoryModel extends QuickOpenModel { constructor( private editorService: IWorkbenchEditorService, private instantiationService: IInstantiationService, private contextService: IWorkspaceContextService ) { super(); } public add(entry: EditorInput): void { // Ensure we have at least a name to show if (!entry.getName()) { return; } // Remove on Dispose let unbind = entry.addListener(EventType.DISPOSE, () => { this.remove(entry); unbind(); }); // Remove any existing entry and add to the beginning this.remove(entry); this.entries.unshift(new EditorHistoryEntry(this.editorService, this.contextService, entry, null, null, this)); // Respect max entries setting if (this.entries.length > MAX_ENTRIES) { this.entries = this.entries.slice(0, MAX_ENTRIES); } } public remove(entry: EditorInput): void { let index = this.indexOf(entry); if (index >= 0) { this.entries.splice(index, 1); } } private indexOf(entryToFind: EditorInput): number { for (let i = 0; i < this.entries.length; i++) { let entry = this.entries[i]; if ((<EditorHistoryEntry>entry).matches(entryToFind)) { return i; } } return -1; } public saveTo(memento: any): void { let registry = (<IEditorRegistry>Registry.as(Extensions.Editors)); let entries: ISerializedEditorInput[] = []; for (let i = this.entries.length - 1; i >= 0; i--) { let entry = this.entries[i]; let input = (<EditorHistoryEntry>entry).getInput(); let factory = registry.getEditorInputFactory(input.getId()); if (factory) { let value = factory.serialize(input); if (types.isString(value)) { entries.push({ id: input.getId(), value: value }); } } } if (entries.length > 0) { memento.entries = entries; } } public loadFrom(memento: any): void { let registry = (<IEditorRegistry>Registry.as(Extensions.Editors)); let entries: ISerializedEditorInput[] = memento.entries; if (entries && entries.length > 0) { for (let i = 0; i < entries.length; i++) { let entry = entries[i]; let factory = registry.getEditorInputFactory(entry.id); if (factory && types.isString(entry.value)) { let input = factory.deserialize(this.instantiationService, entry.value); if (input) { this.add(input); } } } } } public getEntries(): EditorHistoryEntry[] { return <EditorHistoryEntry[]>this.entries.slice(0); } public getResults(searchValue: string): QuickOpenEntry[] { searchValue = searchValue.trim(); let results: QuickOpenEntry[] = []; for (let i = 0; i < this.entries.length; i++) { let entry = <EditorHistoryEntry>this.entries[i]; if (!entry.getResource()) { continue; //For now, only support to match on inputs that provide resource information } let label = entry.getInput().getName(); let description = entry.getInput().getDescription(); let labelHighlights: IHighlight[] = []; let descriptionHighlights: IHighlight[] = []; // Search inside filename if (searchValue.indexOf(paths.nativeSep) < 0) { labelHighlights = filters.matchesFuzzy(searchValue, label); } // Search in full path else { descriptionHighlights = filters.matchesFuzzy(strings.trim(searchValue, paths.nativeSep), description); // If we have no highlights, assume that the match is split among name and parent folder if (!descriptionHighlights || !descriptionHighlights.length) { labelHighlights = filters.matchesFuzzy(paths.basename(searchValue), label); descriptionHighlights = filters.matchesFuzzy(strings.trim(paths.dirname(searchValue), paths.nativeSep), description); } } if ((labelHighlights && labelHighlights.length) || (descriptionHighlights && descriptionHighlights.length)) { results.push(entry.clone(labelHighlights, descriptionHighlights)); } } // If user is searching, use the same sorting that is used for other quick open handlers if (searchValue) { let normalizedSearchValue = strings.stripWildcards(searchValue.toLowerCase()); return results.sort((elementA: EditorHistoryEntry, elementB: EditorHistoryEntry) => QuickOpenEntry.compare(elementA, elementB, normalizedSearchValue)); } // Leave default "most recently used" order if user is not actually searching return results; } }
src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts
1
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.001369592733681202, 0.00022415313287638128, 0.00016533039161004126, 0.00017074373317882419, 0.00023077146033756435 ]
{ "id": 4, "code_window": [ "\n", "\t\treturn {\n", "\t\t\tcontainer: container,\n", "\t\t\ticon: icon,\n", "\t\t\tlabel: label,\n", "\t\t\tmeta: meta,\n", "\t\t\tdescription: description,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tprefix: prefix,\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 399 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import { Promise } from 'vs/base/common/winjs.base'; import dom = require('vs/base/browser/dom'); import { IAction } from 'vs/base/common/actions'; import { BaseActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { IDebugService, ServiceEvents, State } from 'vs/workbench/parts/debug/common/debug'; import { IConfigurationService, ConfigurationServiceEventTypes } from 'vs/platform/configuration/common/configuration'; export class SelectConfigActionItem extends BaseActionItem { private select: HTMLSelectElement; private toDispose: lifecycle.IDisposable[]; constructor( action: IAction, @IDebugService private debugService: IDebugService, @IConfigurationService configurationService: IConfigurationService ) { super(null, action); this.select = document.createElement('select'); this.select.className = 'debug-select action-bar-select'; this.toDispose = []; this.registerListeners(configurationService); } private registerListeners(configurationService: IConfigurationService): void { this.toDispose.push(dom.addStandardDisposableListener(this.select, 'change', (e) => { this.actionRunner.run(this._action, e.target.value).done(null, errors.onUnexpectedError); })); this.toDispose.push(this.debugService.addListener2(ServiceEvents.STATE_CHANGED, () => { this.select.disabled = this.debugService.getState() !== State.Inactive; })); this.toDispose.push(configurationService.addListener2(ConfigurationServiceEventTypes.UPDATED, e => { this.setOptions().done(null, errors.onUnexpectedError); })); } public render(container: HTMLElement): void { dom.addClass(container, 'select-container'); container.appendChild(this.select); this.setOptions().done(null, errors.onUnexpectedError); } private setOptions(): Promise { let previousSelectedIndex = this.select.selectedIndex; this.select.options.length = 0; return this.debugService.loadLaunchConfig().then(config => { if (!config || !config.configurations) { this.select.options.add(this.createOption('<none>')); this.select.disabled = true; return; } const configurations = config.configurations; this.select.disabled = configurations.length < 1; let found = false; const configurationName = this.debugService.getConfigurationName(); for (let i = 0; i < configurations.length; i++) { this.select.options.add(this.createOption(configurations[i].name)); if (configurationName === configurations[i].name) { this.select.selectedIndex = i; found = true; } } if (!found && configurations.length > 0) { if (!previousSelectedIndex || previousSelectedIndex < 0 || previousSelectedIndex >= configurations.length) { previousSelectedIndex = 0; } this.select.selectedIndex = previousSelectedIndex; return this.actionRunner.run(this._action, configurations[previousSelectedIndex].name); } }); } private createOption(value: string): HTMLOptionElement { const option = document.createElement('option'); option.value = value; option.text = value; return option; } public dispose(): void { this.debugService = null; this.toDispose = lifecycle.disposeAll(this.toDispose); super.dispose(); } }
src/vs/workbench/parts/debug/browser/debugActionItems.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.0030034189112484455, 0.0004278315172996372, 0.00016623885312583297, 0.0001702666049823165, 0.0008144773892126977 ]
{ "id": 4, "code_window": [ "\n", "\t\treturn {\n", "\t\t\tcontainer: container,\n", "\t\t\ticon: icon,\n", "\t\t\tlabel: label,\n", "\t\t\tmeta: meta,\n", "\t\t\tdescription: description,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tprefix: prefix,\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 399 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import {Match, FileMatch, SearchResult} from 'vs/workbench/parts/search/common/searchModel'; import model = require('vs/editor/common/model/model'); import {EventSource} from 'vs/base/common/eventSource'; import {IModel} from 'vs/editor/common/editorCommon'; import URI from 'vs/base/common/uri'; import {create} from 'vs/platform/instantiation/common/instantiationService'; import {TestContextService} from 'vs/workbench/test/browser/servicesTestUtils'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IFileMatch} from 'vs/platform/search/common/search'; function toUri(path: string): URI { return URI.file('C:\\' + path); } suite('Search - Model', () => { let instantiation: IInstantiationService; let oneModel: IModel; setup(() => { let event = new EventSource<any>(); oneModel = new model.Model('line1\nline2\nline3', null, URI.parse('file:///folder/file.txt')); instantiation = create({ modelService: { getModel: () => oneModel, onModelAdded: event.value }, requestService: { getRequestUrl: () => 'file:///folder/file.txt' }, contextService: new TestContextService() }); }); teardown(() => { oneModel.dispose(); }); test('Line Match', function() { let fileMatch = new FileMatch(null, toUri('folder\\file.txt')); let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3); assert.equal(lineMatch.text(), 'foo bar'); assert.equal(lineMatch.range().startLineNumber, 2); assert.equal(lineMatch.range().endLineNumber, 2); assert.equal(lineMatch.range().startColumn, 1); assert.equal(lineMatch.range().endColumn, 4); }); test('Line Match - Remove', function() { let fileMatch = new FileMatch(null, toUri('folder\\file.txt')); let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3); fileMatch.add(lineMatch); assert.equal(fileMatch.matches().length, 1); fileMatch.remove(lineMatch); assert.equal(fileMatch.matches().length, 0); }); test('File Match', function() { let fileMatch = new FileMatch(null, toUri('folder\\file.txt')); assert.equal(fileMatch.matches(), 0); assert.equal(fileMatch.resource().toString(), 'file:///c%3A/folder/file.txt'); assert.equal(fileMatch.name(), 'file.txt'); fileMatch = new FileMatch(null, toUri('file.txt')); assert.equal(fileMatch.matches(), 0); assert.equal(fileMatch.resource().toString(), 'file:///c%3A/file.txt'); assert.equal(fileMatch.name(), 'file.txt'); }); test('Search Result', function() { let searchResult = instantiation.createInstance(SearchResult, null); assert.equal(searchResult.isEmpty(), true); let raw: IFileMatch[] = []; for (let i = 0; i < 10; i++) { raw.push({ resource: URI.parse('file://c:/' + i), lineMatches: [{ preview: String(i), lineNumber: 1, offsetAndLengths: [[0, 1]] }] }); } searchResult.append(raw); assert.equal(searchResult.isEmpty(), false); assert.equal(searchResult.matches().length, 10); }); test('Alle Drei Zusammen', function() { let searchResult = instantiation.createInstance(SearchResult, null); let fileMatch = new FileMatch(searchResult, toUri('far\\boo')); let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3); assert(lineMatch.parent() === fileMatch); assert(fileMatch.parent() === searchResult); }); //// ----- utils //function lineHasDecorations(model: editor.IModel, lineNumber: number, decorations: { start: number; end: number; }[]): void { // let lineDecorations:typeof decorations = []; // let decs = model.getLineDecorations(lineNumber); // for (let i = 0, len = decs.length; i < len; i++) { // lineDecorations.push({ // start: decs[i].range.startColumn, // end: decs[i].range.endColumn // }); // } // assert.deepEqual(lineDecorations, decorations); //} // //function lineHasNoDecoration(model: editor.IModel, lineNumber: number): void { // lineHasDecorations(model, lineNumber, []); //} // //function lineHasDecoration(model: editor.IModel, lineNumber: number, start: number, end: number): void { // lineHasDecorations(model, lineNumber, [{ // start: start, // end: end // }]); //} //// ----- end utils // //test('Model Highlights', function () { // // let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt')); // fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2)); // fileMatch.connect(); // lineHasDecoration(oneModel, 2, 1, 3); //}); // //test('Dispose', function () { // // let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt')); // fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2)); // fileMatch.connect(); // lineHasDecoration(oneModel, 2, 1, 3); // // fileMatch.dispose(); // lineHasNoDecoration(oneModel, 2); //}); });
src/vs/workbench/parts/search/test/common/searchModel.test.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017640336591284722, 0.00017215429397765547, 0.00016995941405184567, 0.00017191182996612042, 0.000001536726585982251 ]
{ "id": 4, "code_window": [ "\n", "\t\treturn {\n", "\t\t\tcontainer: container,\n", "\t\t\ticon: icon,\n", "\t\t\tlabel: label,\n", "\t\t\tmeta: meta,\n", "\t\t\tdescription: description,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tprefix: prefix,\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 399 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path fill="#e8e8e8" d="M6 4v8l4-4-4-4zm1 2.414l1.586 1.586-1.586 1.586v-3.172z"/></svg>
src/vs/base/browser/ui/splitview/arrow-collapse-dark.svg
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00016948765551205724, 0.00016948765551205724, 0.00016948765551205724, 0.00016948765551205724, 0 ]
{ "id": 5, "code_window": [ "\t\t\t// Icon\n", "\t\t\tlet iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : '';\n", "\t\t\tdata.icon.className = iconClass;\n", "\n", "\t\t\t// Label\n", "\t\t\tlet labelHighlights = highlights[0];\n", "\t\t\tdata.label.set(entry.getLabel() || '', labelHighlights || []);\n", "\n", "\t\t\t// Meta\n", "\t\t\tlet metaLabel = entry.getMeta() || '';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// Prefix\n", "\t\t\tlet prefix = entry.getPrefix() || '';\n", "\t\t\tdata.prefix.textContent = prefix;\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "replace", "edit_start_line_idx": 460 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {Registry} from 'vs/platform/platform'; import filters = require('vs/base/common/filters'); import strings = require('vs/base/common/strings'); import types = require('vs/base/common/types'); import paths = require('vs/base/common/paths'); import URI from 'vs/base/common/uri'; import {EventType} from 'vs/base/common/events'; import comparers = require('vs/base/common/comparers'); import {Mode, IContext} from 'vs/base/parts/quickopen/browser/quickOpen'; import {QuickOpenEntry, QuickOpenModel, IHighlight} from 'vs/base/parts/quickopen/browser/quickOpenModel'; import {EditorInput, getUntitledOrFileResource} from 'vs/workbench/common/editor'; import {IEditorRegistry, Extensions} from 'vs/workbench/browser/parts/editor/baseEditor'; import {EditorQuickOpenEntry} from 'vs/workbench/browser/quickopen'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; const MAX_ENTRIES = 200; export class EditorHistoryEntry extends EditorQuickOpenEntry { private input: EditorInput; private model: EditorHistoryModel; private resource: URI; constructor( editorService: IWorkbenchEditorService, private contextService: IWorkspaceContextService, input: EditorInput, labelHighlights: IHighlight[], descriptionHighlights: IHighlight[], model: EditorHistoryModel ) { super(editorService); this.input = input; this.model = model; let resource = getUntitledOrFileResource(input); if (resource) { this.resource = resource; } else { let inputWithResource: { getResource(): URI } = <any>input; if (types.isFunction(inputWithResource.getResource)) { this.resource = inputWithResource.getResource(); } } this.setHighlights(labelHighlights, descriptionHighlights); } public clone(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): EditorHistoryEntry { return new EditorHistoryEntry(this.editorService, this.contextService, this.input, labelHighlights, descriptionHighlights, this.model); } public getLabel(): string { let status = this.input.getStatus(); if (status && status.decoration) { return status.decoration + ' ' + this.input.getName(); } return this.input.getName(); } public getDescription(): string { return this.input.getDescription(); } public getResource(): URI { return this.resource; } public getInput(): EditorInput { return this.input; } public matches(input: EditorInput): boolean { return this.input.matches(input); } public run(mode: Mode, context: IContext): boolean { if (mode === Mode.OPEN) { let event = context.event; let sideBySide = !context.quickNavigateConfiguration && (event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey)))); this.editorService.openEditor(this.input, null, sideBySide).done(() => { // Automatically clean up stale history entries when the input can not be opened if (!this.input.matches(this.editorService.getActiveEditorInput())) { this.model.remove(this.input); } }); return true; } return false; } } interface ISerializedEditorInput { id: string; value: string; } export class EditorHistoryModel extends QuickOpenModel { constructor( private editorService: IWorkbenchEditorService, private instantiationService: IInstantiationService, private contextService: IWorkspaceContextService ) { super(); } public add(entry: EditorInput): void { // Ensure we have at least a name to show if (!entry.getName()) { return; } // Remove on Dispose let unbind = entry.addListener(EventType.DISPOSE, () => { this.remove(entry); unbind(); }); // Remove any existing entry and add to the beginning this.remove(entry); this.entries.unshift(new EditorHistoryEntry(this.editorService, this.contextService, entry, null, null, this)); // Respect max entries setting if (this.entries.length > MAX_ENTRIES) { this.entries = this.entries.slice(0, MAX_ENTRIES); } } public remove(entry: EditorInput): void { let index = this.indexOf(entry); if (index >= 0) { this.entries.splice(index, 1); } } private indexOf(entryToFind: EditorInput): number { for (let i = 0; i < this.entries.length; i++) { let entry = this.entries[i]; if ((<EditorHistoryEntry>entry).matches(entryToFind)) { return i; } } return -1; } public saveTo(memento: any): void { let registry = (<IEditorRegistry>Registry.as(Extensions.Editors)); let entries: ISerializedEditorInput[] = []; for (let i = this.entries.length - 1; i >= 0; i--) { let entry = this.entries[i]; let input = (<EditorHistoryEntry>entry).getInput(); let factory = registry.getEditorInputFactory(input.getId()); if (factory) { let value = factory.serialize(input); if (types.isString(value)) { entries.push({ id: input.getId(), value: value }); } } } if (entries.length > 0) { memento.entries = entries; } } public loadFrom(memento: any): void { let registry = (<IEditorRegistry>Registry.as(Extensions.Editors)); let entries: ISerializedEditorInput[] = memento.entries; if (entries && entries.length > 0) { for (let i = 0; i < entries.length; i++) { let entry = entries[i]; let factory = registry.getEditorInputFactory(entry.id); if (factory && types.isString(entry.value)) { let input = factory.deserialize(this.instantiationService, entry.value); if (input) { this.add(input); } } } } } public getEntries(): EditorHistoryEntry[] { return <EditorHistoryEntry[]>this.entries.slice(0); } public getResults(searchValue: string): QuickOpenEntry[] { searchValue = searchValue.trim(); let results: QuickOpenEntry[] = []; for (let i = 0; i < this.entries.length; i++) { let entry = <EditorHistoryEntry>this.entries[i]; if (!entry.getResource()) { continue; //For now, only support to match on inputs that provide resource information } let label = entry.getInput().getName(); let description = entry.getInput().getDescription(); let labelHighlights: IHighlight[] = []; let descriptionHighlights: IHighlight[] = []; // Search inside filename if (searchValue.indexOf(paths.nativeSep) < 0) { labelHighlights = filters.matchesFuzzy(searchValue, label); } // Search in full path else { descriptionHighlights = filters.matchesFuzzy(strings.trim(searchValue, paths.nativeSep), description); // If we have no highlights, assume that the match is split among name and parent folder if (!descriptionHighlights || !descriptionHighlights.length) { labelHighlights = filters.matchesFuzzy(paths.basename(searchValue), label); descriptionHighlights = filters.matchesFuzzy(strings.trim(paths.dirname(searchValue), paths.nativeSep), description); } } if ((labelHighlights && labelHighlights.length) || (descriptionHighlights && descriptionHighlights.length)) { results.push(entry.clone(labelHighlights, descriptionHighlights)); } } // If user is searching, use the same sorting that is used for other quick open handlers if (searchValue) { let normalizedSearchValue = strings.stripWildcards(searchValue.toLowerCase()); return results.sort((elementA: EditorHistoryEntry, elementB: EditorHistoryEntry) => QuickOpenEntry.compare(elementA, elementB, normalizedSearchValue)); } // Leave default "most recently used" order if user is not actually searching return results; } }
src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts
1
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.9984667897224426, 0.11589618772268295, 0.0001632021158002317, 0.00026633814559318125, 0.31849405169487 ]
{ "id": 5, "code_window": [ "\t\t\t// Icon\n", "\t\t\tlet iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : '';\n", "\t\t\tdata.icon.className = iconClass;\n", "\n", "\t\t\t// Label\n", "\t\t\tlet labelHighlights = highlights[0];\n", "\t\t\tdata.label.set(entry.getLabel() || '', labelHighlights || []);\n", "\n", "\t\t\t// Meta\n", "\t\t\tlet metaLabel = entry.getMeta() || '';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// Prefix\n", "\t\t\tlet prefix = entry.getPrefix() || '';\n", "\t\t\tdata.prefix.textContent = prefix;\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "replace", "edit_start_line_idx": 460 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-inputbox { position: relative; display: block; padding: 0; -webkit-box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; font-family: "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; line-height: auto !important; /* Customizable */ font-size: inherit; } .monaco-inputbox > .wrapper > .input, .monaco-inputbox > .wrapper > .mirror { /* Customizable */ padding: 4px; } .monaco-inputbox > .wrapper { position: relative; width: 100%; height: 100%; } .monaco-inputbox > .wrapper > .input { display: inline-block; -webkit-box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; width: 100%; height: 100%; line-height: inherit; border: none; font-family: inherit; font-size: inherit; resize: none; color: inherit; } .monaco-inputbox > .wrapper > input { text-overflow: ellipsis; } .monaco-inputbox > .wrapper > textarea.input { display: block; overflow: hidden; } .monaco-inputbox > .wrapper > .input:focus { outline: none; } .monaco-inputbox > .wrapper > .mirror { position: absolute; display: inline-block; width: 100%; top: 0; left: 0; -webkit-box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; white-space: pre-wrap; visibility: hidden; min-height: 26px; word-wrap: break-word; } /* Context view */ .monaco-inputbox-container { text-align: right; } .monaco-inputbox-container .monaco-inputbox-message { display: inline-block; overflow: hidden; text-align: left; width: 100%; -webkit-box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; padding: 0.4em; font-size: 12px; line-height: 17px; min-height: 34px; margin-top: -1px; } /* Action bar support */ .monaco-inputbox .monaco-action-bar { position: absolute; right: 0px; top: 4px; } /* Theming */ .monaco-inputbox.idle { border: 1px solid transparent; } .monaco-inputbox.info { border: 1px solid #009CCC; } .monaco-inputbox-container .monaco-inputbox-message.info { background: #D6ECF2; border: 1px solid #009CCC; } .monaco-inputbox.warning { border: 1px solid #F2CB1D; } .monaco-inputbox-container .monaco-inputbox-message.warning { background: #F6F5D2; border: 1px solid #F2CB1D; } .monaco-inputbox.error { border: 1px solid #E51400; } .monaco-inputbox-container .monaco-inputbox-message.error { background: #f2dede; border: 1px solid #E51400; } /* VS Dark */ .vs-dark .monaco-inputbox.info { border-color: #55AAFF; } .vs-dark .monaco-inputbox-container .monaco-inputbox-message.info { background-color: #063B49; border-color: #55AAFF; } .vs-dark .monaco-inputbox.warning { border-color: #B89500; } .vs-dark .monaco-inputbox-container .monaco-inputbox-message.warning { background-color: #352A05; border-color: #B89500; } .vs-dark .monaco-inputbox.error { border-color: #BE1100; } .vs-dark .monaco-inputbox-container .monaco-inputbox-message.error { background-color: #5A1D1D; border-color: #BE1100; } /* High Contrast Theming */ .hc-black .monaco-inputbox.idle { border: 1px solid #6FC3DF; } .hc-black .monaco-inputbox-container .monaco-inputbox-message.info { background-color: #000; border-color: #6FC3DF; } .hc-black .monaco-inputbox.warning { border-color: #B89500; } .hc-black .monaco-inputbox-container .monaco-inputbox-message.warning { background-color: #000; border-color: #B89500; } .hc-black .monaco-inputbox.error { border-color: #BE1100; } .hc-black .monaco-inputbox-container .monaco-inputbox-message.error { background-color: #000; border-color: #BE1100; }
src/vs/base/browser/ui/inputbox/inputBox.css
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00023518112720921636, 0.00017736188601702452, 0.00017177188419736922, 0.0001746205671224743, 0.000013031603884883225 ]
{ "id": 5, "code_window": [ "\t\t\t// Icon\n", "\t\t\tlet iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : '';\n", "\t\t\tdata.icon.className = iconClass;\n", "\n", "\t\t\t// Label\n", "\t\t\tlet labelHighlights = highlights[0];\n", "\t\t\tdata.label.set(entry.getLabel() || '', labelHighlights || []);\n", "\n", "\t\t\t// Meta\n", "\t\t\tlet metaLabel = entry.getMeta() || '';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// Prefix\n", "\t\t\tlet prefix = entry.getPrefix() || '';\n", "\t\t\tdata.prefix.textContent = prefix;\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "replace", "edit_start_line_idx": 460 }
{ "comments": { "lineComment": "#" }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ] }
extensions/shellscript/shellscript.configuration.json
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00023518290254287422, 0.00020379845227580518, 0.00017241400200873613, 0.00020379845227580518, 0.00003138445026706904 ]
{ "id": 5, "code_window": [ "\t\t\t// Icon\n", "\t\t\tlet iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : '';\n", "\t\t\tdata.icon.className = iconClass;\n", "\n", "\t\t\t// Label\n", "\t\t\tlet labelHighlights = highlights[0];\n", "\t\t\tdata.label.set(entry.getLabel() || '', labelHighlights || []);\n", "\n", "\t\t\t// Meta\n", "\t\t\tlet metaLabel = entry.getMeta() || '';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// Prefix\n", "\t\t\tlet prefix = entry.getPrefix() || '';\n", "\t\t\tdata.prefix.textContent = prefix;\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "replace", "edit_start_line_idx": 460 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {TPromise} from 'vs/base/common/winjs.base'; import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions'; import {CommonEditorRegistry, ContextKey, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions'; import {EditorAction, Behaviour} from 'vs/editor/common/editorAction'; import FindWidget = require('./findWidget'); import FindModel = require('vs/editor/contrib/find/common/findModel'); import nls = require('vs/nls'); import EventEmitter = require('vs/base/common/eventEmitter'); import EditorBrowser = require('vs/editor/browser/editorBrowser'); import Lifecycle = require('vs/base/common/lifecycle'); import config = require('vs/editor/common/config/config'); import EditorCommon = require('vs/editor/common/editorCommon'); import {Selection} from 'vs/editor/common/core/selection'; import {IKeybindingService, IKeybindingContextKey} from 'vs/platform/keybinding/common/keybindingService'; import {IContextViewService} from 'vs/platform/contextview/browser/contextView'; import {INullService} from 'vs/platform/instantiation/common/instantiation'; import {KeyMod, KeyCode} from 'vs/base/common/keyCodes'; /** * The Find controller will survive an editor.setModel(..) call */ export class FindController implements EditorCommon.IEditorContribution, FindWidget.IFindController { static ID = 'editor.contrib.findController'; private editor:EditorBrowser.ICodeEditor; private _findWidgetVisible: IKeybindingContextKey<boolean>; private model:FindModel.IFindModel; private widget:FindWidget.IFindWidget; private widgetIsVisible:boolean; private widgetListeners:Lifecycle.IDisposable[]; private editorListeners:EventEmitter.ListenerUnbind[]; private lastState:FindModel.IFindState; static getFindController(editor:EditorCommon.ICommonCodeEditor): FindController { return <FindController>editor.getContribution(FindController.ID); } constructor(editor:EditorBrowser.ICodeEditor, @IContextViewService contextViewService: IContextViewService, @IKeybindingService keybindingService: IKeybindingService) { this._findWidgetVisible = keybindingService.createKey(CONTEXT_FIND_WIDGET_VISIBLE, false); this.editor = editor; this.model = null; this.widgetIsVisible = false; this.lastState = null; this.widget = new FindWidget.FindWidget(this.editor, this, contextViewService); this.widgetListeners = []; this.widgetListeners.push(this.widget.addUserInputEventListener((e) => this.onWidgetUserInput(e))); this.widgetListeners.push(this.widget.addClosedEventListener(() => this.onWidgetClosed())); this.editorListeners = []; this.editorListeners.push(this.editor.addListener(EditorCommon.EventType.ModelChanged, () => { this.disposeBindingAndModel(); if (this.editor.getModel() && this.lastState && this.widgetIsVisible) { this._start(false, false, false, false); } })); this.editorListeners.push(this.editor.addListener(EditorCommon.EventType.Disposed, () => { this.editorListeners.forEach((element:EventEmitter.ListenerUnbind) => { element(); }); this.editorListeners = []; })); } public getId(): string { return FindController.ID; } public dispose(): void { this.widgetListeners = Lifecycle.disposeAll(this.widgetListeners); if (this.widget) { this.widget.dispose(); this.widget = null; } this.disposeBindingAndModel(); } private disposeBindingAndModel(): void { this._findWidgetVisible.reset(); if (this.widget) { this.widget.setModel(null); } if (this.model) { this.model.dispose(); this.model = null; } } public closeFindWidget(): void { this.widgetIsVisible = false; this.disposeBindingAndModel(); this.editor.focus(); } private onWidgetClosed(): void { this.widgetIsVisible = false; this.disposeBindingAndModel(); } public getFindState(): FindModel.IFindState { return this.lastState; } public setSearchString(searchString:string): void { this.widget.setSearchString(searchString); this.lastState = this.widget.getState(); if (this.model) { this.model.recomputeMatches(this.lastState, false); } } private onWidgetUserInput(e:FindWidget.IUserInputEvent): void { this.lastState = this.widget.getState(); if (this.model) { this.model.recomputeMatches(this.lastState, e.jumpToNextMatch); } } private _start(forceRevealReplace:boolean, seedSearchStringFromSelection:boolean, seedSearchScopeFromSelection:boolean, shouldFocus:boolean): void { if (!this.model) { this.model = new FindModel.FindModelBoundToEditorModel(this.editor); this.widget.setModel(this.model); } this._findWidgetVisible.set(true); // Get a default state if none existed before this.lastState = this.lastState || this.widget.getState(); // Consider editor selection and overwrite the state with it var selection = this.editor.getSelection(); if (!selection) { // Someone started the find controller with an editor that doesn't have a model... return; } if (seedSearchStringFromSelection) { if (selection.startLineNumber === selection.endLineNumber) { if (selection.isEmpty()) { let wordAtPosition = this.editor.getModel().getWordAtPosition(selection.getStartPosition()); if (wordAtPosition) { this.lastState.searchString = wordAtPosition.word; } } else { this.lastState.searchString = this.editor.getModel().getValueInRange(selection); } } } var searchScope:EditorCommon.IEditorRange = null; if (seedSearchScopeFromSelection && selection.startLineNumber < selection.endLineNumber) { // Take search scope into account only if it is more than one line. searchScope = selection; } // Overwrite isReplaceRevealed if (forceRevealReplace) { this.lastState.isReplaceRevealed = forceRevealReplace; } // Start searching this.model.start(this.lastState, searchScope, shouldFocus); this.widgetIsVisible = true; } public startFromAction(withReplace:boolean): void { this._start(withReplace, true, true, true); } public next(): boolean { if (this.model) { this.model.next(); return true; } return false; } public prev(): boolean { if (this.model) { this.model.prev(); return true; } return false; } public enableSelectionFind(): void { if (this.model) { this.model.setFindScope(this.editor.getSelection()); } } public disableSelectionFind(): void { if (this.model) { this.model.setFindScope(null); } } public replace(): boolean { if (this.model) { this.model.replace(); return true; } return false; } public replaceAll(): boolean { if (this.model) { this.model.replaceAll(); return true; } return false; } } export class BaseStartFindAction extends EditorAction { constructor(descriptor: EditorCommon.IEditorActionDescriptorData, editor: EditorCommon.ICommonCodeEditor, condition: Behaviour) { super(descriptor, editor, condition || Behaviour.WidgetFocus); } _startController(controller:FindController): void { controller.startFromAction(false); } public run(): TPromise<boolean> { var controller = FindController.getFindController(this.editor); this._startController(controller); return TPromise.as(true); } } export class StartFindAction extends BaseStartFindAction { constructor(descriptor: EditorCommon.IEditorActionDescriptorData, editor: EditorCommon.ICommonCodeEditor, @INullService ns) { super(descriptor, editor, Behaviour.WidgetFocus); } } export class NextMatchFindAction extends EditorAction { constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) { super(descriptor, editor, Behaviour.WidgetFocus); } public run(): TPromise<boolean> { var controller = FindController.getFindController(this.editor); if (!controller.next()) { controller.startFromAction(false); controller.next(); } return TPromise.as(true); } } export class PreviousMatchFindAction extends EditorAction { constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) { super(descriptor, editor, Behaviour.WidgetFocus); } public run(): TPromise<boolean> { var controller = FindController.getFindController(this.editor); if (!controller.prev()) { controller.startFromAction(false); controller.prev(); } return TPromise.as(true); } } export class StartFindReplaceAction extends BaseStartFindAction { constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) { super(descriptor, editor, Behaviour.WidgetFocus | Behaviour.Writeable); } public getId(): string { return FindModel.START_FIND_REPLACE_ID; } _startController(controller:FindController): void { controller.startFromAction(true); } } export interface IMultiCursorFindResult { searchText:string; isRegex:boolean; matchCase:boolean; wholeWord:boolean; nextMatch: EditorCommon.IEditorSelection; } export function multiCursorFind(editor:EditorCommon.ICommonCodeEditor, changeFindSearchString:boolean): IMultiCursorFindResult { var controller = FindController.getFindController(editor); var state = controller.getFindState(); var searchText: string, isRegex = false, wholeWord = false, matchCase = false, nextMatch: EditorCommon.IEditorSelection; // In any case, if the find widget was ever opened, the options are taken from it if (state) { isRegex = state.properties.isRegex; wholeWord = state.properties.wholeWord; matchCase = state.properties.matchCase; } // Find widget owns what we search for if: // - focus is not in the editor (i.e. it is in the find widget) // - and the search widget is visible // - and the search string is non-empty if (!editor.isFocused() && state && state.searchString.length > 0) { // Find widget owns what is searched for searchText = state.searchString; } else { // Selection owns what is searched for var s = editor.getSelection(); if (s.startLineNumber !== s.endLineNumber) { // Cannot search for multiline string... yet... return null; } if (s.isEmpty()) { // selection is empty => expand to current word var word = editor.getModel().getWordAtPosition(s.getStartPosition()); if (!word) { return null; } searchText = word.word; nextMatch = Selection.createSelection(s.startLineNumber, word.startColumn, s.startLineNumber, word.endColumn); } else { searchText = editor.getModel().getValueInRange(s); } if (changeFindSearchString) { controller.setSearchString(searchText); } } return { searchText: searchText, isRegex: isRegex, matchCase: matchCase, wholeWord: wholeWord, nextMatch: nextMatch }; } class SelectNextFindMatchAction extends EditorAction { constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) { super(descriptor, editor, Behaviour.WidgetFocus); } protected _getNextMatch(): EditorCommon.IEditorSelection { var r = multiCursorFind(this.editor, true); if (!r) { return null; } if (r.nextMatch) { return r.nextMatch; } var allSelections = this.editor.getSelections(); var lastAddedSelection = allSelections[allSelections.length - 1]; var nextMatch = this.editor.getModel().findNextMatch(r.searchText, lastAddedSelection.getEndPosition(), r.isRegex, r.matchCase, r.wholeWord); if (!nextMatch) { return null; } return Selection.createSelection(nextMatch.startLineNumber, nextMatch.startColumn, nextMatch.endLineNumber, nextMatch.endColumn); } } class AddSelectionToNextFindMatchAction extends SelectNextFindMatchAction { static ID = 'editor.action.addSelectionToNextFindMatch'; constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) { super(descriptor, editor, ns); } public run(): TPromise<boolean> { var nextMatch = this._getNextMatch(); if (!nextMatch) { return TPromise.as(false); } var allSelections = this.editor.getSelections(); this.editor.setSelections(allSelections.concat(nextMatch)); this.editor.revealRangeInCenterIfOutsideViewport(nextMatch); return TPromise.as(true); } } class MoveSelectionToNextFindMatchAction extends SelectNextFindMatchAction { static ID = 'editor.action.moveSelectionToNextFindMatch'; constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) { super(descriptor, editor, ns); } public run(): TPromise<boolean> { var nextMatch = this._getNextMatch(); if (!nextMatch) { return TPromise.as(false); } var allSelections = this.editor.getSelections(); var lastAddedSelection = allSelections[allSelections.length - 1]; this.editor.setSelections(allSelections.slice(0, allSelections.length - 1).concat(nextMatch)); this.editor.revealRangeInCenterIfOutsideViewport(nextMatch); return TPromise.as(true); } } class SelectHighlightsAction extends EditorAction { static ID = 'editor.action.selectHighlights'; constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) { super(descriptor, editor, Behaviour.WidgetFocus); } public run(): TPromise<boolean> { var r = multiCursorFind(this.editor, true); if (!r) { return TPromise.as(false); } var matches = this.editor.getModel().findMatches(r.searchText, true, r.isRegex, r.matchCase, r.wholeWord); if (matches.length > 0) { this.editor.setSelections(matches.map(m => Selection.createSelection(m.startLineNumber, m.startColumn, m.endLineNumber, m.endColumn))); } return TPromise.as(true); } } export class SelectionHighlighter implements EditorCommon.IEditorContribution { static ID = 'editor.contrib.selectionHighlighter'; private editor:EditorCommon.ICommonCodeEditor; private model:EditorCommon.IModel; private decorations:string[]; private toUnhook:EventEmitter.ListenerUnbind[]; constructor(editor:EditorCommon.ICommonCodeEditor, @INullService ns) { this.editor = editor; this.model = this.editor.getModel(); this.decorations = []; this.toUnhook = []; this.toUnhook.push(editor.addListener(EditorCommon.EventType.CursorPositionChanged, e => this.onPositionChanged(e))); this.toUnhook.push(editor.addListener(EditorCommon.EventType.ModelChanged, (e) => { this.removeDecorations(); this.model = this.editor.getModel(); })); } public getId(): string { return SelectionHighlighter.ID; } private removeDecorations(): void { if (this.decorations.length > 0) { this.decorations = this.editor.deltaDecorations(this.decorations, []); } } private onPositionChanged(e:EditorCommon.ICursorPositionChangedEvent): void { if (!this.editor.getConfiguration().selectionHighlight) { return; } var r = multiCursorFind(this.editor, false); if (!r) { this.removeDecorations(); return; } if (r.nextMatch) { // This is an empty selection this.removeDecorations(); return; } if (/^[ \t]+$/.test(r.searchText)) { // whitespace only selection this.removeDecorations(); return; } if (r.searchText.length > 200) { // very long selection this.removeDecorations(); return; } var matches = this.editor.getModel().findMatches(r.searchText, true, r.isRegex, r.matchCase, r.wholeWord); var decorations = matches.map(r => { return { range: r, options: { stickiness: EditorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, className: 'selectionHighlight' } }; }); this.decorations = this.editor.deltaDecorations(this.decorations, decorations); } public dispose(): void { this.removeDecorations(); while(this.toUnhook.length > 0) { this.toUnhook.pop()(); } } } CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(SelectHighlightsAction, SelectHighlightsAction.ID, nls.localize('selectAllOccurencesOfFindMatch', "Select All Occurences of Find Match"), { context: ContextKey.EditorFocus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L })); var CONTEXT_FIND_WIDGET_VISIBLE = 'findWidgetVisible'; // register actions CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(StartFindAction, FindModel.START_FIND_ID, nls.localize('startFindAction',"Find"), { context: ContextKey.None, primary: KeyMod.CtrlCmd | KeyCode.KEY_F, secondary: [KeyMod.CtrlCmd | KeyCode.F3] })); CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(NextMatchFindAction, FindModel.NEXT_MATCH_FIND_ID, nls.localize('findNextMatchAction', "Find Next"), { context: ContextKey.EditorFocus, primary: KeyCode.F3, mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_G, secondary: [KeyCode.F3] } })); CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(PreviousMatchFindAction, FindModel.PREVIOUS_MATCH_FIND_ID, nls.localize('findPreviousMatchAction', "Find Previous"), { context: ContextKey.EditorFocus, primary: KeyMod.Shift | KeyCode.F3, mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G, secondary: [KeyMod.Shift | KeyCode.F3] } })); CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(StartFindReplaceAction, FindModel.START_FIND_REPLACE_ID, nls.localize('startReplace', "Replace"), { context: ContextKey.None, primary: KeyMod.CtrlCmd | KeyCode.KEY_H, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_F } })); CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(MoveSelectionToNextFindMatchAction, MoveSelectionToNextFindMatchAction.ID, nls.localize('moveSelectionToNextFindMatch', "Move Last Selection To Next Find Match"), { context: ContextKey.EditorFocus, primary: KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_D) })); CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(AddSelectionToNextFindMatchAction, AddSelectionToNextFindMatchAction.ID, nls.localize('addSelectionToNextFindMatch', "Add Selection To Next Find Match"), { context: ContextKey.EditorFocus, primary: KeyMod.CtrlCmd | KeyCode.KEY_D })); EditorBrowserRegistry.registerEditorContribution(FindController); EditorBrowserRegistry.registerEditorContribution(SelectionHighlighter); CommonEditorRegistry.registerEditorCommand('closeFindWidget', CommonEditorRegistry.commandWeight(5), { primary: KeyCode.Escape }, false, CONTEXT_FIND_WIDGET_VISIBLE, (ctx, editor, args) => { FindController.getFindController(editor).closeFindWidget(); });
src/vs/editor/contrib/find/browser/find.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.03126159682869911, 0.0007004339713603258, 0.00016398877778556198, 0.00017343198123853654, 0.004012881778180599 ]
{ "id": 6, "code_window": [ "\t\treturn new EditorHistoryEntry(this.editorService, this.contextService, this.input, labelHighlights, descriptionHighlights, this.model);\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n", "\t\tlet status = this.input.getStatus();\n", "\t\tif (status && status.decoration) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\tpublic getPrefix(): string {\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "replace", "edit_start_line_idx": 60 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import WinJS = require('vs/base/common/winjs.base'); import Types = require('vs/base/common/types'); import URI from 'vs/base/common/uri'; import Tree = require('vs/base/parts/tree/common/tree'); import {IQuickNavigateConfiguration, IModel, IDataSource, IFilter, IRenderer, IRunner, Mode} from './quickOpen'; import ActionsRenderer = require('vs/base/parts/tree/browser/actionsRenderer'); import Actions = require('vs/base/common/actions'); import {compareAnything} from 'vs/base/common/comparers'; import ActionBar = require('vs/base/browser/ui/actionbar/actionbar'); import TreeDefaults = require('vs/base/parts/tree/browser/treeDefaults'); import HighlightedLabel = require('vs/base/browser/ui/highlightedlabel/highlightedLabel'); import DOM = require('vs/base/browser/dom'); export interface IContext { event: any; quickNavigateConfiguration: IQuickNavigateConfiguration; } export interface IHighlight { start: number; end: number; } let IDS = 0; export class QuickOpenEntry { private id: string; private labelHighlights: IHighlight[]; private descriptionHighlights: IHighlight[]; private hidden: boolean; constructor(highlights: IHighlight[] = []) { this.id = (IDS++).toString(); this.labelHighlights = highlights; this.descriptionHighlights = []; } /** * A unique identifier for the entry */ public getId(): string { return this.id; } /** * The label of the entry to identify it from others in the list */ public getLabel(): string { return null; } /** * Meta information about the entry that is optional and can be shown to the right of the label */ public getMeta(): string { return null; } /** * The icon of the entry to identify it from others in the list */ public getIcon(): string { return null; } /** * A secondary description that is optional and can be shown right to the label */ public getDescription(): string { return null; } /** * A resource for this entry. Resource URIs can be used to compare different kinds of entries and group * them together. */ public getResource(): URI { return null; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public isHidden(): boolean { return this.hidden; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public setHidden(hidden: boolean): void { this.hidden = hidden; } /** * Allows to set highlight ranges that should show up for the entry label and optionally description if set. */ public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.labelHighlights = labelHighlights; this.descriptionHighlights = descriptionHighlights; } /** * Allows to return highlight ranges that should show up for the entry label and description. */ public getHighlights(): [IHighlight[] /* Label */, IHighlight[] /* Description */] { return [this.labelHighlights, this.descriptionHighlights]; } /** * Called when the entry is selected for opening. Returns a boolean value indicating if an action was performed or not. * The mode parameter gives an indication if the element is previewed (using arrow keys) or opened. * * The context parameter provides additional context information how the run was triggered. */ public run(mode: Mode, context: IContext): boolean { return false; } /** * A good default sort implementation for quick open entries */ public static compare(elementA: QuickOpenEntry, elementB: QuickOpenEntry, lookFor: string): number { // Give matches with label highlights higher priority over // those with only description highlights const labelHighlightsA = elementA.getHighlights()[0] || []; const labelHighlightsB = elementB.getHighlights()[0] || []; if (labelHighlightsA.length && !labelHighlightsB.length) { return -1; } else if (!labelHighlightsA.length && labelHighlightsB.length) { return 1; } // Sort by name/path let nameA = elementA.getLabel(); let nameB = elementB.getLabel(); if (nameA === nameB) { let resourceA = elementA.getResource(); let resourceB = elementB.getResource(); if (resourceA && resourceB) { nameA = elementA.getResource().fsPath; nameB = elementB.getResource().fsPath; } } return compareAnything(nameA, nameB, lookFor); } } export class QuickOpenEntryItem extends QuickOpenEntry { /** * Must return the height as being used by the render function. */ public getHeight(): number { return 0; } /** * Allows to present the quick open entry in a custom way inside the tree. */ public render(tree: Tree.ITree, container: HTMLElement, previousCleanupFn: Tree.IElementCallback): Tree.IElementCallback { return null; } } export class QuickOpenEntryGroup extends QuickOpenEntry { private entry: QuickOpenEntry; private groupLabel: string; private withBorder: boolean; constructor(entry?: QuickOpenEntry, groupLabel?: string, withBorder?: boolean) { super(); this.entry = entry; this.groupLabel = groupLabel; this.withBorder = withBorder; } /** * The label of the group or null if none. */ public getGroupLabel(): string { return this.groupLabel; } public setGroupLabel(groupLabel: string): void { this.groupLabel = groupLabel; } /** * Whether to show a border on top of the group entry or not. */ public showBorder(): boolean { return this.withBorder; } public setShowBorder(showBorder: boolean): void { this.withBorder = showBorder; } public getLabel(): string { return this.entry ? this.entry.getLabel() : super.getLabel(); } public getMeta(): string { return this.entry ? this.entry.getMeta() : super.getMeta(); } public getResource(): URI { return this.entry ? this.entry.getResource() : super.getResource(); } public getIcon(): string { return this.entry ? this.entry.getIcon() : super.getIcon(); } public getDescription(): string { return this.entry ? this.entry.getDescription() : super.getDescription(); } public getEntry(): QuickOpenEntry { return this.entry; } public getHighlights(): [IHighlight[], IHighlight[]] { return this.entry ? this.entry.getHighlights() : super.getHighlights(); } public isHidden(): boolean { return this.entry ? this.entry.isHidden() : super.isHidden(); } public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.entry ? this.entry.setHighlights(labelHighlights, descriptionHighlights) : super.setHighlights(labelHighlights, descriptionHighlights); } public setHidden(hidden: boolean): void { this.entry ? this.entry.setHidden(hidden) : super.setHidden(hidden); } public run(mode: Mode, context: IContext): boolean { return this.entry ? this.entry.run(mode, context) : super.run(mode, context); } } const templateEntry = 'quickOpenEntry'; const templateEntryGroup = 'quickOpenEntryGroup'; const templateEntryItem = 'quickOpenEntryItem'; class EntryItemRenderer extends TreeDefaults.LegacyRenderer { public getTemplateId(tree: Tree.ITree, element: any): string { return templateEntryItem; } protected render(tree: Tree.ITree, element: any, container: HTMLElement, previousCleanupFn?: Tree.IElementCallback): Tree.IElementCallback { if (element instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>element).render(tree, container, previousCleanupFn); } return super.render(tree, element, container, previousCleanupFn); } } class NoActionProvider implements ActionsRenderer.IActionProvider { public hasActions(tree: Tree.ITree, element: any): boolean { return false; } public getActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public hasSecondaryActions(tree: Tree.ITree, element: any): boolean { return false; } public getSecondaryActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public getActionItem(tree: Tree.ITree, element: any, action: Actions.Action): ActionBar.IActionItem { return null; } } export interface IQuickOpenEntryTemplateData { container: HTMLElement; icon: HTMLSpanElement; label: HighlightedLabel.HighlightedLabel; meta: HTMLSpanElement; description: HighlightedLabel.HighlightedLabel; actionBar: ActionBar.ActionBar; } export interface IQuickOpenEntryGroupTemplateData extends IQuickOpenEntryTemplateData { group: HTMLDivElement; } class Renderer implements IRenderer<QuickOpenEntry> { private actionProvider: ActionsRenderer.IActionProvider; private actionRunner: Actions.IActionRunner; private entryItemRenderer: EntryItemRenderer; constructor(actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider(), actionRunner: Actions.IActionRunner = null) { this.actionProvider = actionProvider; this.actionRunner = actionRunner; this.entryItemRenderer = new EntryItemRenderer(); } public getHeight(entry: QuickOpenEntry): number { if (entry instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>entry).getHeight(); } return 24; } public getTemplateId(entry: QuickOpenEntry): string { if (entry instanceof QuickOpenEntryItem) { return templateEntryItem; } if (entry instanceof QuickOpenEntryGroup) { return templateEntryGroup; } return templateEntry; } public renderTemplate(templateId: string, container: HTMLElement): IQuickOpenEntryGroupTemplateData { // Entry Item if (templateId === templateEntryItem) { return this.entryItemRenderer.renderTemplate(null, templateId, container); } // Entry Group let group: HTMLDivElement; if (templateId === templateEntryGroup) { group = document.createElement('div'); DOM.addClass(group, 'results-group'); container.appendChild(group); } // Action Bar DOM.addClass(container, 'actions'); let entryContainer = document.createElement('div'); DOM.addClass(entryContainer, 'sub-content'); container.appendChild(entryContainer); let actionBarContainer = document.createElement('div'); DOM.addClass(actionBarContainer, 'primary-action-bar'); container.appendChild(actionBarContainer); let actionBar = new ActionBar.ActionBar(actionBarContainer, { actionRunner: this.actionRunner }); // Entry let entry = document.createElement('div'); DOM.addClass(entry, 'quick-open-entry'); entryContainer.appendChild(entry); // Icon let icon = document.createElement('span'); entry.appendChild(icon); // Label let label = new HighlightedLabel.HighlightedLabel(entry); // Meta let meta = document.createElement('span'); entry.appendChild(meta); DOM.addClass(meta, 'quick-open-entry-meta'); // Description let descriptionContainer = document.createElement('span'); entry.appendChild(descriptionContainer); DOM.addClass(descriptionContainer, 'quick-open-entry-description'); let description = new HighlightedLabel.HighlightedLabel(descriptionContainer); return { container: container, icon: icon, label: label, meta: meta, description: description, group: group, actionBar: actionBar }; } public renderElement(entry: QuickOpenEntry, templateId: string, templateData: any): void { // Entry Item if (templateId === templateEntryItem) { this.entryItemRenderer.renderElement(null, entry, templateId, <TreeDefaults.ILegacyTemplateData>templateData); return; } let data: IQuickOpenEntryTemplateData = templateData; // Action Bar if (this.actionProvider.hasActions(null, entry)) { DOM.addClass(data.container, 'has-actions'); } else { DOM.removeClass(data.container, 'has-actions'); } data.actionBar.context = entry; // make sure the context is the current element this.actionProvider.getActions(null, entry).then((actions) => { // TODO@Ben this will not work anymore as soon as quick open has more actions // but as long as there is only one are ok if (data.actionBar.isEmpty() && actions && actions.length > 0) { data.actionBar.push(actions, { icon: true, label: false }); } else if (!data.actionBar.isEmpty() && (!actions || actions.length === 0)) { data.actionBar.clear(); } }); // Entry group if (entry instanceof QuickOpenEntryGroup) { let group = <QuickOpenEntryGroup>entry; // Border if (group.showBorder()) { DOM.addClass(data.container, 'results-group-separator'); } else { DOM.removeClass(data.container, 'results-group-separator'); } // Group Label let groupLabel = group.getGroupLabel() || ''; (<IQuickOpenEntryGroupTemplateData>templateData).group.textContent = groupLabel; } // Normal Entry if (entry instanceof QuickOpenEntry) { let highlights = entry.getHighlights(); // Icon let iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : ''; data.icon.className = iconClass; // Label let labelHighlights = highlights[0]; data.label.set(entry.getLabel() || '', labelHighlights || []); // Meta let metaLabel = entry.getMeta() || ''; data.meta.textContent = metaLabel; // Description let descriptionHighlights = highlights[1]; data.description.set(entry.getDescription() || '', descriptionHighlights || []); } } public disposeTemplate(templateId: string, templateData: any): void { if (templateId === templateEntryItem) { this.entryItemRenderer.disposeTemplate(null, templateId, templateData); } } } export class QuickOpenModel implements IModel<QuickOpenEntry>, IDataSource<QuickOpenEntry>, IFilter<QuickOpenEntry>, IRunner<QuickOpenEntry> { private _entries: QuickOpenEntry[]; private _dataSource: IDataSource<QuickOpenEntry>; private _renderer: IRenderer<QuickOpenEntry>; private _filter: IFilter<QuickOpenEntry>; private _runner: IRunner<QuickOpenEntry>; constructor(entries: QuickOpenEntry[] = [], actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider()) { this._entries = entries; this._dataSource = this; this._renderer = new Renderer(actionProvider); this._filter = this; this._runner = this; } public get entries() { return this._entries; } public get dataSource() { return this._dataSource; } public get renderer() { return this._renderer; } public get filter() { return this._filter; } public get runner() { return this._runner; } public set entries(entries: QuickOpenEntry[]) { this._entries = entries; } /** * Adds entries that should show up in the quick open viewer. */ public addEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = this._entries.concat(entries); } } /** * Set the entries that should show up in the quick open viewer. */ public setEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = entries; } } /** * Get the entries that should show up in the quick open viewer. * * @visibleOnly optional parameter to only return visible entries */ public getEntries(visibleOnly?: boolean): QuickOpenEntry[] { if (visibleOnly) { return this._entries.filter((e) => !e.isHidden()); } return this._entries; } getId(entry: QuickOpenEntry): string { return entry.getId(); } getLabel(entry: QuickOpenEntry): string { return entry.getLabel(); } isVisible<T>(entry: QuickOpenEntry): boolean { return !entry.isHidden(); } run(entry: QuickOpenEntry, mode: Mode, context: IContext): boolean { return entry.run(mode, context); } }
src/vs/base/parts/quickopen/browser/quickOpenModel.ts
1
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.99847012758255, 0.0716324895620346, 0.00016444084758404642, 0.00017230026423931122, 0.25669389963150024 ]
{ "id": 6, "code_window": [ "\t\treturn new EditorHistoryEntry(this.editorService, this.contextService, this.input, labelHighlights, descriptionHighlights, this.model);\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n", "\t\tlet status = this.input.getStatus();\n", "\t\tif (status && status.decoration) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\tpublic getPrefix(): string {\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "replace", "edit_start_line_idx": 60 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* Checkbox */ .monaco-checkbox .label { width: 12px; height: 12px; border: 1px solid black; background-color: transparent; display: inline-block; } .monaco-checkbox .checkbox { position: absolute; overflow: hidden; clip: rect(0 0 0 0); height: 1px; width: 1px; margin: -1px; padding: 0; border: 0; } .monaco-checkbox .checkbox:checked + .label { background-color: black; } .monaco-checkbox .checkbox:focus + .label { outline: auto 5px rgb(229, 151, 0); } /* Find widget */ .monaco-editor .find-widget { position: absolute; z-index: 10; top: -44px; /* find input height + shadow (10px) */ height: 34px; /* find input height */ overflow: hidden; line-height: 19px; -webkit-transition: top 200ms linear; -o-transition: top 200ms linear; -moz-transition: top 200ms linear; -ms-transition: top 200ms linear; transition: top 200ms linear; padding: 0 4px; } /* Find widget when replace is toggled on */ .monaco-editor .find-widget.replaceToggled { top: -74px; /* find input height + replace input height + shadow (10px) */ height: 64px; /* find input height + replace input height */ } .monaco-editor .find-widget.replaceToggled > .replace-part { display: inline-block; } .monaco-editor .find-widget.visible, .monaco-editor .find-widget.replaceToggled.visible { top: 0; } .monaco-editor .find-widget .monaco-inputbox .input { background-color: transparent; /* Style to compensate for //winjs */ min-height: 0; } .monaco-editor .find-widget .monaco-findInput, .monaco-editor .find-widget .replace-input { background-color: white; } .monaco-editor .find-widget .replace-input .input { font-size: 13px; font-family: "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; } .monaco-editor .find-widget.visible.noanimation { -webkit-transition: none; -o-transition: none; -moz-transition: none; -ms-transition: none; transition: none; } .monaco-editor .find-widget > .find-part, .monaco-editor .find-widget > .replace-part { margin: 4px 0 0 17px; font-size: 12px; } .monaco-editor .find-widget > .find-part .monaco-inputbox, .monaco-editor .find-widget > .replace-part .monaco-inputbox { height: 25px; } .monaco-editor .find-widget > .find-part .monaco-inputbox > .wrapper > .input, .monaco-editor .find-widget > .replace-part .monaco-inputbox > .wrapper > .input { padding-top: 2px; padding-bottom: 2px; } .monaco-editor .find-widget .monaco-findInput { display: inline-block; vertical-align: middle; } .monaco-editor .find-widget.no-results .monaco-findInput .monaco-inputbox { border-color: #E51400; } .monaco-editor .find-widget .button { width: 20px; height: 20px; display: inline-block; vertical-align: middle; margin-left: 3px; background-position: center center; background-repeat: no-repeat; cursor: pointer; } .monaco-editor .find-widget .button:not(.disabled):hover { background-color: #DDD; } .monaco-editor .find-widget .button.left { margin-left: 0; margin-right: 3px; } .monaco-editor .find-widget .button.wide { width: auto; padding: 1px 6px; top: -1px; } .monaco-editor .find-widget .button.toggle { display: none; position: absolute; top: 0; left: 0; width: 18px; height: 100%; -webkit-box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; } .monaco-editor .find-widget.can-replace .button.toggle { display: inherit; } .monaco-editor .find-widget .previous { background-image: url('previous.svg'); } .monaco-editor .find-widget .next { background-image: url('next.svg'); } .monaco-editor .find-widget .disabled { opacity: 0.3; cursor: default; } .monaco-editor .find-widget .monaco-checkbox { width: 20px; height: 20px; display: inline-block; vertical-align: middle; margin-left: 3px; } .monaco-editor .find-widget .monaco-checkbox .label { content: ''; display: inline-block; background-repeat: no-repeat; background-position: 0 0; background-image: url('cancelSelectionFind.svg'); width: 20px; height: 20px; border: none; } .monaco-editor .find-widget .monaco-checkbox .checkbox:disabled + .label { opacity: 0.3; } .monaco-editor .find-widget .monaco-checkbox .checkbox:not(:disabled) + .label { cursor: pointer; } .monaco-editor .find-widget .monaco-checkbox .checkbox:not(:disabled):hover:before + .label { background-color: #DDD; } .monaco-editor .find-widget .monaco-checkbox .checkbox:checked + .label { background-color: rgba(100, 100, 100, 0.2); } .monaco-editor .find-widget .close-fw { background-image: url('close.svg'); } .monaco-editor .find-widget .expand { background-image: url('expando-expanded.svg'); } .monaco-editor .find-widget .collapse { background-image: url('expando-collapsed.svg'); } .monaco-editor .find-widget .replace { background-image: url('replace.svg'); } .monaco-editor .find-widget .replace-all { background-image: url('replace-all.svg'); } .monaco-editor .find-widget > .replace-part { display: none; } .monaco-editor .find-widget > .replace-part > .replace-input { display: inline-block; vertical-align: middle; } .monaco-editor .find-widget > .replace-part > .replace-input > .monaco-inputbox { width: 100%; } .monaco-editor .findMatch { background-color: rgba(234, 92, 0, 0.3); -webkit-animation-duration: 0; -webkit-animation-name: inherit !important; -moz-animation-duration: 0; -moz-animation-name: inherit !important; -ms-animation-duration: 0; -ms-animation-name: inherit !important; animation-duration: 0; animation-name: inherit !important; } .monaco-editor .currentFindMatch { background-color: #A8AC94; } .monaco-editor .findScope { background-color: rgba(239, 239, 242, 0.4); } /* Theming */ .monaco-editor .find-widget { background-color: #EFEFF2; box-shadow: 0 2px 8px #A8A8A8; } .monaco-editor.vs-dark .find-widget { background-color: #2D2D30; box-shadow: 0 2px 8px #000; } .monaco-editor.vs-dark .find-widget .previous { background-image: url('previous-inverse.svg'); } .monaco-editor.vs-dark .find-widget .next { background-image: url('next-inverse.svg'); } .monaco-editor.vs-dark .find-widget .monaco-checkbox .label { background-image: url('cancelSelectionFind-inverse.svg'); } .monaco-editor.vs-dark .find-widget .monaco-checkbox .checkbox:not(:disabled):hover:before + .label { background-color: #2f3334; } .monaco-editor.vs-dark .find-widget .monaco-checkbox .checkbox:checked + .label { background-color: rgba(150, 150, 150, 0.3); } .monaco-editor.vs-dark .find-widget .close-fw { background-image: url('close-dark.svg'); } .monaco-editor.vs-dark .find-widget .replace { background-image: url('replace-inverse.svg'); } .monaco-editor.vs-dark .find-widget .replace-all { background-image: url('replace-all-inverse.svg'); } .monaco-editor.vs-dark .find-widget .expand { background-image: url('expando-expanded-dark.svg'); } .monaco-editor.vs-dark .find-widget .collapse { background-image: url('expando-collapsed-dark.svg'); } .monaco-editor.vs-dark .find-widget .button:not(.disabled):hover { background-color: #2f3334; } .monaco-editor.vs-dark .currentFindMatch { background-color: #515C6A; } .monaco-editor.vs-dark .findScope { background-color: rgba(58, 61, 65, 0.4); } .monaco-editor.vs-dark .find-widget .monaco-findInput, .monaco-editor.vs-dark .find-widget .replace-input { background-color: #3C3C3C; } /* High Contrast Theming */ .monaco-editor.hc-black .find-widget { border: 2px solid #6FC3DF; background: #0C141F; box-shadow: none; } .monaco-editor.hc-black .find-widget .button:not(.disabled):hover { background: none; } .monaco-editor.hc-black .find-widget .button { background: none; } .monaco-editor.hc-black .find-widget .button:before { position: relative; top: 1px; left: 2px; } .monaco-editor.hc-black .find-widget .previous:before { content: url('previous-inverse.svg'); } .monaco-editor.hc-black .find-widget .next:before { content: url('next-inverse.svg'); } .monaco-editor.hc-black .find-widget .replace:before { content: url('replace-inverse.svg'); } .monaco-editor.hc-black .find-widget .replace-all:before { content: url('replace-all-inverse.svg'); } .monaco-editor.hc-black .find-widget .monaco-checkbox .label { content: url('cancelSelectionFind-inverse.svg'); top: 1px; left: 2px; } .monaco-editor.hc-black .find-widget .monaco-checkbox .checkbox:checked + .label { background-color: rgba(150, 150, 150, 0.3); } .monaco-editor.hc-black .find-widget .close-fw:before { content: url('close-dark.svg'); top: 1px; left: 0px; } .monaco-editor.hc-black .find-widget .expand:before { content: url('expando-expanded-dark.svg'); top: 38%; left: 40% } .monaco-editor.hc-black .find-widget .collapse:before { content: url('expando-collapsed-dark.svg'); top: 30%; left: 40%; } .monaco-editor.hc-black .findMatch { background: none; border: 1px dotted #DF740C; -moz-box-sizing: border-box; box-sizing: border-box; } .monaco-editor.hc-black .currentFindMatch { background: none; padding: 1px; border: 2px solid #DF740C; -moz-box-sizing: border-box; box-sizing: border-box; } .monaco-editor.hc-black .findScope { background: none; border: 1px dashed #DF740C; opacity: .4; } .monaco-editor.hc-black .find-widget .monaco-findInput, .monaco-editor.hc-black .find-widget .replace-input { background-color: #000; }
src/vs/editor/contrib/find/browser/findWidget.css
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017995541566051543, 0.0001747936476022005, 0.00017116058734245598, 0.00017487634613644332, 0.0000016229757875407813 ]
{ "id": 6, "code_window": [ "\t\treturn new EditorHistoryEntry(this.editorService, this.contextService, this.input, labelHighlights, descriptionHighlights, this.model);\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n", "\t\tlet status = this.input.getStatus();\n", "\t\tif (status && status.decoration) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\tpublic getPrefix(): string {\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "replace", "edit_start_line_idx": 60 }
src/vs/base/test/node/encoding/fixtures/empty.txt
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.0001799552410375327, 0.0001799552410375327, 0.0001799552410375327, 0.0001799552410375327, 0 ]
{ "id": 6, "code_window": [ "\t\treturn new EditorHistoryEntry(this.editorService, this.contextService, this.input, labelHighlights, descriptionHighlights, this.model);\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n", "\t\tlet status = this.input.getStatus();\n", "\t\tif (status && status.decoration) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\tpublic getPrefix(): string {\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "replace", "edit_start_line_idx": 60 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import env = require('vs/workbench/electron-main/env'); import events = require('vs/base/common/eventEmitter'); import platform = require('vs/base/common/platform'); import BrowserWindow = require('browser-window'); import ipc = require('ipc'); interface ICredentialsContext { id: number; host: string; command: string; } interface ICredentials { username: string; password: string; } interface ICredentialsResult { id: number; credentials: ICredentials; } interface IContext { credentials: ICredentials; window: BrowserWindow; } export function configure(bus: events.EventEmitter): void { var cache: { [id: string]: IContext } = Object.create(null); ipc.on('git:askpass', (event, result: ICredentialsResult) => { cache[result.id].credentials = result.credentials; }); bus.addListener('git:askpass', (context: ICredentialsContext) => { var cachedResult = cache[context.id]; if (typeof cachedResult !== 'undefined') { bus.emit('git:askpass:' + context.id, cachedResult.credentials); return; } if (context.command === 'fetch') { bus.emit('git:askpass:' + context.id, { id: context.id, credentials: { username: '', password: '' }}); return; } var win = new BrowserWindow({ 'always-on-top': true, 'skip-taskbar': true, resizable: false, width: 450, height: platform.isWindows ? 280 : 260, show: true, title: env.product.nameLong }); win.setMenuBarVisibility(false); cache[context.id] = { window: win, credentials: null }; win.loadUrl(require.toUrl('vs/workbench/parts/git/electron-main/index.html')); win.webContents.executeJavaScript('init(' + JSON.stringify(context) + ')'); win.once('closed', () => { bus.emit('git:askpass:' + context.id, cache[context.id].credentials); setTimeout(function () { delete cache[context.id]; }, 1000 * 10); }); }); }
src/vs/workbench/parts/git/electron-main/index.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.0001777978613972664, 0.00017395724717061967, 0.00017178303096443415, 0.00017358866170980036, 0.00000202066303245374 ]
{ "id": 7, "code_window": [ "\t\tlet status = this.input.getStatus();\n", "\t\tif (status && status.decoration) {\n", "\t\t\treturn status.decoration + ' ' + this.input.getName();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn `${status.decoration} `;\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "replace", "edit_start_line_idx": 63 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {Registry} from 'vs/platform/platform'; import filters = require('vs/base/common/filters'); import strings = require('vs/base/common/strings'); import types = require('vs/base/common/types'); import paths = require('vs/base/common/paths'); import URI from 'vs/base/common/uri'; import {EventType} from 'vs/base/common/events'; import comparers = require('vs/base/common/comparers'); import {Mode, IContext} from 'vs/base/parts/quickopen/browser/quickOpen'; import {QuickOpenEntry, QuickOpenModel, IHighlight} from 'vs/base/parts/quickopen/browser/quickOpenModel'; import {EditorInput, getUntitledOrFileResource} from 'vs/workbench/common/editor'; import {IEditorRegistry, Extensions} from 'vs/workbench/browser/parts/editor/baseEditor'; import {EditorQuickOpenEntry} from 'vs/workbench/browser/quickopen'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; const MAX_ENTRIES = 200; export class EditorHistoryEntry extends EditorQuickOpenEntry { private input: EditorInput; private model: EditorHistoryModel; private resource: URI; constructor( editorService: IWorkbenchEditorService, private contextService: IWorkspaceContextService, input: EditorInput, labelHighlights: IHighlight[], descriptionHighlights: IHighlight[], model: EditorHistoryModel ) { super(editorService); this.input = input; this.model = model; let resource = getUntitledOrFileResource(input); if (resource) { this.resource = resource; } else { let inputWithResource: { getResource(): URI } = <any>input; if (types.isFunction(inputWithResource.getResource)) { this.resource = inputWithResource.getResource(); } } this.setHighlights(labelHighlights, descriptionHighlights); } public clone(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): EditorHistoryEntry { return new EditorHistoryEntry(this.editorService, this.contextService, this.input, labelHighlights, descriptionHighlights, this.model); } public getLabel(): string { let status = this.input.getStatus(); if (status && status.decoration) { return status.decoration + ' ' + this.input.getName(); } return this.input.getName(); } public getDescription(): string { return this.input.getDescription(); } public getResource(): URI { return this.resource; } public getInput(): EditorInput { return this.input; } public matches(input: EditorInput): boolean { return this.input.matches(input); } public run(mode: Mode, context: IContext): boolean { if (mode === Mode.OPEN) { let event = context.event; let sideBySide = !context.quickNavigateConfiguration && (event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey)))); this.editorService.openEditor(this.input, null, sideBySide).done(() => { // Automatically clean up stale history entries when the input can not be opened if (!this.input.matches(this.editorService.getActiveEditorInput())) { this.model.remove(this.input); } }); return true; } return false; } } interface ISerializedEditorInput { id: string; value: string; } export class EditorHistoryModel extends QuickOpenModel { constructor( private editorService: IWorkbenchEditorService, private instantiationService: IInstantiationService, private contextService: IWorkspaceContextService ) { super(); } public add(entry: EditorInput): void { // Ensure we have at least a name to show if (!entry.getName()) { return; } // Remove on Dispose let unbind = entry.addListener(EventType.DISPOSE, () => { this.remove(entry); unbind(); }); // Remove any existing entry and add to the beginning this.remove(entry); this.entries.unshift(new EditorHistoryEntry(this.editorService, this.contextService, entry, null, null, this)); // Respect max entries setting if (this.entries.length > MAX_ENTRIES) { this.entries = this.entries.slice(0, MAX_ENTRIES); } } public remove(entry: EditorInput): void { let index = this.indexOf(entry); if (index >= 0) { this.entries.splice(index, 1); } } private indexOf(entryToFind: EditorInput): number { for (let i = 0; i < this.entries.length; i++) { let entry = this.entries[i]; if ((<EditorHistoryEntry>entry).matches(entryToFind)) { return i; } } return -1; } public saveTo(memento: any): void { let registry = (<IEditorRegistry>Registry.as(Extensions.Editors)); let entries: ISerializedEditorInput[] = []; for (let i = this.entries.length - 1; i >= 0; i--) { let entry = this.entries[i]; let input = (<EditorHistoryEntry>entry).getInput(); let factory = registry.getEditorInputFactory(input.getId()); if (factory) { let value = factory.serialize(input); if (types.isString(value)) { entries.push({ id: input.getId(), value: value }); } } } if (entries.length > 0) { memento.entries = entries; } } public loadFrom(memento: any): void { let registry = (<IEditorRegistry>Registry.as(Extensions.Editors)); let entries: ISerializedEditorInput[] = memento.entries; if (entries && entries.length > 0) { for (let i = 0; i < entries.length; i++) { let entry = entries[i]; let factory = registry.getEditorInputFactory(entry.id); if (factory && types.isString(entry.value)) { let input = factory.deserialize(this.instantiationService, entry.value); if (input) { this.add(input); } } } } } public getEntries(): EditorHistoryEntry[] { return <EditorHistoryEntry[]>this.entries.slice(0); } public getResults(searchValue: string): QuickOpenEntry[] { searchValue = searchValue.trim(); let results: QuickOpenEntry[] = []; for (let i = 0; i < this.entries.length; i++) { let entry = <EditorHistoryEntry>this.entries[i]; if (!entry.getResource()) { continue; //For now, only support to match on inputs that provide resource information } let label = entry.getInput().getName(); let description = entry.getInput().getDescription(); let labelHighlights: IHighlight[] = []; let descriptionHighlights: IHighlight[] = []; // Search inside filename if (searchValue.indexOf(paths.nativeSep) < 0) { labelHighlights = filters.matchesFuzzy(searchValue, label); } // Search in full path else { descriptionHighlights = filters.matchesFuzzy(strings.trim(searchValue, paths.nativeSep), description); // If we have no highlights, assume that the match is split among name and parent folder if (!descriptionHighlights || !descriptionHighlights.length) { labelHighlights = filters.matchesFuzzy(paths.basename(searchValue), label); descriptionHighlights = filters.matchesFuzzy(strings.trim(paths.dirname(searchValue), paths.nativeSep), description); } } if ((labelHighlights && labelHighlights.length) || (descriptionHighlights && descriptionHighlights.length)) { results.push(entry.clone(labelHighlights, descriptionHighlights)); } } // If user is searching, use the same sorting that is used for other quick open handlers if (searchValue) { let normalizedSearchValue = strings.stripWildcards(searchValue.toLowerCase()); return results.sort((elementA: EditorHistoryEntry, elementB: EditorHistoryEntry) => QuickOpenEntry.compare(elementA, elementB, normalizedSearchValue)); } // Leave default "most recently used" order if user is not actually searching return results; } }
src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts
1
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.998367965221405, 0.038814179599285126, 0.00016463035717606544, 0.00018162322521675378, 0.1919124722480774 ]
{ "id": 7, "code_window": [ "\t\tlet status = this.input.getStatus();\n", "\t\tif (status && status.decoration) {\n", "\t\t\treturn status.decoration + ' ' + this.input.getName();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn `${status.decoration} `;\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "replace", "edit_start_line_idx": 63 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path="emmet.d.ts" /> 'use strict'; import {TPromise} from 'vs/base/common/winjs.base'; import {IEditorActionDescriptorData, ICommonCodeEditor} from 'vs/editor/common/editorCommon'; import {EditorAction, Behaviour} from 'vs/editor/common/editorAction'; import {EditorAccessor} from './editorAccessor'; import {INullService} from 'vs/platform/instantiation/common/instantiation'; export class ExpandAbbreviationAction extends EditorAction { static ID = 'editor.emmet.action.expandAbbreviation'; private editorAccessor: EditorAccessor; constructor(descriptor: IEditorActionDescriptorData, editor: ICommonCodeEditor, @INullService ns) { super(descriptor, editor, Behaviour.TextFocus); this.editorAccessor = new EditorAccessor(editor); } public run(): TPromise<boolean> { return new TPromise((c, e) => { require(['emmet'], (_module) => { try { if (!this.editorAccessor.isEmmetEnabledMode()) { this.editorAccessor.noExpansionOccurred(); return; } if (!_module.run('expand_abbreviation', this.editorAccessor)) { this.editorAccessor.noExpansionOccurred(); } } catch (err) { // } finally { this.editorAccessor.flushCache(); } }, e); }); } }
src/vs/workbench/parts/emmet/node/emmetActions.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017607718473300338, 0.00017310807015746832, 0.00016956718172878027, 0.00017232917889486998, 0.0000025616143375373213 ]
{ "id": 7, "code_window": [ "\t\tlet status = this.input.getStatus();\n", "\t\tif (status && status.decoration) {\n", "\t\t\treturn status.decoration + ' ' + this.input.getName();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn `${status.decoration} `;\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "replace", "edit_start_line_idx": 63 }
{ "comments": { "lineComment": "//", // "#" "blockComment": [ "/*", "*/" ] }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ] }
extensions/php/php.configuration.json
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017734205175656825, 0.00017357661272399127, 0.0001698111736914143, 0.00017357661272399127, 0.000003765439032576978 ]
{ "id": 7, "code_window": [ "\t\tlet status = this.input.getStatus();\n", "\t\tif (status && status.decoration) {\n", "\t\t\treturn status.decoration + ' ' + this.input.getName();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn `${status.decoration} `;\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "replace", "edit_start_line_idx": 63 }
// Type definitions for vinyl 0.4.3 // Project: https://github.com/wearefractal/vinyl // Definitions by: vvakame <https://github.com/vvakame/>, jedmao <https://github.com/jedmao> // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module 'vinyl' { import fs = require('fs'); /** * A virtual file format. */ class File { constructor(options?: { /** * Default: process.cwd() */ cwd?: string; /** * Used for relative pathing. Typically where a glob starts. */ base?: string; /** * Full path to the file. */ path?: string; /** * Type: Buffer|Stream|null (Default: null) */ contents?: any; }); /** * Default: process.cwd() */ public cwd: string; /** * Used for relative pathing. Typically where a glob starts. */ public base: string; /** * Full path to the file. */ public path: string; public stat: fs.Stats; /** * Type: Buffer|Stream|null (Default: null) */ public contents: any; /** * Returns path.relative for the file base and file path. * Example: * var file = new File({ * cwd: "/", * base: "/test/", * path: "/test/file.js" * }); * console.log(file.relative); // file.js */ public relative: string; public isBuffer(): boolean; public isStream(): boolean; public isNull(): boolean; public isDirectory(): boolean; /** * Returns a new File object with all attributes cloned. Custom attributes are deep-cloned. */ public clone(opts?: { contents?: boolean }): File; /** * If file.contents is a Buffer, it will write it to the stream. * If file.contents is a Stream, it will pipe it to the stream. * If file.contents is null, it will do nothing. */ public pipe<T extends NodeJS.ReadWriteStream>( stream: T, opts?: { /** * If false, the destination stream will not be ended (same as node core). */ end?: boolean; } ): T; /** * Returns a pretty String interpretation of the File. Useful for console.log. */ public inspect(): string; } export = File; }
build/lib/typings/vinyl.d.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017579937411937863, 0.00017060177924577147, 0.00016433518612757325, 0.0001706556067802012, 0.0000033846552014438203 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn this.input.getName();\n", "\t}\n", "\n", "\tpublic getDescription(): string {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn void 0;\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "add", "edit_start_line_idx": 66 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import WinJS = require('vs/base/common/winjs.base'); import Types = require('vs/base/common/types'); import URI from 'vs/base/common/uri'; import Tree = require('vs/base/parts/tree/common/tree'); import {IQuickNavigateConfiguration, IModel, IDataSource, IFilter, IRenderer, IRunner, Mode} from './quickOpen'; import ActionsRenderer = require('vs/base/parts/tree/browser/actionsRenderer'); import Actions = require('vs/base/common/actions'); import {compareAnything} from 'vs/base/common/comparers'; import ActionBar = require('vs/base/browser/ui/actionbar/actionbar'); import TreeDefaults = require('vs/base/parts/tree/browser/treeDefaults'); import HighlightedLabel = require('vs/base/browser/ui/highlightedlabel/highlightedLabel'); import DOM = require('vs/base/browser/dom'); export interface IContext { event: any; quickNavigateConfiguration: IQuickNavigateConfiguration; } export interface IHighlight { start: number; end: number; } let IDS = 0; export class QuickOpenEntry { private id: string; private labelHighlights: IHighlight[]; private descriptionHighlights: IHighlight[]; private hidden: boolean; constructor(highlights: IHighlight[] = []) { this.id = (IDS++).toString(); this.labelHighlights = highlights; this.descriptionHighlights = []; } /** * A unique identifier for the entry */ public getId(): string { return this.id; } /** * The label of the entry to identify it from others in the list */ public getLabel(): string { return null; } /** * Meta information about the entry that is optional and can be shown to the right of the label */ public getMeta(): string { return null; } /** * The icon of the entry to identify it from others in the list */ public getIcon(): string { return null; } /** * A secondary description that is optional and can be shown right to the label */ public getDescription(): string { return null; } /** * A resource for this entry. Resource URIs can be used to compare different kinds of entries and group * them together. */ public getResource(): URI { return null; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public isHidden(): boolean { return this.hidden; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public setHidden(hidden: boolean): void { this.hidden = hidden; } /** * Allows to set highlight ranges that should show up for the entry label and optionally description if set. */ public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.labelHighlights = labelHighlights; this.descriptionHighlights = descriptionHighlights; } /** * Allows to return highlight ranges that should show up for the entry label and description. */ public getHighlights(): [IHighlight[] /* Label */, IHighlight[] /* Description */] { return [this.labelHighlights, this.descriptionHighlights]; } /** * Called when the entry is selected for opening. Returns a boolean value indicating if an action was performed or not. * The mode parameter gives an indication if the element is previewed (using arrow keys) or opened. * * The context parameter provides additional context information how the run was triggered. */ public run(mode: Mode, context: IContext): boolean { return false; } /** * A good default sort implementation for quick open entries */ public static compare(elementA: QuickOpenEntry, elementB: QuickOpenEntry, lookFor: string): number { // Give matches with label highlights higher priority over // those with only description highlights const labelHighlightsA = elementA.getHighlights()[0] || []; const labelHighlightsB = elementB.getHighlights()[0] || []; if (labelHighlightsA.length && !labelHighlightsB.length) { return -1; } else if (!labelHighlightsA.length && labelHighlightsB.length) { return 1; } // Sort by name/path let nameA = elementA.getLabel(); let nameB = elementB.getLabel(); if (nameA === nameB) { let resourceA = elementA.getResource(); let resourceB = elementB.getResource(); if (resourceA && resourceB) { nameA = elementA.getResource().fsPath; nameB = elementB.getResource().fsPath; } } return compareAnything(nameA, nameB, lookFor); } } export class QuickOpenEntryItem extends QuickOpenEntry { /** * Must return the height as being used by the render function. */ public getHeight(): number { return 0; } /** * Allows to present the quick open entry in a custom way inside the tree. */ public render(tree: Tree.ITree, container: HTMLElement, previousCleanupFn: Tree.IElementCallback): Tree.IElementCallback { return null; } } export class QuickOpenEntryGroup extends QuickOpenEntry { private entry: QuickOpenEntry; private groupLabel: string; private withBorder: boolean; constructor(entry?: QuickOpenEntry, groupLabel?: string, withBorder?: boolean) { super(); this.entry = entry; this.groupLabel = groupLabel; this.withBorder = withBorder; } /** * The label of the group or null if none. */ public getGroupLabel(): string { return this.groupLabel; } public setGroupLabel(groupLabel: string): void { this.groupLabel = groupLabel; } /** * Whether to show a border on top of the group entry or not. */ public showBorder(): boolean { return this.withBorder; } public setShowBorder(showBorder: boolean): void { this.withBorder = showBorder; } public getLabel(): string { return this.entry ? this.entry.getLabel() : super.getLabel(); } public getMeta(): string { return this.entry ? this.entry.getMeta() : super.getMeta(); } public getResource(): URI { return this.entry ? this.entry.getResource() : super.getResource(); } public getIcon(): string { return this.entry ? this.entry.getIcon() : super.getIcon(); } public getDescription(): string { return this.entry ? this.entry.getDescription() : super.getDescription(); } public getEntry(): QuickOpenEntry { return this.entry; } public getHighlights(): [IHighlight[], IHighlight[]] { return this.entry ? this.entry.getHighlights() : super.getHighlights(); } public isHidden(): boolean { return this.entry ? this.entry.isHidden() : super.isHidden(); } public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.entry ? this.entry.setHighlights(labelHighlights, descriptionHighlights) : super.setHighlights(labelHighlights, descriptionHighlights); } public setHidden(hidden: boolean): void { this.entry ? this.entry.setHidden(hidden) : super.setHidden(hidden); } public run(mode: Mode, context: IContext): boolean { return this.entry ? this.entry.run(mode, context) : super.run(mode, context); } } const templateEntry = 'quickOpenEntry'; const templateEntryGroup = 'quickOpenEntryGroup'; const templateEntryItem = 'quickOpenEntryItem'; class EntryItemRenderer extends TreeDefaults.LegacyRenderer { public getTemplateId(tree: Tree.ITree, element: any): string { return templateEntryItem; } protected render(tree: Tree.ITree, element: any, container: HTMLElement, previousCleanupFn?: Tree.IElementCallback): Tree.IElementCallback { if (element instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>element).render(tree, container, previousCleanupFn); } return super.render(tree, element, container, previousCleanupFn); } } class NoActionProvider implements ActionsRenderer.IActionProvider { public hasActions(tree: Tree.ITree, element: any): boolean { return false; } public getActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public hasSecondaryActions(tree: Tree.ITree, element: any): boolean { return false; } public getSecondaryActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public getActionItem(tree: Tree.ITree, element: any, action: Actions.Action): ActionBar.IActionItem { return null; } } export interface IQuickOpenEntryTemplateData { container: HTMLElement; icon: HTMLSpanElement; label: HighlightedLabel.HighlightedLabel; meta: HTMLSpanElement; description: HighlightedLabel.HighlightedLabel; actionBar: ActionBar.ActionBar; } export interface IQuickOpenEntryGroupTemplateData extends IQuickOpenEntryTemplateData { group: HTMLDivElement; } class Renderer implements IRenderer<QuickOpenEntry> { private actionProvider: ActionsRenderer.IActionProvider; private actionRunner: Actions.IActionRunner; private entryItemRenderer: EntryItemRenderer; constructor(actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider(), actionRunner: Actions.IActionRunner = null) { this.actionProvider = actionProvider; this.actionRunner = actionRunner; this.entryItemRenderer = new EntryItemRenderer(); } public getHeight(entry: QuickOpenEntry): number { if (entry instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>entry).getHeight(); } return 24; } public getTemplateId(entry: QuickOpenEntry): string { if (entry instanceof QuickOpenEntryItem) { return templateEntryItem; } if (entry instanceof QuickOpenEntryGroup) { return templateEntryGroup; } return templateEntry; } public renderTemplate(templateId: string, container: HTMLElement): IQuickOpenEntryGroupTemplateData { // Entry Item if (templateId === templateEntryItem) { return this.entryItemRenderer.renderTemplate(null, templateId, container); } // Entry Group let group: HTMLDivElement; if (templateId === templateEntryGroup) { group = document.createElement('div'); DOM.addClass(group, 'results-group'); container.appendChild(group); } // Action Bar DOM.addClass(container, 'actions'); let entryContainer = document.createElement('div'); DOM.addClass(entryContainer, 'sub-content'); container.appendChild(entryContainer); let actionBarContainer = document.createElement('div'); DOM.addClass(actionBarContainer, 'primary-action-bar'); container.appendChild(actionBarContainer); let actionBar = new ActionBar.ActionBar(actionBarContainer, { actionRunner: this.actionRunner }); // Entry let entry = document.createElement('div'); DOM.addClass(entry, 'quick-open-entry'); entryContainer.appendChild(entry); // Icon let icon = document.createElement('span'); entry.appendChild(icon); // Label let label = new HighlightedLabel.HighlightedLabel(entry); // Meta let meta = document.createElement('span'); entry.appendChild(meta); DOM.addClass(meta, 'quick-open-entry-meta'); // Description let descriptionContainer = document.createElement('span'); entry.appendChild(descriptionContainer); DOM.addClass(descriptionContainer, 'quick-open-entry-description'); let description = new HighlightedLabel.HighlightedLabel(descriptionContainer); return { container: container, icon: icon, label: label, meta: meta, description: description, group: group, actionBar: actionBar }; } public renderElement(entry: QuickOpenEntry, templateId: string, templateData: any): void { // Entry Item if (templateId === templateEntryItem) { this.entryItemRenderer.renderElement(null, entry, templateId, <TreeDefaults.ILegacyTemplateData>templateData); return; } let data: IQuickOpenEntryTemplateData = templateData; // Action Bar if (this.actionProvider.hasActions(null, entry)) { DOM.addClass(data.container, 'has-actions'); } else { DOM.removeClass(data.container, 'has-actions'); } data.actionBar.context = entry; // make sure the context is the current element this.actionProvider.getActions(null, entry).then((actions) => { // TODO@Ben this will not work anymore as soon as quick open has more actions // but as long as there is only one are ok if (data.actionBar.isEmpty() && actions && actions.length > 0) { data.actionBar.push(actions, { icon: true, label: false }); } else if (!data.actionBar.isEmpty() && (!actions || actions.length === 0)) { data.actionBar.clear(); } }); // Entry group if (entry instanceof QuickOpenEntryGroup) { let group = <QuickOpenEntryGroup>entry; // Border if (group.showBorder()) { DOM.addClass(data.container, 'results-group-separator'); } else { DOM.removeClass(data.container, 'results-group-separator'); } // Group Label let groupLabel = group.getGroupLabel() || ''; (<IQuickOpenEntryGroupTemplateData>templateData).group.textContent = groupLabel; } // Normal Entry if (entry instanceof QuickOpenEntry) { let highlights = entry.getHighlights(); // Icon let iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : ''; data.icon.className = iconClass; // Label let labelHighlights = highlights[0]; data.label.set(entry.getLabel() || '', labelHighlights || []); // Meta let metaLabel = entry.getMeta() || ''; data.meta.textContent = metaLabel; // Description let descriptionHighlights = highlights[1]; data.description.set(entry.getDescription() || '', descriptionHighlights || []); } } public disposeTemplate(templateId: string, templateData: any): void { if (templateId === templateEntryItem) { this.entryItemRenderer.disposeTemplate(null, templateId, templateData); } } } export class QuickOpenModel implements IModel<QuickOpenEntry>, IDataSource<QuickOpenEntry>, IFilter<QuickOpenEntry>, IRunner<QuickOpenEntry> { private _entries: QuickOpenEntry[]; private _dataSource: IDataSource<QuickOpenEntry>; private _renderer: IRenderer<QuickOpenEntry>; private _filter: IFilter<QuickOpenEntry>; private _runner: IRunner<QuickOpenEntry>; constructor(entries: QuickOpenEntry[] = [], actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider()) { this._entries = entries; this._dataSource = this; this._renderer = new Renderer(actionProvider); this._filter = this; this._runner = this; } public get entries() { return this._entries; } public get dataSource() { return this._dataSource; } public get renderer() { return this._renderer; } public get filter() { return this._filter; } public get runner() { return this._runner; } public set entries(entries: QuickOpenEntry[]) { this._entries = entries; } /** * Adds entries that should show up in the quick open viewer. */ public addEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = this._entries.concat(entries); } } /** * Set the entries that should show up in the quick open viewer. */ public setEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = entries; } } /** * Get the entries that should show up in the quick open viewer. * * @visibleOnly optional parameter to only return visible entries */ public getEntries(visibleOnly?: boolean): QuickOpenEntry[] { if (visibleOnly) { return this._entries.filter((e) => !e.isHidden()); } return this._entries; } getId(entry: QuickOpenEntry): string { return entry.getId(); } getLabel(entry: QuickOpenEntry): string { return entry.getLabel(); } isVisible<T>(entry: QuickOpenEntry): boolean { return !entry.isHidden(); } run(entry: QuickOpenEntry, mode: Mode, context: IContext): boolean { return entry.run(mode, context); } }
src/vs/base/parts/quickopen/browser/quickOpenModel.ts
1
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.9982732534408569, 0.035883720964193344, 0.00016471325943712145, 0.00017049048619810492, 0.18518897891044617 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn this.input.getName();\n", "\t}\n", "\n", "\tpublic getDescription(): string {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn void 0;\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "add", "edit_start_line_idx": 66 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><style type="text/css">.icon-canvas-transparent{opacity:0;fill:#2D2D30;} .icon-vs-out{fill:#2D2D30;} .icon-vs-bg{fill:#C5C5C5;} .icon-vs-action-blue{fill:#75BEFF;}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M11 13c0-1.526-1.15-2.775-2.624-2.962L12 6.414V1.586l-2 2V1H6v2.586l-2-2v4.828l3.624 3.624C6.15 10.225 5 11.474 5 13c0 1.654 1.346 3 3 3s3-1.346 3-3z" id="outline"/><path class="icon-vs-bg" d="M8 11c1.104 0 2 .896 2 2s-.896 2-2 2-2-.896-2-2 .896-2 2-2z" id="iconBg"/><path class="icon-vs-action-blue" d="M8 9L5 6V4l2 2V2h2v4l2-2v2L8 9z" id="colorAction"/></svg>
src/vs/workbench/parts/debug/browser/media/step-into-inverse.svg
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.0001665385498199612, 0.0001665385498199612, 0.0001665385498199612, 0.0001665385498199612, 0 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn this.input.getName();\n", "\t}\n", "\n", "\tpublic getDescription(): string {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn void 0;\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "add", "edit_start_line_idx": 66 }
.DS_Store npm-debug.log Thumbs.db node_modules/ .build/ out/ out-build/ out-editor/ out-editor-min/ out-editor-ossfree/ out-editor-ossfree-min/ out-vscode/ out-vscode-min/ build/node_modules
.gitignore
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017087651940528303, 0.0001704215246718377, 0.0001699665153864771, 0.0001704215246718377, 4.5500200940296054e-7 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn this.input.getName();\n", "\t}\n", "\n", "\tpublic getDescription(): string {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn void 0;\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n" ], "file_path": "src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts", "type": "add", "edit_start_line_idx": 66 }
{ "name": "markdown", "version": "0.1.0", "publisher": "vscode", "engines": { "vscode": "*" }, "contributes": { "snippets": [{ "language": "markdown", "path": "./snippets/markdown.json" }] } }
extensions/markdown/package.json
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017871685849968344, 0.00017612386727705598, 0.00017353089060634375, 0.00017612386727705598, 0.0000025929839466698468 ]
{ "id": 0, "code_window": [ "\t\t\t\t|| this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'float') {\n", "\t\t\t\treturn this.hide();\n", "\t\t\t}\n", "\n", "\t\t\tconst actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService);\n", "\t\t\tif (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) {\n", "\t\t\t\tthis.actionBar.clear();\n", "\t\t\t\tthis.actionBar.push(actions, { icon: true, label: false });\n", "\t\t\t\tthis.activeActions = actions;\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, false, this.debugService, this.keybindingService, this.instantiationService);\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.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 'vs/css!./media/debugActionsWidget'; import * as errors from 'vs/base/common/errors'; import * as strings from 'vs/base/common/strings'; import * as browser from 'vs/base/browser/browser'; import { $, Builder } from 'vs/base/browser/builder'; import * as dom from 'vs/base/browser/dom'; import * as arrays from 'vs/base/common/arrays'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { IAction, IRunEvent } from 'vs/base/common/actions'; import { ActionBar, ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { IDebugConfiguration, IDebugService, State } from 'vs/workbench/parts/debug/common/debug'; import { AbstractDebugAction, PauseAction, ContinueAction, StepBackAction, ReverseContinueAction, StopAction, DisconnectAction, StepOverAction, StepIntoAction, StepOutAction, RestartAction, FocusSessionAction } from 'vs/workbench/parts/debug/browser/debugActions'; import { FocusSessionActionItem } from 'vs/workbench/parts/debug/browser/debugActionItems'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { Themable } from 'vs/workbench/common/theme'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { registerColor, contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { localize } from 'vs/nls'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IDisposable } from 'vs/base/common/lifecycle'; const DEBUG_ACTIONS_WIDGET_POSITION_KEY = 'debug.actionswidgetposition'; export const debugToolBarBackground = registerColor('debugToolBar.background', { dark: '#333333', light: '#F3F3F3', hc: '#000000' }, localize('debugToolBarBackground', "Debug toolbar background color.")); export const debugToolBarBorder = registerColor('debugToolBar.border', { dark: null, light: null, hc: null }, localize('debugToolBarBorder', "Debug toolbar border color.")); export class DebugActionsWidget extends Themable implements IWorkbenchContribution { private $el: Builder; private dragArea: Builder; private actionBar: ActionBar; private allActions: AbstractDebugAction[] = []; private activeActions: AbstractDebugAction[]; private updateScheduler: RunOnceScheduler; private isVisible: boolean; private isBuilt: boolean; constructor( @INotificationService private notificationService: INotificationService, @ITelemetryService private telemetryService: ITelemetryService, @IDebugService private debugService: IDebugService, @IPartService private partService: IPartService, @IStorageService private storageService: IStorageService, @IConfigurationService private configurationService: IConfigurationService, @IThemeService themeService: IThemeService, @IKeybindingService private keybindingService: IKeybindingService, @IContextViewService contextViewService: IContextViewService, @IInstantiationService private instantiationService: IInstantiationService ) { super(themeService); this.$el = $().div().addClass('debug-actions-widget').style('top', `${partService.getTitleBarOffset()}px`); this.dragArea = $().div().addClass('drag-area'); this.$el.append(this.dragArea); const actionBarContainter = $().div().addClass('.action-bar-container'); this.$el.append(actionBarContainter); this.activeActions = []; this.actionBar = new ActionBar(actionBarContainter.getHTMLElement(), { orientation: ActionsOrientation.HORIZONTAL, actionItemProvider: (action: IAction) => { if (action.id === FocusSessionAction.ID) { return new FocusSessionActionItem(action, this.debugService, this.themeService, contextViewService); } return null; } }); this.updateScheduler = new RunOnceScheduler(() => { const state = this.debugService.state; if (state === State.Inactive || state === State.Initializing || this.configurationService.getValue<IDebugConfiguration>('debug').hideActionBar || this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'float') { return this.hide(); } const actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService); if (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) { this.actionBar.clear(); this.actionBar.push(actions, { icon: true, label: false }); this.activeActions = actions; } this.show(); }, 20); this.updateStyles(); this.toUnbind.push(this.actionBar); this.registerListeners(); this.hide(); this.isBuilt = false; } private registerListeners(): void { this.toUnbind.push(this.debugService.onDidChangeState(() => this.updateScheduler.schedule())); this.toUnbind.push(this.debugService.getViewModel().onDidFocusSession(() => this.updateScheduler.schedule())); this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.onDidConfigurationChange(e))); this.toUnbind.push(this.actionBar.actionRunner.onDidRun((e: IRunEvent) => { // check for error if (e.error && !errors.isPromiseCanceledError(e.error)) { this.notificationService.error(e.error); } // log in telemetry if (this.telemetryService) { /* __GDPR__ "workbenchActionExecuted" : { "id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "from": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('workbenchActionExecuted', { id: e.action.id, from: 'debugActionsWidget' }); } })); $(window).on(dom.EventType.RESIZE, () => this.setXCoordinate(), this.toUnbind); this.dragArea.on(dom.EventType.MOUSE_UP, (event: MouseEvent) => { const mouseClickEvent = new StandardMouseEvent(event); if (mouseClickEvent.detail === 2) { // double click on debug bar centers it again #8250 const widgetWidth = this.$el.getHTMLElement().clientWidth; this.setXCoordinate(0.5 * window.innerWidth - 0.5 * widgetWidth); this.storePosition(); } }); this.dragArea.on(dom.EventType.MOUSE_DOWN, (event: MouseEvent) => { const $window = $(window); this.dragArea.addClass('dragged'); $window.on('mousemove', (e: MouseEvent) => { const mouseMoveEvent = new StandardMouseEvent(e); // Prevent default to stop editor selecting text #8524 mouseMoveEvent.preventDefault(); // Reduce x by width of drag handle to reduce jarring #16604 this.setXCoordinate(mouseMoveEvent.posx - 14); }).once('mouseup', (e: MouseEvent) => { this.storePosition(); this.dragArea.removeClass('dragged'); $window.off('mousemove'); }); }); this.toUnbind.push(this.partService.onTitleBarVisibilityChange(() => this.positionDebugWidget())); this.toUnbind.push(browser.onDidChangeZoomLevel(() => this.positionDebugWidget())); } private storePosition(): void { const position = parseFloat(this.$el.getComputedStyle().left) / window.innerWidth; this.storageService.store(DEBUG_ACTIONS_WIDGET_POSITION_KEY, position, StorageScope.WORKSPACE); } protected updateStyles(): void { super.updateStyles(); if (this.$el) { this.$el.style('background-color', this.getColor(debugToolBarBackground)); const widgetShadowColor = this.getColor(widgetShadow); this.$el.style('box-shadow', widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : null); const contrastBorderColor = this.getColor(contrastBorder); const borderColor = this.getColor(debugToolBarBorder); if (contrastBorderColor) { this.$el.style('border', `1px solid ${contrastBorderColor}`); } else { this.$el.style({ 'border': borderColor ? `solid ${borderColor}` : 'none', 'border-width': '1px 0' }); } } } private positionDebugWidget(): void { const titlebarOffset = this.partService.getTitleBarOffset(); $(this.$el).style('top', `${titlebarOffset}px`); } private setXCoordinate(x?: number): void { if (!this.isVisible) { return; } const widgetWidth = this.$el.getHTMLElement().clientWidth; if (x === undefined) { const positionPercentage = this.storageService.get(DEBUG_ACTIONS_WIDGET_POSITION_KEY, StorageScope.WORKSPACE); x = positionPercentage !== undefined ? parseFloat(positionPercentage) * window.innerWidth : (0.5 * window.innerWidth - 0.5 * widgetWidth); } x = Math.max(0, Math.min(x, window.innerWidth - widgetWidth)); // do not allow the widget to overflow on the right this.$el.style('left', `${x}px`); } private onDidConfigurationChange(event: IConfigurationChangeEvent): void { if (event.affectsConfiguration('debug.hideActionBar') || event.affectsConfiguration('debug.toolbar')) { this.updateScheduler.schedule(); } } private show(): void { if (this.isVisible) { return; } if (!this.isBuilt) { this.isBuilt = true; this.$el.build(document.getElementById(this.partService.getWorkbenchElementId())); } this.isVisible = true; this.$el.show(); this.setXCoordinate(); } private hide(): void { this.isVisible = false; this.$el.hide(); } public static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] { if (allActions.length === 0) { allActions.push(new ContinueAction(ContinueAction.ID, ContinueAction.LABEL, debugService, keybindingService)); allActions.push(new PauseAction(PauseAction.ID, PauseAction.LABEL, debugService, keybindingService)); allActions.push(new StopAction(StopAction.ID, StopAction.LABEL, debugService, keybindingService)); allActions.push(new DisconnectAction(DisconnectAction.ID, DisconnectAction.LABEL, debugService, keybindingService)); allActions.push(new StepOverAction(StepOverAction.ID, StepOverAction.LABEL, debugService, keybindingService)); allActions.push(new StepIntoAction(StepIntoAction.ID, StepIntoAction.LABEL, debugService, keybindingService)); allActions.push(new StepOutAction(StepOutAction.ID, StepOutAction.LABEL, debugService, keybindingService)); allActions.push(instantiationService.createInstance(RestartAction, RestartAction.ID, RestartAction.LABEL)); allActions.push(new StepBackAction(StepBackAction.ID, StepBackAction.LABEL, debugService, keybindingService)); allActions.push(new ReverseContinueAction(ReverseContinueAction.ID, ReverseContinueAction.LABEL, debugService, keybindingService)); allActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL)); allActions.forEach(a => { toUnbind.push(a); }); } const state = debugService.state; const session = debugService.getViewModel().focusedSession; const attached = session && session.configuration.request === 'attach' && session.configuration.type && !strings.equalsIgnoreCase(session.configuration.type, 'extensionHost'); return allActions.filter(a => { if (a.id === ContinueAction.ID) { return state !== State.Running; } if (a.id === PauseAction.ID) { return state === State.Running; } if (a.id === StepBackAction.ID) { return session && session.raw.capabilities.supportsStepBack; } if (a.id === ReverseContinueAction.ID) { return session && session.raw.capabilities.supportsStepBack; } if (a.id === DisconnectAction.ID) { return attached; } if (a.id === StopAction.ID) { return !attached; } if (a.id === FocusSessionAction.ID) { return debugService.getViewModel().isMultiSessionView(); } return true; }).sort((first, second) => first.weight - second.weight); } public dispose(): void { super.dispose(); if (this.$el) { this.$el.destroy(); delete this.$el; } } }
src/vs/workbench/parts/debug/browser/debugActionsWidget.ts
1
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.9983475208282471, 0.0647960677742958, 0.00016391952522099018, 0.00017245214257854968, 0.24512137472629547 ]
{ "id": 0, "code_window": [ "\t\t\t\t|| this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'float') {\n", "\t\t\t\treturn this.hide();\n", "\t\t\t}\n", "\n", "\t\t\tconst actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService);\n", "\t\t\tif (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) {\n", "\t\t\t\tthis.actionBar.clear();\n", "\t\t\t\tthis.actionBar.push(actions, { icon: true, label: false });\n", "\t\t\t\tthis.activeActions = actions;\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, false, this.debugService, this.keybindingService, this.instantiationService);\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.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. *--------------------------------------------------------------------------------------------*/ /* Activity Bar */ .monaco-workbench > .activitybar .monaco-action-bar .action-label.debug { -webkit-mask: url('debug-dark.svg') no-repeat 50% 50%; -webkit-mask-size: 28px; } .monaco-editor .debug-top-stack-frame-line, .monaco-editor .debug-top-stack-frame-exception-line { background: rgba(255, 255, 102, 0.45); } .monaco-editor .debug-top-stack-frame-range { background: rgba(255, 255, 102, 0.6); } .monaco-editor .debug-top-stack-frame-column::before { background: url('current-arrow.svg') center center no-repeat; } .monaco-editor .debug-focused-stack-frame-line { background: rgba(206, 231, 206, 0.45); } .monaco-editor .debug-focused-stack-frame-range { background: rgba(206, 231, 206, 1); } .debug-breakpoint-hint { background: url('breakpoint-hint.svg') center center no-repeat; } .debug-breakpoint-disabled, .monaco-editor .debug-breakpoint-column.debug-breakpoint-disabled-column::before { background: url('breakpoint-disabled.svg') center center no-repeat; } .debug-breakpoint-unverified, .monaco-editor .debug-breakpoint-column.debug-breakpoint-unverified-column::before { background: url('breakpoint-unverified.svg') center center no-repeat; } .monaco-editor .debug-top-stack-frame { background: url('current-arrow.svg') center center no-repeat; } .monaco-editor .debug-focused-stack-frame { background: url('stackframe-arrow.svg') center center no-repeat; } .debug-breakpoint, .monaco-editor .debug-breakpoint-column.debug-breakpoint-column::before { background: url('breakpoint.svg') center center no-repeat; } .monaco-editor .debug-breakpoint-column::before, .monaco-editor .debug-top-stack-frame-column::before { content: " "; width: 1.3em; height: 1.3em; display: inline-block; vertical-align: text-bottom; margin-right: 2px; margin-left: 2px; } .debug-function-breakpoint { background: url('breakpoint-function.svg') center center no-repeat; } .debug-function-breakpoint-unverified { background: url('breakpoint-function-unverified.svg') center center no-repeat; } .debug-function-breakpoint-disabled { background: url('breakpoint-function-disabled.svg') center center no-repeat; } .debug-breakpoint-conditional, .monaco-editor .debug-breakpoint-column.debug-breakpoint-conditional-column::before { background: url('breakpoint-conditional.svg') center center no-repeat; } .debug-breakpoint-log, .monaco-editor .debug-breakpoint-column.debug-breakpoint-log-column::before { background: url('breakpoint-log.svg') center center no-repeat; } .debug-breakpoint-log-disabled { background: url('breakpoint-log-disabled.svg') center center no-repeat; } .debug-breakpoint-log-unverified { background: url('breakpoint-log-unverified.svg') center center no-repeat; } .debug-breakpoint-unsupported, .monaco-editor .debug-breakpoint-column.debug-breakpoint-unsupported-column::before { background: url('breakpoint-unsupported.svg') center center no-repeat; } .monaco-editor .debug-top-stack-frame.debug-breakpoint, .monaco-editor .debug-top-stack-frame.debug-breakpoint-conditional, .monaco-editor .debug-top-stack-frame.debug-breakpoint-log, .monaco-editor .debug-breakpoint-column.debug-breakpoint-column.debug-top-stack-frame-column::before { background: url('current-and-breakpoint.svg') center center no-repeat; } .monaco-editor .debug-focused-stack-frame.debug-breakpoint, .monaco-editor .debug-focused-stack-frame.debug-breakpoint-conditional, .monaco-editor .debug-focused-stack-frame.debug-breakpoint-log { background: url('stackframe-and-breakpoint.svg') center center no-repeat; } /* Error editor */ .debug-error-editor:focus { outline: none !important; } .debug-error-editor { padding: 5px 0 0 10px; box-sizing: border-box; } /* Debug status */ /* A very precise css rule to overwrite the display set in statusbar.css */ .monaco-workbench > .part.statusbar > .statusbar-item > .debug-statusbar-item > a { display: flex; padding: 0 5px 0 5px; } .monaco-workbench .part.statusbar .debug-statusbar-item.hidden { display: none; } .monaco-workbench .part.statusbar .debug-statusbar-item .icon { -webkit-mask: url('start.svg') no-repeat 50% 50%; -webkit-mask-size: 16px; display: inline-block; padding-right: 2px; width: 16px; } /* Expressions */ .monaco-workbench .monaco-tree-row .expression { overflow: hidden; text-overflow: ellipsis; font-family: Monaco, Menlo, Consolas, "Droid Sans Mono", "Inconsolata", "Courier New", monospace, "Droid Sans Fallback"; } .monaco-workbench.mac .monaco-tree-row .expression { font-size: 11px; } .monaco-workbench.windows .monaco-tree-row .expression, .monaco-workbench.linux .monaco-tree-row .expression { font-size: 13px; } .monaco-workbench .monaco-tree-row .expression .value { margin-left: 6px; } .monaco-workbench .monaco-tree-row:not(.selected) .expression .name { color: #9B46B0; } .monaco-workbench .monaco-tree-row:not(.selected) .expression .name.virtual { opacity: 0.5; } .monaco-workbench > .monaco-tree-row:not(.selected) .expression .value { color: rgba(108, 108, 108, 0.8); } .monaco-workbench .monaco-tree-row .expression .unavailable { font-style: italic; } .monaco-workbench .monaco-tree-row:not(.selected) .expression .error { color: #E51400; } .monaco-workbench .monaco-tree-row:not(.selected) .expression .value.number { color: #09885A; } .monaco-workbench .monaco-tree-row:not(.selected) .expression .value.boolean { color: #0000FF; } .monaco-workbench .monaco-tree-row:not(.selected) .expression .value.string { color: #A31515; } .vs-dark .monaco-workbench > .monaco-tree-row:not(.selected) .expression .value { color: rgba(204, 204, 204, 0.6); } .vs-dark .monaco-workbench .monaco-tree-row:not(.selected) .expression .error { color: #F48771; } .vs-dark .monaco-workbench .monaco-tree-row:not(.selected) .expression .value.number { color: #B5CEA8; } .hc-black .monaco-workbench .monaco-tree-row:not(.selected) .expression .value.number { color: #89d185; } .hc-black .monaco-workbench .monaco-tree-row:not(.selected) .expression .value.boolean { color: #75bdfe; } .hc-black .monaco-workbench .monaco-tree-row:not(.selected) .expression .value.string { color: #f48771; } .vs-dark .monaco-workbench .monaco-tree-row:not(.selected) .expression .value.boolean { color: #4E94CE; } .vs-dark .monaco-workbench .monaco-tree-row:not(.selected) .expression .value.string { color: #CE9178; } .hc-black .monaco-workbench .monaco-tree-row:not(.selected) .expression .error { color: #F48771; } /* Dark theme */ .vs-dark .monaco-workbench .monaco-tree-row:not(.selected) .expression .name { color: #C586C0; } .monaco-editor.vs-dark .debug-focused-stack-frame-line { background: rgba(122, 189, 122, 0.3); } .monaco-editor.vs-dark .debug-focused-stack-frame-range { background: rgba(122, 189, 122, 0.5); } .monaco-editor.vs-dark .debug-top-stack-frame-line, .monaco-editor.vs-dark .debug-top-stack-frame-exception-line { background-color: rgba(255, 255, 0, 0.2) } .monaco-editor.vs-dark .debug-top-stack-frame-range { background-color: rgba(255, 255, 0, 0.3) } /* High Contrast Theming */ .monaco-editor.hc-black .debug-focused-stack-frame-line { background: rgba(206, 231, 206, 1); } .hc-black .monaco-workbench .monaco-tree-row:not(.selected) .expression .name { color: inherit; } .hc-black .monaco-editor .debug-top-stack-frame-line { background: rgba(255, 246, 0, 1); } .hc-black .monaco-editor .debug-remove-token-colors { color:black; }
src/vs/workbench/parts/debug/browser/media/debug.contribution.css
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.00017661810852587223, 0.00017220656445715576, 0.00016328399942722172, 0.00017200062575284392, 0.000002699493052205071 ]
{ "id": 0, "code_window": [ "\t\t\t\t|| this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'float') {\n", "\t\t\t\treturn this.hide();\n", "\t\t\t}\n", "\n", "\t\t\tconst actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService);\n", "\t\t\tif (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) {\n", "\t\t\t\tthis.actionBar.clear();\n", "\t\t\t\tthis.actionBar.push(actions, { icon: true, label: false });\n", "\t\t\t\tthis.activeActions = actions;\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, false, this.debugService, this.keybindingService, this.instantiationService);\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.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. *--------------------------------------------------------------------------------------------*/ 'use strict'; const enum Constants { MINIMUM_HEIGHT = 4 } export class ColorZone { _colorZoneBrand: void; public readonly from: number; public readonly to: number; public readonly colorId: number; constructor(from: number, to: number, colorId: number) { this.from = from | 0; this.to = to | 0; this.colorId = colorId | 0; } public static compare(a: ColorZone, b: ColorZone): number { if (a.colorId === b.colorId) { if (a.from === b.from) { return a.to - b.to; } return a.from - b.from; } return a.colorId - b.colorId; } } /** * A zone in the overview ruler */ export class OverviewRulerZone { _overviewRulerZoneBrand: void; public readonly startLineNumber: number; public readonly endLineNumber: number; public readonly color: string; private _colorZone: ColorZone; constructor( startLineNumber: number, endLineNumber: number, color: string ) { this.startLineNumber = startLineNumber; this.endLineNumber = endLineNumber; this.color = color; this._colorZone = null; } public static compare(a: OverviewRulerZone, b: OverviewRulerZone): number { if (a.color === b.color) { if (a.startLineNumber === b.startLineNumber) { return a.endLineNumber - b.endLineNumber; } return a.startLineNumber - b.startLineNumber; } return a.color < b.color ? -1 : 1; } public setColorZone(colorZone: ColorZone): void { this._colorZone = colorZone; } public getColorZones(): ColorZone { return this._colorZone; } } export class OverviewZoneManager { private _getVerticalOffsetForLine: (lineNumber: number) => number; private _zones: OverviewRulerZone[]; private _colorZonesInvalid: boolean; private _lineHeight: number; private _domWidth: number; private _domHeight: number; private _outerHeight: number; private _pixelRatio: number; private _lastAssignedId: number; private _color2Id: { [color: string]: number; }; private _id2Color: string[]; constructor(getVerticalOffsetForLine: (lineNumber: number) => number) { this._getVerticalOffsetForLine = getVerticalOffsetForLine; this._zones = []; this._colorZonesInvalid = false; this._lineHeight = 0; this._domWidth = 0; this._domHeight = 0; this._outerHeight = 0; this._pixelRatio = 1; this._lastAssignedId = 0; this._color2Id = Object.create(null); this._id2Color = []; } public getId2Color(): string[] { return this._id2Color; } public setZones(newZones: OverviewRulerZone[]): void { this._zones = newZones; this._zones.sort(OverviewRulerZone.compare); } public setLineHeight(lineHeight: number): boolean { if (this._lineHeight === lineHeight) { return false; } this._lineHeight = lineHeight; this._colorZonesInvalid = true; return true; } public setPixelRatio(pixelRatio: number): void { this._pixelRatio = pixelRatio; this._colorZonesInvalid = true; } public getDOMWidth(): number { return this._domWidth; } public getCanvasWidth(): number { return this._domWidth * this._pixelRatio; } public setDOMWidth(width: number): boolean { if (this._domWidth === width) { return false; } this._domWidth = width; this._colorZonesInvalid = true; return true; } public getDOMHeight(): number { return this._domHeight; } public getCanvasHeight(): number { return this._domHeight * this._pixelRatio; } public setDOMHeight(height: number): boolean { if (this._domHeight === height) { return false; } this._domHeight = height; this._colorZonesInvalid = true; return true; } public getOuterHeight(): number { return this._outerHeight; } public setOuterHeight(outerHeight: number): boolean { if (this._outerHeight === outerHeight) { return false; } this._outerHeight = outerHeight; this._colorZonesInvalid = true; return true; } public resolveColorZones(): ColorZone[] { const colorZonesInvalid = this._colorZonesInvalid; const lineHeight = Math.floor(this._lineHeight); // @perf const totalHeight = Math.floor(this.getCanvasHeight()); // @perf const outerHeight = Math.floor(this._outerHeight); // @perf const heightRatio = totalHeight / outerHeight; const halfMinimumHeight = Math.floor(Constants.MINIMUM_HEIGHT * this._pixelRatio / 2); let allColorZones: ColorZone[] = []; for (let i = 0, len = this._zones.length; i < len; i++) { const zone = this._zones[i]; if (!colorZonesInvalid) { const colorZone = zone.getColorZones(); if (colorZone) { allColorZones.push(colorZone); continue; } } const y1 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.startLineNumber))); const y2 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight)); let ycenter = Math.floor((y1 + y2) / 2); let halfHeight = (y2 - ycenter); if (halfHeight < halfMinimumHeight) { halfHeight = halfMinimumHeight; } if (ycenter - halfHeight < 0) { ycenter = halfHeight; } if (ycenter + halfHeight > totalHeight) { ycenter = totalHeight - halfHeight; } const color = zone.color; let colorId = this._color2Id[color]; if (!colorId) { colorId = (++this._lastAssignedId); this._color2Id[color] = colorId; this._id2Color[colorId] = color; } const colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId); zone.setColorZone(colorZone); allColorZones.push(colorZone); } this._colorZonesInvalid = false; allColorZones.sort(ColorZone.compare); return allColorZones; } }
src/vs/editor/common/view/overviewZoneManager.ts
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.00017647063941694796, 0.0001734801335260272, 0.0001686143223196268, 0.00017332924471702427, 0.0000019493936633807607 ]
{ "id": 0, "code_window": [ "\t\t\t\t|| this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'float') {\n", "\t\t\t\treturn this.hide();\n", "\t\t\t}\n", "\n", "\t\t\tconst actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService);\n", "\t\t\tif (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) {\n", "\t\t\t\tthis.actionBar.clear();\n", "\t\t\t\tthis.actionBar.push(actions, { icon: true, label: false });\n", "\t\t\t\tthis.activeActions = actions;\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, false, this.debugService, this.keybindingService, this.instantiationService);\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.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.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "yesButton": "&&Да", "cancelButton": "Отмена" }
i18n/rus/src/vs/workbench/services/message/electron-browser/messageService.i18n.json
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.00017812415899243206, 0.00017545686569064856, 0.00017278955783694983, 0.00017545686569064856, 0.0000026673005777411163 ]
{ "id": 1, "code_window": [ "\t\tthis.isVisible = false;\n", "\t\tthis.$el.hide();\n", "\t}\n", "\n", "\tpublic static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] {\n", "\t\tif (allActions.length === 0) {\n", "\t\t\tallActions.push(new ContinueAction(ContinueAction.ID, ContinueAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new PauseAction(PauseAction.ID, PauseAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new StopAction(StopAction.ID, StopAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new DisconnectAction(DisconnectAction.ID, DisconnectAction.LABEL, debugService, keybindingService));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], ignoreFocusSessionAction: boolean, debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] {\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 244 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/debugViewlet'; import * as nls from 'vs/nls'; import { Action, IAction } from 'vs/base/common/actions'; import * as DOM from 'vs/base/browser/dom'; import { TPromise } from 'vs/base/common/winjs.base'; import { IActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { PersistentViewsViewlet, ViewsViewletPanel } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IDebugService, VIEWLET_ID, State, VARIABLES_VIEW_ID, WATCH_VIEW_ID, CALLSTACK_VIEW_ID, BREAKPOINTS_VIEW_ID, IDebugConfiguration } from 'vs/workbench/parts/debug/common/debug'; import { StartAction, ToggleReplAction, ConfigureAction, AbstractDebugAction, SelectAndStartAction, FocusSessionAction } from 'vs/workbench/parts/debug/browser/debugActions'; import { StartDebugActionItem, FocusSessionActionItem } from 'vs/workbench/parts/debug/browser/debugActionItems'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IProgressService, IProgressRunner } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { ViewLocation } from 'vs/workbench/common/views'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { DebugActionsWidget } from 'vs/workbench/parts/debug/browser/debugActionsWidget'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; export class DebugViewlet extends PersistentViewsViewlet { private startDebugActionItem: StartDebugActionItem; private progressRunner: IProgressRunner; private breakpointView: ViewsViewletPanel; private panelListeners = new Map<string, IDisposable>(); private allActions: AbstractDebugAction[] = []; constructor( @IPartService partService: IPartService, @ITelemetryService telemetryService: ITelemetryService, @IProgressService private progressService: IProgressService, @IDebugService private debugService: IDebugService, @IInstantiationService instantiationService: IInstantiationService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IStorageService storageService: IStorageService, @IThemeService themeService: IThemeService, @IContextKeyService contextKeyService: IContextKeyService, @IContextMenuService contextMenuService: IContextMenuService, @IExtensionService extensionService: IExtensionService, @IConfigurationService private configurationService: IConfigurationService, @IKeybindingService private keybindingService: IKeybindingService, @IContextViewService private contextViewService: IContextViewService, ) { super(VIEWLET_ID, ViewLocation.Debug, `${VIEWLET_ID}.state`, false, partService, telemetryService, storageService, instantiationService, themeService, contextService, contextKeyService, contextMenuService, extensionService); this.progressRunner = null; this._register(this.debugService.onDidChangeState(state => this.onDebugServiceStateChange(state))); this._register(this.contextService.onDidChangeWorkbenchState(() => this.updateTitleArea())); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('debug.toolbar')) { this.updateTitleArea(); } })); } async create(parent: HTMLElement): TPromise<void> { await super.create(parent); DOM.addClass(parent, 'debug-viewlet'); } public focus(): void { super.focus(); if (this.startDebugActionItem) { this.startDebugActionItem.focus(); } } @memoize private get startAction(): StartAction { return this._register(this.instantiationService.createInstance(StartAction, StartAction.ID, StartAction.LABEL)); } @memoize private get configureAction(): ConfigureAction { return this._register(this.instantiationService.createInstance(ConfigureAction, ConfigureAction.ID, ConfigureAction.LABEL)); } @memoize private get toggleReplAction(): ToggleReplAction { return this._register(this.instantiationService.createInstance(ToggleReplAction, ToggleReplAction.ID, ToggleReplAction.LABEL)); } @memoize private get selectAndStartAction(): SelectAndStartAction { return this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', "Start Additional Session"))); } public getActions(): IAction[] { if (this.showInitialDebugActions) { return [this.startAction, this.configureAction, this.toggleReplAction]; } return DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService); } public get showInitialDebugActions(): boolean { const state = this.debugService.state; return state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'dock'; } public getSecondaryActions(): IAction[] { if (this.showInitialDebugActions) { return []; } return [this.selectAndStartAction, this.configureAction, this.toggleReplAction]; } public getActionItem(action: IAction): IActionItem { if (action.id === StartAction.ID) { this.startDebugActionItem = this.instantiationService.createInstance(StartDebugActionItem, null, action); return this.startDebugActionItem; } if (action.id === FocusSessionAction.ID) { return new FocusSessionActionItem(action, this.debugService, this.themeService, this.contextViewService); } return null; } public focusView(id: string): void { const view = this.getView(id); if (view) { view.focus(); } } private onDebugServiceStateChange(state: State): void { if (this.progressRunner) { this.progressRunner.done(); } if (state === State.Initializing) { this.progressRunner = this.progressService.show(true); } else { this.progressRunner = null; } if (this.configurationService.getValue<IDebugConfiguration>('debug').toolbar === 'dock') { this.updateTitleArea(); } } addPanels(panels: { panel: ViewsViewletPanel, size: number, index?: number }[]): void { super.addPanels(panels); for (const { panel } of panels) { // attach event listener to if (panel.id === BREAKPOINTS_VIEW_ID) { this.breakpointView = panel; this.updateBreakpointsMaxSize(); } else { this.panelListeners.set(panel.id, panel.onDidChange(() => this.updateBreakpointsMaxSize())); } } } removePanels(panels: ViewsViewletPanel[]): void { super.removePanels(panels); for (const panel of panels) { dispose(this.panelListeners.get(panel.id)); this.panelListeners.delete(panel.id); } } private updateBreakpointsMaxSize(): void { if (this.breakpointView) { // We need to update the breakpoints view since all other views are collapsed #25384 const allOtherCollapsed = this.views.every(view => !view.isExpanded() || view === this.breakpointView); this.breakpointView.maximumBodySize = allOtherCollapsed ? Number.POSITIVE_INFINITY : this.breakpointView.minimumBodySize; } } } export class FocusVariablesViewAction extends Action { static readonly ID = 'workbench.debug.action.focusVariablesView'; static LABEL = nls.localize('debugFocusVariablesView', 'Focus Variables'); constructor(id: string, label: string, @IViewletService private viewletService: IViewletService ) { super(id, label); } public run(): TPromise<any> { return this.viewletService.openViewlet(VIEWLET_ID).then((viewlet: DebugViewlet) => { viewlet.focusView(VARIABLES_VIEW_ID); }); } } export class FocusWatchViewAction extends Action { static readonly ID = 'workbench.debug.action.focusWatchView'; static LABEL = nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugFocusWatchView' }, 'Focus Watch'); constructor(id: string, label: string, @IViewletService private viewletService: IViewletService ) { super(id, label); } public run(): TPromise<any> { return this.viewletService.openViewlet(VIEWLET_ID).then((viewlet: DebugViewlet) => { viewlet.focusView(WATCH_VIEW_ID); }); } } export class FocusCallStackViewAction extends Action { static readonly ID = 'workbench.debug.action.focusCallStackView'; static LABEL = nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugFocusCallStackView' }, 'Focus CallStack'); constructor(id: string, label: string, @IViewletService private viewletService: IViewletService ) { super(id, label); } public run(): TPromise<any> { return this.viewletService.openViewlet(VIEWLET_ID).then((viewlet: DebugViewlet) => { viewlet.focusView(CALLSTACK_VIEW_ID); }); } } export class FocusBreakpointsViewAction extends Action { static readonly ID = 'workbench.debug.action.focusBreakpointsView'; static LABEL = nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugFocusBreakpointsView' }, 'Focus Breakpoints'); constructor(id: string, label: string, @IViewletService private viewletService: IViewletService ) { super(id, label); } public run(): TPromise<any> { return this.viewletService.openViewlet(VIEWLET_ID).then((viewlet: DebugViewlet) => { viewlet.focusView(BREAKPOINTS_VIEW_ID); }); } }
src/vs/workbench/parts/debug/browser/debugViewlet.ts
1
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.9993622899055481, 0.03737500309944153, 0.00016162623069249094, 0.00017114034562837332, 0.18866248428821564 ]
{ "id": 1, "code_window": [ "\t\tthis.isVisible = false;\n", "\t\tthis.$el.hide();\n", "\t}\n", "\n", "\tpublic static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] {\n", "\t\tif (allActions.length === 0) {\n", "\t\t\tallActions.push(new ContinueAction(ContinueAction.ID, ContinueAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new PauseAction(PauseAction.ID, PauseAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new StopAction(StopAction.ID, StopAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new DisconnectAction(DisconnectAction.ID, DisconnectAction.LABEL, debugService, keybindingService));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], ignoreFocusSessionAction: boolean, debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] {\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 244 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="3 3 16 16" enable-background="new 3 3 16 16"><polygon fill="#e8e8e8" points="12.597,11.042 15.4,13.845 13.844,15.4 11.042,12.598 8.239,15.4 6.683,13.845 9.485,11.042 6.683,8.239 8.238,6.683 11.042,9.486 13.845,6.683 15.4,8.239"/></svg>
src/vs/workbench/browser/parts/notifications/media/close-inverse.svg
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.00017424252291675657, 0.00017424252291675657, 0.00017424252291675657, 0.00017424252291675657, 0 ]
{ "id": 1, "code_window": [ "\t\tthis.isVisible = false;\n", "\t\tthis.$el.hide();\n", "\t}\n", "\n", "\tpublic static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] {\n", "\t\tif (allActions.length === 0) {\n", "\t\t\tallActions.push(new ContinueAction(ContinueAction.ID, ContinueAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new PauseAction(PauseAction.ID, PauseAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new StopAction(StopAction.ID, StopAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new DisconnectAction(DisconnectAction.ID, DisconnectAction.LABEL, debugService, keybindingService));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], ignoreFocusSessionAction: boolean, debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] {\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 244 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><defs><style>.icon-canvas-transparent,.icon-vs-out{fill:#f6f6f6;}.icon-canvas-transparent{opacity:0;}.icon-vs-action-red{fill:#a1260d;}</style></defs><title>stop</title><g id="canvas"><path class="icon-canvas-transparent" d="M16,0V16H0V0Z"/></g><g id="outline" style="display: none;"><path class="icon-vs-out" d="M14,2V14H2V2Z"/></g><g id="iconBg"><path class="icon-vs-action-red" d="M13,3V13H3V3Z"/></g></svg>
src/vs/workbench/parts/debug/browser/media/stop.svg
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.00017575126548763365, 0.00017575126548763365, 0.00017575126548763365, 0.00017575126548763365, 0 ]
{ "id": 1, "code_window": [ "\t\tthis.isVisible = false;\n", "\t\tthis.$el.hide();\n", "\t}\n", "\n", "\tpublic static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] {\n", "\t\tif (allActions.length === 0) {\n", "\t\t\tallActions.push(new ContinueAction(ContinueAction.ID, ContinueAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new PauseAction(PauseAction.ID, PauseAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new StopAction(StopAction.ID, StopAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new DisconnectAction(DisconnectAction.ID, DisconnectAction.LABEL, debugService, keybindingService));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], ignoreFocusSessionAction: boolean, debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] {\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 244 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "console.title": "VS Code Konsolu", "mac.terminal.script.failed": "'{0}' betiği, {1} çıkış koduyla başarısız oldu", "mac.terminal.type.not.supported": "'{0}' desteklenmiyor", "press.any.key": "Devam etmek için bir tuşa basın ...", "linux.term.failed": "'{0}', {1} çıkış koduyla başarısız oldu" }
i18n/trk/src/vs/workbench/parts/execution/electron-browser/terminalService.i18n.json
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.00017718841263558716, 0.0001750822993926704, 0.0001729761715978384, 0.0001750822993926704, 0.000002106120518874377 ]
{ "id": 2, "code_window": [ "\t\t\tallActions.push(instantiationService.createInstance(RestartAction, RestartAction.ID, RestartAction.LABEL));\n", "\t\t\tallActions.push(new StepBackAction(StepBackAction.ID, StepBackAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new ReverseContinueAction(ReverseContinueAction.ID, ReverseContinueAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL));\n", "\t\t\tallActions.forEach(a => {\n", "\t\t\t\ttoUnbind.push(a);\n", "\t\t\t});\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!ignoreFocusSessionAction) {\n", "\t\t\t\tallActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL));\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 256 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/debugActionsWidget'; import * as errors from 'vs/base/common/errors'; import * as strings from 'vs/base/common/strings'; import * as browser from 'vs/base/browser/browser'; import { $, Builder } from 'vs/base/browser/builder'; import * as dom from 'vs/base/browser/dom'; import * as arrays from 'vs/base/common/arrays'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { IAction, IRunEvent } from 'vs/base/common/actions'; import { ActionBar, ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { IDebugConfiguration, IDebugService, State } from 'vs/workbench/parts/debug/common/debug'; import { AbstractDebugAction, PauseAction, ContinueAction, StepBackAction, ReverseContinueAction, StopAction, DisconnectAction, StepOverAction, StepIntoAction, StepOutAction, RestartAction, FocusSessionAction } from 'vs/workbench/parts/debug/browser/debugActions'; import { FocusSessionActionItem } from 'vs/workbench/parts/debug/browser/debugActionItems'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { Themable } from 'vs/workbench/common/theme'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { registerColor, contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { localize } from 'vs/nls'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IDisposable } from 'vs/base/common/lifecycle'; const DEBUG_ACTIONS_WIDGET_POSITION_KEY = 'debug.actionswidgetposition'; export const debugToolBarBackground = registerColor('debugToolBar.background', { dark: '#333333', light: '#F3F3F3', hc: '#000000' }, localize('debugToolBarBackground', "Debug toolbar background color.")); export const debugToolBarBorder = registerColor('debugToolBar.border', { dark: null, light: null, hc: null }, localize('debugToolBarBorder', "Debug toolbar border color.")); export class DebugActionsWidget extends Themable implements IWorkbenchContribution { private $el: Builder; private dragArea: Builder; private actionBar: ActionBar; private allActions: AbstractDebugAction[] = []; private activeActions: AbstractDebugAction[]; private updateScheduler: RunOnceScheduler; private isVisible: boolean; private isBuilt: boolean; constructor( @INotificationService private notificationService: INotificationService, @ITelemetryService private telemetryService: ITelemetryService, @IDebugService private debugService: IDebugService, @IPartService private partService: IPartService, @IStorageService private storageService: IStorageService, @IConfigurationService private configurationService: IConfigurationService, @IThemeService themeService: IThemeService, @IKeybindingService private keybindingService: IKeybindingService, @IContextViewService contextViewService: IContextViewService, @IInstantiationService private instantiationService: IInstantiationService ) { super(themeService); this.$el = $().div().addClass('debug-actions-widget').style('top', `${partService.getTitleBarOffset()}px`); this.dragArea = $().div().addClass('drag-area'); this.$el.append(this.dragArea); const actionBarContainter = $().div().addClass('.action-bar-container'); this.$el.append(actionBarContainter); this.activeActions = []; this.actionBar = new ActionBar(actionBarContainter.getHTMLElement(), { orientation: ActionsOrientation.HORIZONTAL, actionItemProvider: (action: IAction) => { if (action.id === FocusSessionAction.ID) { return new FocusSessionActionItem(action, this.debugService, this.themeService, contextViewService); } return null; } }); this.updateScheduler = new RunOnceScheduler(() => { const state = this.debugService.state; if (state === State.Inactive || state === State.Initializing || this.configurationService.getValue<IDebugConfiguration>('debug').hideActionBar || this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'float') { return this.hide(); } const actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService); if (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) { this.actionBar.clear(); this.actionBar.push(actions, { icon: true, label: false }); this.activeActions = actions; } this.show(); }, 20); this.updateStyles(); this.toUnbind.push(this.actionBar); this.registerListeners(); this.hide(); this.isBuilt = false; } private registerListeners(): void { this.toUnbind.push(this.debugService.onDidChangeState(() => this.updateScheduler.schedule())); this.toUnbind.push(this.debugService.getViewModel().onDidFocusSession(() => this.updateScheduler.schedule())); this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.onDidConfigurationChange(e))); this.toUnbind.push(this.actionBar.actionRunner.onDidRun((e: IRunEvent) => { // check for error if (e.error && !errors.isPromiseCanceledError(e.error)) { this.notificationService.error(e.error); } // log in telemetry if (this.telemetryService) { /* __GDPR__ "workbenchActionExecuted" : { "id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "from": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('workbenchActionExecuted', { id: e.action.id, from: 'debugActionsWidget' }); } })); $(window).on(dom.EventType.RESIZE, () => this.setXCoordinate(), this.toUnbind); this.dragArea.on(dom.EventType.MOUSE_UP, (event: MouseEvent) => { const mouseClickEvent = new StandardMouseEvent(event); if (mouseClickEvent.detail === 2) { // double click on debug bar centers it again #8250 const widgetWidth = this.$el.getHTMLElement().clientWidth; this.setXCoordinate(0.5 * window.innerWidth - 0.5 * widgetWidth); this.storePosition(); } }); this.dragArea.on(dom.EventType.MOUSE_DOWN, (event: MouseEvent) => { const $window = $(window); this.dragArea.addClass('dragged'); $window.on('mousemove', (e: MouseEvent) => { const mouseMoveEvent = new StandardMouseEvent(e); // Prevent default to stop editor selecting text #8524 mouseMoveEvent.preventDefault(); // Reduce x by width of drag handle to reduce jarring #16604 this.setXCoordinate(mouseMoveEvent.posx - 14); }).once('mouseup', (e: MouseEvent) => { this.storePosition(); this.dragArea.removeClass('dragged'); $window.off('mousemove'); }); }); this.toUnbind.push(this.partService.onTitleBarVisibilityChange(() => this.positionDebugWidget())); this.toUnbind.push(browser.onDidChangeZoomLevel(() => this.positionDebugWidget())); } private storePosition(): void { const position = parseFloat(this.$el.getComputedStyle().left) / window.innerWidth; this.storageService.store(DEBUG_ACTIONS_WIDGET_POSITION_KEY, position, StorageScope.WORKSPACE); } protected updateStyles(): void { super.updateStyles(); if (this.$el) { this.$el.style('background-color', this.getColor(debugToolBarBackground)); const widgetShadowColor = this.getColor(widgetShadow); this.$el.style('box-shadow', widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : null); const contrastBorderColor = this.getColor(contrastBorder); const borderColor = this.getColor(debugToolBarBorder); if (contrastBorderColor) { this.$el.style('border', `1px solid ${contrastBorderColor}`); } else { this.$el.style({ 'border': borderColor ? `solid ${borderColor}` : 'none', 'border-width': '1px 0' }); } } } private positionDebugWidget(): void { const titlebarOffset = this.partService.getTitleBarOffset(); $(this.$el).style('top', `${titlebarOffset}px`); } private setXCoordinate(x?: number): void { if (!this.isVisible) { return; } const widgetWidth = this.$el.getHTMLElement().clientWidth; if (x === undefined) { const positionPercentage = this.storageService.get(DEBUG_ACTIONS_WIDGET_POSITION_KEY, StorageScope.WORKSPACE); x = positionPercentage !== undefined ? parseFloat(positionPercentage) * window.innerWidth : (0.5 * window.innerWidth - 0.5 * widgetWidth); } x = Math.max(0, Math.min(x, window.innerWidth - widgetWidth)); // do not allow the widget to overflow on the right this.$el.style('left', `${x}px`); } private onDidConfigurationChange(event: IConfigurationChangeEvent): void { if (event.affectsConfiguration('debug.hideActionBar') || event.affectsConfiguration('debug.toolbar')) { this.updateScheduler.schedule(); } } private show(): void { if (this.isVisible) { return; } if (!this.isBuilt) { this.isBuilt = true; this.$el.build(document.getElementById(this.partService.getWorkbenchElementId())); } this.isVisible = true; this.$el.show(); this.setXCoordinate(); } private hide(): void { this.isVisible = false; this.$el.hide(); } public static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] { if (allActions.length === 0) { allActions.push(new ContinueAction(ContinueAction.ID, ContinueAction.LABEL, debugService, keybindingService)); allActions.push(new PauseAction(PauseAction.ID, PauseAction.LABEL, debugService, keybindingService)); allActions.push(new StopAction(StopAction.ID, StopAction.LABEL, debugService, keybindingService)); allActions.push(new DisconnectAction(DisconnectAction.ID, DisconnectAction.LABEL, debugService, keybindingService)); allActions.push(new StepOverAction(StepOverAction.ID, StepOverAction.LABEL, debugService, keybindingService)); allActions.push(new StepIntoAction(StepIntoAction.ID, StepIntoAction.LABEL, debugService, keybindingService)); allActions.push(new StepOutAction(StepOutAction.ID, StepOutAction.LABEL, debugService, keybindingService)); allActions.push(instantiationService.createInstance(RestartAction, RestartAction.ID, RestartAction.LABEL)); allActions.push(new StepBackAction(StepBackAction.ID, StepBackAction.LABEL, debugService, keybindingService)); allActions.push(new ReverseContinueAction(ReverseContinueAction.ID, ReverseContinueAction.LABEL, debugService, keybindingService)); allActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL)); allActions.forEach(a => { toUnbind.push(a); }); } const state = debugService.state; const session = debugService.getViewModel().focusedSession; const attached = session && session.configuration.request === 'attach' && session.configuration.type && !strings.equalsIgnoreCase(session.configuration.type, 'extensionHost'); return allActions.filter(a => { if (a.id === ContinueAction.ID) { return state !== State.Running; } if (a.id === PauseAction.ID) { return state === State.Running; } if (a.id === StepBackAction.ID) { return session && session.raw.capabilities.supportsStepBack; } if (a.id === ReverseContinueAction.ID) { return session && session.raw.capabilities.supportsStepBack; } if (a.id === DisconnectAction.ID) { return attached; } if (a.id === StopAction.ID) { return !attached; } if (a.id === FocusSessionAction.ID) { return debugService.getViewModel().isMultiSessionView(); } return true; }).sort((first, second) => first.weight - second.weight); } public dispose(): void { super.dispose(); if (this.$el) { this.$el.destroy(); delete this.$el; } } }
src/vs/workbench/parts/debug/browser/debugActionsWidget.ts
1
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.9927901029586792, 0.032432787120342255, 0.00016242588753812015, 0.00016974723257590085, 0.17533747851848602 ]
{ "id": 2, "code_window": [ "\t\t\tallActions.push(instantiationService.createInstance(RestartAction, RestartAction.ID, RestartAction.LABEL));\n", "\t\t\tallActions.push(new StepBackAction(StepBackAction.ID, StepBackAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new ReverseContinueAction(ReverseContinueAction.ID, ReverseContinueAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL));\n", "\t\t\tallActions.forEach(a => {\n", "\t\t\t\ttoUnbind.push(a);\n", "\t\t\t});\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!ignoreFocusSessionAction) {\n", "\t\t\t\tallActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL));\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 256 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "invalid.path.0": "Chaîne attendue dans 'contributes.{0}.path'. Valeur fournie : {1}", "invalid.language.0": "Si le langage est omis, la valeur de 'contributes.{0}.path' doit être un fichier `.code-snippets`. Valeur fournie : {1}", "invalid.language": "Langage inconnu dans 'contributes.{0}.language'. Valeur fournie : {1}", "invalid.path.1": "'contributes.{0}.path' ({1}) est censé être inclus dans le dossier ({2}) de l'extension. Cela risque de rendre l'extension non portable.", "vscode.extension.contributes.snippets": "Ajoute des extraits de code.", "vscode.extension.contributes.snippets-language": "Identificateur de langage pour lequel cet extrait de code est ajouté.", "vscode.extension.contributes.snippets-path": "Chemin du fichier d'extraits de code. Le chemin est relatif au dossier d'extensions et commence généralement par './snippets/'.", "badVariableUse": "Un ou plusieurs extraits de l’extension '{0}' confondent très probablement des snippet-variables et des snippet-placeholders (Voir https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax pour plus de détails)", "badFile": "Le fichier d’extrait \"{0}\" n’a pas pu être lu.", "detail.snippet": "{0} ({1})", "snippetSuggest.longLabel": "{0}, {1}" }
i18n/fra/src/vs/workbench/parts/snippets/electron-browser/snippetsService.i18n.json
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.00017666377243585885, 0.00017162504082079977, 0.00016774068353697658, 0.00017047063738573343, 0.000003733170842679101 ]
{ "id": 2, "code_window": [ "\t\t\tallActions.push(instantiationService.createInstance(RestartAction, RestartAction.ID, RestartAction.LABEL));\n", "\t\t\tallActions.push(new StepBackAction(StepBackAction.ID, StepBackAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new ReverseContinueAction(ReverseContinueAction.ID, ReverseContinueAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL));\n", "\t\t\tallActions.forEach(a => {\n", "\t\t\t\ttoUnbind.push(a);\n", "\t\t\t});\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!ignoreFocusSessionAction) {\n", "\t\t\t\tallActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL));\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 256 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "cssserver.name": "Server di linguaggio CSS", "folding.start": "Inizio di una regione riducibile", "folding.end": "Fine di una regione riducibile" }
i18n/ita/extensions/css-language-features/client/out/cssMain.i18n.json
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.00017619290156289935, 0.00017353429575450718, 0.00017087570449803025, 0.00017353429575450718, 0.000002658598532434553 ]
{ "id": 2, "code_window": [ "\t\t\tallActions.push(instantiationService.createInstance(RestartAction, RestartAction.ID, RestartAction.LABEL));\n", "\t\t\tallActions.push(new StepBackAction(StepBackAction.ID, StepBackAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(new ReverseContinueAction(ReverseContinueAction.ID, ReverseContinueAction.LABEL, debugService, keybindingService));\n", "\t\t\tallActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL));\n", "\t\t\tallActions.forEach(a => {\n", "\t\t\t\ttoUnbind.push(a);\n", "\t\t\t});\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!ignoreFocusSessionAction) {\n", "\t\t\t\tallActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL));\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 256 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/explorerviewlet'; import { localize } from 'vs/nls'; import { IActionRunner } from 'vs/base/common/actions'; import { TPromise } from 'vs/base/common/winjs.base'; import * as DOM from 'vs/base/browser/dom'; import { VIEWLET_ID, ExplorerViewletVisibleContext, IFilesConfiguration, OpenEditorsVisibleContext, OpenEditorsVisibleCondition, IExplorerViewlet } from 'vs/workbench/parts/files/common/files'; import { PersistentViewsViewlet, IViewletViewOptions, ViewsViewletPanel } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { ActionRunner, FileViewletState } from 'vs/workbench/parts/files/electron-browser/views/explorerViewer'; import { ExplorerView, IExplorerViewOptions } from 'vs/workbench/parts/files/electron-browser/views/explorerView'; import { EmptyView } from 'vs/workbench/parts/files/electron-browser/views/emptyView'; import { OpenEditorsView } from 'vs/workbench/parts/files/electron-browser/views/openEditorsView'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { EditorInput, EditorOptions } from 'vs/workbench/common/editor'; import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor'; import { IWorkbenchEditorService, DelegatingWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { ViewsRegistry, ViewLocation, IViewDescriptor } from 'vs/workbench/common/views'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { Disposable } from 'vs/base/common/lifecycle'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { IPartService } from 'vs/workbench/services/part/common/partService'; export class ExplorerViewletViewsContribution extends Disposable implements IWorkbenchContribution { private openEditorsVisibleContextKey: IContextKey<boolean>; constructor( @IWorkspaceContextService private workspaceContextService: IWorkspaceContextService, @IConfigurationService private configurationService: IConfigurationService, @IContextKeyService contextKeyService: IContextKeyService ) { super(); this.registerViews(); this.openEditorsVisibleContextKey = OpenEditorsVisibleContext.bindTo(contextKeyService); this.updateOpenEditorsVisibility(); this._register(workspaceContextService.onDidChangeWorkbenchState(() => this.registerViews())); this._register(workspaceContextService.onDidChangeWorkspaceFolders(() => this.registerViews())); this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e))); } private registerViews(): void { const viewDescriptors = ViewsRegistry.getViews(ViewLocation.Explorer); let viewDescriptorsToRegister = []; let viewDescriptorsToDeregister: string[] = []; const openEditorsViewDescriptor = this.createOpenEditorsViewDescriptor(); const openEditorsViewDescriptorExists = viewDescriptors.some(v => v.id === openEditorsViewDescriptor.id); const explorerViewDescriptor = this.createExplorerViewDescriptor(); const explorerViewDescriptorExists = viewDescriptors.some(v => v.id === explorerViewDescriptor.id); const emptyViewDescriptor = this.createEmptyViewDescriptor(); const emptyViewDescriptorExists = viewDescriptors.some(v => v.id === emptyViewDescriptor.id); if (!openEditorsViewDescriptorExists) { viewDescriptorsToRegister.push(openEditorsViewDescriptor); } if (this.workspaceContextService.getWorkbenchState() === WorkbenchState.EMPTY || this.workspaceContextService.getWorkspace().folders.length === 0) { if (explorerViewDescriptorExists) { viewDescriptorsToDeregister.push(explorerViewDescriptor.id); } if (!emptyViewDescriptorExists) { viewDescriptorsToRegister.push(emptyViewDescriptor); } } else { if (emptyViewDescriptorExists) { viewDescriptorsToDeregister.push(emptyViewDescriptor.id); } if (!explorerViewDescriptorExists) { viewDescriptorsToRegister.push(explorerViewDescriptor); } } if (viewDescriptorsToRegister.length) { ViewsRegistry.registerViews(viewDescriptorsToRegister); } if (viewDescriptorsToDeregister.length) { ViewsRegistry.deregisterViews(viewDescriptorsToDeregister, ViewLocation.Explorer); } } private createOpenEditorsViewDescriptor(): IViewDescriptor { return { id: OpenEditorsView.ID, name: OpenEditorsView.NAME, location: ViewLocation.Explorer, ctor: OpenEditorsView, order: 0, when: OpenEditorsVisibleCondition, canToggleVisibility: true }; } private createEmptyViewDescriptor(): IViewDescriptor { return { id: EmptyView.ID, name: EmptyView.NAME, location: ViewLocation.Explorer, ctor: EmptyView, order: 1, canToggleVisibility: false }; } private createExplorerViewDescriptor(): IViewDescriptor { return { id: ExplorerView.ID, name: localize('folders', "Folders"), location: ViewLocation.Explorer, ctor: ExplorerView, order: 1, canToggleVisibility: false }; } private onConfigurationUpdated(e: IConfigurationChangeEvent): void { if (e.affectsConfiguration('explorer.openEditors.visible')) { this.updateOpenEditorsVisibility(); } } private updateOpenEditorsVisibility(): void { this.openEditorsVisibleContextKey.set(this.workspaceContextService.getWorkbenchState() === WorkbenchState.EMPTY || this.configurationService.getValue('explorer.openEditors.visible') !== 0); } } export class ExplorerViewlet extends PersistentViewsViewlet implements IExplorerViewlet { private static readonly EXPLORER_VIEWS_STATE = 'workbench.explorer.views.state'; private viewletState: FileViewletState; private viewletVisibleContextKey: IContextKey<boolean>; constructor( @IPartService partService: IPartService, @ITelemetryService telemetryService: ITelemetryService, @IWorkspaceContextService protected contextService: IWorkspaceContextService, @IStorageService protected storageService: IStorageService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IConfigurationService private configurationService: IConfigurationService, @IInstantiationService protected instantiationService: IInstantiationService, @IContextKeyService contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IContextMenuService contextMenuService: IContextMenuService, @IExtensionService extensionService: IExtensionService ) { super(VIEWLET_ID, ViewLocation.Explorer, ExplorerViewlet.EXPLORER_VIEWS_STATE, true, partService, telemetryService, storageService, instantiationService, themeService, contextService, contextKeyService, contextMenuService, extensionService); this.viewletState = new FileViewletState(); this.viewletVisibleContextKey = ExplorerViewletVisibleContext.bindTo(contextKeyService); this._register(this.contextService.onDidChangeWorkspaceName(e => this.updateTitleArea())); } async create(parent: HTMLElement): TPromise<void> { await super.create(parent); DOM.addClass(parent, 'explorer-viewlet'); } private isOpenEditorsVisible(): boolean { return this.contextService.getWorkbenchState() === WorkbenchState.EMPTY || this.configurationService.getValue('explorer.openEditors.visible') !== 0; } protected createView(viewDescriptor: IViewDescriptor, options: IViewletViewOptions): ViewsViewletPanel { if (viewDescriptor.id === ExplorerView.ID) { // Create a delegating editor service for the explorer to be able to delay the refresh in the opened // editors view above. This is a workaround for being able to double click on a file to make it pinned // without causing the animation in the opened editors view to kick in and change scroll position. // We try to be smart and only use the delay if we recognize that the user action is likely to cause // a new entry in the opened editors view. const delegatingEditorService = this.instantiationService.createInstance(DelegatingWorkbenchEditorService); delegatingEditorService.setEditorOpenHandler((input: EditorInput, options?: EditorOptions, arg3?: any) => { let openEditorsView = this.getOpenEditorsView(); if (openEditorsView) { let delay = 0; const config = this.configurationService.getValue<IFilesConfiguration>(); // No need to delay if preview is disabled const delayEditorOpeningInOpenedEditors = !!config.workbench.editor.enablePreview; if (delayEditorOpeningInOpenedEditors && (arg3 === false /* not side by side */ || typeof arg3 !== 'number' /* no explicit position */)) { const activeGroup = this.editorGroupService.getStacksModel().activeGroup; if (!activeGroup || !activeGroup.previewEditor) { delay = 250; // a new editor entry is likely because there is either no group or no preview in group } } openEditorsView.setStructuralRefreshDelay(delay); } const onSuccessOrError = (editor?: BaseEditor) => { let openEditorsView = this.getOpenEditorsView(); if (openEditorsView) { openEditorsView.setStructuralRefreshDelay(0); } return editor; }; return this.editorService.openEditor(input, options, arg3).then(onSuccessOrError, onSuccessOrError); }); const explorerInstantiator = this.instantiationService.createChild(new ServiceCollection([IWorkbenchEditorService, delegatingEditorService])); return explorerInstantiator.createInstance(ExplorerView, <IExplorerViewOptions>{ ...options, viewletState: this.viewletState }); } return super.createView(viewDescriptor, options); } public getExplorerView(): ExplorerView { return <ExplorerView>this.getView(ExplorerView.ID); } public getOpenEditorsView(): OpenEditorsView { return <OpenEditorsView>this.getView(OpenEditorsView.ID); } public getEmptyView(): EmptyView { return <EmptyView>this.getView(EmptyView.ID); } public setVisible(visible: boolean): TPromise<void> { this.viewletVisibleContextKey.set(visible); return super.setVisible(visible); } public getActionRunner(): IActionRunner { if (!this.actionRunner) { this.actionRunner = new ActionRunner(this.viewletState); } return this.actionRunner; } public getViewletState(): FileViewletState { return this.viewletState; } focus(): void { const explorerView = this.getExplorerView(); if (explorerView && explorerView.isExpanded()) { explorerView.focus(); } else { super.focus(); } } protected loadViewsStates(): void { super.loadViewsStates(); // Remove the open editors view state if it is removed globally if (!this.isOpenEditorsVisible()) { this.viewsStates.delete(OpenEditorsView.ID); } } }
src/vs/workbench/parts/files/electron-browser/explorerViewlet.ts
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.00041053767199628055, 0.00018179444305133075, 0.00016098361811600626, 0.0001703829038888216, 0.00004722572339233011 ]
{ "id": 3, "code_window": [ "\t\tif (this.showInitialDebugActions) {\n", "\t\t\treturn [this.startAction, this.configureAction, this.toggleReplAction];\n", "\t\t}\n", "\n", "\t\treturn DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService);\n", "\t}\n", "\n", "\tpublic get showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n", "\t\treturn state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'dock';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DebugActionsWidget.getActions(this.allActions, this.toUnbind, true, this.debugService, this.keybindingService, this.instantiationService);\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 109 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/debugViewlet'; import * as nls from 'vs/nls'; import { Action, IAction } from 'vs/base/common/actions'; import * as DOM from 'vs/base/browser/dom'; import { TPromise } from 'vs/base/common/winjs.base'; import { IActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { PersistentViewsViewlet, ViewsViewletPanel } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IDebugService, VIEWLET_ID, State, VARIABLES_VIEW_ID, WATCH_VIEW_ID, CALLSTACK_VIEW_ID, BREAKPOINTS_VIEW_ID, IDebugConfiguration } from 'vs/workbench/parts/debug/common/debug'; import { StartAction, ToggleReplAction, ConfigureAction, AbstractDebugAction, SelectAndStartAction, FocusSessionAction } from 'vs/workbench/parts/debug/browser/debugActions'; import { StartDebugActionItem, FocusSessionActionItem } from 'vs/workbench/parts/debug/browser/debugActionItems'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IProgressService, IProgressRunner } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { ViewLocation } from 'vs/workbench/common/views'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { DebugActionsWidget } from 'vs/workbench/parts/debug/browser/debugActionsWidget'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; export class DebugViewlet extends PersistentViewsViewlet { private startDebugActionItem: StartDebugActionItem; private progressRunner: IProgressRunner; private breakpointView: ViewsViewletPanel; private panelListeners = new Map<string, IDisposable>(); private allActions: AbstractDebugAction[] = []; constructor( @IPartService partService: IPartService, @ITelemetryService telemetryService: ITelemetryService, @IProgressService private progressService: IProgressService, @IDebugService private debugService: IDebugService, @IInstantiationService instantiationService: IInstantiationService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IStorageService storageService: IStorageService, @IThemeService themeService: IThemeService, @IContextKeyService contextKeyService: IContextKeyService, @IContextMenuService contextMenuService: IContextMenuService, @IExtensionService extensionService: IExtensionService, @IConfigurationService private configurationService: IConfigurationService, @IKeybindingService private keybindingService: IKeybindingService, @IContextViewService private contextViewService: IContextViewService, ) { super(VIEWLET_ID, ViewLocation.Debug, `${VIEWLET_ID}.state`, false, partService, telemetryService, storageService, instantiationService, themeService, contextService, contextKeyService, contextMenuService, extensionService); this.progressRunner = null; this._register(this.debugService.onDidChangeState(state => this.onDebugServiceStateChange(state))); this._register(this.contextService.onDidChangeWorkbenchState(() => this.updateTitleArea())); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('debug.toolbar')) { this.updateTitleArea(); } })); } async create(parent: HTMLElement): TPromise<void> { await super.create(parent); DOM.addClass(parent, 'debug-viewlet'); } public focus(): void { super.focus(); if (this.startDebugActionItem) { this.startDebugActionItem.focus(); } } @memoize private get startAction(): StartAction { return this._register(this.instantiationService.createInstance(StartAction, StartAction.ID, StartAction.LABEL)); } @memoize private get configureAction(): ConfigureAction { return this._register(this.instantiationService.createInstance(ConfigureAction, ConfigureAction.ID, ConfigureAction.LABEL)); } @memoize private get toggleReplAction(): ToggleReplAction { return this._register(this.instantiationService.createInstance(ToggleReplAction, ToggleReplAction.ID, ToggleReplAction.LABEL)); } @memoize private get selectAndStartAction(): SelectAndStartAction { return this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', "Start Additional Session"))); } public getActions(): IAction[] { if (this.showInitialDebugActions) { return [this.startAction, this.configureAction, this.toggleReplAction]; } return DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService); } public get showInitialDebugActions(): boolean { const state = this.debugService.state; return state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'dock'; } public getSecondaryActions(): IAction[] { if (this.showInitialDebugActions) { return []; } return [this.selectAndStartAction, this.configureAction, this.toggleReplAction]; } public getActionItem(action: IAction): IActionItem { if (action.id === StartAction.ID) { this.startDebugActionItem = this.instantiationService.createInstance(StartDebugActionItem, null, action); return this.startDebugActionItem; } if (action.id === FocusSessionAction.ID) { return new FocusSessionActionItem(action, this.debugService, this.themeService, this.contextViewService); } return null; } public focusView(id: string): void { const view = this.getView(id); if (view) { view.focus(); } } private onDebugServiceStateChange(state: State): void { if (this.progressRunner) { this.progressRunner.done(); } if (state === State.Initializing) { this.progressRunner = this.progressService.show(true); } else { this.progressRunner = null; } if (this.configurationService.getValue<IDebugConfiguration>('debug').toolbar === 'dock') { this.updateTitleArea(); } } addPanels(panels: { panel: ViewsViewletPanel, size: number, index?: number }[]): void { super.addPanels(panels); for (const { panel } of panels) { // attach event listener to if (panel.id === BREAKPOINTS_VIEW_ID) { this.breakpointView = panel; this.updateBreakpointsMaxSize(); } else { this.panelListeners.set(panel.id, panel.onDidChange(() => this.updateBreakpointsMaxSize())); } } } removePanels(panels: ViewsViewletPanel[]): void { super.removePanels(panels); for (const panel of panels) { dispose(this.panelListeners.get(panel.id)); this.panelListeners.delete(panel.id); } } private updateBreakpointsMaxSize(): void { if (this.breakpointView) { // We need to update the breakpoints view since all other views are collapsed #25384 const allOtherCollapsed = this.views.every(view => !view.isExpanded() || view === this.breakpointView); this.breakpointView.maximumBodySize = allOtherCollapsed ? Number.POSITIVE_INFINITY : this.breakpointView.minimumBodySize; } } } export class FocusVariablesViewAction extends Action { static readonly ID = 'workbench.debug.action.focusVariablesView'; static LABEL = nls.localize('debugFocusVariablesView', 'Focus Variables'); constructor(id: string, label: string, @IViewletService private viewletService: IViewletService ) { super(id, label); } public run(): TPromise<any> { return this.viewletService.openViewlet(VIEWLET_ID).then((viewlet: DebugViewlet) => { viewlet.focusView(VARIABLES_VIEW_ID); }); } } export class FocusWatchViewAction extends Action { static readonly ID = 'workbench.debug.action.focusWatchView'; static LABEL = nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugFocusWatchView' }, 'Focus Watch'); constructor(id: string, label: string, @IViewletService private viewletService: IViewletService ) { super(id, label); } public run(): TPromise<any> { return this.viewletService.openViewlet(VIEWLET_ID).then((viewlet: DebugViewlet) => { viewlet.focusView(WATCH_VIEW_ID); }); } } export class FocusCallStackViewAction extends Action { static readonly ID = 'workbench.debug.action.focusCallStackView'; static LABEL = nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugFocusCallStackView' }, 'Focus CallStack'); constructor(id: string, label: string, @IViewletService private viewletService: IViewletService ) { super(id, label); } public run(): TPromise<any> { return this.viewletService.openViewlet(VIEWLET_ID).then((viewlet: DebugViewlet) => { viewlet.focusView(CALLSTACK_VIEW_ID); }); } } export class FocusBreakpointsViewAction extends Action { static readonly ID = 'workbench.debug.action.focusBreakpointsView'; static LABEL = nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugFocusBreakpointsView' }, 'Focus Breakpoints'); constructor(id: string, label: string, @IViewletService private viewletService: IViewletService ) { super(id, label); } public run(): TPromise<any> { return this.viewletService.openViewlet(VIEWLET_ID).then((viewlet: DebugViewlet) => { viewlet.focusView(BREAKPOINTS_VIEW_ID); }); } }
src/vs/workbench/parts/debug/browser/debugViewlet.ts
1
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.9981088638305664, 0.14151698350906372, 0.0001653201470617205, 0.0020008007995784283, 0.32874879240989685 ]
{ "id": 3, "code_window": [ "\t\tif (this.showInitialDebugActions) {\n", "\t\t\treturn [this.startAction, this.configureAction, this.toggleReplAction];\n", "\t\t}\n", "\n", "\t\treturn DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService);\n", "\t}\n", "\n", "\tpublic get showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n", "\t\treturn state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'dock';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DebugActionsWidget.getActions(this.allActions, this.toUnbind, true, this.debugService, this.keybindingService, this.instantiationService);\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 109 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { Url, parse as parseUrl } from 'url'; import { isBoolean } from 'vs/base/common/types'; import { Agent } from './request'; import { TPromise } from 'vs/base/common/winjs.base'; function getSystemProxyURI(requestURL: Url): string { if (requestURL.protocol === 'http:') { return process.env.HTTP_PROXY || process.env.http_proxy || null; } else if (requestURL.protocol === 'https:') { return process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null; } return null; } export interface IOptions { proxyUrl?: string; strictSSL?: boolean; } export async function getProxyAgent(rawRequestURL: string, options: IOptions = {}): TPromise<Agent> { const requestURL = parseUrl(rawRequestURL); const proxyURL = options.proxyUrl || getSystemProxyURI(requestURL); if (!proxyURL) { return null; } const proxyEndpoint = parseUrl(proxyURL); if (!/^https?:$/.test(proxyEndpoint.protocol)) { return null; } const opts = { host: proxyEndpoint.hostname, port: Number(proxyEndpoint.port), auth: proxyEndpoint.auth, rejectUnauthorized: isBoolean(options.strictSSL) ? options.strictSSL : true }; const Ctor = requestURL.protocol === 'http:' ? await import('http-proxy-agent') : await import('https-proxy-agent'); return new Ctor(opts); }
src/vs/base/node/proxy.ts
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.0023648052010685205, 0.0006565316580235958, 0.00016560553922317922, 0.0002632485411595553, 0.0007846644730307162 ]
{ "id": 3, "code_window": [ "\t\tif (this.showInitialDebugActions) {\n", "\t\t\treturn [this.startAction, this.configureAction, this.toggleReplAction];\n", "\t\t}\n", "\n", "\t\treturn DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService);\n", "\t}\n", "\n", "\tpublic get showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n", "\t\treturn state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'dock';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DebugActionsWidget.getActions(this.allActions, this.toUnbind, true, this.debugService, this.keybindingService, this.instantiationService);\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 109 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "issueReporter": "Reportero de tema", "processExplorer": "Process Explorer" }
i18n/esn/src/vs/platform/issue/electron-main/issueService.i18n.json
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.0016569934086874127, 0.0009207946714013815, 0.00018459594866726547, 0.0009207946714013815, 0.0007361987372860312 ]
{ "id": 3, "code_window": [ "\t\tif (this.showInitialDebugActions) {\n", "\t\t\treturn [this.startAction, this.configureAction, this.toggleReplAction];\n", "\t\t}\n", "\n", "\t\treturn DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService);\n", "\t}\n", "\n", "\tpublic get showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n", "\t\treturn state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolbar !== 'dock';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DebugActionsWidget.getActions(this.allActions, this.toUnbind, true, this.debugService, this.keybindingService, this.instantiationService);\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 109 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { HoverOperation, IHoverComputer } from './hoverOperation'; import { GlyphHoverWidget } from './hoverWidgets'; import { $ } from 'vs/base/browser/dom'; import { MarkdownRenderer } from 'vs/editor/contrib/markdown/markdownRenderer'; import { IMarkdownString, isEmptyMarkdownString } from 'vs/base/common/htmlContent'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; export interface IHoverMessage { value: IMarkdownString; } class MarginComputer implements IHoverComputer<IHoverMessage[]> { private _editor: ICodeEditor; private _lineNumber: number; private _result: IHoverMessage[]; constructor(editor: ICodeEditor) { this._editor = editor; this._lineNumber = -1; } public setLineNumber(lineNumber: number): void { this._lineNumber = lineNumber; this._result = []; } public clearResult(): void { this._result = []; } public computeSync(): IHoverMessage[] { const toHoverMessage = (contents: IMarkdownString): IHoverMessage => { return { value: contents }; }; let lineDecorations = this._editor.getLineDecorations(this._lineNumber); let result: IHoverMessage[] = []; for (let i = 0, len = lineDecorations.length; i < len; i++) { let d = lineDecorations[i]; if (!d.options.glyphMarginClassName) { continue; } let hoverMessage = d.options.glyphMarginHoverMessage; if (isEmptyMarkdownString(hoverMessage)) { continue; } if (Array.isArray(hoverMessage)) { result = result.concat(hoverMessage.map(toHoverMessage)); } else { result.push(toHoverMessage(hoverMessage)); } } return result; } public onResult(result: IHoverMessage[], isFromSynchronousComputation: boolean): void { this._result = this._result.concat(result); } public getResult(): IHoverMessage[] { return this._result; } public getResultWithLoadingMessage(): IHoverMessage[] { return this.getResult(); } } export class ModesGlyphHoverWidget extends GlyphHoverWidget { public static readonly ID = 'editor.contrib.modesGlyphHoverWidget'; private _messages: IHoverMessage[]; private _lastLineNumber: number; private _markdownRenderer: MarkdownRenderer; private _computer: MarginComputer; private _hoverOperation: HoverOperation<IHoverMessage[]>; private _renderDisposeables: IDisposable[]; constructor(editor: ICodeEditor, markdownRenderer: MarkdownRenderer) { super(ModesGlyphHoverWidget.ID, editor); this._lastLineNumber = -1; this._markdownRenderer = markdownRenderer; this._computer = new MarginComputer(this._editor); this._hoverOperation = new HoverOperation( this._computer, (result: IHoverMessage[]) => this._withResult(result), null, (result: any) => this._withResult(result) ); } public dispose(): void { this._renderDisposeables = dispose(this._renderDisposeables); this._hoverOperation.cancel(); super.dispose(); } public onModelDecorationsChanged(): void { if (this.isVisible) { // The decorations have changed and the hover is visible, // we need to recompute the displayed text this._hoverOperation.cancel(); this._computer.clearResult(); this._hoverOperation.start(); } } public startShowingAt(lineNumber: number): void { if (this._lastLineNumber === lineNumber) { // We have to show the widget at the exact same line number as before, so no work is needed return; } this._hoverOperation.cancel(); this.hide(); this._lastLineNumber = lineNumber; this._computer.setLineNumber(lineNumber); this._hoverOperation.start(); } public hide(): void { this._lastLineNumber = -1; this._hoverOperation.cancel(); super.hide(); } public _withResult(result: IHoverMessage[]): void { this._messages = result; if (this._messages.length > 0) { this._renderMessages(this._lastLineNumber, this._messages); } else { this.hide(); } } private _renderMessages(lineNumber: number, messages: IHoverMessage[]): void { dispose(this._renderDisposeables); this._renderDisposeables = []; const fragment = document.createDocumentFragment(); messages.forEach((msg) => { const renderedContents = this._markdownRenderer.render(msg.value); this._renderDisposeables.push(renderedContents); fragment.appendChild($('div.hover-row', null, renderedContents.element)); }); this.updateContents(fragment); this.showAt(lineNumber); } }
src/vs/editor/contrib/hover/modesGlyphHover.ts
0
https://github.com/microsoft/vscode/commit/a86699e5b26a76cf974d29248f5795b37f64e0aa
[ 0.0030563431791961193, 0.0005169968353584409, 0.00016718196275178343, 0.000322748557664454, 0.0006552182603627443 ]
{ "id": 0, "code_window": [ "\n", "// Commands can get exeucted from a command pallete, from a context menu or from some list using a keybinding\n", "// To cover all these cases we need to properly compute the resource on which the command is being executed\n", "export function getResourceForCommand(resource: URI | object, listService: IListService, editorService: IEditorService): URI | null {\n", "\tif (URI.isUri(resource)) {\n", "\t\treturn resource;\n", "\t}\n", "\n", "\tlet list = listService.lastFocusedList;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | null {\n" ], "file_path": "src/vs/workbench/contrib/files/browser/files.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { IListService, WorkbenchAsyncDataTree } from 'vs/platform/list/browser/listService'; import { OpenEditor } from 'vs/workbench/contrib/files/common/files'; import { toResource } from 'vs/workbench/common/editor'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel'; import { coalesce } from 'vs/base/common/arrays'; // Commands can get exeucted from a command pallete, from a context menu or from some list using a keybinding // To cover all these cases we need to properly compute the resource on which the command is being executed export function getResourceForCommand(resource: URI | object, listService: IListService, editorService: IEditorService): URI | null { if (URI.isUri(resource)) { return resource; } let list = listService.lastFocusedList; if (list && list.getHTMLElement() === document.activeElement) { let focus: any; if (list instanceof List) { const focused = list.getFocusedElements(); if (focused.length) { focus = focused[0]; } } else if (list instanceof WorkbenchAsyncDataTree) { const focused = list.getFocus(); if (focused.length) { focus = focused[0]; } } if (focus instanceof ExplorerItem) { return focus.resource; } else if (focus instanceof OpenEditor) { return focus.getResource(); } } return editorService.activeEditor ? toResource(editorService.activeEditor, { supportSideBySide: true }) : null; } export function getMultiSelectedResources(resource: URI | object, listService: IListService, editorService: IEditorService): Array<URI> { const list = listService.lastFocusedList; if (list && list.getHTMLElement() === document.activeElement) { // Explorer if (list instanceof WorkbenchAsyncDataTree) { const selection = list.getSelection().map((fs: ExplorerItem) => fs.resource); const focusedElements = list.getFocus(); const focus = focusedElements.length ? focusedElements[0] : undefined; const mainUriStr = URI.isUri(resource) ? resource.toString() : focus instanceof ExplorerItem ? focus.resource.toString() : undefined; // If the resource is passed it has to be a part of the returned context. // We only respect the selection if it contains the focused element. if (selection.some(s => URI.isUri(s) && s.toString() === mainUriStr)) { return selection; } } // Open editors view if (list instanceof List) { const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource())); const focusedElements = list.getFocusedElements(); const focus = focusedElements.length ? focusedElements[0] : undefined; let mainUriStr: string | undefined = undefined; if (URI.isUri(resource)) { mainUriStr = resource.toString(); } else if (focus instanceof OpenEditor) { const focusedResource = focus.getResource(); mainUriStr = focusedResource ? focusedResource.toString() : undefined; } // We only respect the selection if it contains the main element. if (selection.some(s => s.toString() === mainUriStr)) { return selection; } } } const result = getResourceForCommand(resource, listService, editorService); return !!result ? [result] : []; }
src/vs/workbench/contrib/files/browser/files.ts
1
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.9991503953933716, 0.6575815677642822, 0.00016671937191858888, 0.9778842329978943, 0.4648789167404175 ]
{ "id": 0, "code_window": [ "\n", "// Commands can get exeucted from a command pallete, from a context menu or from some list using a keybinding\n", "// To cover all these cases we need to properly compute the resource on which the command is being executed\n", "export function getResourceForCommand(resource: URI | object, listService: IListService, editorService: IEditorService): URI | null {\n", "\tif (URI.isUri(resource)) {\n", "\t\treturn resource;\n", "\t}\n", "\n", "\tlet list = listService.lastFocusedList;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | null {\n" ], "file_path": "src/vs/workbench/contrib/files/browser/files.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import * as assert from 'assert'; import { join } from 'vs/base/common/path'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IUntitledEditorService, UntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { workbenchInstantiationService } from 'vs/workbench/test/workbenchTestServices'; import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel'; import { IModeService } from 'vs/editor/common/services/modeService'; import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl'; import { UntitledEditorInput } from 'vs/workbench/common/editor/untitledEditorInput'; import { snapshotToString } from 'vs/platform/files/common/files'; import { timeout } from 'vs/base/common/async'; export class TestUntitledEditorService extends UntitledEditorService { get(resource: URI) { return super.get(resource); } getAll(resources?: URI[]): UntitledEditorInput[] { return super.getAll(resources); } } class ServiceAccessor { constructor( @IUntitledEditorService public untitledEditorService: TestUntitledEditorService, @IModeService public modeService: ModeServiceImpl, @IConfigurationService public testConfigurationService: TestConfigurationService) { } } suite('Workbench untitled editors', () => { let instantiationService: IInstantiationService; let accessor: ServiceAccessor; setup(() => { instantiationService = workbenchInstantiationService(); accessor = instantiationService.createInstance(ServiceAccessor); }); teardown(() => { accessor.untitledEditorService.revertAll(); accessor.untitledEditorService.dispose(); }); test('Untitled Editor Service', function (done) { const service = accessor.untitledEditorService; assert.equal(service.getAll().length, 0); const input1 = service.createOrGet(); assert.equal(input1, service.createOrGet(input1.getResource())); assert.ok(service.exists(input1.getResource())); assert.ok(!service.exists(URI.file('testing'))); const input2 = service.createOrGet(); // get() / getAll() assert.equal(service.get(input1.getResource()), input1); assert.equal(service.getAll().length, 2); assert.equal(service.getAll([input1.getResource(), input2.getResource()]).length, 2); // revertAll() service.revertAll([input1.getResource()]); assert.ok(input1.isDisposed()); assert.equal(service.getAll().length, 1); // dirty input2.resolve().then(model => { assert.ok(!service.isDirty(input2.getResource())); const listener = service.onDidChangeDirty(resource => { listener.dispose(); assert.equal(resource.toString(), input2.getResource().toString()); assert.ok(service.isDirty(input2.getResource())); assert.equal(service.getDirty()[0].toString(), input2.getResource().toString()); assert.equal(service.getDirty([input2.getResource()])[0].toString(), input2.getResource().toString()); assert.equal(service.getDirty([input1.getResource()]).length, 0); service.revertAll(); assert.equal(service.getAll().length, 0); assert.ok(!input2.isDirty()); assert.ok(!model.isDirty()); input2.dispose(); assert.ok(!service.exists(input2.getResource())); done(); }); model.textEditorModel.setValue('foo bar'); }, err => done(err)); }); test('Untitled with associated resource', function () { const service = accessor.untitledEditorService; const file = URI.file(join('C:\\', '/foo/file.txt')); const untitled = service.createOrGet(file); assert.ok(service.hasAssociatedFilePath(untitled.getResource())); untitled.dispose(); }); test('Untitled no longer dirty when content gets empty', function () { const service = accessor.untitledEditorService; const input = service.createOrGet(); // dirty return input.resolve().then(model => { model.textEditorModel.setValue('foo bar'); assert.ok(model.isDirty()); model.textEditorModel.setValue(''); assert.ok(!model.isDirty()); input.dispose(); }); }); test('Untitled via loadOrCreate', function () { const service = accessor.untitledEditorService; service.loadOrCreate().then(model1 => { model1.textEditorModel!.setValue('foo bar'); assert.ok(model1.isDirty()); model1.textEditorModel!.setValue(''); assert.ok(!model1.isDirty()); return service.loadOrCreate({ initialValue: 'Hello World' }).then(model2 => { assert.equal(snapshotToString(model2.createSnapshot()!), 'Hello World'); const input = service.createOrGet(); return service.loadOrCreate({ resource: input.getResource() }).then(model3 => { assert.equal(model3.getResource().toString(), input.getResource().toString()); const file = URI.file(join('C:\\', '/foo/file44.txt')); return service.loadOrCreate({ resource: file }).then(model4 => { assert.ok(service.hasAssociatedFilePath(model4.getResource())); assert.ok(model4.isDirty()); model1.dispose(); model2.dispose(); model3.dispose(); model4.dispose(); input.dispose(); }); }); }); }); }); test('Untitled suggest name', function () { const service = accessor.untitledEditorService; const input = service.createOrGet(); assert.ok(service.suggestFileName(input.getResource())); }); test('Untitled with associated path remains dirty when content gets empty', function () { const service = accessor.untitledEditorService; const file = URI.file(join('C:\\', '/foo/file.txt')); const input = service.createOrGet(file); // dirty return input.resolve().then(model => { model.textEditorModel.setValue('foo bar'); assert.ok(model.isDirty()); model.textEditorModel.setValue(''); assert.ok(model.isDirty()); input.dispose(); }); }); test('Untitled created with files.defaultLanguage setting', function () { const defaultLanguage = 'javascript'; const config = accessor.testConfigurationService; config.setUserConfiguration('files', { 'defaultLanguage': defaultLanguage }); const service = accessor.untitledEditorService; const input = service.createOrGet(); assert.equal(input.getModeId(), defaultLanguage); config.setUserConfiguration('files', { 'defaultLanguage': undefined }); input.dispose(); }); test('Untitled created with modeId overrides files.defaultLanguage setting', function () { const modeId = 'typescript'; const defaultLanguage = 'javascript'; const config = accessor.testConfigurationService; config.setUserConfiguration('files', { 'defaultLanguage': defaultLanguage }); const service = accessor.untitledEditorService; const input = service.createOrGet(null!, modeId); assert.equal(input.getModeId(), modeId); config.setUserConfiguration('files', { 'defaultLanguage': undefined }); input.dispose(); }); test('encoding change event', function () { const service = accessor.untitledEditorService; const input = service.createOrGet(); let counter = 0; service.onDidChangeEncoding(r => { counter++; assert.equal(r.toString(), input.getResource().toString()); }); // dirty return input.resolve().then(model => { model.setEncoding('utf16'); assert.equal(counter, 1); input.dispose(); }); }); test('onDidChangeContent event', () => { const service = accessor.untitledEditorService; const input = service.createOrGet(); UntitledEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = 0; let counter = 0; service.onDidChangeContent(r => { counter++; assert.equal(r.toString(), input.getResource().toString()); }); return input.resolve().then(model => { model.textEditorModel.setValue('foo'); assert.equal(counter, 0, 'Dirty model should not trigger event immediately'); return timeout(3).then(() => { assert.equal(counter, 1, 'Dirty model should trigger event'); model.textEditorModel.setValue('bar'); return timeout(3).then(() => { assert.equal(counter, 2, 'Content change when dirty should trigger event'); model.textEditorModel.setValue(''); return timeout(3).then(() => { assert.equal(counter, 3, 'Manual revert should trigger event'); model.textEditorModel.setValue('foo'); return timeout(3).then(() => { assert.equal(counter, 4, 'Dirty model should trigger event'); model.revert(); return timeout(3).then(() => { assert.equal(counter, 5, 'Revert should trigger event'); input.dispose(); }); }); }); }); }); }); }); test('onDidDisposeModel event', () => { const service = accessor.untitledEditorService; const input = service.createOrGet(); let counter = 0; service.onDidDisposeModel(r => { counter++; assert.equal(r.toString(), input.getResource().toString()); }); return input.resolve().then(model => { assert.equal(counter, 0); input.dispose(); assert.equal(counter, 1); }); }); });
src/vs/workbench/test/common/editor/untitledEditor.test.ts
0
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.00020266303909011185, 0.000172775995451957, 0.0001634787186048925, 0.00017015598132275045, 0.00000952781192609109 ]
{ "id": 0, "code_window": [ "\n", "// Commands can get exeucted from a command pallete, from a context menu or from some list using a keybinding\n", "// To cover all these cases we need to properly compute the resource on which the command is being executed\n", "export function getResourceForCommand(resource: URI | object, listService: IListService, editorService: IEditorService): URI | null {\n", "\tif (URI.isUri(resource)) {\n", "\t\treturn resource;\n", "\t}\n", "\n", "\tlet list = listService.lastFocusedList;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | null {\n" ], "file_path": "src/vs/workbench/contrib/files/browser/files.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { OnBeforeRequestDetails, OnHeadersReceivedDetails, Response } from 'electron'; import { addClass, addDisposableListener } from 'vs/base/browser/dom'; import { Emitter, Event } from 'vs/base/common/event'; import { once } from 'vs/base/common/functional'; import { Disposable } from 'vs/base/common/lifecycle'; import { isMacintosh } from 'vs/base/common/platform'; import { endsWith } from 'vs/base/common/strings'; import { URI } from 'vs/base/common/uri'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IFileService } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import { DARK, ITheme, IThemeService, LIGHT } from 'vs/platform/theme/common/themeService'; import { registerFileProtocol, WebviewProtocol } from 'vs/workbench/contrib/webview/electron-browser/webviewProtocols'; import { areWebviewInputOptionsEqual } from './webviewEditorService'; import { WebviewFindWidget } from './webviewFindWidget'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; export interface WebviewPortMapping { readonly port: number; readonly resolvedPort: number; } export interface WebviewPortMapping { readonly port: number; readonly resolvedPort: number; } export interface WebviewOptions { readonly allowSvgs?: boolean; readonly extension?: { readonly location: URI; readonly id?: ExtensionIdentifier; }; readonly enableFindWidget?: boolean; } export interface WebviewContentOptions { readonly allowScripts?: boolean; readonly svgWhiteList?: string[]; readonly localResourceRoots?: ReadonlyArray<URI>; readonly portMappings?: ReadonlyArray<WebviewPortMapping>; } interface IKeydownEvent { key: string; keyCode: number; code: string; shiftKey: boolean; altKey: boolean; ctrlKey: boolean; metaKey: boolean; repeat: boolean; } type OnBeforeRequestDelegate = (details: OnBeforeRequestDetails) => Promise<Response | undefined>; type OnHeadersReceivedDelegate = (details: OnHeadersReceivedDetails) => { cancel: boolean } | undefined; class WebviewSession extends Disposable { private readonly _onBeforeRequestDelegates: Array<OnBeforeRequestDelegate> = []; private readonly _onHeadersReceivedDelegates: Array<OnHeadersReceivedDelegate> = []; public constructor( webview: Electron.WebviewTag, ) { super(); this._register(addDisposableListener(webview, 'did-start-loading', once(() => { const contents = webview.getWebContents(); if (!contents) { return; } contents.session.webRequest.onBeforeRequest(async (details, callback) => { for (const delegate of this._onBeforeRequestDelegates) { const result = await delegate(details); if (typeof result !== 'undefined') { callback(result); return; } } callback({}); }); contents.session.webRequest.onHeadersReceived((details, callback) => { for (const delegate of this._onHeadersReceivedDelegates) { const result = delegate(details); if (typeof result !== 'undefined') { callback(result); return; } } callback({ cancel: false, responseHeaders: details.responseHeaders }); }); }))); } public onBeforeRequest(delegate: OnBeforeRequestDelegate) { this._onBeforeRequestDelegates.push(delegate); } public onHeadersReceived(delegate: OnHeadersReceivedDelegate) { this._onHeadersReceivedDelegates.push(delegate); } } class WebviewProtocolProvider extends Disposable { constructor( webview: Electron.WebviewTag, private readonly _extensionLocation: URI | undefined, private readonly _getLocalResourceRoots: () => ReadonlyArray<URI>, private readonly _environmentService: IEnvironmentService, private readonly _fileService: IFileService, ) { super(); this._register(addDisposableListener(webview, 'did-start-loading', once(() => { const contents = webview.getWebContents(); if (contents) { this.registerProtocols(contents); } }))); } private registerProtocols(contents: Electron.WebContents) { if (contents.isDestroyed()) { return; } const appRootUri = URI.file(this._environmentService.appRoot); registerFileProtocol(contents, WebviewProtocol.CoreResource, this._fileService, undefined, () => [ appRootUri ]); registerFileProtocol(contents, WebviewProtocol.VsCodeResource, this._fileService, this._extensionLocation, () => this._getLocalResourceRoots() ); } } class WebviewPortMappingProvider extends Disposable { constructor( session: WebviewSession, mappings: () => ReadonlyArray<WebviewPortMapping>, extensionId: ExtensionIdentifier | undefined, @ITelemetryService telemetryService: ITelemetryService, ) { super(); let hasLogged = false; session.onBeforeRequest(async (details) => { const uri = URI.parse(details.url); if (uri.scheme !== 'http' && uri.scheme !== 'https') { return undefined; } const localhostMatch = /^localhost:(\d+)$/.exec(uri.authority); if (localhostMatch) { if (!hasLogged && extensionId) { hasLogged = true; /* __GDPR__ "webview.accessLocalhost" : { "extension" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ telemetryService.publicLog('webview.accessLocalhost', { extension: extensionId.value }); } const port = +localhostMatch[1]; for (const mapping of mappings()) { if (mapping.port === port && mapping.port !== mapping.resolvedPort) { return { redirectURL: details.url.replace( new RegExp(`^${uri.scheme}://localhost:${mapping.port}/`), `${uri.scheme}://localhost:${mapping.resolvedPort}/`) }; } } } return undefined; }); } } class SvgBlocker extends Disposable { private readonly _onDidBlockSvg = this._register(new Emitter<void>()); public readonly onDidBlockSvg = this._onDidBlockSvg.event; constructor( session: WebviewSession, private readonly _options: WebviewContentOptions, ) { super(); session.onBeforeRequest(async (details) => { if (details.url.indexOf('.svg') > 0) { const uri = URI.parse(details.url); if (uri && !uri.scheme.match(/file/i) && endsWith(uri.path, '.svg') && !this.isAllowedSvg(uri)) { this._onDidBlockSvg.fire(); return { cancel: true }; } } return undefined; }); session.onHeadersReceived((details) => { const contentType: string[] = details.responseHeaders['content-type'] || details.responseHeaders['Content-Type']; if (contentType && Array.isArray(contentType) && contentType.some(x => x.toLowerCase().indexOf('image/svg') >= 0)) { const uri = URI.parse(details.url); if (uri && !this.isAllowedSvg(uri)) { this._onDidBlockSvg.fire(); return { cancel: true }; } } return undefined; }); } private isAllowedSvg(uri: URI): boolean { if (this._options.svgWhiteList) { return this._options.svgWhiteList.indexOf(uri.authority.toLowerCase()) >= 0; } return false; } } class WebviewKeyboardHandler extends Disposable { private _ignoreMenuShortcut = false; constructor( private readonly _webview: Electron.WebviewTag ) { super(); if (this.shouldToggleMenuShortcutsEnablement) { this._register(addDisposableListener(this._webview, 'did-start-loading', () => { const contents = this.getWebContents(); if (contents) { contents.on('before-input-event', (_event, input) => { if (input.type === 'keyDown' && document.activeElement === this._webview) { this._ignoreMenuShortcut = input.control || input.meta; this.setIgnoreMenuShortcuts(this._ignoreMenuShortcut); } }); } })); } this._register(addDisposableListener(this._webview, 'ipc-message', (event) => { switch (event.channel) { case 'did-keydown': // Electron: workaround for https://github.com/electron/electron/issues/14258 // We have to detect keyboard events in the <webview> and dispatch them to our // keybinding service because these events do not bubble to the parent window anymore. this.handleKeydown(event.args[0]); return; case 'did-focus': this.setIgnoreMenuShortcuts(this._ignoreMenuShortcut); break; case 'did-blur': this.setIgnoreMenuShortcuts(false); return; } })); } private get shouldToggleMenuShortcutsEnablement() { return isMacintosh; } private setIgnoreMenuShortcuts(value: boolean) { if (!this.shouldToggleMenuShortcutsEnablement) { return; } const contents = this.getWebContents(); if (contents) { contents.setIgnoreMenuShortcuts(value); } } private getWebContents(): Electron.WebContents | undefined { const contents = this._webview.getWebContents(); if (contents && !contents.isDestroyed()) { return contents; } return undefined; } private handleKeydown(event: IKeydownEvent): void { // Create a fake KeyboardEvent from the data provided const emulatedKeyboardEvent = new KeyboardEvent('keydown', event); // Force override the target Object.defineProperty(emulatedKeyboardEvent, 'target', { get: () => this._webview }); // And re-dispatch window.dispatchEvent(emulatedKeyboardEvent); } } export class WebviewElement extends Disposable { private _webview: Electron.WebviewTag; private _ready: Promise<void>; private _webviewFindWidget: WebviewFindWidget; private _findStarted: boolean = false; private _contents: string = ''; private _state: string | undefined = undefined; private _focused = false; private readonly _onDidFocus = this._register(new Emitter<void>()); public get onDidFocus(): Event<void> { return this._onDidFocus.event; } constructor( private readonly _styleElement: Element, private readonly _options: WebviewOptions, private _contentOptions: WebviewContentOptions, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IEnvironmentService environmentService: IEnvironmentService, @IFileService fileService: IFileService, @ITelemetryService telemetryService: ITelemetryService, ) { super(); this._webview = document.createElement('webview'); this._webview.setAttribute('partition', `webview${Date.now()}`); this._webview.setAttribute('webpreferences', 'contextIsolation=yes'); this._webview.style.flex = '0 1'; this._webview.style.width = '0'; this._webview.style.height = '0'; this._webview.style.outline = '0'; this._webview.preload = require.toUrl('./webview-pre.js'); this._webview.src = 'data:text/html;charset=utf-8,%3C%21DOCTYPE%20html%3E%0D%0A%3Chtml%20lang%3D%22en%22%20style%3D%22width%3A%20100%25%3B%20height%3A%20100%25%22%3E%0D%0A%3Chead%3E%0D%0A%09%3Ctitle%3EVirtual%20Document%3C%2Ftitle%3E%0D%0A%3C%2Fhead%3E%0D%0A%3Cbody%20style%3D%22margin%3A%200%3B%20overflow%3A%20hidden%3B%20width%3A%20100%25%3B%20height%3A%20100%25%22%3E%0D%0A%3C%2Fbody%3E%0D%0A%3C%2Fhtml%3E'; this._ready = new Promise(resolve => { const subscription = this._register(addDisposableListener(this._webview, 'ipc-message', (event) => { if (event.channel === 'webview-ready') { // console.info('[PID Webview] ' event.args[0]); addClass(this._webview, 'ready'); // can be found by debug command subscription.dispose(); resolve(); } })); }); const session = this._register(new WebviewSession(this._webview)); this._register(new WebviewProtocolProvider( this._webview, this._options.extension ? this._options.extension.location : undefined, () => (this._contentOptions.localResourceRoots || []), environmentService, fileService)); this._register(new WebviewPortMappingProvider( session, () => (this._contentOptions.portMappings || []), _options.extension ? _options.extension.id : undefined, telemetryService)); if (!this._options.allowSvgs) { const svgBlocker = this._register(new SvgBlocker(session, this._contentOptions)); svgBlocker.onDidBlockSvg(() => this.onDidBlockSvg()); } this._register(new WebviewKeyboardHandler(this._webview)); this._register(addDisposableListener(this._webview, 'console-message', function (e: { level: number; message: string; line: number; sourceId: string; }) { console.log(`[Embedded Page] ${e.message}`); })); this._register(addDisposableListener(this._webview, 'dom-ready', () => { this.layout(); // Workaround for https://github.com/electron/electron/issues/14474 if (this._focused || document.activeElement === this._webview) { this._webview.blur(); this._webview.focus(); } })); this._register(addDisposableListener(this._webview, 'crashed', () => { console.error('embedded page crashed'); })); this._register(addDisposableListener(this._webview, 'ipc-message', (event) => { switch (event.channel) { case 'onmessage': if (event.args && event.args.length) { this._onMessage.fire(event.args[0]); } return; case 'did-click-link': let [uri] = event.args; this._onDidClickLink.fire(URI.parse(uri)); return; case 'did-set-content': this._webview.style.flex = ''; this._webview.style.width = '100%'; this._webview.style.height = '100%'; this.layout(); return; case 'did-scroll': if (event.args && typeof event.args[0] === 'number') { this._onDidScroll.fire({ scrollYPercentage: event.args[0] }); } return; case 'do-reload': this.reload(); return; case 'do-update-state': this._state = event.args[0]; this._onDidUpdateState.fire(this._state); return; case 'did-focus': this.handleFocusChange(true); return; case 'did-blur': this.handleFocusChange(false); return; } })); this._register(addDisposableListener(this._webview, 'devtools-opened', () => { this._send('devtools-opened'); })); if (_options.enableFindWidget) { this._webviewFindWidget = this._register(instantiationService.createInstance(WebviewFindWidget, this)); } this.style(themeService.getTheme()); themeService.onThemeChange(this.style, this, this._toDispose); } public mountTo(parent: HTMLElement) { if (this._webviewFindWidget) { parent.appendChild(this._webviewFindWidget.getDomNode()!); } parent.appendChild(this._webview); } dispose(): void { if (this._webview) { if (this._webview.parentElement) { this._webview.parentElement.removeChild(this._webview); } } this._webview = undefined!; this._webviewFindWidget = undefined!; super.dispose(); } private readonly _onDidClickLink = this._register(new Emitter<URI>()); public readonly onDidClickLink = this._onDidClickLink.event; private readonly _onDidScroll = this._register(new Emitter<{ scrollYPercentage: number }>()); public readonly onDidScroll = this._onDidScroll.event; private readonly _onDidUpdateState = this._register(new Emitter<string | undefined>()); public readonly onDidUpdateState = this._onDidUpdateState.event; private readonly _onMessage = this._register(new Emitter<any>()); public readonly onMessage = this._onMessage.event; private _send(channel: string, ...args: any[]): void { this._ready .then(() => this._webview.send(channel, ...args)) .catch(err => console.error(err)); } public set initialScrollProgress(value: number) { this._send('initial-scroll-position', value); } public set state(value: string | undefined) { this._state = value; } public set options(value: WebviewContentOptions) { if (this._contentOptions && areWebviewInputOptionsEqual(value, this._contentOptions)) { return; } this._contentOptions = value; this._send('content', { contents: this._contents, options: this._contentOptions, state: this._state }); } public set contents(value: string) { this._contents = value; this._send('content', { contents: value, options: this._contentOptions, state: this._state }); } public update(value: string, options: WebviewContentOptions, retainContextWhenHidden: boolean) { if (retainContextWhenHidden && value === this._contents && this._contentOptions && areWebviewInputOptionsEqual(options, this._contentOptions)) { return; } this._contents = value; this._contentOptions = options; this._send('content', { contents: this._contents, options: this._contentOptions, state: this._state }); } public set baseUrl(value: string) { this._send('baseUrl', value); } public focus(): void { this._webview.focus(); this._send('focus'); // Handle focus change programmatically (do not rely on event from <webview>) this.handleFocusChange(true); } private handleFocusChange(isFocused: boolean): void { this._focused = isFocused; if (isFocused) { this._onDidFocus.fire(); } } public sendMessage(data: any): void { this._send('message', data); } private onDidBlockSvg() { this.sendMessage({ name: 'vscode-did-block-svg' }); } private style(theme: ITheme): void { const { fontFamily, fontWeight, fontSize } = window.getComputedStyle(this._styleElement); // TODO@theme avoid styleElement const exportedColors = colorRegistry.getColorRegistry().getColors().reduce((colors, entry) => { const color = theme.getColor(entry.id); if (color) { colors['vscode-' + entry.id.replace('.', '-')] = color.toString(); } return colors; }, {} as { [key: string]: string }); const styles = { 'vscode-editor-font-family': fontFamily, 'vscode-editor-font-weight': fontWeight, 'vscode-editor-font-size': fontSize, ...exportedColors }; const activeTheme = ApiThemeClassName.fromTheme(theme); this._send('styles', styles, activeTheme); if (this._webviewFindWidget) { this._webviewFindWidget.updateTheme(theme); } } public layout(): void { const contents = this._webview.getWebContents(); if (!contents || contents.isDestroyed()) { return; } const window = (contents as any).getOwnerBrowserWindow(); if (!window || !window.webContents || window.webContents.isDestroyed()) { return; } window.webContents.getZoomFactor((factor: number) => { if (contents.isDestroyed()) { return; } contents.setZoomFactor(factor); }); } public startFind(value: string, options?: Electron.FindInPageOptions) { if (!value) { return; } // ensure options is defined without modifying the original options = options || {}; // FindNext must be false for a first request const findOptions: Electron.FindInPageOptions = { forward: options.forward, findNext: false, matchCase: options.matchCase, medialCapitalAsWordStart: options.medialCapitalAsWordStart }; this._findStarted = true; this._webview.findInPage(value, findOptions); } /** * Webviews expose a stateful find API. * Successive calls to find will move forward or backward through onFindResults * depending on the supplied options. * * @param value The string to search for. Empty strings are ignored. */ public find(value: string, options?: Electron.FindInPageOptions): void { // Searching with an empty value will throw an exception if (!value) { return; } if (!this._findStarted) { this.startFind(value, options); return; } this._webview.findInPage(value, options); } public stopFind(keepSelection?: boolean): void { this._findStarted = false; this._webview.stopFindInPage(keepSelection ? 'keepSelection' : 'clearSelection'); } public showFind() { if (this._webviewFindWidget) { this._webviewFindWidget.reveal(); } } public hideFind() { if (this._webviewFindWidget) { this._webviewFindWidget.hide(); } } public reload() { this.contents = this._contents; } public selectAll() { this._webview.selectAll(); } public copy() { this._webview.copy(); } public paste() { this._webview.paste(); } public cut() { this._webview.cut(); } public undo() { this._webview.undo(); } public redo() { this._webview.redo(); } } enum ApiThemeClassName { light = 'vscode-light', dark = 'vscode-dark', highContrast = 'vscode-high-contrast' } namespace ApiThemeClassName { export function fromTheme(theme: ITheme): ApiThemeClassName { if (theme.type === LIGHT) { return ApiThemeClassName.light; } else if (theme.type === DARK) { return ApiThemeClassName.dark; } else { return ApiThemeClassName.highContrast; } } }
src/vs/workbench/contrib/webview/electron-browser/webviewElement.ts
0
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.00020659712026827037, 0.00017014263721648604, 0.00016235961811617017, 0.0001697569532552734, 0.000005267922915663803 ]
{ "id": 0, "code_window": [ "\n", "// Commands can get exeucted from a command pallete, from a context menu or from some list using a keybinding\n", "// To cover all these cases we need to properly compute the resource on which the command is being executed\n", "export function getResourceForCommand(resource: URI | object, listService: IListService, editorService: IEditorService): URI | null {\n", "\tif (URI.isUri(resource)) {\n", "\t\treturn resource;\n", "\t}\n", "\n", "\tlet list = listService.lastFocusedList;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | null {\n" ], "file_path": "src/vs/workbench/contrib/files/browser/files.ts", "type": "replace", "edit_start_line_idx": 16 }
{ "description": "Extension to add Grunt capabilities to VS Code.", "displayName": "Grunt support for VS Code", "config.grunt.autoDetect": "Controls whether auto detection of Grunt tasks is on or off. Default is on.", "grunt.taskDefinition.type.description": "The Grunt task to customize.", "grunt.taskDefinition.file.description": "The Grunt file that provides the task. Can be omitted." }
extensions/grunt/package.nls.json
0
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.0001755702105583623, 0.0001755702105583623, 0.0001755702105583623, 0.0001755702105583623, 0 ]
{ "id": 1, "code_window": [ "\n", "\treturn editorService.activeEditor ? toResource(editorService.activeEditor, { supportSideBySide: true }) : null;\n", "}\n", "\n", "export function getMultiSelectedResources(resource: URI | object, listService: IListService, editorService: IEditorService): Array<URI> {\n", "\tconst list = listService.lastFocusedList;\n", "\tif (list && list.getHTMLElement() === document.activeElement) {\n", "\t\t// Explorer\n", "\t\tif (list instanceof WorkbenchAsyncDataTree) {\n", "\t\t\tconst selection = list.getSelection().map((fs: ExplorerItem) => fs.resource);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): Array<URI> {\n" ], "file_path": "src/vs/workbench/contrib/files/browser/files.ts", "type": "replace", "edit_start_line_idx": 46 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { IListService, WorkbenchAsyncDataTree } from 'vs/platform/list/browser/listService'; import { OpenEditor } from 'vs/workbench/contrib/files/common/files'; import { toResource } from 'vs/workbench/common/editor'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel'; import { coalesce } from 'vs/base/common/arrays'; // Commands can get exeucted from a command pallete, from a context menu or from some list using a keybinding // To cover all these cases we need to properly compute the resource on which the command is being executed export function getResourceForCommand(resource: URI | object, listService: IListService, editorService: IEditorService): URI | null { if (URI.isUri(resource)) { return resource; } let list = listService.lastFocusedList; if (list && list.getHTMLElement() === document.activeElement) { let focus: any; if (list instanceof List) { const focused = list.getFocusedElements(); if (focused.length) { focus = focused[0]; } } else if (list instanceof WorkbenchAsyncDataTree) { const focused = list.getFocus(); if (focused.length) { focus = focused[0]; } } if (focus instanceof ExplorerItem) { return focus.resource; } else if (focus instanceof OpenEditor) { return focus.getResource(); } } return editorService.activeEditor ? toResource(editorService.activeEditor, { supportSideBySide: true }) : null; } export function getMultiSelectedResources(resource: URI | object, listService: IListService, editorService: IEditorService): Array<URI> { const list = listService.lastFocusedList; if (list && list.getHTMLElement() === document.activeElement) { // Explorer if (list instanceof WorkbenchAsyncDataTree) { const selection = list.getSelection().map((fs: ExplorerItem) => fs.resource); const focusedElements = list.getFocus(); const focus = focusedElements.length ? focusedElements[0] : undefined; const mainUriStr = URI.isUri(resource) ? resource.toString() : focus instanceof ExplorerItem ? focus.resource.toString() : undefined; // If the resource is passed it has to be a part of the returned context. // We only respect the selection if it contains the focused element. if (selection.some(s => URI.isUri(s) && s.toString() === mainUriStr)) { return selection; } } // Open editors view if (list instanceof List) { const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource())); const focusedElements = list.getFocusedElements(); const focus = focusedElements.length ? focusedElements[0] : undefined; let mainUriStr: string | undefined = undefined; if (URI.isUri(resource)) { mainUriStr = resource.toString(); } else if (focus instanceof OpenEditor) { const focusedResource = focus.getResource(); mainUriStr = focusedResource ? focusedResource.toString() : undefined; } // We only respect the selection if it contains the main element. if (selection.some(s => s.toString() === mainUriStr)) { return selection; } } } const result = getResourceForCommand(resource, listService, editorService); return !!result ? [result] : []; }
src/vs/workbench/contrib/files/browser/files.ts
1
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.9985999464988708, 0.5571058392524719, 0.00016545370453968644, 0.9943015575408936, 0.4919224977493286 ]
{ "id": 1, "code_window": [ "\n", "\treturn editorService.activeEditor ? toResource(editorService.activeEditor, { supportSideBySide: true }) : null;\n", "}\n", "\n", "export function getMultiSelectedResources(resource: URI | object, listService: IListService, editorService: IEditorService): Array<URI> {\n", "\tconst list = listService.lastFocusedList;\n", "\tif (list && list.getHTMLElement() === document.activeElement) {\n", "\t\t// Explorer\n", "\t\tif (list instanceof WorkbenchAsyncDataTree) {\n", "\t\t\tconst selection = list.getSelection().map((fs: ExplorerItem) => fs.resource);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): Array<URI> {\n" ], "file_path": "src/vs/workbench/contrib/files/browser/files.ts", "type": "replace", "edit_start_line_idx": 46 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getLanguageService as getHTMLLanguageService, DocumentContext, IHTMLDataProvider, SelectionRange } from 'vscode-html-languageservice'; import { CompletionItem, Location, SignatureHelp, Definition, TextEdit, TextDocument, Diagnostic, DocumentLink, Range, Hover, DocumentHighlight, CompletionList, Position, FormattingOptions, SymbolInformation, FoldingRange } from 'vscode-languageserver-types'; import { ColorInformation, ColorPresentation, Color, WorkspaceFolder } from 'vscode-languageserver'; import { getLanguageModelCache, LanguageModelCache } from '../languageModelCache'; import { getDocumentRegions, HTMLDocumentRegions } from './embeddedSupport'; import { getCSSMode } from './cssMode'; import { getJavaScriptMode } from './javascriptMode'; import { getHTMLMode } from './htmlMode'; export { ColorInformation, ColorPresentation, Color }; export interface Settings { css?: any; html?: any; javascript?: any; } export interface Workspace { readonly settings: Settings; readonly folders: WorkspaceFolder[]; } export interface LanguageMode { getId(): string; getSelectionRanges?: (document: TextDocument, positions: Position[]) => SelectionRange[][]; doValidation?: (document: TextDocument, settings?: Settings) => Diagnostic[]; doComplete?: (document: TextDocument, position: Position, settings?: Settings) => CompletionList; doResolve?: (document: TextDocument, item: CompletionItem) => CompletionItem; doHover?: (document: TextDocument, position: Position) => Hover | null; doSignatureHelp?: (document: TextDocument, position: Position) => SignatureHelp | null; findDocumentHighlight?: (document: TextDocument, position: Position) => DocumentHighlight[]; findDocumentSymbols?: (document: TextDocument) => SymbolInformation[]; findDocumentLinks?: (document: TextDocument, documentContext: DocumentContext) => DocumentLink[]; findDefinition?: (document: TextDocument, position: Position) => Definition | null; findReferences?: (document: TextDocument, position: Position) => Location[]; format?: (document: TextDocument, range: Range, options: FormattingOptions, settings?: Settings) => TextEdit[]; findDocumentColors?: (document: TextDocument) => ColorInformation[]; getColorPresentations?: (document: TextDocument, color: Color, range: Range) => ColorPresentation[]; doAutoClose?: (document: TextDocument, position: Position) => string | null; getFoldingRanges?: (document: TextDocument) => FoldingRange[]; onDocumentRemoved(document: TextDocument): void; dispose(): void; } export interface LanguageModes { getModeAtPosition(document: TextDocument, position: Position): LanguageMode | undefined; getModesInRange(document: TextDocument, range: Range): LanguageModeRange[]; getAllModes(): LanguageMode[]; getAllModesInDocument(document: TextDocument): LanguageMode[]; getMode(languageId: string): LanguageMode | undefined; onDocumentRemoved(document: TextDocument): void; dispose(): void; } export interface LanguageModeRange extends Range { mode: LanguageMode | undefined; attributeValue?: boolean; } export function getLanguageModes(supportedLanguages: { [languageId: string]: boolean; }, workspace: Workspace, customDataProviders?: IHTMLDataProvider[]): LanguageModes { const htmlLanguageService = getHTMLLanguageService({ customDataProviders }); let documentRegions = getLanguageModelCache<HTMLDocumentRegions>(10, 60, document => getDocumentRegions(htmlLanguageService, document)); let modelCaches: LanguageModelCache<any>[] = []; modelCaches.push(documentRegions); let modes = Object.create(null); modes['html'] = getHTMLMode(htmlLanguageService, workspace); if (supportedLanguages['css']) { modes['css'] = getCSSMode(documentRegions, workspace); } if (supportedLanguages['javascript']) { modes['javascript'] = getJavaScriptMode(documentRegions); } return { getModeAtPosition(document: TextDocument, position: Position): LanguageMode | undefined { let languageId = documentRegions.get(document).getLanguageAtPosition(position); if (languageId) { return modes[languageId]; } return undefined; }, getModesInRange(document: TextDocument, range: Range): LanguageModeRange[] { return documentRegions.get(document).getLanguageRanges(range).map(r => { return <LanguageModeRange>{ start: r.start, end: r.end, mode: r.languageId && modes[r.languageId], attributeValue: r.attributeValue }; }); }, getAllModesInDocument(document: TextDocument): LanguageMode[] { let result = []; for (let languageId of documentRegions.get(document).getLanguagesInDocument()) { let mode = modes[languageId]; if (mode) { result.push(mode); } } return result; }, getAllModes(): LanguageMode[] { let result = []; for (let languageId in modes) { let mode = modes[languageId]; if (mode) { result.push(mode); } } return result; }, getMode(languageId: string): LanguageMode { return modes[languageId]; }, onDocumentRemoved(document: TextDocument) { modelCaches.forEach(mc => mc.onDocumentRemoved(document)); for (let mode in modes) { modes[mode].onDocumentRemoved(document); } }, dispose(): void { modelCaches.forEach(mc => mc.dispose()); modelCaches = []; for (let mode in modes) { modes[mode].dispose(); } modes = {}; } }; }
extensions/html-language-features/server/src/modes/languageModes.ts
0
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.00017743255011737347, 0.00017151780775748193, 0.00016480140038765967, 0.00017069933528546244, 0.0000034544439131423132 ]
{ "id": 1, "code_window": [ "\n", "\treturn editorService.activeEditor ? toResource(editorService.activeEditor, { supportSideBySide: true }) : null;\n", "}\n", "\n", "export function getMultiSelectedResources(resource: URI | object, listService: IListService, editorService: IEditorService): Array<URI> {\n", "\tconst list = listService.lastFocusedList;\n", "\tif (list && list.getHTMLElement() === document.activeElement) {\n", "\t\t// Explorer\n", "\t\tif (list instanceof WorkbenchAsyncDataTree) {\n", "\t\t\tconst selection = list.getSelection().map((fs: ExplorerItem) => fs.resource);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): Array<URI> {\n" ], "file_path": "src/vs/workbench/contrib/files/browser/files.ts", "type": "replace", "edit_start_line_idx": 46 }
/*--------------------------------------------------------------------------------------------- * 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 { URI } from 'vs/base/common/uri'; import { IPosition, Position } from 'vs/editor/common/core/position'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IModelService } from 'vs/editor/common/services/modelService'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/resourceConfiguration'; import { IConfigurationChangeEvent, IConfigurationService } from 'vs/platform/configuration/common/configuration'; export class TextResourceConfigurationService extends Disposable implements ITextResourceConfigurationService { public _serviceBrand: any; private readonly _onDidChangeConfiguration: Emitter<IConfigurationChangeEvent> = this._register(new Emitter<IConfigurationChangeEvent>()); public readonly onDidChangeConfiguration: Event<IConfigurationChangeEvent> = this._onDidChangeConfiguration.event; constructor( @IConfigurationService private readonly configurationService: IConfigurationService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, ) { super(); this._register(this.configurationService.onDidChangeConfiguration(e => this._onDidChangeConfiguration.fire(e))); } getValue<T>(resource: URI, section?: string): T; getValue<T>(resource: URI, at?: IPosition, section?: string): T; getValue<T>(resource: URI, arg2?: any, arg3?: any): T { if (typeof arg3 === 'string') { return this._getValue(resource, Position.isIPosition(arg2) ? arg2 : null, arg3); } return this._getValue(resource, null, typeof arg2 === 'string' ? arg2 : undefined); } private _getValue<T>(resource: URI, position: IPosition | null, section: string | undefined): T { const language = resource ? this.getLanguage(resource, position) : undefined; if (typeof section === 'undefined') { return this.configurationService.getValue<T>({ resource, overrideIdentifier: language }); } return this.configurationService.getValue<T>(section, { resource, overrideIdentifier: language }); } private getLanguage(resource: URI, position: IPosition | null): string | null { const model = this.modelService.getModel(resource); if (model) { return position ? this.modeService.getLanguageIdentifier(model.getLanguageIdAtPosition(position.lineNumber, position.column))!.language : model.getLanguageIdentifier().language; } return this.modeService.getModeIdByFilepathOrFirstLine(resource.path); } }
src/vs/editor/common/services/resourceConfigurationImpl.ts
0
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.00017361398204229772, 0.00016968017735052854, 0.00016687317111063749, 0.0001689284690655768, 0.0000025570836896804394 ]
{ "id": 1, "code_window": [ "\n", "\treturn editorService.activeEditor ? toResource(editorService.activeEditor, { supportSideBySide: true }) : null;\n", "}\n", "\n", "export function getMultiSelectedResources(resource: URI | object, listService: IListService, editorService: IEditorService): Array<URI> {\n", "\tconst list = listService.lastFocusedList;\n", "\tif (list && list.getHTMLElement() === document.activeElement) {\n", "\t\t// Explorer\n", "\t\tif (list instanceof WorkbenchAsyncDataTree) {\n", "\t\t\tconst selection = list.getSelection().map((fs: ExplorerItem) => fs.resource);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): Array<URI> {\n" ], "file_path": "src/vs/workbench/contrib/files/browser/files.ts", "type": "replace", "edit_start_line_idx": 46 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as fancyLog from 'fancy-log'; import * as ansiColors from 'ansi-colors'; export interface BaseTask { displayName?: string; taskName?: string; _tasks?: Task[]; } export interface PromiseTask extends BaseTask { (): Promise<void>; } export interface StreamTask extends BaseTask { (): NodeJS.ReadWriteStream; } export interface CallbackTask extends BaseTask { (cb?: (err?: any) => void): void; } export type Task = PromiseTask | StreamTask | CallbackTask; function _isPromise(p: Promise<void> | NodeJS.ReadWriteStream): p is Promise<void> { if (typeof (<any>p).then === 'function') { return true; } return false; } function _renderTime(time: number): string { return `${Math.round(time)} ms`; } async function _execute(task: Task): Promise<void> { const name = task.taskName || task.displayName || `<anonymous>`; if (!task._tasks) { fancyLog('Starting', ansiColors.cyan(name), '...'); } const startTime = process.hrtime(); await _doExecute(task); const elapsedArr = process.hrtime(startTime); const elapsedNanoseconds = (elapsedArr[0] * 1e9 + elapsedArr[1]); if (!task._tasks) { fancyLog(`Finished`, ansiColors.cyan(name), 'after', ansiColors.magenta(_renderTime(elapsedNanoseconds / 1e6))); } } async function _doExecute(task: Task): Promise<void> { // Always invoke as if it were a callback task return new Promise((resolve, reject) => { if (task.length === 1) { // this is a calback task task((err) => { if (err) { return reject(err); } resolve(); }); return; } const taskResult = task(); if (typeof taskResult === 'undefined') { // this is a sync task resolve(); return; } if (_isPromise(taskResult)) { // this is a promise returning task taskResult.then(resolve, reject); return; } // this is a stream returning task taskResult.on('end', _ => resolve()); taskResult.on('error', err => reject(err)); }); } export function series(...tasks: Task[]): PromiseTask { const result = async () => { for (let i = 0; i < tasks.length; i++) { await _execute(tasks[i]); } }; result._tasks = tasks; return result; } export function parallel(...tasks: Task[]): PromiseTask { const result = async () => { await Promise.all(tasks.map(t => _execute(t))); }; result._tasks = tasks; return result; } export function define(name: string, task: Task): Task { if (task._tasks) { // This is a composite task const lastTask = task._tasks[task._tasks.length - 1]; if (lastTask._tasks || lastTask.taskName) { // This is a composite task without a real task function // => generate a fake task function return define(name, series(task, () => Promise.resolve())); } lastTask.taskName = name; task.displayName = name; return task; } // This is a simple task task.taskName = name; task.displayName = name; return task; }
build/lib/task.ts
0
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.00017743237549439073, 0.00017396324255969375, 0.00017164697055704892, 0.00017388651031069458, 0.000001693093395260803 ]
{ "id": 2, "code_window": [ "\tconst listService = accessor.get(IListService);\n", "\tconst viewletService = accessor.get(IViewletService);\n", "\tconst panelService = accessor.get(IPanelService);\n", "\tconst fileService = accessor.get(IFileService);\n", "\tconst configurationService = accessor.get(IConfigurationService);\n", "\tconst resources = resource && getMultiSelectedResources(resource, listService, accessor.get(IEditorService));\n", "\n", "\treturn openSearchView(viewletService, panelService, configurationService, true).then(searchView => {\n", "\t\tif (resources && resources.length && searchView) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tconst resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService));\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 365 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { IListService, WorkbenchAsyncDataTree } from 'vs/platform/list/browser/listService'; import { OpenEditor } from 'vs/workbench/contrib/files/common/files'; import { toResource } from 'vs/workbench/common/editor'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel'; import { coalesce } from 'vs/base/common/arrays'; // Commands can get exeucted from a command pallete, from a context menu or from some list using a keybinding // To cover all these cases we need to properly compute the resource on which the command is being executed export function getResourceForCommand(resource: URI | object, listService: IListService, editorService: IEditorService): URI | null { if (URI.isUri(resource)) { return resource; } let list = listService.lastFocusedList; if (list && list.getHTMLElement() === document.activeElement) { let focus: any; if (list instanceof List) { const focused = list.getFocusedElements(); if (focused.length) { focus = focused[0]; } } else if (list instanceof WorkbenchAsyncDataTree) { const focused = list.getFocus(); if (focused.length) { focus = focused[0]; } } if (focus instanceof ExplorerItem) { return focus.resource; } else if (focus instanceof OpenEditor) { return focus.getResource(); } } return editorService.activeEditor ? toResource(editorService.activeEditor, { supportSideBySide: true }) : null; } export function getMultiSelectedResources(resource: URI | object, listService: IListService, editorService: IEditorService): Array<URI> { const list = listService.lastFocusedList; if (list && list.getHTMLElement() === document.activeElement) { // Explorer if (list instanceof WorkbenchAsyncDataTree) { const selection = list.getSelection().map((fs: ExplorerItem) => fs.resource); const focusedElements = list.getFocus(); const focus = focusedElements.length ? focusedElements[0] : undefined; const mainUriStr = URI.isUri(resource) ? resource.toString() : focus instanceof ExplorerItem ? focus.resource.toString() : undefined; // If the resource is passed it has to be a part of the returned context. // We only respect the selection if it contains the focused element. if (selection.some(s => URI.isUri(s) && s.toString() === mainUriStr)) { return selection; } } // Open editors view if (list instanceof List) { const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource())); const focusedElements = list.getFocusedElements(); const focus = focusedElements.length ? focusedElements[0] : undefined; let mainUriStr: string | undefined = undefined; if (URI.isUri(resource)) { mainUriStr = resource.toString(); } else if (focus instanceof OpenEditor) { const focusedResource = focus.getResource(); mainUriStr = focusedResource ? focusedResource.toString() : undefined; } // We only respect the selection if it contains the main element. if (selection.some(s => s.toString() === mainUriStr)) { return selection; } } } const result = getResourceForCommand(resource, listService, editorService); return !!result ? [result] : []; }
src/vs/workbench/contrib/files/browser/files.ts
1
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.002075200667604804, 0.0006372605566866696, 0.00016718357801437378, 0.00017784582450985909, 0.0006682770908810198 ]
{ "id": 2, "code_window": [ "\tconst listService = accessor.get(IListService);\n", "\tconst viewletService = accessor.get(IViewletService);\n", "\tconst panelService = accessor.get(IPanelService);\n", "\tconst fileService = accessor.get(IFileService);\n", "\tconst configurationService = accessor.get(IConfigurationService);\n", "\tconst resources = resource && getMultiSelectedResources(resource, listService, accessor.get(IEditorService));\n", "\n", "\treturn openSearchView(viewletService, panelService, configurationService, true).then(searchView => {\n", "\t\tif (resources && resources.length && searchView) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tconst resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService));\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 365 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="3 3 16 16" enable-background="new 3 3 16 16"><polygon fill="#e8e8e8" points="12.597,11.042 15.4,13.845 13.844,15.4 11.042,12.598 8.239,15.4 6.683,13.845 9.485,11.042 6.683,8.239 8.238,6.683 11.042,9.486 13.845,6.683 15.4,8.239"/></svg>
src/vs/editor/browser/widget/media/close-inverse.svg
0
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.00017394106544088572, 0.00017394106544088572, 0.00017394106544088572, 0.00017394106544088572, 0 ]
{ "id": 2, "code_window": [ "\tconst listService = accessor.get(IListService);\n", "\tconst viewletService = accessor.get(IViewletService);\n", "\tconst panelService = accessor.get(IPanelService);\n", "\tconst fileService = accessor.get(IFileService);\n", "\tconst configurationService = accessor.get(IConfigurationService);\n", "\tconst resources = resource && getMultiSelectedResources(resource, listService, accessor.get(IEditorService));\n", "\n", "\treturn openSearchView(viewletService, panelService, configurationService, true).then(searchView => {\n", "\t\tif (resources && resources.length && searchView) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tconst resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService));\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 365 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="-2 -2 16 16" enable-background="new -2 -2 16 16"><polygon fill="#424242" points="9,0 4.5,9 3,6 0,6 3,12 6,12 12,0"/></svg>
src/vs/base/browser/ui/menu/check.svg
0
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.00017279037274420261, 0.00017279037274420261, 0.00017279037274420261, 0.00017279037274420261, 0 ]
{ "id": 2, "code_window": [ "\tconst listService = accessor.get(IListService);\n", "\tconst viewletService = accessor.get(IViewletService);\n", "\tconst panelService = accessor.get(IPanelService);\n", "\tconst fileService = accessor.get(IFileService);\n", "\tconst configurationService = accessor.get(IConfigurationService);\n", "\tconst resources = resource && getMultiSelectedResources(resource, listService, accessor.get(IEditorService));\n", "\n", "\treturn openSearchView(viewletService, panelService, configurationService, true).then(searchView => {\n", "\t\tif (resources && resources.length && searchView) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tconst resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService));\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 365 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as types from 'vs/base/common/types'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkbenchThemeService, IColorTheme, ITokenColorCustomizations, IFileIconTheme, ExtensionData, VS_LIGHT_THEME, VS_DARK_THEME, VS_HC_THEME, COLOR_THEME_SETTING, ICON_THEME_SETTING, CUSTOM_WORKBENCH_COLORS_SETTING, CUSTOM_EDITOR_COLORS_SETTING, DETECT_HC_SETTING, HC_THEME_ID } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { Registry } from 'vs/platform/registry/common/platform'; import * as errors from 'vs/base/common/errors'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions, IConfigurationPropertySchema, IConfigurationNode } from 'vs/platform/configuration/common/configurationRegistry'; import { ColorThemeData } from './colorThemeData'; import { ITheme, Extensions as ThemingExtensions, IThemingRegistry } from 'vs/platform/theme/common/themeService'; import { Event, Emitter } from 'vs/base/common/event'; import { registerFileIconThemeSchemas } from 'vs/workbench/services/themes/common/fileIconThemeSchema'; import { IDisposable } from 'vs/base/common/lifecycle'; import { ColorThemeStore } from 'vs/workbench/services/themes/browser/colorThemeStore'; import { FileIconThemeStore } from 'vs/workbench/services/themes/common/fileIconThemeStore'; import { FileIconThemeData } from 'vs/workbench/services/themes/common/fileIconThemeData'; import { IWindowService } from 'vs/platform/windows/common/windows'; import { removeClasses, addClasses } from 'vs/base/browser/dom'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IFileService, FileChangeType } from 'vs/platform/files/common/files'; import { URI } from 'vs/base/common/uri'; import * as resources from 'vs/base/common/resources'; import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { textmateColorsSchemaId, registerColorThemeSchemas, textmateColorSettingsSchemaId } from 'vs/workbench/services/themes/common/colorThemeSchema'; import { workbenchColorsSchemaId } from 'vs/platform/theme/common/colorRegistry'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; // implementation const DEFAULT_THEME_ID = 'vs-dark vscode-theme-defaults-themes-dark_plus-json'; const DEFAULT_THEME_SETTING_VALUE = 'Default Dark+'; const PERSISTED_THEME_STORAGE_KEY = 'colorThemeData'; const PERSISTED_ICON_THEME_STORAGE_KEY = 'iconThemeData'; const defaultThemeExtensionId = 'vscode-theme-defaults'; const oldDefaultThemeExtensionId = 'vscode-theme-colorful-defaults'; const DEFAULT_ICON_THEME_SETTING_VALUE = 'vs-seti'; const fileIconsEnabledClass = 'file-icons-enabled'; const colorThemeRulesClassName = 'contributedColorTheme'; const iconThemeRulesClassName = 'contributedIconTheme'; const themingRegistry = Registry.as<IThemingRegistry>(ThemingExtensions.ThemingContribution); function validateThemeId(theme: string): string { // migrations switch (theme) { case VS_LIGHT_THEME: return `vs ${defaultThemeExtensionId}-themes-light_vs-json`; case VS_DARK_THEME: return `vs-dark ${defaultThemeExtensionId}-themes-dark_vs-json`; case VS_HC_THEME: return `hc-black ${defaultThemeExtensionId}-themes-hc_black-json`; case `vs ${oldDefaultThemeExtensionId}-themes-light_plus-tmTheme`: return `vs ${defaultThemeExtensionId}-themes-light_plus-json`; case `vs-dark ${oldDefaultThemeExtensionId}-themes-dark_plus-tmTheme`: return `vs-dark ${defaultThemeExtensionId}-themes-dark_plus-json`; } return theme; } export interface IColorCustomizations { [colorIdOrThemeSettingsId: string]: string | IColorCustomizations; } export class WorkbenchThemeService implements IWorkbenchThemeService { _serviceBrand: any; private colorThemeStore: ColorThemeStore; private currentColorTheme: ColorThemeData; private container: HTMLElement; private readonly onColorThemeChange: Emitter<IColorTheme>; private watchedColorThemeLocation: URI | undefined; private iconThemeStore: FileIconThemeStore; private currentIconTheme: FileIconThemeData; private readonly onFileIconThemeChange: Emitter<IFileIconTheme>; private watchedIconThemeLocation: URI | undefined; private themingParticipantChangeListener: IDisposable; private get colorCustomizations(): IColorCustomizations { return this.configurationService.getValue<IColorCustomizations>(CUSTOM_WORKBENCH_COLORS_SETTING) || {}; } private get tokenColorCustomizations(): ITokenColorCustomizations { return this.configurationService.getValue<ITokenColorCustomizations>(CUSTOM_EDITOR_COLORS_SETTING) || {}; } constructor( @IExtensionService extensionService: IExtensionService, @IStorageService private readonly storageService: IStorageService, @IConfigurationService private readonly configurationService: IConfigurationService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWindowService private readonly windowService: IWindowService, @IEnvironmentService private readonly environmentService: IEnvironmentService, @IFileService private readonly fileService: IFileService ) { this.container = document.body; this.colorThemeStore = new ColorThemeStore(extensionService, ColorThemeData.createLoadedEmptyTheme(DEFAULT_THEME_ID, DEFAULT_THEME_SETTING_VALUE)); this.onFileIconThemeChange = new Emitter<IFileIconTheme>(); this.iconThemeStore = new FileIconThemeStore(extensionService); this.onColorThemeChange = new Emitter<IColorTheme>({ leakWarningThreshold: 400 }); this.currentIconTheme = FileIconThemeData.createUnloadedTheme(''); // In order to avoid paint flashing for tokens, because // themes are loaded asynchronously, we need to initialize // a color theme document with good defaults until the theme is loaded let themeData: ColorThemeData | undefined = undefined; let persistedThemeData = this.storageService.get(PERSISTED_THEME_STORAGE_KEY, StorageScope.GLOBAL); if (persistedThemeData) { themeData = ColorThemeData.fromStorageData(persistedThemeData); } let containerBaseTheme = this.getBaseThemeFromContainer(); if (!themeData || themeData.baseTheme !== containerBaseTheme) { themeData = ColorThemeData.createUnloadedTheme(containerBaseTheme); } themeData.setCustomColors(this.colorCustomizations); themeData.setCustomTokenColors(this.tokenColorCustomizations); this.updateDynamicCSSRules(themeData); this.applyTheme(themeData, undefined, true); let persistedIconThemeData = this.storageService.get(PERSISTED_ICON_THEME_STORAGE_KEY, StorageScope.GLOBAL); if (persistedIconThemeData) { const iconData = FileIconThemeData.fromStorageData(persistedIconThemeData); if (iconData) { _applyIconTheme(iconData, () => { this.doSetFileIconTheme(iconData); return Promise.resolve(iconData); }); } } this.initialize().then(undefined, errors.onUnexpectedError).then(_ => { this.installConfigurationListener(); }); let prevColorId: string | undefined = undefined; // update settings schema setting for theme specific settings this.colorThemeStore.onDidChange(async event => { // updates enum for the 'workbench.colorTheme` setting colorThemeSettingSchema.enum = event.themes.map(t => t.settingsId); colorThemeSettingSchema.enumDescriptions = event.themes.map(t => t.description || ''); const themeSpecificWorkbenchColors: IJSONSchema = { properties: {} }; const themeSpecificTokenColors: IJSONSchema = { properties: {} }; const workbenchColors = { $ref: workbenchColorsSchemaId, additionalProperties: false }; const tokenColors = { properties: tokenColorSchema.properties, additionalProperties: false }; for (let t of event.themes) { // add theme specific color customization ("[Abyss]":{ ... }) const themeId = `[${t.settingsId}]`; themeSpecificWorkbenchColors.properties![themeId] = workbenchColors; themeSpecificTokenColors.properties![themeId] = tokenColors; } colorCustomizationsSchema.allOf![1] = themeSpecificWorkbenchColors; tokenColorCustomizationSchema.allOf![1] = themeSpecificTokenColors; configurationRegistry.notifyConfigurationSchemaUpdated(themeSettingsConfiguration, tokenColorCustomizationConfiguration); if (this.currentColorTheme.isLoaded) { const themeData = await this.colorThemeStore.findThemeData(this.currentColorTheme.id); if (!themeData) { // current theme is no longer available prevColorId = this.currentColorTheme.id; this.setColorTheme(DEFAULT_THEME_ID, 'auto'); } else { if (this.currentColorTheme.id === DEFAULT_THEME_ID && !types.isUndefined(prevColorId) && await this.colorThemeStore.findThemeData(prevColorId)) { // restore color this.setColorTheme(prevColorId, 'auto'); prevColorId = undefined; } } } }); let prevFileIconId: string | undefined = undefined; this.iconThemeStore.onDidChange(async event => { iconThemeSettingSchema.enum = [null, ...event.themes.map(t => t.settingsId)]; iconThemeSettingSchema.enumDescriptions = [iconThemeSettingSchema.enumDescriptions![0], ...event.themes.map(t => t.description || '')]; configurationRegistry.notifyConfigurationSchemaUpdated(themeSettingsConfiguration); if (this.currentIconTheme.isLoaded) { const theme = await this.iconThemeStore.findThemeData(this.currentIconTheme.id); if (!theme) { // current theme is no longer available prevFileIconId = this.currentIconTheme.id; this.setFileIconTheme(DEFAULT_ICON_THEME_SETTING_VALUE, 'auto'); } else { // restore color if (this.currentIconTheme.id === DEFAULT_ICON_THEME_SETTING_VALUE && !types.isUndefined(prevFileIconId) && await this.iconThemeStore.findThemeData(prevFileIconId)) { this.setFileIconTheme(prevFileIconId, 'auto'); prevFileIconId = undefined; } } } }); this.fileService.onFileChanges(async e => { if (this.watchedColorThemeLocation && this.currentColorTheme && e.contains(this.watchedColorThemeLocation, FileChangeType.UPDATED)) { await this.currentColorTheme.reload(this.fileService); this.currentColorTheme.setCustomColors(this.colorCustomizations); this.currentColorTheme.setCustomTokenColors(this.tokenColorCustomizations); this.updateDynamicCSSRules(this.currentColorTheme); this.applyTheme(this.currentColorTheme, undefined, false); } if (this.watchedIconThemeLocation && this.currentIconTheme && e.contains(this.watchedIconThemeLocation, FileChangeType.UPDATED)) { await this.currentIconTheme.reload(this.fileService); _applyIconTheme(this.currentIconTheme, () => Promise.resolve(this.currentIconTheme)); } }); } public get onDidColorThemeChange(): Event<IColorTheme> { return this.onColorThemeChange.event; } public get onDidFileIconThemeChange(): Event<IFileIconTheme> { return this.onFileIconThemeChange.event; } public get onIconThemeChange(): Event<IFileIconTheme> { return this.onFileIconThemeChange.event; } public get onThemeChange(): Event<ITheme> { return this.onColorThemeChange.event; } private initialize(): Promise<[IColorTheme | null, IFileIconTheme | null]> { let detectHCThemeSetting = this.configurationService.getValue<boolean>(DETECT_HC_SETTING); let colorThemeSetting: string; if (this.windowService.getConfiguration().highContrast && detectHCThemeSetting) { colorThemeSetting = HC_THEME_ID; } else { colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING); } let iconThemeSetting = this.configurationService.getValue<string | null>(ICON_THEME_SETTING); return Promise.all([ this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, DEFAULT_THEME_ID).then(theme => { return this.colorThemeStore.findThemeDataByParentLocation(this.environmentService.extensionDevelopmentLocationURI).then(devThemes => { if (devThemes.length) { return this.setColorTheme(devThemes[0].id, ConfigurationTarget.MEMORY); } else { return this.setColorTheme(theme && theme.id, undefined); } }); }), this.iconThemeStore.findThemeBySettingsId(iconThemeSetting).then(theme => { return this.iconThemeStore.findThemeDataByParentLocation(this.environmentService.extensionDevelopmentLocationURI).then(devThemes => { if (devThemes.length) { return this.setFileIconTheme(devThemes[0].id, ConfigurationTarget.MEMORY); } else { return this.setFileIconTheme(theme && theme.id, undefined); } }); }), ]); } private installConfigurationListener() { this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(COLOR_THEME_SETTING)) { let colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING); if (colorThemeSetting !== this.currentColorTheme.settingsId) { this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, undefined).then(theme => { if (theme) { this.setColorTheme(theme.id, undefined); } }); } } if (e.affectsConfiguration(ICON_THEME_SETTING)) { let iconThemeSetting = this.configurationService.getValue<string | null>(ICON_THEME_SETTING); if (iconThemeSetting !== this.currentIconTheme.settingsId) { this.iconThemeStore.findThemeBySettingsId(iconThemeSetting).then(theme => { this.setFileIconTheme(theme && theme.id, undefined); }); } } if (this.currentColorTheme) { let hasColorChanges = false; if (e.affectsConfiguration(CUSTOM_WORKBENCH_COLORS_SETTING)) { this.currentColorTheme.setCustomColors(this.colorCustomizations); hasColorChanges = true; } if (e.affectsConfiguration(CUSTOM_EDITOR_COLORS_SETTING)) { this.currentColorTheme.setCustomTokenColors(this.tokenColorCustomizations); hasColorChanges = true; } if (hasColorChanges) { this.updateDynamicCSSRules(this.currentColorTheme); this.onColorThemeChange.fire(this.currentColorTheme); } } }); } public getColorTheme(): IColorTheme { return this.currentColorTheme; } public getColorThemes(): Promise<IColorTheme[]> { return this.colorThemeStore.getColorThemes(); } public getTheme(): ITheme { return this.getColorTheme(); } public setColorTheme(themeId: string | undefined, settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IColorTheme | null> { if (!themeId) { return Promise.resolve(null); } if (themeId === this.currentColorTheme.id && this.currentColorTheme.isLoaded) { return this.writeColorThemeConfiguration(settingsTarget); } themeId = validateThemeId(themeId); // migrate theme ids return this.colorThemeStore.findThemeData(themeId, DEFAULT_THEME_ID).then(data => { if (!data) { return null; } const themeData = data; return themeData.ensureLoaded(this.fileService).then(_ => { if (themeId === this.currentColorTheme.id && !this.currentColorTheme.isLoaded && this.currentColorTheme.hasEqualData(themeData)) { // the loaded theme is identical to the perisisted theme. Don't need to send an event. this.currentColorTheme = themeData; themeData.setCustomColors(this.colorCustomizations); themeData.setCustomTokenColors(this.tokenColorCustomizations); return Promise.resolve(themeData); } themeData.setCustomColors(this.colorCustomizations); themeData.setCustomTokenColors(this.tokenColorCustomizations); this.updateDynamicCSSRules(themeData); return this.applyTheme(themeData, settingsTarget); }, error => { return Promise.reject(new Error(nls.localize('error.cannotloadtheme', "Unable to load {0}: {1}", themeData.location!.toString(), error.message))); }); }); } public restoreColorTheme() { let colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING); if (colorThemeSetting !== this.currentColorTheme.settingsId) { this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, undefined).then(theme => { if (theme) { this.setColorTheme(theme.id, undefined); } }); } } private updateDynamicCSSRules(themeData: ITheme) { let cssRules: string[] = []; let hasRule: { [rule: string]: boolean } = {}; let ruleCollector = { addRule: (rule: string) => { if (!hasRule[rule]) { cssRules.push(rule); hasRule[rule] = true; } } }; themingRegistry.getThemingParticipants().forEach(p => p(themeData, ruleCollector, this.environmentService)); _applyRules(cssRules.join('\n'), colorThemeRulesClassName); } private applyTheme(newTheme: ColorThemeData, settingsTarget: ConfigurationTarget | undefined | 'auto', silent = false): Promise<IColorTheme | null> { if (this.container) { if (this.currentColorTheme) { removeClasses(this.container, this.currentColorTheme.id); } else { removeClasses(this.container, VS_DARK_THEME, VS_LIGHT_THEME, VS_HC_THEME); } addClasses(this.container, newTheme.id); } this.currentColorTheme = newTheme; if (!this.themingParticipantChangeListener) { this.themingParticipantChangeListener = themingRegistry.onThemingParticipantAdded(_ => this.updateDynamicCSSRules(this.currentColorTheme)); } if (this.fileService && !resources.isEqual(newTheme.location, this.watchedColorThemeLocation)) { if (this.watchedColorThemeLocation) { this.fileService.unwatch(this.watchedColorThemeLocation); this.watchedColorThemeLocation = undefined; } if (newTheme.location && (newTheme.watch || !!this.environmentService.extensionDevelopmentLocationURI)) { this.watchedColorThemeLocation = newTheme.location; this.fileService.watch(this.watchedColorThemeLocation); } } this.sendTelemetry(newTheme.id, newTheme.extensionData, 'color'); if (silent) { return Promise.resolve(null); } this.onColorThemeChange.fire(this.currentColorTheme); // remember theme data for a quick restore if (newTheme.isLoaded) { this.storageService.store(PERSISTED_THEME_STORAGE_KEY, newTheme.toStorageData(), StorageScope.GLOBAL); } return this.writeColorThemeConfiguration(settingsTarget); } private writeColorThemeConfiguration(settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IColorTheme> { if (!types.isUndefinedOrNull(settingsTarget)) { return this.writeConfiguration(COLOR_THEME_SETTING, this.currentColorTheme.settingsId, settingsTarget).then(_ => this.currentColorTheme); } return Promise.resolve(this.currentColorTheme); } private themeExtensionsActivated = new Map<string, boolean>(); private sendTelemetry(themeId: string, themeData: ExtensionData | undefined, themeType: string) { if (themeData) { let key = themeType + themeData.extensionId; if (!this.themeExtensionsActivated.get(key)) { /* __GDPR__ "activatePlugin" : { "id" : { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "name": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "publisherDisplayName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "themeId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('activatePlugin', { id: themeData.extensionId, name: themeData.extensionName, isBuiltin: themeData.extensionIsBuiltin, publisherDisplayName: themeData.extensionPublisher, themeId: themeId }); this.themeExtensionsActivated.set(key, true); } } } public getFileIconThemes(): Promise<IFileIconTheme[]> { return this.iconThemeStore.getFileIconThemes(); } public getFileIconTheme() { return this.currentIconTheme; } public getIconTheme() { return this.currentIconTheme; } public setFileIconTheme(iconTheme: string | undefined, settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IFileIconTheme> { iconTheme = iconTheme || ''; if (iconTheme === this.currentIconTheme.id && this.currentIconTheme.isLoaded) { return this.writeFileIconConfiguration(settingsTarget); } let onApply = (newIconTheme: FileIconThemeData) => { this.doSetFileIconTheme(newIconTheme); // remember theme data for a quick restore if (newIconTheme.isLoaded) { this.storageService.store(PERSISTED_ICON_THEME_STORAGE_KEY, newIconTheme.toStorageData(), StorageScope.GLOBAL); } return this.writeFileIconConfiguration(settingsTarget); }; return this.iconThemeStore.findThemeData(iconTheme).then(data => { const iconThemeData = data || FileIconThemeData.noIconTheme(); return iconThemeData.ensureLoaded(this.fileService).then(_ => { return _applyIconTheme(iconThemeData, onApply); }); }); } public restoreFileIconTheme() { let fileIconThemeSetting = this.configurationService.getValue<string | null>(ICON_THEME_SETTING); if (fileIconThemeSetting !== this.currentIconTheme.settingsId) { this.iconThemeStore.findThemeBySettingsId(fileIconThemeSetting).then(theme => { if (theme) { this.setFileIconTheme(theme.id, undefined); } }); } } private doSetFileIconTheme(iconThemeData: FileIconThemeData): void { this.currentIconTheme = iconThemeData; if (this.container) { if (iconThemeData.id) { addClasses(this.container, fileIconsEnabledClass); } else { removeClasses(this.container, fileIconsEnabledClass); } } if (this.fileService && !resources.isEqual(iconThemeData.location, this.watchedIconThemeLocation)) { if (this.watchedIconThemeLocation) { this.fileService.unwatch(this.watchedIconThemeLocation); this.watchedIconThemeLocation = undefined; } if (iconThemeData.location && (iconThemeData.watch || !!this.environmentService.extensionDevelopmentLocationURI)) { this.watchedIconThemeLocation = iconThemeData.location; this.fileService.watch(this.watchedIconThemeLocation); } } if (iconThemeData.id) { this.sendTelemetry(iconThemeData.id, iconThemeData.extensionData, 'fileIcon'); } this.onFileIconThemeChange.fire(this.currentIconTheme); } private writeFileIconConfiguration(settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IFileIconTheme> { if (!types.isUndefinedOrNull(settingsTarget)) { return this.writeConfiguration(ICON_THEME_SETTING, this.currentIconTheme.settingsId, settingsTarget).then(_ => this.currentIconTheme); } return Promise.resolve(this.currentIconTheme); } public writeConfiguration(key: string, value: any, settingsTarget: ConfigurationTarget | 'auto'): Promise<void> { let settings = this.configurationService.inspect(key); if (settingsTarget === 'auto') { if (!types.isUndefined(settings.workspaceFolder)) { settingsTarget = ConfigurationTarget.WORKSPACE_FOLDER; } else if (!types.isUndefined(settings.workspace)) { settingsTarget = ConfigurationTarget.WORKSPACE; } else { settingsTarget = ConfigurationTarget.USER; } } if (settingsTarget === ConfigurationTarget.USER) { if (value === settings.user) { return Promise.resolve(undefined); // nothing to do } else if (value === settings.default) { if (types.isUndefined(settings.user)) { return Promise.resolve(undefined); // nothing to do } value = undefined; // remove configuration from user settings } } else if (settingsTarget === ConfigurationTarget.WORKSPACE || settingsTarget === ConfigurationTarget.WORKSPACE_FOLDER) { if (value === settings.value) { return Promise.resolve(undefined); // nothing to do } } return this.configurationService.updateValue(key, value, settingsTarget); } private getBaseThemeFromContainer() { if (this.container) { for (let i = this.container.classList.length - 1; i >= 0; i--) { const item = document.body.classList.item(i); if (item === VS_LIGHT_THEME || item === VS_DARK_THEME || item === VS_HC_THEME) { return item; } } } return VS_DARK_THEME; } } function _applyIconTheme(data: FileIconThemeData, onApply: (theme: FileIconThemeData) => Promise<IFileIconTheme>): Promise<IFileIconTheme> { _applyRules(data.styleSheetContent!, iconThemeRulesClassName); return onApply(data); } function _applyRules(styleSheetContent: string, rulesClassName: string) { let themeStyles = document.head.getElementsByClassName(rulesClassName); if (themeStyles.length === 0) { let elStyle = document.createElement('style'); elStyle.type = 'text/css'; elStyle.className = rulesClassName; elStyle.innerHTML = styleSheetContent; document.head.appendChild(elStyle); } else { (<HTMLStyleElement>themeStyles[0]).innerHTML = styleSheetContent; } } registerColorThemeSchemas(); registerFileIconThemeSchemas(); // Configuration: Themes const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); const colorThemeSettingSchema: IConfigurationPropertySchema = { type: 'string', description: nls.localize('colorTheme', "Specifies the color theme used in the workbench."), default: DEFAULT_THEME_SETTING_VALUE, enum: [], enumDescriptions: [], errorMessage: nls.localize('colorThemeError', "Theme is unknown or not installed."), }; const iconThemeSettingSchema: IConfigurationPropertySchema = { type: ['string', 'null'], default: DEFAULT_ICON_THEME_SETTING_VALUE, description: nls.localize('iconTheme', "Specifies the icon theme used in the workbench or 'null' to not show any file icons."), enum: [null], enumDescriptions: [nls.localize('noIconThemeDesc', 'No file icons')], errorMessage: nls.localize('iconThemeError', "File icon theme is unknown or not installed.") }; const colorCustomizationsSchema: IConfigurationPropertySchema = { type: 'object', description: nls.localize('workbenchColors', "Overrides colors from the currently selected color theme."), allOf: [{ $ref: workbenchColorsSchemaId }], default: {}, defaultSnippets: [{ body: { } }] }; const themeSettingsConfiguration: IConfigurationNode = { id: 'workbench', order: 7.1, type: 'object', properties: { [COLOR_THEME_SETTING]: colorThemeSettingSchema, [ICON_THEME_SETTING]: iconThemeSettingSchema, [CUSTOM_WORKBENCH_COLORS_SETTING]: colorCustomizationsSchema } }; configurationRegistry.registerConfiguration(themeSettingsConfiguration); function tokenGroupSettings(description: string) { return { description, default: '#FF0000', anyOf: [ { type: 'string', format: 'color-hex' }, { $ref: textmateColorSettingsSchemaId } ] }; } const tokenColorSchema: IJSONSchema = { properties: { comments: tokenGroupSettings(nls.localize('editorColors.comments', "Sets the colors and styles for comments")), strings: tokenGroupSettings(nls.localize('editorColors.strings', "Sets the colors and styles for strings literals.")), keywords: tokenGroupSettings(nls.localize('editorColors.keywords', "Sets the colors and styles for keywords.")), numbers: tokenGroupSettings(nls.localize('editorColors.numbers', "Sets the colors and styles for number literals.")), types: tokenGroupSettings(nls.localize('editorColors.types', "Sets the colors and styles for type declarations and references.")), functions: tokenGroupSettings(nls.localize('editorColors.functions', "Sets the colors and styles for functions declarations and references.")), variables: tokenGroupSettings(nls.localize('editorColors.variables', "Sets the colors and styles for variables declarations and references.")), textMateRules: { description: nls.localize('editorColors.textMateRules', 'Sets colors and styles using textmate theming rules (advanced).'), $ref: textmateColorsSchemaId } } }; const tokenColorCustomizationSchema: IConfigurationPropertySchema = { description: nls.localize('editorColors', "Overrides editor colors and font style from the currently selected color theme."), default: {}, allOf: [tokenColorSchema] }; const tokenColorCustomizationConfiguration: IConfigurationNode = { id: 'editor', order: 7.2, type: 'object', properties: { [CUSTOM_EDITOR_COLORS_SETTING]: tokenColorCustomizationSchema } }; configurationRegistry.registerConfiguration(tokenColorCustomizationConfiguration); registerSingleton(IWorkbenchThemeService, WorkbenchThemeService);
src/vs/workbench/services/themes/browser/workbenchThemeService.ts
0
https://github.com/microsoft/vscode/commit/ff47259fd8ba2236439725017cd2af4a11b15d1a
[ 0.008597352541983128, 0.000317379308398813, 0.0001652771170483902, 0.00017357608885504305, 0.000998141011223197 ]
{ "id": 0, "code_window": [ " },\n", " Edit: {\n", " General: {\n", " headerLink: 'Variable editor Header link',\n", " modeLabelNew: 'Variable editor Header mode New',\n", " modeLabelEdit: 'Variable editor Header mode Edit',\n", " generalNameInput: 'Variable editor Form Name field',\n", " generalTypeSelect: 'Variable editor Form Type select',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * @deprecated\n", " */\n" ], "file_path": "packages/grafana-e2e-selectors/src/selectors/pages.ts", "type": "add", "edit_start_line_idx": 90 }
import React, { HTMLAttributes } from 'react'; import { Label } from './Label'; import { stylesFactory, useTheme2 } from '../../themes'; import { css, cx } from '@emotion/css'; import { GrafanaTheme2 } from '@grafana/data'; import { FieldValidationMessage } from './FieldValidationMessage'; import { getChildId } from '../../utils/children'; export interface FieldProps extends HTMLAttributes<HTMLDivElement> { /** Form input element, i.e Input or Switch */ children: React.ReactElement; /** Label for the field */ label?: React.ReactNode; /** Description of the field */ description?: React.ReactNode; /** Indicates if field is in invalid state */ invalid?: boolean; /** Indicates if field is in loading state */ loading?: boolean; /** Indicates if field is disabled */ disabled?: boolean; /** Indicates if field is required */ required?: boolean; /** Error message to display */ error?: string | null; /** Indicates horizontal layout of the field */ horizontal?: boolean; /** make validation message overflow horizontally. Prevents pushing out adjacent inline components */ validationMessageHorizontalOverflow?: boolean; className?: string; } export const getFieldStyles = stylesFactory((theme: GrafanaTheme2) => { return { field: css` display: flex; flex-direction: column; margin-bottom: ${theme.spacing(2)}; `, fieldHorizontal: css` flex-direction: row; justify-content: space-between; flex-wrap: wrap; `, fieldValidationWrapper: css` margin-top: ${theme.spacing(0.5)}; `, fieldValidationWrapperHorizontal: css` flex: 1 1 100%; `, validationMessageHorizontalOverflow: css` width: 0; overflow-x: visible; & > * { white-space: nowrap; } `, }; }); export const Field: React.FC<FieldProps> = ({ label, description, horizontal, invalid, loading, disabled, required, error, children, className, validationMessageHorizontalOverflow, ...otherProps }) => { const theme = useTheme2(); const styles = getFieldStyles(theme); const inputId = getChildId(children); const labelElement = typeof label === 'string' ? ( <Label htmlFor={inputId} description={description}> {`${label}${required ? ' *' : ''}`} </Label> ) : ( label ); return ( <div className={cx(styles.field, horizontal && styles.fieldHorizontal, className)} {...otherProps}> {labelElement} <div> {React.cloneElement(children, { invalid, disabled, loading })} {invalid && error && !horizontal && ( <div className={cx(styles.fieldValidationWrapper, { [styles.validationMessageHorizontalOverflow]: !!validationMessageHorizontalOverflow, })} > <FieldValidationMessage>{error}</FieldValidationMessage> </div> )} </div> {invalid && error && horizontal && ( <div className={cx(styles.fieldValidationWrapper, styles.fieldValidationWrapperHorizontal, { [styles.validationMessageHorizontalOverflow]: !!validationMessageHorizontalOverflow, })} > <FieldValidationMessage>{error}</FieldValidationMessage> </div> )} </div> ); };
packages/grafana-ui/src/components/Forms/Field.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017729234241414815, 0.00017108242900576442, 0.00016256317030638456, 0.00017207770724780858, 0.000003692435257107718 ]
{ "id": 0, "code_window": [ " },\n", " Edit: {\n", " General: {\n", " headerLink: 'Variable editor Header link',\n", " modeLabelNew: 'Variable editor Header mode New',\n", " modeLabelEdit: 'Variable editor Header mode Edit',\n", " generalNameInput: 'Variable editor Form Name field',\n", " generalTypeSelect: 'Variable editor Form Type select',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * @deprecated\n", " */\n" ], "file_path": "packages/grafana-e2e-selectors/src/selectors/pages.ts", "type": "add", "edit_start_line_idx": 90 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generated by IcoMoon.io --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="12" height="32" viewBox="0 0 12 32"> <g id="icomoon-ignore"> </g> <path d="M0 2h4v4h-4v-4z" fill="#CCC"></path> <path d="M0 10h4v4h-4v-4z" fill="#CCC"></path> <path d="M0 18h4v4h-4v-4z" fill="#CCC"></path> <path d="M0 26h4v4h-4v-4z" fill="#CCC"></path> <path d="M8 2h4v4h-4v-4z" fill="#CCC"></path> <path d="M8 10h4v4h-4v-4z" fill="#CCC"></path> <path d="M8 18h4v4h-4v-4z" fill="#CCC"></path> <path d="M8 26h4v4h-4v-4z" fill="#CCC"></path> </svg>
public/img/grab_light.svg
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001731444790493697, 0.00017283332999795675, 0.00017252219549845904, 0.00017283332999795675, 3.1114177545532584e-7 ]
{ "id": 0, "code_window": [ " },\n", " Edit: {\n", " General: {\n", " headerLink: 'Variable editor Header link',\n", " modeLabelNew: 'Variable editor Header mode New',\n", " modeLabelEdit: 'Variable editor Header mode Edit',\n", " generalNameInput: 'Variable editor Form Name field',\n", " generalTypeSelect: 'Variable editor Form Type select',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * @deprecated\n", " */\n" ], "file_path": "packages/grafana-e2e-selectors/src/selectors/pages.ts", "type": "add", "edit_start_line_idx": 90 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28.5 20"> <circle cx="14.17" cy="2.67" r="2.67" /> <circle cx="25.83" cy="17.33" r="2.67" /> <rect x="19.25" y="-1.21" width="1.5" height="22.42" transform="translate(-1.79 15.03) rotate(-39.57)" /> <circle cx="2.67" cy="17.33" r="2.67" /> <rect x="-2.71" y="9.25" width="22.42" height="1.5" transform="translate(-4.62 10.18) rotate(-50.44)" /> </svg>
public/img/icons/custom/gf-interpolation-linear.svg
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017340105841867626, 0.00017340105841867626, 0.00017340105841867626, 0.00017340105841867626, 0 ]
{ "id": 0, "code_window": [ " },\n", " Edit: {\n", " General: {\n", " headerLink: 'Variable editor Header link',\n", " modeLabelNew: 'Variable editor Header mode New',\n", " modeLabelEdit: 'Variable editor Header mode Edit',\n", " generalNameInput: 'Variable editor Form Name field',\n", " generalTypeSelect: 'Variable editor Form Type select',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * @deprecated\n", " */\n" ], "file_path": "packages/grafana-e2e-selectors/src/selectors/pages.ts", "type": "add", "edit_start_line_idx": 90 }
import { prompt } from 'inquirer'; import path from 'path'; import { promptConfirm } from '../utils/prompt'; import { fetchTemplate, formatPluginDetails, getPluginIdFromName, prepareJsonFiles, printGrafanaTutorialsDetails, promptPluginDetails, promptPluginType, removeGitFiles, verifyGitExists, } from './plugin/create'; import { Task, TaskRunner } from './task'; interface PluginCreateOptions { name?: string; } const pluginCreateRunner: TaskRunner<PluginCreateOptions> = async ({ name }) => { const destPath = path.resolve(process.cwd(), getPluginIdFromName(name || '')); let pluginDetails; // 1. Verifying if git exists in user's env as templates are cloned from git templates await verifyGitExists(); // 2. Prompt plugin template const { type } = await promptPluginType(); // 3. Fetch plugin template from GitHub await fetchTemplate({ type, dest: destPath }); // 4. Prompt plugin details do { pluginDetails = await promptPluginDetails(name); formatPluginDetails(pluginDetails); } while ((await prompt<{ confirm: boolean }>(promptConfirm('confirm', 'Is that ok?'))).confirm === false); // 5. Update json files (package.json, src/plugin.json) await prepareJsonFiles({ type: type, pluginDetails, pluginPath: destPath }); // 6. Remove cloned repository .git dir await removeGitFiles(destPath); // 7. Promote Grafana Tutorials :) printGrafanaTutorialsDetails(type); }; export const pluginCreateTask = new Task<PluginCreateOptions>('plugin:create task', pluginCreateRunner);
packages/grafana-toolkit/src/cli/tasks/plugin.create.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017693667905405164, 0.00017268590454477817, 0.00016842551121953875, 0.00017278992163483053, 0.000002851307499440736 ]
{ "id": 1, "code_window": [ " validationMessageHorizontalOverflow?: boolean;\n", "\n", " className?: string;\n", "}\n", "\n", "export const getFieldStyles = stylesFactory((theme: GrafanaTheme2) => {\n", " return {\n", " field: css`\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * A unique id that associates the label of the Field component with the control with the unique id.\n", " * If the `htmlFor` property is missing the `htmlFor` will be inferred from the `id` or `inputId` property of the first child.\n", " * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#attr-for\n", " */\n", " htmlFor?: string;\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "add", "edit_start_line_idx": 31 }
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 source settings page Save and Test button', alert: 'Data source settings page Alert', }, DataSources: { url: '/datasources', dataSources: (dataSourceName: string) => `Data source list item ${dataSourceName}`, }, AddDataSource: { url: '/datasources/new', dataSourcePlugins: (pluginName: string) => `Data source plugin item ${pluginName}`, }, ConfirmModal: { delete: 'Confirm Modal Danger Button', }, AddDashboard: { url: '/dashboard/new', addNewPanel: 'Add new panel', addNewRow: 'Add new row', addNewPanelLibrary: 'Add new panel from panel library', }, Dashboard: { url: (uid: string) => `/d/${uid}`, DashNav: { nav: 'Dashboard navigation', }, 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}`, }, Settings: { 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', timezone: 'Time zone picker select container', title: 'Dashboard settings page title', }, Annotations: { List: { addAnnotationCTA: Components.CallToActionCard.button('Add annotation query'), }, Settings: { name: 'Annotations settings name input', }, }, Variables: { List: { addVariableCTA: Components.CallToActionCard.button('Add variable'), newButton: 'Variable editor New variable button', table: 'Variable editor Table', tableRowNameFields: (variableName: string) => `Variable editor Table Name field ${variableName}`, tableRowDefinitionFields: (variableName: string) => `Variable editor Table Definition 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', modeLabelEdit: 'Variable editor Header mode Edit', generalNameInput: 'Variable editor Form Name field', generalTypeSelect: 'Variable editor Form Type select', generalLabelInput: 'Variable editor Form Label field', generalHideSelect: 'Variable editor Form Hide select', selectionOptionsMultiSwitch: 'Variable editor Form Multi switch', selectionOptionsIncludeAllSwitch: 'Variable editor Form IncludeAll switch', selectionOptionsCustomAllInput: 'Variable editor Form IncludeAll field', previewOfValuesOption: 'Variable editor Preview of Values option', submitButton: 'Variable editor Submit button', }, QueryVariable: { queryOptionsDataSourceSelect: Components.DataSourcePicker.container, queryOptionsRefreshSelect: 'Variable editor Form Query Refresh select', queryOptionsRegExInput: 'Variable editor Form Query RegEx field', queryOptionsSortSelect: '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', }, TextBoxVariable: { textBoxOptionsQueryInput: 'Variable editor Form TextBox Query field', }, }, }, }, }, Dashboards: { url: '/dashboards', 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', }, Explore: { url: '/explore', General: { container: 'data-testid Explore', graph: 'Explore Graph', table: 'Explore Table', scrollBar: () => '.scrollbar-view', }, Toolbar: { navBar: () => '.explore-toolbar', }, }, 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', itemRow: 'Playlist item row', itemIdType: 'Playlist item dashboard by ID type', itemTagType: 'Playlist item dashboard by Tag type', itemMoveUp: 'Move playlist item order up', itemMoveDown: 'Move playlist item order down', itemDelete: 'Delete playlist item', }, };
packages/grafana-e2e-selectors/src/selectors/pages.ts
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017670603119768202, 0.00017109615146182477, 0.00016454921569675207, 0.00017085975559893996, 0.0000034208073884656187 ]
{ "id": 1, "code_window": [ " validationMessageHorizontalOverflow?: boolean;\n", "\n", " className?: string;\n", "}\n", "\n", "export const getFieldStyles = stylesFactory((theme: GrafanaTheme2) => {\n", " return {\n", " field: css`\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * A unique id that associates the label of the Field component with the control with the unique id.\n", " * If the `htmlFor` property is missing the `htmlFor` will be inferred from the `id` or `inputId` property of the first child.\n", " * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#attr-for\n", " */\n", " htmlFor?: string;\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "add", "edit_start_line_idx": 31 }
import { AnyAction } from 'redux'; import { getRootReducer, getTemplatingRootReducer, RootReducerType, TemplatingReducerType } from './helpers'; import { variableAdapters } from '../adapters'; import { createQueryVariableAdapter } from '../query/adapter'; import { createCustomVariableAdapter } from '../custom/adapter'; import { createTextBoxVariableAdapter } from '../textbox/adapter'; import { createConstantVariableAdapter } from '../constant/adapter'; import { reduxTester } from '../../../../test/core/redux/reduxTester'; import { TemplatingState } from 'app/features/variables/state/reducers'; import { cancelVariables, changeVariableMultiValue, cleanUpVariables, fixSelectedInconsistency, initDashboardTemplating, initVariablesTransaction, isVariableUrlValueDifferentFromCurrent, processVariables, validateVariableSelectionState, } from './actions'; import { addVariable, changeVariableProp, removeVariable, setCurrentVariableValue, variableStateCompleted, variableStateFetching, variableStateNotStarted, } from './sharedReducer'; import { ALL_VARIABLE_TEXT, ALL_VARIABLE_VALUE, NEW_VARIABLE_ID, toVariableIdentifier, toVariablePayload, } from './types'; import { constantBuilder, customBuilder, datasourceBuilder, queryBuilder, textboxBuilder, } from '../shared/testing/builders'; import { changeVariableName } from '../editor/actions'; import { changeVariableNameFailed, changeVariableNameSucceeded, cleanEditorState, initialVariableEditorState, setIdInEditor, } from '../editor/reducer'; import { TransactionStatus, variablesClearTransaction, variablesCompleteTransaction, variablesInitTransaction, } from './transactionReducer'; import { cleanPickerState, initialState } from '../pickers/OptionsPicker/reducer'; import { cleanVariables } from './variablesReducer'; import { expect } from '../../../../test/lib/common'; import { ConstantVariableModel, VariableRefresh } from '../types'; import { updateVariableOptions } from '../query/reducer'; import { setVariableQueryRunner, VariableQueryRunner } from '../query/VariableQueryRunner'; import { setDataSourceSrv, setLocationService } from '@grafana/runtime'; import { LoadingState } from '@grafana/data'; import { toAsyncOfResult } from '../../query/state/DashboardQueryRunner/testHelpers'; variableAdapters.setInit(() => [ createQueryVariableAdapter(), createCustomVariableAdapter(), createTextBoxVariableAdapter(), createConstantVariableAdapter(), ]); const metricFindQuery = jest .fn() .mockResolvedValueOnce([{ text: 'responses' }, { text: 'timers' }]) .mockResolvedValue([{ text: '200' }, { text: '500' }]); const getMetricSources = jest.fn().mockReturnValue([]); const getDatasource = jest.fn().mockResolvedValue({ metricFindQuery }); jest.mock('app/features/dashboard/services/TimeSrv', () => ({ getTimeSrv: () => ({ timeRange: jest.fn().mockReturnValue(undefined), }), })); setDataSourceSrv({ get: getDatasource, getList: getMetricSources, } as any); describe('shared actions', () => { describe('when initDashboardTemplating is dispatched', () => { it('then correct actions are dispatched', () => { const query = queryBuilder().build(); const constant = constantBuilder().build(); const datasource = datasourceBuilder().build(); const custom = customBuilder().build(); const textbox = textboxBuilder().build(); const list = [query, constant, datasource, custom, textbox]; reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(initDashboardTemplating(list)) .thenDispatchedActionsPredicateShouldEqual((dispatchedActions) => { expect(dispatchedActions.length).toEqual(8); expect(dispatchedActions[0]).toEqual( addVariable(toVariablePayload(query, { global: false, index: 0, model: query })) ); expect(dispatchedActions[1]).toEqual( addVariable(toVariablePayload(constant, { global: false, index: 1, model: constant })) ); expect(dispatchedActions[2]).toEqual( addVariable(toVariablePayload(custom, { global: false, index: 2, model: custom })) ); expect(dispatchedActions[3]).toEqual( addVariable(toVariablePayload(textbox, { global: false, index: 3, model: textbox })) ); // because uuid are dynamic we need to get the uuid from the resulting state // an alternative would be to add our own uuids in the model above instead expect(dispatchedActions[4]).toEqual( variableStateNotStarted(toVariablePayload({ ...query, id: dispatchedActions[4].payload.id })) ); expect(dispatchedActions[5]).toEqual( variableStateNotStarted(toVariablePayload({ ...constant, id: dispatchedActions[5].payload.id })) ); expect(dispatchedActions[6]).toEqual( variableStateNotStarted(toVariablePayload({ ...custom, id: dispatchedActions[6].payload.id })) ); expect(dispatchedActions[7]).toEqual( variableStateNotStarted(toVariablePayload({ ...textbox, id: dispatchedActions[7].payload.id })) ); return true; }); }); }); describe('when processVariables is dispatched', () => { it('then correct actions are dispatched', async () => { const query = queryBuilder().build(); const constant = constantBuilder().build(); const datasource = datasourceBuilder().build(); const custom = customBuilder().build(); const textbox = textboxBuilder().build(); const list = [query, constant, datasource, custom, textbox]; const preloadedState = { templating: ({} as unknown) as TemplatingState, }; const locationService: any = { getSearchObject: () => ({}) }; setLocationService(locationService); const variableQueryRunner: any = { cancelRequest: jest.fn(), queueRequest: jest.fn(), getResponse: () => toAsyncOfResult({ state: LoadingState.Done, identifier: toVariableIdentifier(query) }), destroy: jest.fn(), }; setVariableQueryRunner(variableQueryRunner); const tester = await reduxTester<TemplatingReducerType>({ preloadedState }) .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(variablesInitTransaction({ uid: '' })) .whenActionIsDispatched(initDashboardTemplating(list)) .whenAsyncActionIsDispatched(processVariables(), true); await tester.thenDispatchedActionsPredicateShouldEqual((dispatchedActions) => { expect(dispatchedActions.length).toEqual(5); expect(dispatchedActions[0]).toEqual( variableStateFetching(toVariablePayload({ ...query, id: dispatchedActions[0].payload.id })) ); expect(dispatchedActions[1]).toEqual( variableStateCompleted(toVariablePayload({ ...constant, id: dispatchedActions[1].payload.id })) ); expect(dispatchedActions[2]).toEqual( variableStateCompleted(toVariablePayload({ ...custom, id: dispatchedActions[2].payload.id })) ); expect(dispatchedActions[3]).toEqual( variableStateCompleted(toVariablePayload({ ...textbox, id: dispatchedActions[3].payload.id })) ); expect(dispatchedActions[4]).toEqual( variableStateCompleted(toVariablePayload({ ...query, id: dispatchedActions[4].payload.id })) ); return true; }); }); // Fix for https://github.com/grafana/grafana/issues/28791 it('fix for https://github.com/grafana/grafana/issues/28791', async () => { setVariableQueryRunner(new VariableQueryRunner()); const stats = queryBuilder() .withId('stats') .withName('stats') .withQuery('stats.*') .withRefresh(VariableRefresh.onDashboardLoad) .withCurrent(['response'], ['response']) .withMulti() .withIncludeAll() .build(); const substats = queryBuilder() .withId('substats') .withName('substats') .withQuery('stats.$stats.*') .withRefresh(VariableRefresh.onDashboardLoad) .withCurrent([ALL_VARIABLE_TEXT], [ALL_VARIABLE_VALUE]) .withMulti() .withIncludeAll() .build(); const list = [stats, substats]; const query = { orgId: '1', 'var-stats': 'response', 'var-substats': ALL_VARIABLE_TEXT }; const locationService: any = { getSearchObject: () => query }; setLocationService(locationService); const preloadedState = { templating: ({} as unknown) as TemplatingState, }; const tester = await reduxTester<TemplatingReducerType>({ preloadedState }) .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(variablesInitTransaction({ uid: '' })) .whenActionIsDispatched(initDashboardTemplating(list)) .whenAsyncActionIsDispatched(processVariables(), true); await tester.thenDispatchedActionsShouldEqual( variableStateFetching(toVariablePayload(stats)), updateVariableOptions( toVariablePayload(stats, { results: [{ text: 'responses' }, { text: 'timers' }], templatedRegex: '' }) ), setCurrentVariableValue( toVariablePayload(stats, { option: { text: ALL_VARIABLE_TEXT, value: ALL_VARIABLE_VALUE, selected: false } }) ), variableStateCompleted(toVariablePayload(stats)), setCurrentVariableValue( toVariablePayload(stats, { option: { text: ['response'], value: ['response'], selected: false } }) ), variableStateFetching(toVariablePayload(substats)), updateVariableOptions( toVariablePayload(substats, { results: [{ text: '200' }, { text: '500' }], templatedRegex: '' }) ), setCurrentVariableValue( toVariablePayload(substats, { option: { text: [ALL_VARIABLE_TEXT], value: [ALL_VARIABLE_VALUE], selected: true }, }) ), variableStateCompleted(toVariablePayload(substats)), setCurrentVariableValue( toVariablePayload(substats, { option: { text: [ALL_VARIABLE_TEXT], value: [ALL_VARIABLE_VALUE], selected: false }, }) ) ); }); }); describe('when validateVariableSelectionState is dispatched with a custom variable (no dependencies)', () => { describe('and not multivalue', () => { it.each` withOptions | withCurrent | defaultValue | expected ${['A', 'B', 'C']} | ${undefined} | ${undefined} | ${'A'} ${['A', 'B', 'C']} | ${'B'} | ${undefined} | ${'B'} ${['A', 'B', 'C']} | ${'B'} | ${'C'} | ${'B'} ${['A', 'B', 'C']} | ${'X'} | ${undefined} | ${'A'} ${['A', 'B', 'C']} | ${'X'} | ${'C'} | ${'C'} ${undefined} | ${'B'} | ${undefined} | ${'should not dispatch setCurrentVariableValue'} `('then correct actions are dispatched', async ({ withOptions, withCurrent, defaultValue, expected }) => { let custom; if (!withOptions) { custom = customBuilder().withId('0').withCurrent(withCurrent).withoutOptions().build(); } else { custom = customBuilder() .withId('0') .withOptions(...withOptions) .withCurrent(withCurrent) .build(); } const tester = await reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(custom, { global: false, index: 0, model: custom }))) .whenAsyncActionIsDispatched( validateVariableSelectionState(toVariableIdentifier(custom), defaultValue), true ); await tester.thenDispatchedActionsPredicateShouldEqual((dispatchedActions) => { const expectedActions: AnyAction[] = !withOptions ? [] : [ setCurrentVariableValue( toVariablePayload( { type: 'custom', id: '0' }, { option: { text: expected, value: expected, selected: false } } ) ), ]; expect(dispatchedActions).toEqual(expectedActions); return true; }); }); }); describe('and multivalue', () => { it.each` withOptions | withCurrent | defaultValue | expectedText | expectedSelected ${['A', 'B', 'C']} | ${['B']} | ${undefined} | ${['B']} | ${true} ${['A', 'B', 'C']} | ${['B']} | ${'C'} | ${['B']} | ${true} ${['A', 'B', 'C']} | ${['B', 'C']} | ${undefined} | ${['B', 'C']} | ${true} ${['A', 'B', 'C']} | ${['B', 'C']} | ${'C'} | ${['B', 'C']} | ${true} ${['A', 'B', 'C']} | ${['X']} | ${undefined} | ${'A'} | ${false} ${['A', 'B', 'C']} | ${['X']} | ${'C'} | ${'A'} | ${false} `( 'then correct actions are dispatched', async ({ withOptions, withCurrent, defaultValue, expectedText, expectedSelected }) => { let custom; if (!withOptions) { custom = customBuilder().withId('0').withMulti().withCurrent(withCurrent).withoutOptions().build(); } else { custom = customBuilder() .withId('0') .withMulti() .withOptions(...withOptions) .withCurrent(withCurrent) .build(); } const tester = await reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(custom, { global: false, index: 0, model: custom }))) .whenAsyncActionIsDispatched( validateVariableSelectionState(toVariableIdentifier(custom), defaultValue), true ); await tester.thenDispatchedActionsPredicateShouldEqual((dispatchedActions) => { const expectedActions: AnyAction[] = !withOptions ? [] : [ setCurrentVariableValue( toVariablePayload( { type: 'custom', id: '0' }, { option: { text: expectedText, value: expectedText, selected: expectedSelected } } ) ), ]; expect(dispatchedActions).toEqual(expectedActions); return true; }); } ); }); }); describe('changeVariableName', () => { describe('when changeVariableName is dispatched with the same name', () => { it('then the correct actions are dispatched', () => { const textbox = textboxBuilder().withId('textbox').withName('textbox').build(); const constant = constantBuilder().withId('constant').withName('constant').build(); reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(textbox, { global: false, index: 0, model: textbox }))) .whenActionIsDispatched( addVariable(toVariablePayload(constant, { global: false, index: 1, model: constant })) ) .whenActionIsDispatched(changeVariableName(toVariableIdentifier(constant), constant.name), true) .thenDispatchedActionsShouldEqual( changeVariableNameSucceeded({ type: 'constant', id: 'constant', data: { newName: 'constant' } }) ); }); }); describe('when changeVariableName is dispatched with an unique name', () => { it('then the correct actions are dispatched', () => { const textbox = textboxBuilder().withId('textbox').withName('textbox').build(); const constant = constantBuilder().withId('constant').withName('constant').build(); reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(textbox, { global: false, index: 0, model: textbox }))) .whenActionIsDispatched( addVariable(toVariablePayload(constant, { global: false, index: 1, model: constant })) ) .whenActionIsDispatched(changeVariableName(toVariableIdentifier(constant), 'constant1'), true) .thenDispatchedActionsShouldEqual( addVariable({ type: 'constant', id: 'constant1', data: { global: false, index: 1, model: { ...constant, name: 'constant1', id: 'constant1', global: false, index: 1, current: { selected: true, text: '', value: '' }, options: [{ selected: true, text: '', value: '' }], } as ConstantVariableModel, }, }), changeVariableNameSucceeded({ type: 'constant', id: 'constant1', data: { newName: 'constant1' } }), setIdInEditor({ id: 'constant1' }), removeVariable({ type: 'constant', id: 'constant', data: { reIndex: false } }) ); }); }); describe('when changeVariableName is dispatched with an unique name for a new variable', () => { it('then the correct actions are dispatched', () => { const textbox = textboxBuilder().withId('textbox').withName('textbox').build(); const constant = constantBuilder().withId(NEW_VARIABLE_ID).withName('constant').build(); reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(textbox, { global: false, index: 0, model: textbox }))) .whenActionIsDispatched( addVariable(toVariablePayload(constant, { global: false, index: 1, model: constant })) ) .whenActionIsDispatched(changeVariableName(toVariableIdentifier(constant), 'constant1'), true) .thenDispatchedActionsShouldEqual( addVariable({ type: 'constant', id: 'constant1', data: { global: false, index: 1, model: { ...constant, name: 'constant1', id: 'constant1', global: false, index: 1, current: { selected: true, text: '', value: '' }, options: [{ selected: true, text: '', value: '' }], } as ConstantVariableModel, }, }), changeVariableNameSucceeded({ type: 'constant', id: 'constant1', data: { newName: 'constant1' } }), setIdInEditor({ id: 'constant1' }), removeVariable({ type: 'constant', id: NEW_VARIABLE_ID, data: { reIndex: false } }) ); }); }); describe('when changeVariableName is dispatched with __newName', () => { it('then the correct actions are dispatched', () => { const textbox = textboxBuilder().withId('textbox').withName('textbox').build(); const constant = constantBuilder().withId('constant').withName('constant').build(); reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(textbox, { global: false, index: 0, model: textbox }))) .whenActionIsDispatched( addVariable(toVariablePayload(constant, { global: false, index: 1, model: constant })) ) .whenActionIsDispatched(changeVariableName(toVariableIdentifier(constant), '__newName'), true) .thenDispatchedActionsShouldEqual( changeVariableNameFailed({ newName: '__newName', errorText: "Template names cannot begin with '__', that's reserved for Grafana's global variables", }) ); }); }); describe('when changeVariableName is dispatched with illegal characters', () => { it('then the correct actions are dispatched', () => { const textbox = textboxBuilder().withId('textbox').withName('textbox').build(); const constant = constantBuilder().withId('constant').withName('constant').build(); reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(textbox, { global: false, index: 0, model: textbox }))) .whenActionIsDispatched( addVariable(toVariablePayload(constant, { global: false, index: 1, model: constant })) ) .whenActionIsDispatched(changeVariableName(toVariableIdentifier(constant), '#constant!'), true) .thenDispatchedActionsShouldEqual( changeVariableNameFailed({ newName: '#constant!', errorText: 'Only word and digit characters are allowed in variable names', }) ); }); }); describe('when changeVariableName is dispatched with a name that is already used', () => { it('then the correct actions are dispatched', () => { const textbox = textboxBuilder().withId('textbox').withName('textbox').build(); const constant = constantBuilder().withId('constant').withName('constant').build(); reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(textbox, { global: false, index: 0, model: textbox }))) .whenActionIsDispatched( addVariable(toVariablePayload(constant, { global: false, index: 1, model: constant })) ) .whenActionIsDispatched(changeVariableName(toVariableIdentifier(constant), 'textbox'), true) .thenDispatchedActionsShouldEqual( changeVariableNameFailed({ newName: 'textbox', errorText: 'Variable with the same name already exists', }) ); }); }); }); describe('changeVariableMultiValue', () => { describe('when changeVariableMultiValue is dispatched for variable with multi enabled', () => { it('then correct actions are dispatched', () => { const custom = customBuilder().withId('custom').withMulti(true).withCurrent(['A'], ['A']).build(); reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(custom, { global: false, index: 0, model: custom }))) .whenActionIsDispatched(changeVariableMultiValue(toVariableIdentifier(custom), false), true) .thenDispatchedActionsShouldEqual( changeVariableProp( toVariablePayload(custom, { propName: 'multi', propValue: false, }) ), changeVariableProp( toVariablePayload(custom, { propName: 'current', propValue: { value: 'A', text: 'A', selected: true, }, }) ) ); }); }); describe('when changeVariableMultiValue is dispatched for variable with multi disabled', () => { it('then correct actions are dispatched', () => { const custom = customBuilder().withId('custom').withMulti(false).withCurrent(['A'], ['A']).build(); reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(addVariable(toVariablePayload(custom, { global: false, index: 0, model: custom }))) .whenActionIsDispatched(changeVariableMultiValue(toVariableIdentifier(custom), true), true) .thenDispatchedActionsShouldEqual( changeVariableProp( toVariablePayload(custom, { propName: 'multi', propValue: true, }) ), changeVariableProp( toVariablePayload(custom, { propName: 'current', propValue: { value: ['A'], text: ['A'], selected: true, }, }) ) ); }); }); }); describe('initVariablesTransaction', () => { const constant = constantBuilder().withId('constant').withName('constant').build(); const templating: any = { list: [constant] }; const uid = 'uid'; const dashboard: any = { title: 'Some dash', uid, templating }; describe('when called and the previous dashboard has completed', () => { it('then correct actions are dispatched', async () => { const tester = await reduxTester<RootReducerType>() .givenRootReducer(getRootReducer()) .whenAsyncActionIsDispatched(initVariablesTransaction(uid, dashboard)); tester.thenDispatchedActionsPredicateShouldEqual((dispatchedActions) => { expect(dispatchedActions[0]).toEqual(variablesInitTransaction({ uid })); expect(dispatchedActions[1].type).toEqual(addVariable.type); expect(dispatchedActions[1].payload.id).toEqual('__dashboard'); expect(dispatchedActions[2].type).toEqual(addVariable.type); expect(dispatchedActions[2].payload.id).toEqual('__org'); expect(dispatchedActions[3].type).toEqual(addVariable.type); expect(dispatchedActions[3].payload.id).toEqual('__user'); expect(dispatchedActions[4]).toEqual( addVariable(toVariablePayload(constant, { global: false, index: 0, model: constant })) ); expect(dispatchedActions[5]).toEqual(variableStateNotStarted(toVariablePayload(constant))); expect(dispatchedActions[6]).toEqual(variableStateCompleted(toVariablePayload(constant))); expect(dispatchedActions[7]).toEqual(variablesCompleteTransaction({ uid })); return dispatchedActions.length === 8; }); }); }); describe('when called and the previous dashboard is still processing variables', () => { it('then correct actions are dispatched', async () => { const transactionState = { uid: 'previous-uid', status: TransactionStatus.Fetching }; const tester = await reduxTester<RootReducerType>({ preloadedState: ({ templating: { transaction: transactionState, variables: {}, optionsPicker: { ...initialState }, editor: { ...initialVariableEditorState }, }, } as unknown) as RootReducerType, }) .givenRootReducer(getRootReducer()) .whenAsyncActionIsDispatched(initVariablesTransaction(uid, dashboard)); tester.thenDispatchedActionsPredicateShouldEqual((dispatchedActions) => { expect(dispatchedActions[0]).toEqual(cleanVariables()); expect(dispatchedActions[1]).toEqual(cleanEditorState()); expect(dispatchedActions[2]).toEqual(cleanPickerState()); expect(dispatchedActions[3]).toEqual(variablesClearTransaction()); expect(dispatchedActions[4]).toEqual(variablesInitTransaction({ uid })); expect(dispatchedActions[5].type).toEqual(addVariable.type); expect(dispatchedActions[5].payload.id).toEqual('__dashboard'); expect(dispatchedActions[6].type).toEqual(addVariable.type); expect(dispatchedActions[6].payload.id).toEqual('__org'); expect(dispatchedActions[7].type).toEqual(addVariable.type); expect(dispatchedActions[7].payload.id).toEqual('__user'); expect(dispatchedActions[8]).toEqual( addVariable(toVariablePayload(constant, { global: false, index: 0, model: constant })) ); expect(dispatchedActions[9]).toEqual(variableStateNotStarted(toVariablePayload(constant))); expect(dispatchedActions[10]).toEqual(variableStateCompleted(toVariablePayload(constant))); expect(dispatchedActions[11]).toEqual(variablesCompleteTransaction({ uid })); return dispatchedActions.length === 12; }); }); }); }); describe('cleanUpVariables', () => { describe('when called', () => { it('then correct actions are dispatched', async () => { reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(cleanUpVariables()) .thenDispatchedActionsShouldEqual( cleanVariables(), cleanEditorState(), cleanPickerState(), variablesClearTransaction() ); }); }); }); describe('cancelVariables', () => { const cancelAllInFlightRequestsMock = jest.fn(); const backendSrvMock: any = { cancelAllInFlightRequests: cancelAllInFlightRequestsMock, }; describe('when called', () => { it('then cancelAllInFlightRequests should be called and correct actions are dispatched', async () => { reduxTester<{ templating: TemplatingState }>() .givenRootReducer(getTemplatingRootReducer()) .whenActionIsDispatched(cancelVariables({ getBackendSrv: () => backendSrvMock })) .thenDispatchedActionsShouldEqual( cleanVariables(), cleanEditorState(), cleanPickerState(), variablesClearTransaction() ); expect(cancelAllInFlightRequestsMock).toHaveBeenCalledTimes(1); }); }); }); describe('fixSelectedInconsistency', () => { describe('when called for a single value variable', () => { describe('and there is an inconsistency between current and selected in options', () => { it('then it should set the correct selected', () => { const variable = customBuilder().withId('custom').withCurrent('A').withOptions('A', 'B', 'C').build(); variable.options[1].selected = true; expect(variable.options).toEqual([ { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: true }, { text: 'C', value: 'C', selected: false }, ]); fixSelectedInconsistency(variable); expect(variable.options).toEqual([ { text: 'A', value: 'A', selected: true }, { text: 'B', value: 'B', selected: false }, { text: 'C', value: 'C', selected: false }, ]); }); }); describe('and there is no matching option in options', () => { it('then the first option should be selected', () => { const variable = customBuilder().withId('custom').withCurrent('A').withOptions('X', 'Y', 'Z').build(); expect(variable.options).toEqual([ { text: 'X', value: 'X', selected: false }, { text: 'Y', value: 'Y', selected: false }, { text: 'Z', value: 'Z', selected: false }, ]); fixSelectedInconsistency(variable); expect(variable.options).toEqual([ { text: 'X', value: 'X', selected: true }, { text: 'Y', value: 'Y', selected: false }, { text: 'Z', value: 'Z', selected: false }, ]); }); }); }); describe('when called for a multi value variable', () => { describe('and there is an inconsistency between current and selected in options', () => { it('then it should set the correct selected', () => { const variable = customBuilder().withId('custom').withCurrent(['A', 'C']).withOptions('A', 'B', 'C').build(); variable.options[1].selected = true; expect(variable.options).toEqual([ { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: true }, { text: 'C', value: 'C', selected: false }, ]); fixSelectedInconsistency(variable); expect(variable.options).toEqual([ { text: 'A', value: 'A', selected: true }, { text: 'B', value: 'B', selected: false }, { text: 'C', value: 'C', selected: true }, ]); }); }); describe('and there is no matching option in options', () => { it('then the first option should be selected', () => { const variable = customBuilder().withId('custom').withCurrent(['A', 'C']).withOptions('X', 'Y', 'Z').build(); expect(variable.options).toEqual([ { text: 'X', value: 'X', selected: false }, { text: 'Y', value: 'Y', selected: false }, { text: 'Z', value: 'Z', selected: false }, ]); fixSelectedInconsistency(variable); expect(variable.options).toEqual([ { text: 'X', value: 'X', selected: true }, { text: 'Y', value: 'Y', selected: false }, { text: 'Z', value: 'Z', selected: false }, ]); }); }); }); }); describe('isVariableUrlValueDifferentFromCurrent', () => { describe('when called with a single valued variable', () => { describe('and values are equal', () => { it('then it should return false', () => { const variable = queryBuilder().withMulti(false).withCurrent('A', 'A').build(); const urlValue = 'A'; expect(isVariableUrlValueDifferentFromCurrent(variable, urlValue)).toBe(false); }); }); describe('and values are different', () => { it('then it should return true', () => { const variable = queryBuilder().withMulti(false).withCurrent('A', 'A').build(); const urlValue = 'B'; expect(isVariableUrlValueDifferentFromCurrent(variable, urlValue)).toBe(true); }); }); }); describe('when called with a multi valued variable', () => { describe('and values are equal', () => { it('then it should return false', () => { const variable = queryBuilder().withMulti(true).withCurrent(['A'], ['A']).build(); const urlValue = ['A']; expect(isVariableUrlValueDifferentFromCurrent(variable, urlValue)).toBe(false); }); describe('but urlValue is not an array', () => { it('then it should return false', () => { const variable = queryBuilder().withMulti(true).withCurrent(['A'], ['A']).build(); const urlValue = 'A'; expect(isVariableUrlValueDifferentFromCurrent(variable, urlValue)).toBe(false); }); }); }); describe('and values are different', () => { it('then it should return true', () => { const variable = queryBuilder().withMulti(true).withCurrent(['A'], ['A']).build(); const urlValue = ['C']; expect(isVariableUrlValueDifferentFromCurrent(variable, urlValue)).toBe(true); }); describe('but urlValue is not an array', () => { it('then it should return true', () => { const variable = queryBuilder().withMulti(true).withCurrent(['A'], ['A']).build(); const urlValue = 'C'; expect(isVariableUrlValueDifferentFromCurrent(variable, urlValue)).toBe(true); }); }); }); }); }); });
public/app/features/variables/state/actions.test.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00023754785070195794, 0.00017519232642371207, 0.00017000737716443837, 0.00017442263197153807, 0.000007201503649412189 ]
{ "id": 1, "code_window": [ " validationMessageHorizontalOverflow?: boolean;\n", "\n", " className?: string;\n", "}\n", "\n", "export const getFieldStyles = stylesFactory((theme: GrafanaTheme2) => {\n", " return {\n", " field: css`\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * A unique id that associates the label of the Field component with the control with the unique id.\n", " * If the `htmlFor` property is missing the `htmlFor` will be inferred from the `id` or `inputId` property of the first child.\n", " * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#attr-for\n", " */\n", " htmlFor?: string;\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "add", "edit_start_line_idx": 31 }
+++ title = "Datasource Permissions HTTP API " description = "Data Source Permissions API" keywords = ["grafana", "http", "documentation", "api", "datasource", "permission", "permissions", "acl", "enterprise"] aliases = ["/docs/grafana/latest/http_api/datasourcepermissions/"] +++ # Data Source Permissions API > The Data Source Permissions is only available in Grafana Enterprise. Read more about [Grafana Enterprise]({{< relref "../enterprise" >}}). > If you are running Grafana Enterprise and have [Fine-grained access control]({{< relref "../enterprise/access-control/_index.md" >}}) enabled, for some endpoints you would need to have relevant permissions. > Refer to specific resources to understand what permissions are required. This API can be used to enable, disable, list, add and remove permissions for a data source. Permissions can be set for a user or a team. Permissions cannot be set for Admins - they always have access to everything. The permission levels for the permission field: - 1 = Query ## Enable permissions for a data source `POST /api/datasources/:id/enable-permissions` Enables permissions for the data source with the given `id`. No one except Org Admins will be able to query the data source until permissions have been added which permit certain users or teams to query the data source. ### Required permissions See note in the [introduction]({{< ref "#data-source-permissions-api" >}}) for an explanation. | Action | Scope | | ------------------------------ | ---------------------------------------------------------------------------- | | datasources.permissions:toggle | datasources:\*<br>datasources:id:\*<br>datasources:id:1 (single data source) | ### Examples **Example request:** ```http POST /api/datasources/1/enable-permissions Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk {} ``` **Example response:** ```http HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-8 Content-Length: 35 {"message":"Datasource permissions enabled"} ``` Status codes: - **200** - Ok - **400** - Permissions cannot be enabled, see response body for details - **401** - Unauthorized - **403** - Access denied - **404** - Datasource not found ## Disable permissions for a data source `POST /api/datasources/:id/disable-permissions` Disables permissions for the data source with the given `id`. All existing permissions will be removed and anyone will be able to query the data source. ### Required permissions See note in the [introduction]({{< ref "#data-source-permissions-api" >}}) for an explanation. | Action | Scope | | ------------------------------ | ---------------------------------------------------------------------------- | | datasources.permissions:toggle | datasources:\*<br>datasources:id:\*<br>datasources:id:1 (single data source) | ### Examples **Example request:** ```http POST /api/datasources/1/disable-permissions Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk {} ``` **Example response:** ```http HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-8 Content-Length: 35 {"message":"Datasource permissions disabled"} ``` Status codes: - **200** - Ok - **400** - Permissions cannot be disabled, see response body for details - **401** - Unauthorized - **403** - Access denied - **404** - Datasource not found ## Get permissions for a data source `GET /api/datasources/:id/permissions` Gets all existing permissions for the data source with the given `id`. ### Required permissions See note in the [introduction]({{< ref "#data-source-permissions-api" >}}) for an explanation. | Action | Scope | | ---------------------------- | ---------------------------------------------------------------------------- | | datasources.permissions:read | datasources:\*<br>datasources:id:\*<br>datasources:id:1 (single data source) | ### Examples **Example request:** ```http GET /api/datasources/1/permissions HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk ``` **Example response:** ```http HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-8 Content-Length: 551 { "datasourceId": 1, "enabled": true, "permissions": [ { "id": 1, "datasourceId": 1, "userId": 1, "userLogin": "user", "userEmail": "[email protected]", "userAvatarUrl": "/avatar/46d229b033af06a191ff2267bca9ae56", "permission": 1, "permissionName": "Query", "created": "2017-06-20T02:00:00+02:00", "updated": "2017-06-20T02:00:00+02:00", }, { "id": 2, "datasourceId": 1, "teamId": 1, "team": "A Team", "teamAvatarUrl": "/avatar/46d229b033af06a191ff2267bca9ae56", "permission": 1, "permissionName": "Query", "created": "2017-06-20T02:00:00+02:00", "updated": "2017-06-20T02:00:00+02:00", } ] } ``` Status codes: - **200** - Ok - **401** - Unauthorized - **403** - Access denied - **404** - Datasource not found ## Add permission for a data source `POST /api/datasources/:id/permissions` Adds a user permission for the data source with the given `id`. ### Required permissions See note in the [introduction]({{< ref "#data-source-permissions-api" >}}) for an explanation. | Action | Scope | | ------------------------------ | ---------------------------------------------------------------------------- | | datasources.permissions:create | datasources:\*<br>datasources:id:\*<br>datasources:id:1 (single data source) | ### Examples **Example request:** ```http POST /api/datasources/1/permissions Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk { "userId": 1, "permission": 1 } ``` **Example response:** ```http HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-8 Content-Length: 35 {"message":"Datasource permission added"} ``` Adds a team permission for the data source with the given `id`. **Example request:** ```http POST /api/datasources/1/permissions Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk { "teamId": 1, "permission": 1 } ``` **Example response:** ```http HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-8 Content-Length: 35 {"message":"Datasource permission added"} ``` Status codes: - **200** - Ok - **400** - Permission cannot be added, see response body for details - **401** - Unauthorized - **403** - Access denied - **404** - Datasource not found ## Remove permission for a data source `DELETE /api/datasources/:id/permissions/:permissionId` Removes the permission with the given `permissionId` for the data source with the given `id`. ### Required permissions See note in the [introduction]({{< ref "#data-source-permissions-api" >}}) for an explanation. | Action | Scope | | ------------------------------ | ---------------------------------------------------------------------------- | | datasources.permissions:delete | datasources:\*<br>datasources:id:\*<br>datasources:id:1 (single data source) | ### Examples **Example request:** ```http DELETE /api/datasources/1/permissions/2 Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk ``` **Example response:** ```http HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-8 Content-Length: 35 {"message":"Datasource permission removed"} ``` Status codes: - **200** - Ok - **401** - Unauthorized - **403** - Access denied - **404** - Datasource not found or permission not found
docs/sources/http_api/datasource_permissions.md
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00018441476277075708, 0.00017032926552928984, 0.000162634183652699, 0.0001705562899587676, 0.000004562880349112675 ]
{ "id": 1, "code_window": [ " validationMessageHorizontalOverflow?: boolean;\n", "\n", " className?: string;\n", "}\n", "\n", "export const getFieldStyles = stylesFactory((theme: GrafanaTheme2) => {\n", " return {\n", " field: css`\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * A unique id that associates the label of the Field component with the control with the unique id.\n", " * If the `htmlFor` property is missing the `htmlFor` will be inferred from the `id` or `inputId` property of the first child.\n", " * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#attr-for\n", " */\n", " htmlFor?: string;\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "add", "edit_start_line_idx": 31 }
import { lastValueFrom, Observable, of } from 'rxjs'; import { DataQuery, DataQueryResponse, DataSourceApi, DataSourceInstanceSettings } from '@grafana/data'; import { BackendSrvRequest, getBackendSrv } from '@grafana/runtime'; import { AlertManagerDataSourceJsonData, AlertManagerImplementation } from './types'; export type AlertManagerQuery = { query: string; } & DataQuery; export class AlertManagerDatasource extends DataSourceApi<AlertManagerQuery, AlertManagerDataSourceJsonData> { constructor(public instanceSettings: DataSourceInstanceSettings<AlertManagerDataSourceJsonData>) { super(instanceSettings); } // `query()` has to be implemented but we actually don't use it, just need this // data source to proxy requests. // @ts-ignore query(): Observable<DataQueryResponse> { return of({ data: [], }); } _request(url: string) { const options: BackendSrvRequest = { headers: {}, method: 'GET', url: this.instanceSettings.url + url, }; if (this.instanceSettings.basicAuth || this.instanceSettings.withCredentials) { this.instanceSettings.withCredentials = true; } if (this.instanceSettings.basicAuth) { options.headers!.Authorization = this.instanceSettings.basicAuth; } return lastValueFrom(getBackendSrv().fetch<any>(options)); } async testDatasource() { let alertmanagerResponse; if (this.instanceSettings.jsonData.implementation === AlertManagerImplementation.prometheus) { try { alertmanagerResponse = await this._request('/alertmanager/api/v2/status'); if (alertmanagerResponse && alertmanagerResponse?.status === 200) { return { status: 'error', message: 'It looks like you have chosen Prometheus implementation, but detected a Cortex endpoint. Please update implementation selection and try again.', }; } } catch (e) {} try { alertmanagerResponse = await this._request('/api/v2/status'); } catch (e) {} } else { try { alertmanagerResponse = await this._request('/api/v2/status'); if (alertmanagerResponse && alertmanagerResponse?.status === 200) { return { status: 'error', message: 'It looks like you have chosen Cortex implementation, but detected a Prometheus endpoint. Please update implementation selection and try again.', }; } } catch (e) {} try { alertmanagerResponse = await this._request('/alertmanager/api/v2/status'); } catch (e) {} } return alertmanagerResponse?.status === 200 ? { status: 'success', message: 'Health check passed.', } : { status: 'error', message: 'Health check failed.', }; } }
public/app/plugins/datasource/alertmanager/DataSource.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017794880841393024, 0.0001729572977637872, 0.00016623189731035382, 0.0001733397220959887, 0.000003822400231001666 ]
{ "id": 2, "code_window": [ " children,\n", " className,\n", " validationMessageHorizontalOverflow,\n", " ...otherProps\n", "}) => {\n", " const theme = useTheme2();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " htmlFor,\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "add", "edit_start_line_idx": 74 }
import React, { FormEvent, PureComponent } from 'react'; import { connect, ConnectedProps } from 'react-redux'; import { css } from '@emotion/css'; import { InlineField, InlineFieldRow, VerticalGroup } from '@grafana/ui'; import { selectors } from '@grafana/e2e-selectors'; import { DataSourcePicker, getTemplateSrv } from '@grafana/runtime'; import { DataSourceInstanceSettings, LoadingState, SelectableValue } from '@grafana/data'; import { SelectionOptionsEditor } from '../editor/SelectionOptionsEditor'; import { QueryVariableModel, VariableRefresh, VariableSort, VariableWithMultiSupport } from '../types'; import { QueryVariableEditorState } from './reducer'; import { changeQueryVariableDataSource, changeQueryVariableQuery, initQueryVariableEditor } from './actions'; import { VariableEditorState } from '../editor/reducer'; import { OnPropChangeArguments, VariableEditorProps } from '../editor/types'; import { StoreState } from '../../../types'; import { toVariableIdentifier } from '../state/types'; import { changeVariableMultiValue } from '../state/actions'; import { getTimeSrv } from '../../dashboard/services/TimeSrv'; import { isLegacyQueryEditor, isQueryEditor } from '../guard'; import { VariableSectionHeader } from '../editor/VariableSectionHeader'; import { VariableTextField } from '../editor/VariableTextField'; import { QueryVariableRefreshSelect } from './QueryVariableRefreshSelect'; import { QueryVariableSortSelect } from './QueryVariableSortSelect'; const mapStateToProps = (state: StoreState) => ({ editor: state.templating.editor as VariableEditorState<QueryVariableEditorState>, }); const mapDispatchToProps = { initQueryVariableEditor, changeQueryVariableDataSource, changeQueryVariableQuery, changeVariableMultiValue, }; const connector = connect(mapStateToProps, mapDispatchToProps); export interface OwnProps extends VariableEditorProps<QueryVariableModel> {} export type Props = OwnProps & ConnectedProps<typeof connector>; export interface State { regex: string | null; tagsQuery: string | null; tagValuesQuery: string | null; } export class QueryVariableEditorUnConnected extends PureComponent<Props, State> { state: State = { regex: null, tagsQuery: null, tagValuesQuery: null, }; async componentDidMount() { await this.props.initQueryVariableEditor(toVariableIdentifier(this.props.variable)); } componentDidUpdate(prevProps: Readonly<Props>): void { if (prevProps.variable.datasource !== this.props.variable.datasource) { this.props.changeQueryVariableDataSource( toVariableIdentifier(this.props.variable), this.props.variable.datasource ); } } onDataSourceChange = (dsSettings: DataSourceInstanceSettings) => { this.props.onPropChange({ propName: 'datasource', propValue: dsSettings.isDefault ? null : dsSettings.name, }); }; onLegacyQueryChange = async (query: any, definition: string) => { if (this.props.variable.query !== query) { this.props.changeQueryVariableQuery(toVariableIdentifier(this.props.variable), query, definition); } }; onQueryChange = async (query: any) => { if (this.props.variable.query !== query) { let definition = ''; if (query && query.hasOwnProperty('query') && typeof query.query === 'string') { definition = query.query; } this.props.changeQueryVariableQuery(toVariableIdentifier(this.props.variable), query, definition); } }; onRegExChange = (event: FormEvent<HTMLInputElement>) => { this.setState({ regex: event.currentTarget.value }); }; onRegExBlur = async (event: FormEvent<HTMLInputElement>) => { const regex = event.currentTarget.value; if (this.props.variable.regex !== regex) { this.props.onPropChange({ propName: 'regex', propValue: regex, updateOptions: true }); } }; onRefreshChange = (option: SelectableValue<VariableRefresh>) => { this.props.onPropChange({ propName: 'refresh', propValue: option.value }); }; onSortChange = async (option: SelectableValue<VariableSort>) => { this.props.onPropChange({ propName: 'sort', propValue: option.value, updateOptions: true }); }; onSelectionOptionsChange = async ({ propValue, propName }: OnPropChangeArguments<VariableWithMultiSupport>) => { this.props.onPropChange({ propName, propValue, updateOptions: true }); }; renderQueryEditor = () => { const { editor, variable } = this.props; if (!editor.extended || !editor.extended.dataSource || !editor.extended.VariableQueryEditor) { return null; } const query = variable.query; const datasource = editor.extended.dataSource; const VariableQueryEditor = editor.extended.VariableQueryEditor; if (isLegacyQueryEditor(VariableQueryEditor, datasource)) { return ( <VariableQueryEditor datasource={datasource} query={query} templateSrv={getTemplateSrv()} onChange={this.onLegacyQueryChange} /> ); } const range = getTimeSrv().timeRange(); if (isQueryEditor(VariableQueryEditor, datasource)) { return ( <VariableQueryEditor datasource={datasource} query={query} onChange={this.onQueryChange} onRunQuery={() => {}} data={{ series: [], state: LoadingState.Done, timeRange: range }} range={range} onBlur={() => {}} history={[]} /> ); } return null; }; render() { return ( <VerticalGroup spacing="xs"> <VariableSectionHeader name="Query Options" /> <VerticalGroup spacing="lg"> <VerticalGroup spacing="none"> <InlineFieldRow> <InlineField label="Data source" labelWidth={20}> <DataSourcePicker current={this.props.variable.datasource} onChange={this.onDataSourceChange} variables={true} /> </InlineField> <QueryVariableRefreshSelect onChange={this.onRefreshChange} refresh={this.props.variable.refresh} /> </InlineFieldRow> <div className={css` flex-direction: column; width: 100%; `} > {this.renderQueryEditor()} </div> <VariableTextField value={this.state.regex ?? this.props.variable.regex} name="Regex" placeholder="/.*-(?<text>.*)-(?<value>.*)-.*/" onChange={this.onRegExChange} onBlur={this.onRegExBlur} labelWidth={20} tooltip={ <div> Optional, if you want to extract part of a series name or metric node segment. Named capture groups can be used to separate the display text and value ( <a href="https://grafana.com/docs/grafana/latest/variables/filter-variables-with-regex#filter-and-modify-using-named-text-and-value-capture-groups" target="__blank" > see examples </a> ). </div> } ariaLabel={selectors.pages.Dashboard.Settings.Variables.Edit.QueryVariable.queryOptionsRegExInput} grow /> <QueryVariableSortSelect onChange={this.onSortChange} sort={this.props.variable.sort} /> </VerticalGroup> <SelectionOptionsEditor variable={this.props.variable} onPropChange={this.onSelectionOptionsChange} onMultiChanged={this.props.changeVariableMultiValue} /> </VerticalGroup> </VerticalGroup> ); } } export const QueryVariableEditor = connector(QueryVariableEditorUnConnected);
public/app/features/variables/query/QueryVariableEditor.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00021513353567570448, 0.00017292494885623455, 0.00016394047997891903, 0.00017075976938940585, 0.000009978821253753267 ]
{ "id": 2, "code_window": [ " children,\n", " className,\n", " validationMessageHorizontalOverflow,\n", " ...otherProps\n", "}) => {\n", " const theme = useTheme2();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " htmlFor,\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "add", "edit_start_line_idx": 74 }
import { ArgsTable } from '@storybook/addon-docs/blocks'; import { ErrorBoundary, ErrorBoundaryAlert } from './ErrorBoundary'; import { ErrorWithStack } from './ErrorWithStack'; # ErrorBoundary A React component that catches errors in child components. Useful for logging or displaying a fallback UI in case of errors. More information about error boundaries is available at [React documentation website](https://reactjs.org/docs/error-boundaries.html). ### Usage ```jsx import { ErrorBoundary, Alert } from '@grafana/ui'; <ErrorBoundary> {({ error }) => { if (error) { return <Alert title={error.message} />; } return <Component />; }} </ErrorBoundary>; ``` # ErrorBoundaryAlert An error boundary component with built-in alert to display in case of error. ### Usage ```jsx import { ErrorBoundaryAlert } from '@grafana/ui'; <ErrorBoundaryAlert> <Component /> </ErrorBoundaryAlert>; ``` ### Props <ArgsTable of={ErrorBoundaryAlert} /> # ErrorWithStack A component that displays error together with its stack trace. ### Usage ```jsx import { ErrorWithStack } from '@grafana/ui'; <ErrorWithStack error={new Error('Test error')} title={'Unexpected error'} errorInfo={null} />; ``` ### Props <ArgsTable of={ErrorWithStack} /> # withErrorBoundary a HOC to conveniently wrap component in an error boundary ### Usage ```jsx import { withErrorBoundary } from '@grafana/ui'; interface MyCompProps {} const MyComp = withErrorBoundary( (props: MyCompProps) => { return <>...</>; }, { style: 'page' } ); ```
packages/grafana-ui/src/components/ErrorBoundary/ErrorBoundary.mdx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.002423673402518034, 0.0004544805269688368, 0.0001689911150606349, 0.00017034460324794054, 0.000744313292670995 ]
{ "id": 2, "code_window": [ " children,\n", " className,\n", " validationMessageHorizontalOverflow,\n", " ...otherProps\n", "}) => {\n", " const theme = useTheme2();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " htmlFor,\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "add", "edit_start_line_idx": 74 }
import { Meta, Props } from '@storybook/addon-docs/blocks'; import { Form } from './Form'; <Meta title="MDX|Form" component={Form} /> # Form Form component provides a way to build simple forms at Grafana. It is built on top of [react-hook-form](https://react-hook-form.com/) library and incorporates the same concepts while adjusting the API slightly. ## Usage ```tsx import { Forms } from '@grafana/ui'; interface UserDTO { name: string; email: string; //... } const defaultUser: Partial<UserDTO> = { name: 'Roger Waters', // ... } <Form defaultValues={defaultUser} onSubmit={async (user: UserDTO) => await createUser(user)} >{({register, errors}) => { return ( <Field> <Input {...register("name")}/> <Input {...register("email", {required: true})} type="email" /> <Button type="submit">Create User</Button> </Field> ) }}</Form> ``` ### Form API `Form` component exposes API via render prop. Three properties are exposed: `register`, `errors` and `control` #### `register` `register` allows registering form elements (inputs, selects, radios, etc) in the form. In order to do that you need to invoke the function itself and spread the props into the input. For example: ```jsx <Input {...register('inputName')} /> ``` The first argument for `register` is the field name. It also accepts an object, which describes validation rules for a given input: ```jsx <Input {...register("inputName", { required: true, minLength: 10, validate: v => { // custom validation rule } })} /> ``` See [Validation](#validation) for examples on validation and validation rules. #### `errors` `errors` is an object that contains validation errors of the form. To show error message and invalid input indication in your form, wrap input element with `<Field ...>` component and pass `invalid` and `error` props to it: ```jsx <Field label="Name" invalid={!!errors.name} error="Name is required"> <Input {...register('name', { required: true })} /> </Field> ``` #### `control` By default `Form` component assumes form elements are uncontrolled (https://reactjs.org/docs/glossary.html#controlled-vs-uncontrolled-components). There are some components like `RadioButton` or `Select` that are controlled-only and require some extra work. To make them work with the form, you need to render those using `InputControl` component: ```jsx import { Form, Field, InputControl } from '@grafana/ui'; // render function <Form ...>{({register, errors, control}) => ( <> <Field label="RadioButtonExample"> <InputControl {/* Render InputControl as controlled input (RadioButtonGroup) */} render={({field}) => <RadioButtonGroup {...field} options={...} />} {/* Pass control exposed from Form render prop */} control={control} name="radio" /> </Field> <Field label="SelectExample"> <InputControl {/* Render InputControl as controlled input (Select) */} render={({field}) => <Select {...field} options={...} />} {/* Pass control exposed from Form render prop */} control={control} name="select" /> </Field> </> )} </Form> ``` In case we want to modify the selected value before passing it to the form, we can use the `onChange` callback from the render's `field` argument: ```jsx <Field label="SelectExample"> <InputControl {/* Here `value` has a nested `value` property, which we want to save onto the form. */} render={(field: {onChange, ...field}) => <Select {...field} onChange={(value) => onChange(value.value)}/>} control={control} name="select" /> </Field> ``` Note that `field` also contains `ref` prop, which is passed down to the rendered component by default. In case if that component doesn't support this prop, it will need to be removed before spreading the `field`. ```jsx <Field label="SelectExample"> <InputControl {/*Remove `ref` prop, so it doesn't get passed down to the component that doesn't support it. */} render={(field: {onChange, ref, ...field}) => <Select {...field} onChange={(value) => onChange(value.value)}/>} control={control} name="select" /> </Field> ``` ### Default values Default values of the form can be passed either via `defaultValues` property on the `Form` element, or directly on form's input via `defaultValue` prop. Note that changing/updating `defaultValues` passed to the form will reset the form's state, which might be undesirable in case it has both controlled and uncontrolled components. In that case it's better to pass `defaultValue` to each form component separately. ```jsx // Passing default values to the Form interface FormDTO { name: string; isAdmin: boolean; } const defaultValues: FormDto { name: 'Roger Waters', isAdmin: false, } <Form defaultValues={defaultValues} ...>{...}</Form> ``` ```jsx // Passing default value directly to form inputs interface FormDTO { name: string; isAdmin: boolean; } const defaultValues: FormDto { name: 'Roger Waters', isAdmin: false, } <Form ...>{ ({register}) => ( <> <Input {...register("name")} defaultValue={default.name} /> </> )} </Form> ``` ### Validation Validation can be performed either synchronously or asynchronously. What's important here is that the validation function must return either a `boolean` or a `string`. #### Basic required example ```jsx <Form ...>{ ({register, errors}) => ( <> <Field invalid={!!errors.name} error={errors.name && 'Name is required'} <Input {...register("name", { required: true })} defaultValue={default.name} /> </> )} </Form> ``` #### Required with synchronous custom validation One important thing to note is that if you want to provide different error messages for different kind of validation errors you'll need to return a `string` instead of a `boolean`. ```jsx <Form ...>{ ({register, errors}) => ( <> <Field invalid={!!errors.name} error={errors.name?.message } <Input defaultValue={default.name} {...register("name", { required: 'Name is required', validation: v => { return v !== 'John' && 'Name must be John' }, )} /> </> )} </Form> ``` #### Asynchronous validation For cases when you might want to validate fields asynchronously (on the backend or via some service) you can provide an asynchronous function to the field. Consider this function that simulates a call to some service. Remember, if you want to display an error message replace `return true` or `return false` with `return 'your error message'`. ```jsx validateAsync = (newValue: string) => { try { await new Promise<ValidateResult>((resolve, reject) => { setTimeout(() => { reject('Something went wrong...'); }, 2000); }); return true; } catch (e) { return false; } }; ``` ```jsx <Form ...>{ ({register, errors}) => ( <> <Field invalid={!!errors.name} error={errors.name?.message} <Input defaultValue={default.name} {...register("name", { required: 'Name is required', validation: async v => { return await validateAsync(v); }, )} /> </> )} </Form> ``` ### Upgrading to v8 Version 8 of Grafana-UI is using version 7 of `react-hook-form` (previously version 5 was used), which introduced a few breaking changes to the `Form` API. The detailed list of changes can be found in the library's migration guides: - [Migration guide v5 to v6](https://react-hook-form.com/migrate-v5-to-v6/) - [Migration guide v6 to v7](https://react-hook-form.com/migrate-v6-to-v7/) In a nutshell, the two most important changes are: - register method is no longer passed as a `ref`, but instead its result is spread onto the input component: ```jsx -(<input ref={register({ required: true })} name="test" />) + <input {...register('test', { required: true })} />; ``` - `InputControl`'s `as` prop has been replaced with `render`, which has `field` and `fieldState` objects as arguments. `onChange`, `onBlur`, `value`, `name`, and `ref` are parts of `field`. ```jsx - <Controller as={<input />} /> + <Controller render={({ field }) => <input {...field} />} // or + <Controller render={({ field, fieldState }) => <input {...field} />} /> ``` ### Props <Props of={Form} />
packages/grafana-ui/src/components/Forms/Form.mdx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001742823951644823, 0.00016887120727915317, 0.00016462690837215632, 0.00016881500778254122, 0.0000024149117052729707 ]
{ "id": 2, "code_window": [ " children,\n", " className,\n", " validationMessageHorizontalOverflow,\n", " ...otherProps\n", "}) => {\n", " const theme = useTheme2();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " htmlFor,\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "add", "edit_start_line_idx": 74 }
package azuremonitor import ( "context" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "path" "sort" "strings" "time" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util/errutil" opentracing "github.com/opentracing/opentracing-go" "golang.org/x/net/context/ctxhttp" ) // AzureMonitorDatasource calls the Azure Monitor API - one of the four API's supported type AzureMonitorDatasource struct { proxy serviceProxy } var ( // 1m, 5m, 15m, 30m, 1h, 6h, 12h, 1d in milliseconds defaultAllowedIntervalsMS = []int64{60000, 300000, 900000, 1800000, 3600000, 21600000, 43200000, 86400000} // Used to convert the aggregation value to the Azure enum for deep linking aggregationTypeMap = map[string]int{"None": 0, "Total": 1, "Minimum": 2, "Maximum": 3, "Average": 4, "Count": 7} ) const azureMonitorAPIVersion = "2018-01-01" func (e *AzureMonitorDatasource) resourceRequest(rw http.ResponseWriter, req *http.Request, cli *http.Client) { e.proxy.Do(rw, req, cli) } // executeTimeSeriesQuery does the following: // 1. build the AzureMonitor url and querystring for each query // 2. executes each query by calling the Azure Monitor API // 3. parses the responses for each query into data frames func (e *AzureMonitorDatasource) executeTimeSeriesQuery(ctx context.Context, originalQueries []backend.DataQuery, dsInfo datasourceInfo, client *http.Client, url string) (*backend.QueryDataResponse, error) { result := backend.NewQueryDataResponse() queries, err := e.buildQueries(originalQueries, dsInfo) if err != nil { return nil, err } for _, query := range queries { result.Responses[query.RefID] = e.executeQuery(ctx, query, dsInfo, client, url) } return result, nil } func (e *AzureMonitorDatasource) buildQueries(queries []backend.DataQuery, dsInfo datasourceInfo) ([]*AzureMonitorQuery, error) { azureMonitorQueries := []*AzureMonitorQuery{} for _, query := range queries { var target string queryJSONModel := azureMonitorJSONQuery{} err := json.Unmarshal(query.JSON, &queryJSONModel) if err != nil { return nil, fmt.Errorf("failed to decode the Azure Monitor query object from JSON: %w", err) } azJSONModel := queryJSONModel.AzureMonitor urlComponents := map[string]string{} urlComponents["subscription"] = queryJSONModel.Subscription urlComponents["resourceGroup"] = azJSONModel.ResourceGroup urlComponents["metricDefinition"] = azJSONModel.MetricDefinition urlComponents["resourceName"] = azJSONModel.ResourceName ub := urlBuilder{ DefaultSubscription: dsInfo.Settings.SubscriptionId, Subscription: queryJSONModel.Subscription, ResourceGroup: queryJSONModel.AzureMonitor.ResourceGroup, MetricDefinition: azJSONModel.MetricDefinition, ResourceName: azJSONModel.ResourceName, } azureURL := ub.Build() alias := azJSONModel.Alias timeGrain := azJSONModel.TimeGrain timeGrains := azJSONModel.AllowedTimeGrainsMs if timeGrain == "auto" { timeGrain, err = setAutoTimeGrain(query.Interval.Milliseconds(), timeGrains) if err != nil { return nil, err } } params := url.Values{} params.Add("api-version", azureMonitorAPIVersion) params.Add("timespan", fmt.Sprintf("%v/%v", query.TimeRange.From.UTC().Format(time.RFC3339), query.TimeRange.To.UTC().Format(time.RFC3339))) params.Add("interval", timeGrain) params.Add("aggregation", azJSONModel.Aggregation) params.Add("metricnames", azJSONModel.MetricName) // MetricName or MetricNames ? params.Add("metricnamespace", azJSONModel.MetricNamespace) // old model dimension := strings.TrimSpace(azJSONModel.Dimension) dimensionFilter := strings.TrimSpace(azJSONModel.DimensionFilter) dimSB := strings.Builder{} if dimension != "" && dimensionFilter != "" && dimension != "None" && len(azJSONModel.DimensionFilters) == 0 { dimSB.WriteString(fmt.Sprintf("%s eq '%s'", dimension, dimensionFilter)) } else { for i, filter := range azJSONModel.DimensionFilters { dimSB.WriteString(filter.String()) if i != len(azJSONModel.DimensionFilters)-1 { dimSB.WriteString(" and ") } } } if dimSB.String() != "" { params.Add("$filter", dimSB.String()) params.Add("top", azJSONModel.Top) } target = params.Encode() if setting.Env == setting.Dev { azlog.Debug("Azuremonitor request", "params", params) } azureMonitorQueries = append(azureMonitorQueries, &AzureMonitorQuery{ URL: azureURL, UrlComponents: urlComponents, Target: target, Params: params, RefID: query.RefID, Alias: alias, TimeRange: query.TimeRange, }) } return azureMonitorQueries, nil } func (e *AzureMonitorDatasource) executeQuery(ctx context.Context, query *AzureMonitorQuery, dsInfo datasourceInfo, cli *http.Client, url string) backend.DataResponse { dataResponse := backend.DataResponse{} req, err := e.createRequest(ctx, dsInfo, url) if err != nil { dataResponse.Error = err return dataResponse } req.URL.Path = path.Join(req.URL.Path, query.URL) req.URL.RawQuery = query.Params.Encode() span, ctx := opentracing.StartSpanFromContext(ctx, "azuremonitor query") span.SetTag("target", query.Target) span.SetTag("from", query.TimeRange.From.UnixNano()/int64(time.Millisecond)) span.SetTag("until", query.TimeRange.To.UnixNano()/int64(time.Millisecond)) span.SetTag("datasource_id", dsInfo.DatasourceID) span.SetTag("org_id", dsInfo.OrgID) defer span.Finish() if err := opentracing.GlobalTracer().Inject( span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header)); err != nil { dataResponse.Error = err return dataResponse } azlog.Debug("AzureMonitor", "Request ApiURL", req.URL.String()) azlog.Debug("AzureMonitor", "Target", query.Target) res, err := ctxhttp.Do(ctx, cli, req) if err != nil { dataResponse.Error = err return dataResponse } defer func() { if err := res.Body.Close(); err != nil { azlog.Warn("Failed to close response body", "err", err) } }() data, err := e.unmarshalResponse(res) if err != nil { dataResponse.Error = err return dataResponse } azurePortalUrl, err := getAzurePortalUrl(dsInfo.Cloud) if err != nil { dataResponse.Error = err return dataResponse } dataResponse.Frames, err = e.parseResponse(data, query, azurePortalUrl) if err != nil { dataResponse.Error = err return dataResponse } return dataResponse } func (e *AzureMonitorDatasource) createRequest(ctx context.Context, dsInfo datasourceInfo, url string) (*http.Request, error) { req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { azlog.Debug("Failed to create request", "error", err) return nil, errutil.Wrap("Failed to create request", err) } req.URL.Path = "/subscriptions" req.Header.Set("Content-Type", "application/json") return req, nil } func (e *AzureMonitorDatasource) unmarshalResponse(res *http.Response) (AzureMonitorResponse, error) { body, err := ioutil.ReadAll(res.Body) if err != nil { return AzureMonitorResponse{}, err } if res.StatusCode/100 != 2 { azlog.Debug("Request failed", "status", res.Status, "body", string(body)) return AzureMonitorResponse{}, fmt.Errorf("request failed, status: %s", res.Status) } var data AzureMonitorResponse err = json.Unmarshal(body, &data) if err != nil { azlog.Debug("Failed to unmarshal AzureMonitor response", "error", err, "status", res.Status, "body", string(body)) return AzureMonitorResponse{}, err } return data, nil } func (e *AzureMonitorDatasource) parseResponse(amr AzureMonitorResponse, query *AzureMonitorQuery, azurePortalUrl string) (data.Frames, error) { if len(amr.Value) == 0 { return nil, nil } queryUrl, err := getQueryUrl(query, azurePortalUrl) if err != nil { return nil, err } frames := data.Frames{} for _, series := range amr.Value[0].Timeseries { labels := data.Labels{} for _, md := range series.Metadatavalues { labels[md.Name.LocalizedValue] = md.Value } frame := data.NewFrameOfFieldTypes("", len(series.Data), data.FieldTypeTime, data.FieldTypeNullableFloat64) frame.RefID = query.RefID timeField := frame.Fields[0] timeField.Name = data.TimeSeriesTimeFieldName dataField := frame.Fields[1] dataField.Name = amr.Value[0].Name.LocalizedValue dataField.Labels = labels if amr.Value[0].Unit != "Unspecified" { dataField.SetConfig(&data.FieldConfig{ Unit: toGrafanaUnit(amr.Value[0].Unit), }) } if query.Alias != "" { displayName := formatAzureMonitorLegendKey(query.Alias, query.UrlComponents["resourceName"], amr.Value[0].Name.LocalizedValue, "", "", amr.Namespace, amr.Value[0].ID, labels) if dataField.Config != nil { dataField.Config.DisplayName = displayName } else { dataField.SetConfig(&data.FieldConfig{ DisplayName: displayName, }) } } requestedAgg := query.Params.Get("aggregation") for i, point := range series.Data { var value *float64 switch requestedAgg { case "Average": value = point.Average case "Total": value = point.Total case "Maximum": value = point.Maximum case "Minimum": value = point.Minimum case "Count": value = point.Count default: value = point.Count } frame.SetRow(i, point.TimeStamp, value) } frameWithLink := addConfigLinks(*frame, queryUrl) frames = append(frames, &frameWithLink) } return frames, nil } // Gets the deep link for the given query func getQueryUrl(query *AzureMonitorQuery, azurePortalUrl string) (string, error) { aggregationType := aggregationTypeMap["Average"] aggregation := query.Params.Get("aggregation") if aggregation != "" { if aggType, ok := aggregationTypeMap[aggregation]; ok { aggregationType = aggType } } timespan, err := json.Marshal(map[string]interface{}{ "absolute": struct { Start string `json:"startTime"` End string `json:"endTime"` }{ Start: query.TimeRange.From.UTC().Format(time.RFC3339Nano), End: query.TimeRange.To.UTC().Format(time.RFC3339Nano), }, }) if err != nil { return "", err } escapedTime := url.QueryEscape(string(timespan)) id := fmt.Sprintf("/subscriptions/%v/resourceGroups/%v/providers/%v/%v", query.UrlComponents["subscription"], query.UrlComponents["resourceGroup"], query.UrlComponents["metricDefinition"], query.UrlComponents["resourceName"], ) chartDef, err := json.Marshal(map[string]interface{}{ "v2charts": []interface{}{ map[string]interface{}{ "metrics": []metricChartDefinition{ { ResourceMetadata: map[string]string{ "id": id, }, Name: query.Params.Get("metricnames"), AggregationType: aggregationType, Namespace: query.Params.Get("metricnamespace"), MetricVisualization: metricVisualization{ DisplayName: query.Params.Get("metricnames"), ResourceDisplayName: query.UrlComponents["resourceName"], }, }, }, }, }, }) if err != nil { return "", err } escapedChart := url.QueryEscape(string(chartDef)) return fmt.Sprintf("%s/#blade/Microsoft_Azure_MonitoringMetrics/Metrics.ReactView/Referer/MetricsExplorer/TimeContext/%s/ChartDefinition/%s", azurePortalUrl, escapedTime, escapedChart), nil } // formatAzureMonitorLegendKey builds the legend key or timeseries name // Alias patterns like {{resourcename}} are replaced with the appropriate data values. func formatAzureMonitorLegendKey(alias string, resourceName string, metricName string, metadataName string, metadataValue string, namespace string, seriesID string, labels data.Labels) string { startIndex := strings.Index(seriesID, "/resourceGroups/") + 16 endIndex := strings.Index(seriesID, "/providers") resourceGroup := seriesID[startIndex:endIndex] // Could be a collision problem if there were two keys that varied only in case, but I don't think that would happen in azure. lowerLabels := data.Labels{} for k, v := range labels { lowerLabels[strings.ToLower(k)] = v } keys := make([]string, 0, len(labels)) for k := range lowerLabels { keys = append(keys, k) } keys = sort.StringSlice(keys) result := legendKeyFormat.ReplaceAllFunc([]byte(alias), func(in []byte) []byte { metaPartName := strings.Replace(string(in), "{{", "", 1) metaPartName = strings.Replace(metaPartName, "}}", "", 1) metaPartName = strings.ToLower(strings.TrimSpace(metaPartName)) if metaPartName == "resourcegroup" { return []byte(resourceGroup) } if metaPartName == "namespace" { return []byte(namespace) } if metaPartName == "resourcename" { return []byte(resourceName) } if metaPartName == "metric" { return []byte(metricName) } if metaPartName == "dimensionname" { if len(keys) == 0 { return []byte{} } return []byte(keys[0]) } if metaPartName == "dimensionvalue" { if len(keys) == 0 { return []byte{} } return []byte(lowerLabels[keys[0]]) } if v, ok := lowerLabels[metaPartName]; ok { return []byte(v) } return in }) return string(result) } // Map values from: // https://docs.microsoft.com/en-us/rest/api/monitor/metrics/list#unit // to // https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts#L24 func toGrafanaUnit(unit string) string { switch unit { case "BitsPerSecond": return "bps" case "Bytes": return "decbytes" // or ICE case "BytesPerSecond": return "Bps" case "Count": return "short" // this is used for integers case "CountPerSecond": return "cps" case "Percent": return "percent" case "MilliSeconds": return "ms" case "Seconds": return "s" } return unit // this will become a suffix in the display // "ByteSeconds", "Cores", "MilliCores", and "NanoCores" all both: // 1. Do not have a corresponding unit in Grafana's current list. // 2. Do not have the unit listed in any of Azure Monitor's supported metrics anyways. }
pkg/tsdb/azuremonitor/azuremonitor-datasource.go
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00019859203894156963, 0.00017246972129214555, 0.0001638592075323686, 0.00017256365390494466, 0.000004870343218499329 ]
{ "id": 3, "code_window": [ "}) => {\n", " const theme = useTheme2();\n", " const styles = getFieldStyles(theme);\n", " const inputId = getChildId(children);\n", "\n", " const labelElement =\n", " typeof label === 'string' ? (\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const inputId = htmlFor ?? getChildId(children);\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "replace", "edit_start_line_idx": 78 }
import React, { MouseEvent, PureComponent } from 'react'; import { Icon, LinkButton } from '@grafana/ui'; import { selectors } from '@grafana/e2e-selectors'; import { toVariableIdentifier, toVariablePayload, VariableIdentifier } from '../state/types'; import { StoreState } from '../../../types'; import { VariableEditorEditor } from './VariableEditorEditor'; import { connect, ConnectedProps } from 'react-redux'; import { getEditorVariables } from '../state/selectors'; import { switchToEditMode, switchToListMode, switchToNewMode } from './actions'; import { changeVariableOrder, duplicateVariable, removeVariable } from '../state/sharedReducer'; import { VariableEditorList } from './VariableEditorList'; import { VariablesUnknownTable } from '../inspect/VariablesUnknownTable'; import { VariablesDependenciesButton } from '../inspect/VariablesDependenciesButton'; const mapStateToProps = (state: StoreState) => ({ variables: getEditorVariables(state), idInEditor: state.templating.editor.id, dashboard: state.dashboard.getModel(), unknownsNetwork: state.templating.inspect.unknownsNetwork, unknownExists: state.templating.inspect.unknownExits, usagesNetwork: state.templating.inspect.usagesNetwork, unknown: state.templating.inspect.unknown, usages: state.templating.inspect.usages, }); const mapDispatchToProps = { changeVariableOrder, duplicateVariable, removeVariable, switchToNewMode, switchToEditMode, switchToListMode, }; interface OwnProps {} const connector = connect(mapStateToProps, mapDispatchToProps); type Props = OwnProps & ConnectedProps<typeof connector>; class VariableEditorContainerUnconnected extends PureComponent<Props> { componentDidMount(): void { this.props.switchToListMode(); } onChangeToListMode = (event: MouseEvent<HTMLAnchorElement>) => { event.preventDefault(); this.props.switchToListMode(); }; onEditVariable = (identifier: VariableIdentifier) => { this.props.switchToEditMode(identifier); }; onNewVariable = (event: MouseEvent) => { event.preventDefault(); this.props.switchToNewMode(); }; onChangeVariableOrder = (identifier: VariableIdentifier, fromIndex: number, toIndex: number) => { this.props.changeVariableOrder(toVariablePayload(identifier, { fromIndex, toIndex })); }; onDuplicateVariable = (identifier: VariableIdentifier) => { this.props.duplicateVariable(toVariablePayload(identifier, { newId: (undefined as unknown) as string })); }; onRemoveVariable = (identifier: VariableIdentifier) => { this.props.removeVariable(toVariablePayload(identifier, { reIndex: true })); }; render() { const variableToEdit = this.props.variables.find((s) => s.id === this.props.idInEditor) ?? null; return ( <div> <div className="page-action-bar"> <h3 className="dashboard-settings__header"> <a onClick={this.onChangeToListMode} aria-label={selectors.pages.Dashboard.Settings.Variables.Edit.General.headerLink} > Variables </a> {this.props.idInEditor && ( <span> <Icon name="angle-right" aria-label={selectors.pages.Dashboard.Settings.Variables.Edit.General.modeLabelEdit} /> Edit </span> )} </h3> <div className="page-action-bar__spacer" /> {this.props.variables.length > 0 && variableToEdit === null && ( <> <VariablesDependenciesButton variables={this.props.variables} /> <LinkButton type="button" onClick={this.onNewVariable} aria-label={selectors.pages.Dashboard.Settings.Variables.List.newButton} > New </LinkButton> </> )} </div> {!variableToEdit && ( <> <VariableEditorList dashboard={this.props.dashboard} variables={this.props.variables} onAddClick={this.onNewVariable} onEditClick={this.onEditVariable} onChangeVariableOrder={this.onChangeVariableOrder} onDuplicateVariable={this.onDuplicateVariable} onRemoveVariable={this.onRemoveVariable} usages={this.props.usages} usagesNetwork={this.props.usagesNetwork} /> {this.props.unknownExists ? <VariablesUnknownTable usages={this.props.unknownsNetwork} /> : null} </> )} {variableToEdit && <VariableEditorEditor identifier={toVariableIdentifier(variableToEdit)} />} </div> ); } } export const VariableEditorContainer = connector(VariableEditorContainerUnconnected);
public/app/features/variables/editor/VariableEditorContainer.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017425150144845247, 0.00016960999346338212, 0.00016726042667869478, 0.00016916466120164841, 0.0000019920157683372963 ]
{ "id": 3, "code_window": [ "}) => {\n", " const theme = useTheme2();\n", " const styles = getFieldStyles(theme);\n", " const inputId = getChildId(children);\n", "\n", " const labelElement =\n", " typeof label === 'string' ? (\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const inputId = htmlFor ?? getChildId(children);\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "replace", "edit_start_line_idx": 78 }
package influxdb import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "path" "strings" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/backend/datasource" "github.com/grafana/grafana-plugin-sdk-go/backend/instancemgmt" "github.com/grafana/grafana/pkg/infra/httpclient" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/plugins/backendplugin" "github.com/grafana/grafana/pkg/plugins/backendplugin/coreplugin" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/tsdb/influxdb/flux" "github.com/grafana/grafana/pkg/tsdb/influxdb/models" ) type Service struct { QueryParser *InfluxdbQueryParser ResponseParser *ResponseParser glog log.Logger im instancemgmt.InstanceManager } var ErrInvalidHttpMode = errors.New("'httpMode' should be either 'GET' or 'POST'") func ProvideService(httpClient httpclient.Provider, backendPluginManager backendplugin.Manager) (*Service, error) { im := datasource.NewInstanceManager(newInstanceSettings(httpClient)) s := &Service{ QueryParser: &InfluxdbQueryParser{}, ResponseParser: &ResponseParser{}, glog: log.New("tsdb.influxdb"), im: im, } factory := coreplugin.New(backend.ServeOpts{ QueryDataHandler: s, }) if err := backendPluginManager.Register("influxdb", factory); err != nil { s.glog.Error("Failed to register plugin", "error", err) return nil, err } return s, nil } func newInstanceSettings(httpClientProvider httpclient.Provider) datasource.InstanceFactoryFunc { return func(settings backend.DataSourceInstanceSettings) (instancemgmt.Instance, error) { opts, err := settings.HTTPClientOptions() if err != nil { return nil, err } client, err := httpClientProvider.New(opts) if err != nil { return nil, err } jsonData := models.DatasourceInfo{} err = json.Unmarshal(settings.JSONData, &jsonData) if err != nil { return nil, fmt.Errorf("error reading settings: %w", err) } httpMode := jsonData.HTTPMode if httpMode == "" { httpMode = "GET" } maxSeries := jsonData.MaxSeries if maxSeries == 0 { maxSeries = 1000 } model := &models.DatasourceInfo{ HTTPClient: client, URL: settings.URL, Database: settings.Database, Version: jsonData.Version, HTTPMode: httpMode, TimeInterval: jsonData.TimeInterval, DefaultBucket: jsonData.DefaultBucket, Organization: jsonData.Organization, MaxSeries: maxSeries, Token: settings.DecryptedSecureJSONData["token"], } return model, nil } } func (s *Service) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) { s.glog.Debug("Received a query request", "numQueries", len(req.Queries)) dsInfo, err := s.getDSInfo(req.PluginContext) if err != nil { return nil, err } version := dsInfo.Version if version == "Flux" { return flux.Query(ctx, dsInfo, *req) } s.glog.Debug("Making a non-Flux type query") // NOTE: the following path is currently only called from alerting queries // In dashboards, the request runs through proxy and are managed in the frontend query, err := s.getQuery(dsInfo, req) if err != nil { return &backend.QueryDataResponse{}, err } rawQuery, err := query.Build(req) if err != nil { return &backend.QueryDataResponse{}, err } if setting.Env == setting.Dev { s.glog.Debug("Influxdb query", "raw query", rawQuery) } request, err := s.createRequest(ctx, dsInfo, rawQuery) if err != nil { return &backend.QueryDataResponse{}, err } res, err := dsInfo.HTTPClient.Do(request) if err != nil { return &backend.QueryDataResponse{}, err } defer func() { if err := res.Body.Close(); err != nil { s.glog.Warn("Failed to close response body", "err", err) } }() if res.StatusCode/100 != 2 { return &backend.QueryDataResponse{}, fmt.Errorf("InfluxDB returned error status: %s", res.Status) } resp := s.ResponseParser.Parse(res.Body, query) return resp, nil } func (s *Service) getQuery(dsInfo *models.DatasourceInfo, query *backend.QueryDataRequest) (*Query, error) { queryCount := len(query.Queries) // The model supports multiple queries, but right now this is only used from // alerting so we only needed to support batch executing 1 query at a time. if queryCount != 1 { return nil, fmt.Errorf("query request should contain exactly 1 query, it contains: %d", queryCount) } q := query.Queries[0] return s.QueryParser.Parse(q) } func (s *Service) createRequest(ctx context.Context, dsInfo *models.DatasourceInfo, query string) (*http.Request, error) { u, err := url.Parse(dsInfo.URL) if err != nil { return nil, err } u.Path = path.Join(u.Path, "query") httpMode := dsInfo.HTTPMode var req *http.Request switch httpMode { case "GET": req, err = http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { return nil, err } case "POST": bodyValues := url.Values{} bodyValues.Add("q", query) body := bodyValues.Encode() req, err = http.NewRequestWithContext(ctx, http.MethodPost, u.String(), strings.NewReader(body)) if err != nil { return nil, err } default: return nil, ErrInvalidHttpMode } req.Header.Set("User-Agent", "Grafana") params := req.URL.Query() params.Set("db", dsInfo.Database) params.Set("epoch", "s") if httpMode == "GET" { params.Set("q", query) } else if httpMode == "POST" { req.Header.Set("Content-type", "application/x-www-form-urlencoded") } req.URL.RawQuery = params.Encode() s.glog.Debug("Influxdb request", "url", req.URL.String()) return req, nil } func (s *Service) getDSInfo(pluginCtx backend.PluginContext) (*models.DatasourceInfo, error) { i, err := s.im.Get(pluginCtx) if err != nil { return nil, err } instance, ok := i.(*models.DatasourceInfo) if !ok { return nil, fmt.Errorf("failed to cast datsource info") } return instance, nil }
pkg/tsdb/influxdb/influxdb.go
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017662350728642195, 0.00017153896624222398, 0.000166412050020881, 0.00017207337077707052, 0.00000290402954306046 ]
{ "id": 3, "code_window": [ "}) => {\n", " const theme = useTheme2();\n", " const styles = getFieldStyles(theme);\n", " const inputId = getChildId(children);\n", "\n", " const labelElement =\n", " typeof label === 'string' ? (\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const inputId = htmlFor ?? getChildId(children);\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "replace", "edit_start_line_idx": 78 }
package response import ( "bytes" "encoding/json" "net/http" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" jsoniter "github.com/json-iterator/go" ) // Response is an HTTP response interface. type Response interface { // WriteTo writes to a context. WriteTo(ctx *models.ReqContext) // Body gets the response's body. Body() []byte // Status gets the response's status. Status() int } func CreateNormalResponse(header http.Header, body []byte, status int) *NormalResponse { return &NormalResponse{ header: header, body: bytes.NewBuffer(body), status: status, } } type NormalResponse struct { status int body *bytes.Buffer header http.Header errMessage string err error } // Write implements http.ResponseWriter func (r *NormalResponse) Write(b []byte) (int, error) { return r.body.Write(b) } // Header implements http.ResponseWriter func (r *NormalResponse) Header() http.Header { return r.header } // WriteHeader implements http.ResponseWriter func (r *NormalResponse) WriteHeader(statusCode int) { r.status = statusCode } // Status gets the response's status. func (r *NormalResponse) Status() int { return r.status } // Body gets the response's body. func (r *NormalResponse) Body() []byte { return r.body.Bytes() } // Err gets the response's err. func (r *NormalResponse) Err() error { return r.err } // ErrMessage gets the response's errMessage. func (r *NormalResponse) ErrMessage() string { return r.errMessage } func (r *NormalResponse) WriteTo(ctx *models.ReqContext) { if r.err != nil { ctx.Logger.Error(r.errMessage, "error", r.err, "remote_addr", ctx.RemoteAddr()) } header := ctx.Resp.Header() for k, v := range r.header { header[k] = v } ctx.Resp.WriteHeader(r.status) if _, err := ctx.Resp.Write(r.body.Bytes()); err != nil { ctx.Logger.Error("Error writing to response", "err", err) } } func (r *NormalResponse) SetHeader(key, value string) *NormalResponse { r.header.Set(key, value) return r } // StreamingResponse is a response that streams itself back to the client. type StreamingResponse struct { body interface{} status int header http.Header } // Status gets the response's status. // Required to implement api.Response. func (r StreamingResponse) Status() int { return r.status } // Body gets the response's body. // Required to implement api.Response. func (r StreamingResponse) Body() []byte { return nil } // WriteTo writes the response to the provided context. // Required to implement api.Response. func (r StreamingResponse) WriteTo(ctx *models.ReqContext) { header := ctx.Resp.Header() for k, v := range r.header { header[k] = v } ctx.Resp.WriteHeader(r.status) // Use a configuration that's compatible with the standard library // to minimize the risk of introducing bugs. This will make sure // that map keys is ordered. jsonCfg := jsoniter.ConfigCompatibleWithStandardLibrary enc := jsonCfg.NewEncoder(ctx.Resp) if err := enc.Encode(r.body); err != nil { ctx.Logger.Error("Error writing to response", "err", err) } } // RedirectResponse represents a redirect response. type RedirectResponse struct { location string } // WriteTo writes to a response. func (r *RedirectResponse) WriteTo(ctx *models.ReqContext) { ctx.Redirect(r.location) } // Status gets the response's status. // Required to implement api.Response. func (*RedirectResponse) Status() int { return http.StatusFound } // Body gets the response's body. // Required to implement api.Response. func (r *RedirectResponse) Body() []byte { return nil } // JSON creates a JSON response. func JSON(status int, body interface{}) *NormalResponse { return Respond(status, body).SetHeader("Content-Type", "application/json") } // JSONStreaming creates a streaming JSON response. func JSONStreaming(status int, body interface{}) StreamingResponse { header := make(http.Header) header.Set("Content-Type", "application/json") return StreamingResponse{ body: body, status: status, header: header, } } // Success create a successful response func Success(message string) *NormalResponse { resp := make(map[string]interface{}) resp["message"] = message return JSON(200, resp) } // Error creates an error response. func Error(status int, message string, err error) *NormalResponse { data := make(map[string]interface{}) switch status { case 404: data["message"] = "Not Found" case 500: data["message"] = "Internal Server Error" } if message != "" { data["message"] = message } if err != nil { if setting.Env != setting.Prod { data["error"] = err.Error() } } resp := JSON(status, data) if err != nil { resp.errMessage = message resp.err = err } return resp } // Empty creates an empty NormalResponse. func Empty(status int) *NormalResponse { return Respond(status, nil) } // Respond creates a response. func Respond(status int, body interface{}) *NormalResponse { var b []byte switch t := body.(type) { case []byte: b = t case string: b = []byte(t) default: var err error if b, err = json.Marshal(body); err != nil { return Error(500, "body json marshal", err) } } return &NormalResponse{ status: status, body: bytes.NewBuffer(b), header: make(http.Header), } } func Redirect(location string) *RedirectResponse { return &RedirectResponse{location: location} }
pkg/api/response/response.go
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00022865553910378367, 0.00017384078819304705, 0.000162552620167844, 0.00017212846432812512, 0.00001296524078497896 ]
{ "id": 3, "code_window": [ "}) => {\n", " const theme = useTheme2();\n", " const styles = getFieldStyles(theme);\n", " const inputId = getChildId(children);\n", "\n", " const labelElement =\n", " typeof label === 'string' ? (\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const inputId = htmlFor ?? getChildId(children);\n" ], "file_path": "packages/grafana-ui/src/components/Forms/Field.tsx", "type": "replace", "edit_start_line_idx": 78 }
import React from 'react'; import { FieldConfigEditorProps, SelectFieldConfigSettings, SelectableValue } from '@grafana/data'; import { MultiSelect } from '../Select/Select'; interface State<T> { isLoading: boolean; options: Array<SelectableValue<T>>; } type Props<T> = FieldConfigEditorProps<T[], SelectFieldConfigSettings<T>>; /** * MultiSelect for options UI * @alpha */ export class MultiSelectValueEditor<T> extends React.PureComponent<Props<T>, State<T>> { state: State<T> = { isLoading: true, options: [], }; componentDidMount() { this.updateOptions(); } componentDidUpdate(oldProps: Props<T>) { const old = oldProps.item?.settings; const now = this.props.item?.settings; if (old !== now) { this.updateOptions(); } else if (now?.getOptions) { const old = oldProps.context?.data; const now = this.props.context?.data; if (old !== now) { this.updateOptions(); } } } updateOptions = async () => { const { item } = this.props; const { settings } = item; let options: Array<SelectableValue<T>> = item.settings?.options || []; if (settings?.getOptions) { options = await settings.getOptions(this.props.context); } if (this.state.options !== options) { this.setState({ isLoading: false, options, }); } }; render() { const { options, isLoading } = this.state; const { value, onChange, item } = this.props; const { settings } = item; return ( <MultiSelect<T> menuShouldPortal isLoading={isLoading} value={value} defaultValue={value} allowCustomValue={settings?.allowCustomValue} onChange={(e) => { onChange(e.map((v) => v.value).flatMap((v) => (v !== undefined ? [v] : []))); }} options={options} /> ); } }
packages/grafana-ui/src/components/OptionsUI/multiSelect.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001748755166772753, 0.00017189496429637074, 0.00016785300977062434, 0.0001722141169011593, 0.0000023328757379204035 ]
{ "id": 4, "code_window": [ "import { Checkbox, CollapsableSection, ColorValueEditor, Field, HorizontalGroup, Input } from '@grafana/ui';\n", "import { DashboardModel } from '../../state/DashboardModel';\n", "import { AnnotationQuery, DataSourceInstanceSettings } from '@grafana/data';\n", "import { getDataSourceSrv, DataSourcePicker } from '@grafana/runtime';\n", "import { useAsync } from 'react-use';\n", "import StandardAnnotationQueryEditor from 'app/features/annotations/components/StandardAnnotationQueryEditor';\n", "import { AngularEditorLoader } from './AngularEditorLoader';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DataSourcePicker, getDataSourceSrv } from '@grafana/runtime';\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx", "type": "replace", "edit_start_line_idx": 4 }
import React, { useState } from 'react'; import { Checkbox, CollapsableSection, ColorValueEditor, Field, HorizontalGroup, Input } from '@grafana/ui'; import { DashboardModel } from '../../state/DashboardModel'; import { AnnotationQuery, DataSourceInstanceSettings } from '@grafana/data'; import { getDataSourceSrv, DataSourcePicker } from '@grafana/runtime'; import { useAsync } from 'react-use'; import StandardAnnotationQueryEditor from 'app/features/annotations/components/StandardAnnotationQueryEditor'; import { AngularEditorLoader } from './AngularEditorLoader'; import { selectors } from '@grafana/e2e-selectors'; export const newAnnotation: AnnotationQuery = { name: 'New annotation', enable: true, datasource: null, iconColor: 'red', }; type Props = { editIdx: number; dashboard: DashboardModel; }; export const AnnotationSettingsEdit: React.FC<Props> = ({ editIdx, dashboard }) => { const [annotation, setAnnotation] = useState(editIdx !== null ? dashboard.annotations.list[editIdx] : newAnnotation); const { value: ds } = useAsync(() => { return getDataSourceSrv().get(annotation.datasource); }, [annotation.datasource]); const onUpdate = (annotation: AnnotationQuery) => { const list = [...dashboard.annotations.list]; list.splice(editIdx, 1, annotation); setAnnotation(annotation); dashboard.annotations.list = list; }; const onNameChange = (ev: React.FocusEvent<HTMLInputElement>) => { onUpdate({ ...annotation, name: ev.currentTarget.value, }); }; const onDataSourceChange = (ds: DataSourceInstanceSettings) => { onUpdate({ ...annotation, datasource: ds.name, }); }; const onChange = (ev: React.FocusEvent<HTMLInputElement>) => { const target = ev.currentTarget; onUpdate({ ...annotation, [target.name]: target.type === 'checkbox' ? target.checked : target.value, }); }; const onColorChange = (color: string) => { onUpdate({ ...annotation, iconColor: color, }); }; const isNewAnnotation = annotation.name === newAnnotation.name; return ( <div> <Field label="Name"> <Input aria-label={selectors.pages.Dashboard.Settings.Annotations.Settings.name} name="name" id="name" autoFocus={isNewAnnotation} value={annotation.name} onChange={onNameChange} width={50} /> </Field> <Field label="Data source"> <DataSourcePicker width={50} annotations variables current={annotation.datasource} onChange={onDataSourceChange} /> </Field> <Field label="Enabled" description="When enabled the annotation query is issued every dashboard refresh"> <Checkbox name="enable" id="enable" value={annotation.enable} onChange={onChange} /> </Field> <Field label="Hidden" description="Annotation queries can be toggled on or off at the top of the dashboard. With this option checked this toggle will be hidden." > <Checkbox name="hide" id="hide" value={annotation.hide} onChange={onChange} /> </Field> <Field label="Color" description="Color to use for the annotation event markers"> <HorizontalGroup> <ColorValueEditor value={annotation?.iconColor} onChange={onColorChange} /> </HorizontalGroup> </Field> <CollapsableSection isOpen={true} label="Query"> {ds?.annotations && ( <StandardAnnotationQueryEditor datasource={ds} annotation={annotation} onChange={onUpdate} /> )} {ds && !ds.annotations && <AngularEditorLoader datasource={ds} annotation={annotation} onChange={onUpdate} />} </CollapsableSection> </div> ); }; AnnotationSettingsEdit.displayName = 'AnnotationSettingsEdit';
public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.9932742118835449, 0.08334562927484512, 0.00016860515461303294, 0.0002308967086719349, 0.2743552327156067 ]
{ "id": 4, "code_window": [ "import { Checkbox, CollapsableSection, ColorValueEditor, Field, HorizontalGroup, Input } from '@grafana/ui';\n", "import { DashboardModel } from '../../state/DashboardModel';\n", "import { AnnotationQuery, DataSourceInstanceSettings } from '@grafana/data';\n", "import { getDataSourceSrv, DataSourcePicker } from '@grafana/runtime';\n", "import { useAsync } from 'react-use';\n", "import StandardAnnotationQueryEditor from 'app/features/annotations/components/StandardAnnotationQueryEditor';\n", "import { AngularEditorLoader } from './AngularEditorLoader';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DataSourcePicker, getDataSourceSrv } from '@grafana/runtime';\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx", "type": "replace", "edit_start_line_idx": 4 }
+++ title = "Legacy snapshot mode" aliases = ["/docs/grafana/latest/plugins/developing/snapshot-mode/"] +++ # Legacy snapshot mode {{< figure class="float-right" src="/static/img/docs/Grafana-snapshot-example.png" caption="A dashboard using snapshot data and not live data." >}} Grafana has this great feature where you can [save a snapshot of your dashboard]({{< relref "../../../dashboards/json-model.md" >}}). Instead of sending a screenshot of a dashboard to someone, you can send them a working, interactive Grafana dashboard with the snapshot data embedded inside it. The snapshot can be saved on your Grafana server and is available to all your co-workers. Raintank also hosts a [snapshot server](http://snapshot.raintank.io/) if you want to send the snapshot to someone who does not have access to your Grafana server. {{< figure class="float-right" src="/static/img/docs/animated_gifs/snapshots.gif" caption="Selecting a snapshot" >}} This all works because Grafana saves a snapshot of the current data in the dashboard json instead of fetching the data from a data source. However, if you are building a custom panel plugin then this will not work straight out of the box. You will need to make some small (and easy!) changes first. ## Enabling support for loading snapshot data Grafana automatically saves data from data sources in the dashboard json when the snapshot is created so we do not have to write any code for that. Enabling snapshot support for reading time series data is very simple. First in the constructor, we need to add an event handler for `data-snapshot-load`. This event is triggered by Grafana when the snapshot data is loaded from the dashboard json. ```javascript constructor($scope, $injector, contextSrv) { super($scope, $injector); ... this.events.on('init-edit-mode', this.onInitEditMode.bind(this)); this.events.on('data-received', this.onDataReceived.bind(this)); this.events.on('panel-teardown', this.onPanelTeardown.bind(this)); this.events.on('data-snapshot-load', this.onDataSnapshotLoad.bind(this)); ``` Then we need to create a simple event handler that just forwards the data on to our regular `data-received` handler: ```javascript onDataSnapshotLoad(snapshotData) { this.onDataReceived(snapshotData); } ``` This will cover most use cases for snapshot support. Sometimes you will want to save data that is not time series data from a Grafana data source and then you have to do a bit more work to get snapshot support. ## Saving custom data for snapshots Data that is not time series data from a Grafana data source is not saved automatically by Grafana. Saving custom data for snapshot mode has to be done manually. {{< figure class="float-right" src="/static/img/docs/Grafana-save-snapshot.png" caption="Save snapshot" >}} Grafana gives us a chance to save data to the dashboard json when it is creating a snapshot. In the 'data-received' event handler, you can check the snapshot flag on the dashboard object. If this is true, then Grafana is creating a snapshot and you can manually save custom data to the panel json. In the example, a new field called snapshotLocationData in the panel json is initialized with a snapshot of the custom data. ```javascript onDataReceived(dataList) { if (!dataList) return; if (this.dashboard.snapshot && this.locations) { this.panel.snapshotLocationData = this.locations; } ``` Now the location data is saved in the dashboard json but we will have to load it manually as well. ## Loading custom data for snapshots The example below shows a function that loads the custom data. The data source for the custom data (an external API in this case) is not available in snapshot mode so a guard check is made to see if there is any snapshot data available first. If there is, then the snapshot data is used instead of trying to load the data from the external API. ```javascript loadLocationDataFromFile(reload) { if (this.map && !reload) return; if (this.panel.snapshotLocationData) { this.locations = this.panel.snapshotLocationData; return; } ``` It is really easy to forget to add this support but it enables a great feature and can be used to demo your panel. If there is a panel plugin that you would like to be installed on the Raintank Snapshot server then please contact us via [Slack](https://raintank.slack.com) or [GitHub](https://github.com/grafana/grafana).
docs/sources/developers/plugins/legacy/snapshot-mode.md
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0002181139134336263, 0.00017093506176024675, 0.0001605266734259203, 0.00016415331629104912, 0.00001798001176211983 ]
{ "id": 4, "code_window": [ "import { Checkbox, CollapsableSection, ColorValueEditor, Field, HorizontalGroup, Input } from '@grafana/ui';\n", "import { DashboardModel } from '../../state/DashboardModel';\n", "import { AnnotationQuery, DataSourceInstanceSettings } from '@grafana/data';\n", "import { getDataSourceSrv, DataSourcePicker } from '@grafana/runtime';\n", "import { useAsync } from 'react-use';\n", "import StandardAnnotationQueryEditor from 'app/features/annotations/components/StandardAnnotationQueryEditor';\n", "import { AngularEditorLoader } from './AngularEditorLoader';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DataSourcePicker, getDataSourceSrv } from '@grafana/runtime';\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx", "type": "replace", "edit_start_line_idx": 4 }
import React, { useState } from 'react'; import { RuleSettingsEditor } from './RuleSettingsEditor'; import { RuleType, RuleSetting, PipeLineEntitiesInfo } from './types'; import { Select } from '@grafana/ui'; import { SelectableValue } from '../../../../../packages/grafana-data/src'; interface Props { ruleType: RuleType; onChange: (value: RuleSetting[]) => void; value: RuleSetting[]; entitiesInfo: PipeLineEntitiesInfo; } export const RuleSettingsArray: React.FC<Props> = ({ onChange, value, ruleType, entitiesInfo }) => { const [index, setIndex] = useState<number>(0); const arr = value ?? []; const onRuleChange = (v: RuleSetting) => { if (!value) { onChange([v]); } else { const copy = [...value]; copy[index] = v; onChange(copy); } }; // create array of value.length + 1 let indexArr: Array<SelectableValue<number>> = []; for (let i = 0; i <= arr.length; i++) { indexArr.push({ label: `${ruleType}: ${i}`, value: i, }); } return ( <> <Select placeholder="Select an index" menuShouldPortal={true} options={indexArr} value={index} onChange={(index) => { // set index to find the correct setting setIndex(index.value!); }} ></Select> <RuleSettingsEditor onChange={onRuleChange} value={arr[index]} ruleType={ruleType} entitiesInfo={entitiesInfo} /> </> ); };
public/app/features/live/pages/RuleSettingsArray.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017637156997807324, 0.00017260391905438155, 0.00016504059021826833, 0.00017348636174574494, 0.0000035842629131366266 ]
{ "id": 4, "code_window": [ "import { Checkbox, CollapsableSection, ColorValueEditor, Field, HorizontalGroup, Input } from '@grafana/ui';\n", "import { DashboardModel } from '../../state/DashboardModel';\n", "import { AnnotationQuery, DataSourceInstanceSettings } from '@grafana/data';\n", "import { getDataSourceSrv, DataSourcePicker } from '@grafana/runtime';\n", "import { useAsync } from 'react-use';\n", "import StandardAnnotationQueryEditor from 'app/features/annotations/components/StandardAnnotationQueryEditor';\n", "import { AngularEditorLoader } from './AngularEditorLoader';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DataSourcePicker, getDataSourceSrv } from '@grafana/runtime';\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx", "type": "replace", "edit_start_line_idx": 4 }
import { from, of, OperatorFunction } from 'rxjs'; import { map, mergeMap } from 'rxjs/operators'; import { QueryVariableModel } from '../types'; import { ThunkDispatch } from '../../../types'; import { toVariableIdentifier, toVariablePayload } from '../state/types'; import { validateVariableSelectionState } from '../state/actions'; import { FieldType, getFieldDisplayName, isDataFrame, MetricFindValue, PanelData } from '@grafana/data'; import { updateVariableOptions } from './reducer'; import { getTemplatedRegex } from '../utils'; import { getProcessedDataFrames } from 'app/features/query/state/runRequest'; export function toMetricFindValues(): OperatorFunction<PanelData, MetricFindValue[]> { return (source) => source.pipe( map((panelData) => { const frames = panelData.series; if (!frames || !frames.length) { return []; } if (areMetricFindValues(frames)) { return frames; } const processedDataFrames = getProcessedDataFrames(frames); const metrics: MetricFindValue[] = []; let valueIndex = -1; let textIndex = -1; let stringIndex = -1; let expandableIndex = -1; for (const frame of processedDataFrames) { for (let index = 0; index < frame.fields.length; index++) { const field = frame.fields[index]; const fieldName = getFieldDisplayName(field, frame, frames).toLowerCase(); if (field.type === FieldType.string && stringIndex === -1) { stringIndex = index; } if (fieldName === 'text' && field.type === FieldType.string && textIndex === -1) { textIndex = index; } if (fieldName === 'value' && field.type === FieldType.string && valueIndex === -1) { valueIndex = index; } if ( fieldName === 'expandable' && (field.type === FieldType.boolean || field.type === FieldType.number) && expandableIndex === -1 ) { expandableIndex = index; } } } if (stringIndex === -1) { throw new Error("Couldn't find any field of type string in the results."); } for (const frame of frames) { for (let index = 0; index < frame.length; index++) { const expandable = expandableIndex !== -1 ? frame.fields[expandableIndex].values.get(index) : undefined; const string = frame.fields[stringIndex].values.get(index); const text = textIndex !== -1 ? frame.fields[textIndex].values.get(index) : null; const value = valueIndex !== -1 ? frame.fields[valueIndex].values.get(index) : null; if (valueIndex === -1 && textIndex === -1) { metrics.push({ text: string, value: string, expandable }); continue; } if (valueIndex === -1 && textIndex !== -1) { metrics.push({ text, value: text, expandable }); continue; } if (valueIndex !== -1 && textIndex === -1) { metrics.push({ text: value, value, expandable }); continue; } metrics.push({ text, value, expandable }); } } return metrics; }) ); } export function updateOptionsState(args: { variable: QueryVariableModel; dispatch: ThunkDispatch; getTemplatedRegexFunc: typeof getTemplatedRegex; }): OperatorFunction<MetricFindValue[], void> { return (source) => source.pipe( map((results) => { const { variable, dispatch, getTemplatedRegexFunc } = args; const templatedRegex = getTemplatedRegexFunc(variable); const payload = toVariablePayload(variable, { results, templatedRegex }); dispatch(updateVariableOptions(payload)); }) ); } export function validateVariableSelection(args: { variable: QueryVariableModel; dispatch: ThunkDispatch; searchFilter?: string; }): OperatorFunction<void, void> { return (source) => source.pipe( mergeMap(() => { const { dispatch, variable, searchFilter } = args; // If we are searching options there is no need to validate selection state // This condition was added to as validateVariableSelectionState will update the current value of the variable // So after search and selection the current value is already update so no setValue, refresh and URL update is performed // The if statement below fixes https://github.com/grafana/grafana/issues/25671 if (!searchFilter) { return from(dispatch(validateVariableSelectionState(toVariableIdentifier(variable)))); } return of<void>(); }) ); } export function areMetricFindValues(data: any[]): data is MetricFindValue[] { if (!data) { return false; } if (!data.length) { return true; } const firstValue: any = data[0]; if (isDataFrame(firstValue)) { return false; } for (const firstValueKey in firstValue) { if (!firstValue.hasOwnProperty(firstValueKey)) { continue; } if ( firstValue[firstValueKey] !== null && typeof firstValue[firstValueKey] !== 'string' && typeof firstValue[firstValueKey] !== 'number' ) { continue; } const key = firstValueKey.toLowerCase(); if (key === 'text' || key === 'value') { return true; } } return false; }
public/app/features/variables/query/operators.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00019215457723475993, 0.0001721804146654904, 0.00016404023335780948, 0.00017193281382787973, 0.000006632084932789439 ]
{ "id": 5, "code_window": [ " value={annotation.name}\n", " onChange={onNameChange}\n", " width={50}\n", " />\n", " </Field>\n", " <Field label=\"Data source\">\n", " <DataSourcePicker\n", " width={50}\n", " annotations\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Field label=\"Data source\" htmlFor=\"data-source-picker\">\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx", "type": "replace", "edit_start_line_idx": 80 }
import React, { HTMLAttributes } from 'react'; import { Label } from './Label'; import { stylesFactory, useTheme2 } from '../../themes'; import { css, cx } from '@emotion/css'; import { GrafanaTheme2 } from '@grafana/data'; import { FieldValidationMessage } from './FieldValidationMessage'; import { getChildId } from '../../utils/children'; export interface FieldProps extends HTMLAttributes<HTMLDivElement> { /** Form input element, i.e Input or Switch */ children: React.ReactElement; /** Label for the field */ label?: React.ReactNode; /** Description of the field */ description?: React.ReactNode; /** Indicates if field is in invalid state */ invalid?: boolean; /** Indicates if field is in loading state */ loading?: boolean; /** Indicates if field is disabled */ disabled?: boolean; /** Indicates if field is required */ required?: boolean; /** Error message to display */ error?: string | null; /** Indicates horizontal layout of the field */ horizontal?: boolean; /** make validation message overflow horizontally. Prevents pushing out adjacent inline components */ validationMessageHorizontalOverflow?: boolean; className?: string; } export const getFieldStyles = stylesFactory((theme: GrafanaTheme2) => { return { field: css` display: flex; flex-direction: column; margin-bottom: ${theme.spacing(2)}; `, fieldHorizontal: css` flex-direction: row; justify-content: space-between; flex-wrap: wrap; `, fieldValidationWrapper: css` margin-top: ${theme.spacing(0.5)}; `, fieldValidationWrapperHorizontal: css` flex: 1 1 100%; `, validationMessageHorizontalOverflow: css` width: 0; overflow-x: visible; & > * { white-space: nowrap; } `, }; }); export const Field: React.FC<FieldProps> = ({ label, description, horizontal, invalid, loading, disabled, required, error, children, className, validationMessageHorizontalOverflow, ...otherProps }) => { const theme = useTheme2(); const styles = getFieldStyles(theme); const inputId = getChildId(children); const labelElement = typeof label === 'string' ? ( <Label htmlFor={inputId} description={description}> {`${label}${required ? ' *' : ''}`} </Label> ) : ( label ); return ( <div className={cx(styles.field, horizontal && styles.fieldHorizontal, className)} {...otherProps}> {labelElement} <div> {React.cloneElement(children, { invalid, disabled, loading })} {invalid && error && !horizontal && ( <div className={cx(styles.fieldValidationWrapper, { [styles.validationMessageHorizontalOverflow]: !!validationMessageHorizontalOverflow, })} > <FieldValidationMessage>{error}</FieldValidationMessage> </div> )} </div> {invalid && error && horizontal && ( <div className={cx(styles.fieldValidationWrapper, styles.fieldValidationWrapperHorizontal, { [styles.validationMessageHorizontalOverflow]: !!validationMessageHorizontalOverflow, })} > <FieldValidationMessage>{error}</FieldValidationMessage> </div> )} </div> ); };
packages/grafana-ui/src/components/Forms/Field.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0024770470336079597, 0.0003802704450208694, 0.00016441840853076428, 0.00017172397929243743, 0.0006333572091534734 ]
{ "id": 5, "code_window": [ " value={annotation.name}\n", " onChange={onNameChange}\n", " width={50}\n", " />\n", " </Field>\n", " <Field label=\"Data source\">\n", " <DataSourcePicker\n", " width={50}\n", " annotations\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Field label=\"Data source\" htmlFor=\"data-source-picker\">\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx", "type": "replace", "edit_start_line_idx": 80 }
import { parseLabels, formatLabels, findCommonLabels, findUniqueLabels, matchAllLabels } from './labels'; import { Labels } from '../types/data'; describe('parseLabels()', () => { it('returns no labels on empty labels string', () => { expect(parseLabels('')).toEqual({}); expect(parseLabels('{}')).toEqual({}); }); it('returns labels on labels string', () => { expect(parseLabels('{foo="bar", baz="42"}')).toEqual({ foo: 'bar', baz: '42' }); }); }); describe('formatLabels()', () => { it('returns no labels on empty label set', () => { expect(formatLabels({})).toEqual(''); expect(formatLabels({}, 'foo')).toEqual('foo'); }); it('returns label string on label set', () => { expect(formatLabels({ foo: 'bar', baz: '42' })).toEqual('{baz="42", foo="bar"}'); }); }); describe('findCommonLabels()', () => { it('returns no common labels on empty sets', () => { expect(findCommonLabels([{}])).toEqual({}); expect(findCommonLabels([{}, {}])).toEqual({}); }); it('returns no common labels on differing sets', () => { expect(findCommonLabels([{ foo: 'bar' }, {}])).toEqual({}); expect(findCommonLabels([{}, { foo: 'bar' }])).toEqual({}); expect(findCommonLabels([{ baz: '42' }, { foo: 'bar' }])).toEqual({}); expect(findCommonLabels([{ foo: '42', baz: 'bar' }, { foo: 'bar' }])).toEqual({}); }); it('returns the single labels set as common labels', () => { expect(findCommonLabels([{ foo: 'bar' }])).toEqual({ foo: 'bar' }); }); }); describe('findUniqueLabels()', () => { it('returns no uncommon labels on empty sets', () => { expect(findUniqueLabels({}, {})).toEqual({}); }); it('returns all labels given no common labels', () => { expect(findUniqueLabels({ foo: '"bar"' }, {})).toEqual({ foo: '"bar"' }); }); it('returns all labels except the common labels', () => { expect(findUniqueLabels({ foo: '"bar"', baz: '"42"' }, { foo: '"bar"' })).toEqual({ baz: '"42"' }); }); }); describe('matchAllLabels()', () => { it('empty labels do math', () => { expect(matchAllLabels({}, {})).toBeTruthy(); }); it('missing labels', () => { expect(matchAllLabels({ foo: 'bar' }, {})).toBeFalsy(); }); it('extra labels should match', () => { expect(matchAllLabels({ foo: 'bar' }, { foo: 'bar', baz: '22' })).toBeTruthy(); }); it('be graceful with null values (match)', () => { expect(matchAllLabels({ foo: 'bar' })).toBeFalsy(); }); it('be graceful with null values (match)', () => { expect(matchAllLabels((undefined as unknown) as Labels, { foo: 'bar' })).toBeTruthy(); }); });
packages/grafana-data/src/utils/labels.test.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017608641064725816, 0.00017315959848929197, 0.00016928704280871898, 0.00017332404968328774, 0.0000018920419506684993 ]
{ "id": 5, "code_window": [ " value={annotation.name}\n", " onChange={onNameChange}\n", " width={50}\n", " />\n", " </Field>\n", " <Field label=\"Data source\">\n", " <DataSourcePicker\n", " width={50}\n", " annotations\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Field label=\"Data source\" htmlFor=\"data-source-picker\">\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx", "type": "replace", "edit_start_line_idx": 80 }
import { SelectableValue } from '@grafana/data'; export interface Converter extends RuleSetting { [t: string]: any; } export interface Processor extends RuleSetting { [t: string]: any; } export interface Output extends RuleSetting { [t: string]: any; } export interface RuleSetting<T = any> { type: string; [key: string]: any; } export interface RuleSettings { converter?: Converter; frameProcessors?: Processor[]; frameOutputs?: Output[]; } export interface Rule { pattern: string; settings: RuleSettings; } export interface Pipeline { rules: Rule[]; } export interface GrafanaCloudBackend { uid: string; settings: any; } export type RuleType = 'converter' | 'frameProcessors' | 'frameOutputs'; export interface PipelineListOption { type: string; description: string; example?: object; } export interface EntitiesTypes { converters: PipelineListOption[]; frameProcessors: PipelineListOption[]; frameOutputs: PipelineListOption[]; } export interface PipeLineEntitiesInfo { converter: SelectableValue[]; frameProcessors: SelectableValue[]; frameOutputs: SelectableValue[]; getExample: (rule: RuleType, type: string) => object; }
public/app/features/live/pages/types.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0005183301982469857, 0.00022571609588339925, 0.00016483817307744175, 0.000168019556440413, 0.0001308740465901792 ]
{ "id": 5, "code_window": [ " value={annotation.name}\n", " onChange={onNameChange}\n", " width={50}\n", " />\n", " </Field>\n", " <Field label=\"Data source\">\n", " <DataSourcePicker\n", " width={50}\n", " annotations\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Field label=\"Data source\" htmlFor=\"data-source-picker\">\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx", "type": "replace", "edit_start_line_idx": 80 }
import { Meta, Props } from '@storybook/addon-docs/blocks'; import { Alert } from './Alert'; <Meta title="MDX|Alert" component={Alert} /> # Alert An alert displays an important message in a way that attracts the user's attention without interrupting the user's task. `onRemove` handler can be used to enable manually dismissing the alert. # Usage ```jsx <Alert title="Some very important message" severity="info" /> ``` <Props of={Alert} />
packages/grafana-ui/src/components/Alert/Alert.mdx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00016972862067632377, 0.0001696332765277475, 0.00016953791782725602, 0.0001696332765277475, 9.53514245338738e-8 ]
{ "id": 6, "code_window": [ " ) : null}\n", " </td>\n", " <td style={{ width: '1%' }}>\n", " <DeleteButton size=\"sm\" onConfirm={() => onDelete(idx)} />\n", " </td>\n", " </tr>\n", " ))}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <DeleteButton\n", " size=\"sm\"\n", " onConfirm={() => onDelete(idx)}\n", " aria-label={`Delete query with title \"${annotation.name}\"`}\n", " />\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsList.tsx", "type": "replace", "edit_start_line_idx": 76 }
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 source settings page Save and Test button', alert: 'Data source settings page Alert', }, DataSources: { url: '/datasources', dataSources: (dataSourceName: string) => `Data source list item ${dataSourceName}`, }, AddDataSource: { url: '/datasources/new', dataSourcePlugins: (pluginName: string) => `Data source plugin item ${pluginName}`, }, ConfirmModal: { delete: 'Confirm Modal Danger Button', }, AddDashboard: { url: '/dashboard/new', addNewPanel: 'Add new panel', addNewRow: 'Add new row', addNewPanelLibrary: 'Add new panel from panel library', }, Dashboard: { url: (uid: string) => `/d/${uid}`, DashNav: { nav: 'Dashboard navigation', }, 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}`, }, Settings: { 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', timezone: 'Time zone picker select container', title: 'Dashboard settings page title', }, Annotations: { List: { addAnnotationCTA: Components.CallToActionCard.button('Add annotation query'), }, Settings: { name: 'Annotations settings name input', }, }, Variables: { List: { addVariableCTA: Components.CallToActionCard.button('Add variable'), newButton: 'Variable editor New variable button', table: 'Variable editor Table', tableRowNameFields: (variableName: string) => `Variable editor Table Name field ${variableName}`, tableRowDefinitionFields: (variableName: string) => `Variable editor Table Definition 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', modeLabelEdit: 'Variable editor Header mode Edit', generalNameInput: 'Variable editor Form Name field', generalTypeSelect: 'Variable editor Form Type select', generalLabelInput: 'Variable editor Form Label field', generalHideSelect: 'Variable editor Form Hide select', selectionOptionsMultiSwitch: 'Variable editor Form Multi switch', selectionOptionsIncludeAllSwitch: 'Variable editor Form IncludeAll switch', selectionOptionsCustomAllInput: 'Variable editor Form IncludeAll field', previewOfValuesOption: 'Variable editor Preview of Values option', submitButton: 'Variable editor Submit button', }, QueryVariable: { queryOptionsDataSourceSelect: Components.DataSourcePicker.container, queryOptionsRefreshSelect: 'Variable editor Form Query Refresh select', queryOptionsRegExInput: 'Variable editor Form Query RegEx field', queryOptionsSortSelect: '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', }, TextBoxVariable: { textBoxOptionsQueryInput: 'Variable editor Form TextBox Query field', }, }, }, }, }, Dashboards: { url: '/dashboards', 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', }, Explore: { url: '/explore', General: { container: 'data-testid Explore', graph: 'Explore Graph', table: 'Explore Table', scrollBar: () => '.scrollbar-view', }, Toolbar: { navBar: () => '.explore-toolbar', }, }, 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', itemRow: 'Playlist item row', itemIdType: 'Playlist item dashboard by ID type', itemTagType: 'Playlist item dashboard by Tag type', itemMoveUp: 'Move playlist item order up', itemMoveDown: 'Move playlist item order down', itemDelete: 'Delete playlist item', }, };
packages/grafana-e2e-selectors/src/selectors/pages.ts
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001737885468173772, 0.00016882881755009294, 0.00016402662731707096, 0.0001691878424026072, 0.0000027302405669615837 ]
{ "id": 6, "code_window": [ " ) : null}\n", " </td>\n", " <td style={{ width: '1%' }}>\n", " <DeleteButton size=\"sm\" onConfirm={() => onDelete(idx)} />\n", " </td>\n", " </tr>\n", " ))}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <DeleteButton\n", " size=\"sm\"\n", " onConfirm={() => onDelete(idx)}\n", " aria-label={`Delete query with title \"${annotation.name}\"`}\n", " />\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsList.tsx", "type": "replace", "edit_start_line_idx": 76 }
import React, { FC, useCallback, useMemo } from 'react'; import { GrafanaTheme2, SelectableValue, StandardEditorProps } from '@grafana/data'; import { ScaleDimensionConfig, ScaleDimensionOptions } from '../types'; import { InlineField, InlineFieldRow, Select, useStyles2 } from '@grafana/ui'; import { useFieldDisplayNames, useSelectOptions, } from '../../../../../packages/grafana-ui/src/components/MatchersUI/utils'; import { NumberInput } from './NumberInput'; import { css } from '@emotion/css'; import { validateScaleOptions, validateScaleConfig } from '../scale'; const fixedValueOption: SelectableValue<string> = { label: 'Fixed value', value: '_____fixed_____', }; export const ScaleDimensionEditor: FC<StandardEditorProps<ScaleDimensionConfig, ScaleDimensionOptions, any>> = ( props ) => { const { value, context, onChange, item } = props; const { settings } = item; const styles = useStyles2(getStyles); const fieldName = value?.field; const isFixed = Boolean(!fieldName); const names = useFieldDisplayNames(context.data); const selectOptions = useSelectOptions(names, fieldName, fixedValueOption); const minMaxStep = useMemo(() => { return validateScaleOptions(settings); }, [settings]); // Validate and update const validateAndDoChange = useCallback( (v: ScaleDimensionConfig) => { // always called with a copy so no need to spread onChange(validateScaleConfig(v, minMaxStep)); }, [onChange, minMaxStep] ); const onSelectChange = useCallback( (selection: SelectableValue<string>) => { const field = selection.value; if (field && field !== fixedValueOption.value) { validateAndDoChange({ ...value, field, }); } else { validateAndDoChange({ ...value, field: undefined, }); } }, [validateAndDoChange, value] ); const onMinChange = useCallback( (min?: number) => { if (min !== undefined) { validateAndDoChange({ ...value, min, }); } }, [validateAndDoChange, value] ); const onMaxChange = useCallback( (max?: number) => { if (max !== undefined) { validateAndDoChange({ ...value, max, }); } }, [validateAndDoChange, value] ); const onValueChange = useCallback( (fixed?: number) => { if (fixed !== undefined) { validateAndDoChange({ ...value, fixed, }); } }, [validateAndDoChange, value] ); const val = value ?? {}; const selectedOption = isFixed ? fixedValueOption : selectOptions.find((v) => v.value === fieldName); return ( <> <div> <Select menuShouldPortal value={selectedOption} options={selectOptions} onChange={onSelectChange} noOptionsMessage="No fields found" /> </div> <div className={styles.range}> {isFixed && ( <InlineFieldRow> <InlineField label="Value" labelWidth={8} grow={true}> <NumberInput value={val.fixed} {...minMaxStep} onChange={onValueChange} /> </InlineField> </InlineFieldRow> )} {!isFixed && !minMaxStep.hideRange && ( <> <InlineFieldRow> <InlineField label="Min" labelWidth={8} grow={true}> <NumberInput value={val.min} {...minMaxStep} onChange={onMinChange} /> </InlineField> </InlineFieldRow> <InlineFieldRow> <InlineField label="Max" labelWidth={8} grow={true}> <NumberInput value={val.max} {...minMaxStep} onChange={onMaxChange} /> </InlineField> </InlineFieldRow> </> )} </div> </> ); }; const getStyles = (theme: GrafanaTheme2) => ({ range: css` padding-top: 8px; `, });
public/app/features/dimensions/editors/ScaleDimensionEditor.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00019154085021000355, 0.00017115862283390015, 0.00016515376046299934, 0.00016986153787001967, 0.000006358539849316003 ]
{ "id": 6, "code_window": [ " ) : null}\n", " </td>\n", " <td style={{ width: '1%' }}>\n", " <DeleteButton size=\"sm\" onConfirm={() => onDelete(idx)} />\n", " </td>\n", " </tr>\n", " ))}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <DeleteButton\n", " size=\"sm\"\n", " onConfirm={() => onDelete(idx)}\n", " aria-label={`Delete query with title \"${annotation.name}\"`}\n", " />\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsList.tsx", "type": "replace", "edit_start_line_idx": 76 }
import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { defaultQuery } from './constants'; import { QueryEditor, Props } from './QueryEditor'; import { scenarios } from './__mocks__/scenarios'; import { defaultStreamQuery } from './runStreams'; beforeEach(() => { jest.clearAllMocks(); }); const mockOnChange = jest.fn(); const props = { onRunQuery: jest.fn(), query: defaultQuery, onChange: mockOnChange, datasource: { getScenarios: () => Promise.resolve(scenarios), } as any, }; const setup = (testProps?: Partial<Props>) => { const editorProps = { ...props, ...testProps }; return render(<QueryEditor {...editorProps} />); }; describe('Test Datasource Query Editor', () => { it('should render with default scenario', async () => { setup(); expect(await screen.findByText(/random walk/i)).toBeInTheDocument(); expect(screen.getByRole('textbox', { name: 'Alias' })).toBeInTheDocument(); expect(screen.getByRole('textbox', { name: 'Labels' })).toBeInTheDocument(); }); it('should switch scenario and display its default values', async () => { const { rerender } = setup(); let select = (await screen.findByText('Scenario')).nextSibling!; await fireEvent.keyDown(select, { keyCode: 40 }); const scs = screen.getAllByLabelText('Select option'); expect(scs).toHaveLength(scenarios.length); await userEvent.click(screen.getByText('CSV Metric Values')); expect(mockOnChange).toHaveBeenCalledWith(expect.objectContaining({ scenarioId: 'csv_metric_values' })); await rerender( <QueryEditor {...props} query={{ ...defaultQuery, scenarioId: 'csv_metric_values', stringInput: '1,20,90,30,5,0' }} /> ); expect(await screen.findByRole('textbox', { name: /string input/i })).toBeInTheDocument(); expect(screen.getByRole('textbox', { name: /string input/i })).toHaveValue('1,20,90,30,5,0'); await fireEvent.keyDown(select, { keyCode: 40 }); await userEvent.click(screen.getByText('Grafana API')); expect(mockOnChange).toHaveBeenCalledWith( expect.objectContaining({ scenarioId: 'grafana_api', stringInput: 'datasources' }) ); rerender( <QueryEditor {...props} query={{ ...defaultQuery, scenarioId: 'grafana_api', stringInput: 'datasources' }} /> ); expect(await screen.findByText('Grafana API')).toBeInTheDocument(); expect(screen.getByText('Data Sources')).toBeInTheDocument(); await fireEvent.keyDown(select, { keyCode: 40 }); await userEvent.click(screen.getByText('Streaming Client')); expect(mockOnChange).toHaveBeenCalledWith( expect.objectContaining({ scenarioId: 'streaming_client', stream: defaultStreamQuery }) ); const streamQuery = { ...defaultQuery, stream: defaultStreamQuery, scenarioId: 'streaming_client' }; rerender(<QueryEditor {...props} query={streamQuery} />); expect(await screen.findByText('Streaming Client')).toBeInTheDocument(); expect(screen.getByText('Type')).toBeInTheDocument(); expect(screen.getByLabelText('Noise')).toHaveValue(2.2); expect(screen.getByLabelText('Speed (ms)')).toHaveValue(250); expect(screen.getByLabelText('Spread')).toHaveValue(3.5); expect(screen.getByLabelText('Bands')).toHaveValue(1); }); });
public/app/plugins/datasource/testdata/QueryEditor.test.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017547179595567286, 0.00017406820552423596, 0.00017051796021405607, 0.00017442737589590251, 0.0000014107577044342179 ]
{ "id": 6, "code_window": [ " ) : null}\n", " </td>\n", " <td style={{ width: '1%' }}>\n", " <DeleteButton size=\"sm\" onConfirm={() => onDelete(idx)} />\n", " </td>\n", " </tr>\n", " ))}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <DeleteButton\n", " size=\"sm\"\n", " onConfirm={() => onDelete(idx)}\n", " aria-label={`Delete query with title \"${annotation.name}\"`}\n", " />\n" ], "file_path": "public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsList.tsx", "type": "replace", "edit_start_line_idx": 76 }
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./index.production.js'); } else { module.exports = require('./index.development.js'); }
packages/grafana-schema/index.js
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00016963834059424698, 0.00016963834059424698, 0.00016963834059424698, 0.00016963834059424698, 0 ]
{ "id": 7, "code_window": [ " screen.queryByLabelText(selectors.components.CallToActionCard.button('Add annotation query'))\n", " ).toBeInTheDocument();\n", " expect(screen.queryByRole('button', { name: /new query/i })).not.toBeInTheDocument();\n", "\n", " userEvent.click(screen.getByRole('button', { name: /delete/i }));\n", "\n", " expect(screen.queryAllByRole('row').length).toBe(0);\n", " expect(\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " userEvent.click(screen.getByRole('button', { name: /^delete$/i }));\n" ], "file_path": "public/app/features/dashboard/components/DashboardSettings/AnnotationsSettings.test.tsx", "type": "replace", "edit_start_line_idx": 150 }
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 source settings page Save and Test button', alert: 'Data source settings page Alert', }, DataSources: { url: '/datasources', dataSources: (dataSourceName: string) => `Data source list item ${dataSourceName}`, }, AddDataSource: { url: '/datasources/new', dataSourcePlugins: (pluginName: string) => `Data source plugin item ${pluginName}`, }, ConfirmModal: { delete: 'Confirm Modal Danger Button', }, AddDashboard: { url: '/dashboard/new', addNewPanel: 'Add new panel', addNewRow: 'Add new row', addNewPanelLibrary: 'Add new panel from panel library', }, Dashboard: { url: (uid: string) => `/d/${uid}`, DashNav: { nav: 'Dashboard navigation', }, 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}`, }, Settings: { 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', timezone: 'Time zone picker select container', title: 'Dashboard settings page title', }, Annotations: { List: { addAnnotationCTA: Components.CallToActionCard.button('Add annotation query'), }, Settings: { name: 'Annotations settings name input', }, }, Variables: { List: { addVariableCTA: Components.CallToActionCard.button('Add variable'), newButton: 'Variable editor New variable button', table: 'Variable editor Table', tableRowNameFields: (variableName: string) => `Variable editor Table Name field ${variableName}`, tableRowDefinitionFields: (variableName: string) => `Variable editor Table Definition 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', modeLabelEdit: 'Variable editor Header mode Edit', generalNameInput: 'Variable editor Form Name field', generalTypeSelect: 'Variable editor Form Type select', generalLabelInput: 'Variable editor Form Label field', generalHideSelect: 'Variable editor Form Hide select', selectionOptionsMultiSwitch: 'Variable editor Form Multi switch', selectionOptionsIncludeAllSwitch: 'Variable editor Form IncludeAll switch', selectionOptionsCustomAllInput: 'Variable editor Form IncludeAll field', previewOfValuesOption: 'Variable editor Preview of Values option', submitButton: 'Variable editor Submit button', }, QueryVariable: { queryOptionsDataSourceSelect: Components.DataSourcePicker.container, queryOptionsRefreshSelect: 'Variable editor Form Query Refresh select', queryOptionsRegExInput: 'Variable editor Form Query RegEx field', queryOptionsSortSelect: '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', }, TextBoxVariable: { textBoxOptionsQueryInput: 'Variable editor Form TextBox Query field', }, }, }, }, }, Dashboards: { url: '/dashboards', 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', }, Explore: { url: '/explore', General: { container: 'data-testid Explore', graph: 'Explore Graph', table: 'Explore Table', scrollBar: () => '.scrollbar-view', }, Toolbar: { navBar: () => '.explore-toolbar', }, }, 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', itemRow: 'Playlist item row', itemIdType: 'Playlist item dashboard by ID type', itemTagType: 'Playlist item dashboard by Tag type', itemMoveUp: 'Move playlist item order up', itemMoveDown: 'Move playlist item order down', itemDelete: 'Delete playlist item', }, };
packages/grafana-e2e-selectors/src/selectors/pages.ts
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0005758840125054121, 0.00019556614279281348, 0.00016406307986471802, 0.00017095428484026343, 0.00009300438250647858 ]
{ "id": 7, "code_window": [ " screen.queryByLabelText(selectors.components.CallToActionCard.button('Add annotation query'))\n", " ).toBeInTheDocument();\n", " expect(screen.queryByRole('button', { name: /new query/i })).not.toBeInTheDocument();\n", "\n", " userEvent.click(screen.getByRole('button', { name: /delete/i }));\n", "\n", " expect(screen.queryAllByRole('row').length).toBe(0);\n", " expect(\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " userEvent.click(screen.getByRole('button', { name: /^delete$/i }));\n" ], "file_path": "public/app/features/dashboard/components/DashboardSettings/AnnotationsSettings.test.tsx", "type": "replace", "edit_start_line_idx": 150 }
import React from 'react'; import { QueryOperationRow } from './QueryOperationRow'; import { mount, shallow } from 'enzyme'; import { act } from 'react-dom/test-utils'; describe('QueryOperationRow', () => { it('renders', () => { expect(() => shallow( <QueryOperationRow id="test-id" index={0}> <div>Test</div> </QueryOperationRow> ) ).not.toThrow(); }); describe('callbacks', () => { it('should not call onOpen when component is shallowed', async () => { const onOpenSpy = jest.fn(); // @ts-ignore strict null error, you shouldn't use promise like approach with act but I don't know what the intention is here await act(async () => { shallow( <QueryOperationRow onOpen={onOpenSpy} id="test-id" index={0}> <div>Test</div> </QueryOperationRow> ); }); expect(onOpenSpy).not.toBeCalled(); }); it('should call onOpen when row is opened and onClose when row is collapsed', async () => { const onOpenSpy = jest.fn(); const onCloseSpy = jest.fn(); const wrapper = mount( <QueryOperationRow title="title" onOpen={onOpenSpy} onClose={onCloseSpy} isOpen={false} id="test-id" index={0}> <div>Test</div> </QueryOperationRow> ); const titleEl = wrapper.find({ 'aria-label': 'Query operation row title' }); expect(titleEl).toHaveLength(1); // @ts-ignore strict null error, you shouldn't use promise like approach with act but I don't know what the intention is here await act(async () => { // open titleEl.first().simulate('click'); }); // @ts-ignore strict null error, you shouldn't use promise like approach with act but I don't know what the intention is here await act(async () => { // close titleEl.first().simulate('click'); }); expect(onOpenSpy).toBeCalledTimes(1); expect(onCloseSpy).toBeCalledTimes(1); }); }); describe('headerElement rendering', () => { it('should render headerElement provided as element', () => { const title = <div aria-label="test title">Test</div>; const wrapper = shallow( <QueryOperationRow headerElement={title} id="test-id" index={0}> <div>Test</div> </QueryOperationRow> ); const titleEl = wrapper.find({ 'aria-label': 'test title' }); expect(titleEl).toHaveLength(1); }); it('should render headerElement provided as function', () => { const title = () => <div aria-label="test title">Test</div>; const wrapper = shallow( <QueryOperationRow headerElement={title} id="test-id" index={0}> <div>Test</div> </QueryOperationRow> ); const titleEl = wrapper.find({ 'aria-label': 'test title' }); expect(titleEl).toHaveLength(1); }); it('should expose api to headerElement rendered as function', () => { const propsSpy = jest.fn(); const title = (props: any) => { propsSpy(props); return <div aria-label="test title">Test</div>; }; shallow( <QueryOperationRow headerElement={title} id="test-id" index={0}> <div>Test</div> </QueryOperationRow> ); expect(Object.keys(propsSpy.mock.calls[0][0])).toContain('isOpen'); }); }); describe('actions rendering', () => { it('should render actions provided as element', () => { const actions = <div aria-label="test actions">Test</div>; const wrapper = shallow( <QueryOperationRow actions={actions} id="test-id" index={0}> <div>Test</div> </QueryOperationRow> ); const actionsEl = wrapper.find({ 'aria-label': 'test actions' }); expect(actionsEl).toHaveLength(1); }); it('should render actions provided as function', () => { const actions = () => <div aria-label="test actions">Test</div>; const wrapper = shallow( <QueryOperationRow actions={actions} id="test-id" index={0}> <div>Test</div> </QueryOperationRow> ); const actionsEl = wrapper.find({ 'aria-label': 'test actions' }); expect(actionsEl).toHaveLength(1); }); it('should expose api to title rendered as function', () => { const propsSpy = jest.fn(); const actions = (props: any) => { propsSpy(props); return <div aria-label="test actions">Test</div>; }; shallow( <QueryOperationRow actions={actions} id="test-id" index={0}> <div>Test</div> </QueryOperationRow> ); expect(Object.keys(propsSpy.mock.calls[0][0])).toEqual(['isOpen', 'onOpen', 'onClose']); }); }); });
public/app/core/components/QueryOperationRow/QueryOperationRow.test.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017486599972471595, 0.0001713810343062505, 0.00016734609380364418, 0.00017180785653181374, 0.000002068228013740736 ]
{ "id": 7, "code_window": [ " screen.queryByLabelText(selectors.components.CallToActionCard.button('Add annotation query'))\n", " ).toBeInTheDocument();\n", " expect(screen.queryByRole('button', { name: /new query/i })).not.toBeInTheDocument();\n", "\n", " userEvent.click(screen.getByRole('button', { name: /delete/i }));\n", "\n", " expect(screen.queryAllByRole('row').length).toBe(0);\n", " expect(\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " userEvent.click(screen.getByRole('button', { name: /^delete$/i }));\n" ], "file_path": "public/app/features/dashboard/components/DashboardSettings/AnnotationsSettings.test.tsx", "type": "replace", "edit_start_line_idx": 150 }
import React, { createElement } from 'react'; import { HighlightPart } from '../../types'; interface Props { text: string; highlightParts: HighlightPart[]; highlightClassName: string; } /** * Flattens parts into a list of indices pointing to the index where a part * (highlighted or not highlighted) starts. Adds extra indices if needed * at the beginning or the end to ensure the entire text is covered. */ function getStartIndices(parts: HighlightPart[], length: number): number[] { const indices: number[] = []; parts.forEach((part) => { indices.push(part.start, part.end + 1); }); if (indices[0] !== 0) { indices.unshift(0); } if (indices[indices.length - 1] !== length) { indices.push(length); } return indices; } export const PartialHighlighter: React.FC<Props> = (props: Props) => { let { highlightParts, text, highlightClassName } = props; if (!highlightParts?.length) { return null; } let children = []; let indices = getStartIndices(highlightParts, text.length); let highlighted = highlightParts[0].start === 0; for (let i = 1; i < indices.length; i++) { let start = indices[i - 1]; let end = indices[i]; children.push( createElement(highlighted ? 'mark' : 'span', { key: i - 1, children: text.substring(start, end), className: highlighted ? highlightClassName : undefined, }) ); highlighted = !highlighted; } return <div>{children}</div>; };
packages/grafana-ui/src/components/Typeahead/PartialHighlighter.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017747316451277584, 0.00017231014498975128, 0.0001660997368162498, 0.00017303362255916, 0.0000034453532862244174 ]
{ "id": 7, "code_window": [ " screen.queryByLabelText(selectors.components.CallToActionCard.button('Add annotation query'))\n", " ).toBeInTheDocument();\n", " expect(screen.queryByRole('button', { name: /new query/i })).not.toBeInTheDocument();\n", "\n", " userEvent.click(screen.getByRole('button', { name: /delete/i }));\n", "\n", " expect(screen.queryAllByRole('row').length).toBe(0);\n", " expect(\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " userEvent.click(screen.getByRole('button', { name: /^delete$/i }));\n" ], "file_path": "public/app/features/dashboard/components/DashboardSettings/AnnotationsSettings.test.tsx", "type": "replace", "edit_start_line_idx": 150 }
import { TOGGLE_ALL_CHECKED, TOGGLE_CHECKED, DELETE_ITEMS, MOVE_ITEMS } from './actionTypes'; import { manageDashboardsReducer as reducer, manageDashboardsState as state } from './manageDashboards'; import { sections } from '../testData'; import { DashboardSection, UidsToDelete } from '../types'; // Remove Recent and Starred sections as they're not used in manage dashboards const results = sections.slice(2); describe('Manage dashboards reducer', () => { it('should return the initial state', () => { expect(reducer(state, {} as any)).toEqual(state); }); it('should handle TOGGLE_ALL_CHECKED', () => { const newState = reducer({ ...state, results }, { type: TOGGLE_ALL_CHECKED }); expect(newState.results.every((result: any) => result.checked === true)).toBe(true); expect(newState.results.every((result: any) => result.items.every((item: any) => item.checked === true))).toBe( true ); expect(newState.allChecked).toBe(true); const newState2 = reducer({ ...newState, results }, { type: TOGGLE_ALL_CHECKED }); expect(newState2.results.every((result: any) => result.checked === false)).toBe(true); expect(newState2.results.every((result: any) => result.items.every((item: any) => item.checked === false))).toBe( true ); expect(newState2.allChecked).toBe(false); }); it('should handle TOGGLE_CHECKED sections', () => { const newState = reducer({ ...state, results }, { type: TOGGLE_CHECKED, payload: results[0] }); expect(newState.results[0].checked).toBe(true); expect(newState.results[1].checked).toBeFalsy(); const newState2 = reducer(newState, { type: TOGGLE_CHECKED, payload: results[1] }); expect(newState2.results[0].checked).toBe(true); expect(newState2.results[1].checked).toBe(true); }); it('should handle TOGGLE_CHECKED items', () => { const newState = reducer({ ...state, results }, { type: TOGGLE_CHECKED, payload: { id: 4069 } }); expect(newState.results[3].items[0].checked).toBe(true); const newState2 = reducer(newState, { type: TOGGLE_CHECKED, payload: { id: 1 } }); expect(newState2.results[3].items[0].checked).toBe(true); expect(newState2.results[3].items[1].checked).toBeFalsy(); expect(newState2.results[3].items[2].checked).toBe(true); }); it('should handle DELETE_ITEMS', () => { const toDelete: UidsToDelete = { dashboards: ['OzAIf_rWz', 'lBdLINUWk'], folders: ['search-test-data'] }; const newState = reducer({ ...state, results }, { type: DELETE_ITEMS, payload: toDelete }); expect(newState.results).toHaveLength(3); expect(newState.results[1].id).toEqual(4074); expect(newState.results[2].items).toHaveLength(1); expect(newState.results[2].items[0].id).toEqual(4069); }); it('should handle MOVE_ITEMS', () => { // Move 2 dashboards to a folder with id 2 const toMove = { dashboards: [ { id: 4072, uid: 'OzAIf_rWz', title: 'New dashboard Copy 3', type: 'dash-db', isStarred: false, }, { id: 1, uid: 'lBdLINUWk', title: 'Prom dash', type: 'dash-db', isStarred: true, }, ], folder: { id: 2 }, }; const newState = reducer({ ...state, results }, { type: MOVE_ITEMS, payload: toMove }); expect(newState.results[0].items).toHaveLength(2); expect(newState.results[0].items[0].uid).toEqual('OzAIf_rWz'); expect(newState.results[0].items[1].uid).toEqual('lBdLINUWk'); expect(newState.results[3].items).toHaveLength(1); expect(newState.results[3].items[0].uid).toEqual('LCFWfl9Zz'); }); it('should not display dashboards in a non-expanded folder', () => { const general = results.find((res) => res.id === 0); const toMove = { dashboards: general?.items, folder: { id: 4074 } }; const newState = reducer({ ...state, results }, { type: MOVE_ITEMS, payload: toMove }); expect(newState.results.find((res: DashboardSection) => res.id === 4074).items).toHaveLength(0); expect(newState.results.find((res: DashboardSection) => res.id === 0).items).toHaveLength(0); }); });
public/app/features/search/reducers/manageDashboards.test.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017801328795030713, 0.00017355053569190204, 0.00017026546993292868, 0.00017299466708209366, 0.0000022130031993583543 ]
{ "id": 8, "code_window": [ " const containerClassNames = classnames(styles.dashboardContainer, {\n", " 'panel-in-fullscreen': viewPanel,\n", " });\n", "\n", " return (\n", " <div className={containerClassNames}>\n", " {kioskMode !== KioskMode.Full && (\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " const showSubMenu = !editPanel && kioskMode === KioskMode.Off && !this.props.queryParams.editview;\n" ], "file_path": "public/app/features/dashboard/containers/DashboardPage.tsx", "type": "add", "edit_start_line_idx": 337 }
import React, { PropsWithChildren, ReactElement } from 'react'; import { InlineFormLabel, Select, useStyles } from '@grafana/ui'; import { GrafanaTheme, SelectableValue } from '@grafana/data'; import { css } from '@emotion/css'; interface VariableSelectFieldProps<T> { name: string; value: SelectableValue<T>; options: Array<SelectableValue<T>>; onChange: (option: SelectableValue<T>) => void; tooltip?: string; ariaLabel?: string; width?: number; labelWidth?: number; } export function VariableSelectField({ name, value, options, tooltip, onChange, ariaLabel, width, labelWidth, }: PropsWithChildren<VariableSelectFieldProps<any>>): ReactElement { const styles = useStyles(getStyles); return ( <> <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip}> {name} </InlineFormLabel> <div aria-label={ariaLabel}> <Select menuShouldPortal onChange={onChange} value={value} width={width ?? 25} options={options} className={styles.selectContainer} /> </div> </> ); } function getStyles(theme: GrafanaTheme) { return { selectContainer: css` margin-right: ${theme.spacing.xs}; `, }; }
public/app/features/variables/editor/VariableSelectField.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0018507445929571986, 0.0006740600802004337, 0.00017189249047078192, 0.00017539114924147725, 0.0007140713278204203 ]
{ "id": 8, "code_window": [ " const containerClassNames = classnames(styles.dashboardContainer, {\n", " 'panel-in-fullscreen': viewPanel,\n", " });\n", "\n", " return (\n", " <div className={containerClassNames}>\n", " {kioskMode !== KioskMode.Full && (\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " const showSubMenu = !editPanel && kioskMode === KioskMode.Off && !this.props.queryParams.editview;\n" ], "file_path": "public/app/features/dashboard/containers/DashboardPage.tsx", "type": "add", "edit_start_line_idx": 337 }
import { CoreApp, DataQueryRequest, DataSourceApi, PanelData, rangeUtil, ScopedVars, QueryRunnerOptions, QueryRunner as QueryRunnerSrv, LoadingState, } from '@grafana/data'; import { getTemplateSrv } from '@grafana/runtime'; import { getDatasourceSrv } from 'app/features/plugins/datasource_srv'; import { cloneDeep } from 'lodash'; import { from, Observable, ReplaySubject, Unsubscribable } from 'rxjs'; import { first } from 'rxjs/operators'; import { getNextRequestId } from './PanelQueryRunner'; import { setStructureRevision } from './processing/revision'; import { preProcessPanelData, runRequest } from './runRequest'; export class QueryRunner implements QueryRunnerSrv { private subject: ReplaySubject<PanelData>; private subscription?: Unsubscribable; private lastResult?: PanelData; constructor() { this.subject = new ReplaySubject(1); } get(): Observable<PanelData> { return this.subject.asObservable(); } run(options: QueryRunnerOptions): void { const { queries, timezone, datasource, panelId, app, dashboardId, timeRange, timeInfo, cacheTimeout, maxDataPoints, scopedVars, minInterval, } = options; if (this.subscription) { this.subscription.unsubscribe(); } const request: DataQueryRequest = { app: app ?? CoreApp.Unknown, requestId: getNextRequestId(), timezone, panelId, dashboardId, range: timeRange, timeInfo, interval: '', intervalMs: 0, targets: cloneDeep(queries), maxDataPoints: maxDataPoints, scopedVars: scopedVars || {}, cacheTimeout, startTime: Date.now(), }; // Add deprecated property (request as any).rangeRaw = timeRange.raw; from(getDataSource(datasource, request.scopedVars)) .pipe(first()) .subscribe({ next: (ds) => { // Attach the datasource name to each query request.targets = request.targets.map((query) => { if (!query.datasource) { query.datasource = ds.name; } return query; }); const lowerIntervalLimit = minInterval ? getTemplateSrv().replace(minInterval, request.scopedVars) : ds.interval; const norm = rangeUtil.calculateInterval(timeRange, maxDataPoints, lowerIntervalLimit); // make shallow copy of scoped vars, // and add built in variables interval and interval_ms request.scopedVars = Object.assign({}, request.scopedVars, { __interval: { text: norm.interval, value: norm.interval }, __interval_ms: { text: norm.intervalMs.toString(), value: norm.intervalMs }, }); request.interval = norm.interval; request.intervalMs = norm.intervalMs; this.subscription = runRequest(ds, request).subscribe({ next: (data) => { const results = preProcessPanelData(data, this.lastResult); this.lastResult = setStructureRevision(results, this.lastResult); // Store preprocessed query results for applying overrides later on in the pipeline this.subject.next(this.lastResult); }, }); }, error: (error) => console.error('PanelQueryRunner Error', error), }); } cancel(): void { if (!this.subscription) { return; } this.subscription.unsubscribe(); // If we have an old result with loading state, send it with done state if (this.lastResult && this.lastResult.state === LoadingState.Loading) { this.subject.next({ ...this.lastResult, state: LoadingState.Done, }); } } destroy(): void { // Tell anyone listening that we are done if (this.subject) { this.subject.complete(); } if (this.subscription) { this.subscription.unsubscribe(); } } } async function getDataSource( datasource: string | DataSourceApi | null, scopedVars: ScopedVars ): Promise<DataSourceApi> { if (datasource && (datasource as any).query) { return datasource as DataSourceApi; } return await getDatasourceSrv().get(datasource as string, scopedVars); }
public/app/features/query/state/QueryRunner.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00200891331769526, 0.0003272532485425472, 0.0001637233217479661, 0.00017444553668610752, 0.00046180011122487485 ]
{ "id": 8, "code_window": [ " const containerClassNames = classnames(styles.dashboardContainer, {\n", " 'panel-in-fullscreen': viewPanel,\n", " });\n", "\n", " return (\n", " <div className={containerClassNames}>\n", " {kioskMode !== KioskMode.Full && (\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " const showSubMenu = !editPanel && kioskMode === KioskMode.Off && !this.props.queryParams.editview;\n" ], "file_path": "public/app/features/dashboard/containers/DashboardPage.tsx", "type": "add", "edit_start_line_idx": 337 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100px" height="100px" viewBox="692 0 100 100" style="enable-background:new 692 0 100 100;" xml:space="preserve"> <style type="text/css"> .st0{fill:#787878;} </style> <g> <path class="st0" d="M780.9,44.8c-3.2,0-5.9,2.1-6.7,5h-18.6c-0.2-1.6-0.6-3.1-1.2-4.6l12.5-7.2c1.5,1.6,3.6,2.5,5.9,2.5 c4.5,0,8.2-3.7,8.2-8.2s-3.7-8.2-8.2-8.2s-8.2,3.7-8.2,8.2c0,0.8,0.1,1.5,0.3,2.3l-12.5,7.2c-0.9-1.3-2.1-2.4-3.3-3.3l2.3-4.1 c0.8,0.2,1.5,0.3,2.4,0.3c4.6,0,8.4-3.8,8.4-8.4s-3.8-8.4-8.4-8.4c-4.6,0-8.4,3.8-8.4,8.4c0,2.4,1,4.6,2.6,6.1l-2.3,4 c-1.4-0.6-3-1-4.6-1.2V12c2.4-0.8,4.2-3.1,4.2-5.8c0-3.4-2.8-6.2-6.2-6.2c-3.4,0-6.2,2.8-6.2,6.2c0,2.7,1.8,5,4.2,5.8v23.3 c-1.6,0.2-3.1,0.6-4.6,1.2l-8.3-14.3c1.1-1.2,1.8-2.8,1.8-4.6c0-3.8-3.1-6.8-6.8-6.8c-3.7,0-6.8,3.1-6.8,6.8s3.1,6.8,6.8,6.8 c0.5,0,1-0.1,1.5-0.2l8.2,14.3c-1.3,1-2.4,2.1-3.4,3.4l-14.3-8.2c0.1-0.5,0.2-1,0.2-1.6c0-3.8-3.1-6.8-6.8-6.8 c-3.7,0-6.8,3.1-6.8,6.8c0,3.8,3.1,6.8,6.8,6.8c1.8,0,3.4-0.7,4.6-1.8l14.3,8.2c-0.6,1.4-1,2.9-1.2,4.5h-5.6 c-0.9-4.1-4.6-7.3-9-7.3c-5.1,0-9.2,4.1-9.2,9.2s4.1,9.2,9.2,9.2c4.4,0,8.1-3.1,9-7.2h5.6c0.2,1.6,0.6,3.1,1.2,4.6l-15.3,8.8 c-1.3-1.3-3.1-2.1-5.1-2.1c-4,0-7.3,3.3-7.3,7.3c0,4,3.3,7.3,7.3,7.3c4,0,7.3-3.3,7.3-7.3c0-0.6-0.1-1.2-0.2-1.8l15.3-8.8 c1,1.3,2.1,2.4,3.4,3.4L717.2,86c-0.5-0.1-1.1-0.2-1.7-0.2c-3.9,0-7.1,3.2-7.1,7.1c0,3.9,3.2,7.1,7.1,7.1s7.1-3.2,7.1-7.1 c0-1.9-0.8-3.7-2-5l11.9-20.7c1.4,0.6,2.9,1,4.5,1.2V74c-3.6,0.9-6.2,4.1-6.2,8c0,4.5,3.7,8.2,8.2,8.2s8.2-3.7,8.2-8.2 c0-3.8-2.7-7.1-6.2-8v-5.6c1.6-0.2,3.1-0.6,4.6-1.2l9.8,17c-1.3,1.3-2.1,3.1-2.1,5.1c0,4,3.3,7.3,7.3,7.3c4,0,7.3-3.3,7.3-7.3 s-3.3-7.3-7.3-7.3c-0.6,0-1.2,0.1-1.8,0.2L749,65.2c1.3-0.9,2.4-2,3.3-3.3l1.8,1c-0.3,0.9-0.5,1.9-0.5,2.9c0,5.3,4.3,9.6,9.6,9.6 s9.6-4.3,9.6-9.6c0-5.3-4.3-9.6-9.6-9.6c-2.8,0-5.3,1.2-7.1,3.2l-1.8-1c0.6-1.4,1-3,1.2-4.6h18.6c0.9,2.9,3.6,5,6.7,5 c3.9,0,7-3.1,7-7C788,48,784.8,44.8,780.9,44.8z M780.9,55.7c-2.1,0-3.8-1.7-3.8-3.8c0-2.1,1.7-3.8,3.8-3.8c2.1,0,3.8,1.7,3.8,3.8 C784.8,54,783.1,55.7,780.9,55.7z M739.1,64.6c-7,0-12.7-5.7-12.7-12.7s5.7-12.7,12.7-12.7s12.7,5.7,12.7,12.7 S746.1,64.6,739.1,64.6z M767.7,32.4c0-2.8,2.3-5,5-5c2.8,0,5,2.3,5,5s-2.3,5-5,5C770,37.4,767.7,35.2,767.7,32.4z M759,26.4 c0,2.9-2.4,5.3-5.3,5.3c-2.9,0-5.3-2.4-5.3-5.3s2.4-5.3,5.3-5.3C756.6,21.1,759,23.5,759,26.4z M736,6.2c0-1.7,1.3-3,3-3 c1.7,0,3,1.3,3,3c0,1.7-1.3,3-3,3C737.4,9.2,736,7.8,736,6.2z M715.6,17.6c0-2,1.6-3.6,3.6-3.6c2,0,3.6,1.6,3.6,3.6 c0,2-1.6,3.6-3.6,3.6C717.3,21.3,715.6,19.6,715.6,17.6z M704.8,35.7c-2,0-3.6-1.6-3.6-3.6c0-2,1.6-3.6,3.6-3.6s3.6,1.6,3.6,3.6 C708.5,34.1,706.8,35.7,704.8,35.7z M707.9,57.8c-3.3,0-6-2.7-6-6c0-3.3,2.7-6,6-6c3.3,0,6,2.7,6,6 C713.9,55.1,711.2,57.8,707.9,57.8z M707.5,72.4c0,2.3-1.9,4.1-4.1,4.1s-4.1-1.9-4.1-4.1c0-2.3,1.9-4.1,4.1-4.1 S707.5,70.2,707.5,72.4z M719.4,92.9c0,2.2-1.8,3.9-3.9,3.9c-2.2,0-3.9-1.8-3.9-3.9s1.8-3.9,3.9-3.9 C717.7,88.9,719.4,90.7,719.4,92.9z M739.1,87c-2.8,0-5-2.3-5-5s2.3-5,5-5c2.8,0,5,2.3,5,5S741.8,87,739.1,87z M764.8,89.3 c0,2.3-1.9,4.1-4.1,4.1c-2.3,0-4.1-1.9-4.1-4.1s1.9-4.1,4.1-4.1C762.9,85.2,764.8,87,764.8,89.3z M763.2,59.5 c3.5,0,6.4,2.9,6.4,6.4s-2.9,6.4-6.4,6.4c-3.5,0-6.4-2.9-6.4-6.4S759.7,59.5,763.2,59.5z"/> </g> </svg>
public/img/icn-app.svg
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0002529401972424239, 0.00018763341358862817, 0.00016398722073063254, 0.00016680311819072813, 0.000037753408832941204 ]
{ "id": 8, "code_window": [ " const containerClassNames = classnames(styles.dashboardContainer, {\n", " 'panel-in-fullscreen': viewPanel,\n", " });\n", "\n", " return (\n", " <div className={containerClassNames}>\n", " {kioskMode !== KioskMode.Full && (\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " const showSubMenu = !editPanel && kioskMode === KioskMode.Off && !this.props.queryParams.editview;\n" ], "file_path": "public/app/features/dashboard/containers/DashboardPage.tsx", "type": "add", "edit_start_line_idx": 337 }
import React from 'react'; import { stylesFactory, useTheme } from '@grafana/ui'; import { css } from '@emotion/css'; import { GrafanaTheme } from '@grafana/data'; const title = { fontWeight: 500, fontSize: '26px', lineHeight: '123%' }; const getStyles = stylesFactory((theme: GrafanaTheme) => { const backgroundUrl = theme.isDark ? 'public/img/licensing/header_dark.svg' : 'public/img/licensing/header_light.svg'; const footerBg = theme.isDark ? theme.palette.dark9 : theme.palette.gray6; return { container: css` padding: 36px 79px; background: ${theme.colors.panelBg}; `, footer: css` text-align: center; padding: 16px; background: ${footerBg}; `, header: css` height: 137px; padding: 40px 0 0 79px; position: relative; background: url('${backgroundUrl}') right; `, }; }); interface Props { header: string; subheader?: string; editionNotice?: string; } export const LicenseChrome: React.FC<Props> = ({ header, editionNotice, subheader, children }) => { const theme = useTheme(); const styles = getStyles(theme); return ( <> <div className={styles.header}> <h2 style={title}>{header}</h2> {subheader && <h3>{subheader}</h3>} <Circle size="128px" style={{ boxShadow: '0px 0px 24px rgba(24, 58, 110, 0.45)', background: '#0A1C36', position: 'absolute', top: '19px', left: '71%', }} > <img src="public/img/grafana_icon.svg" alt="Grafana" width="80px" style={{ position: 'absolute', left: '23px', top: '20px' }} /> </Circle> </div> <div className={styles.container}>{children}</div> {editionNotice && <div className={styles.footer}>{editionNotice}</div>} </> ); }; interface CircleProps { size: string; style?: React.CSSProperties; } export const Circle: React.FC<CircleProps> = ({ size, style, children }) => { return ( <div style={{ width: size, height: size, position: 'absolute', bottom: 0, right: 0, borderRadius: '50%', ...style, }} > {children} </div> ); };
public/app/features/admin/LicenseChrome.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0023272286634892225, 0.00041040917858481407, 0.00016811824752949178, 0.0001742670137900859, 0.0006425547762773931 ]
{ "id": 9, "code_window": [ " >\n", " <div className={styles.dashboardContent}>\n", " {initError && <DashboardFailed />}\n", " {!editPanel && kioskMode === KioskMode.Off && (\n", " <section aria-label={selectors.pages.Dashboard.SubMenu.submenu}>\n", " <SubMenu dashboard={dashboard} annotations={dashboard.annotations.list} links={dashboard.links} />\n", " </section>\n", " )}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {showSubMenu && (\n" ], "file_path": "public/app/features/dashboard/containers/DashboardPage.tsx", "type": "replace", "edit_start_line_idx": 366 }
import React, { PureComponent } from 'react'; import { css } from 'emotion'; import { connect, ConnectedProps } from 'react-redux'; import { locationService } from '@grafana/runtime'; import { selectors } from '@grafana/e2e-selectors'; import { CustomScrollbar, ScrollbarPosition, stylesFactory, Themeable2, withTheme2 } from '@grafana/ui'; import { createErrorNotification } from 'app/core/copy/appNotification'; import { Branding } from 'app/core/components/Branding/Branding'; import { DashboardGrid } from '../dashgrid/DashboardGrid'; import { DashNav } from '../components/DashNav'; import { DashboardSettings } from '../components/DashboardSettings'; import { PanelEditor } from '../components/PanelEditor/PanelEditor'; import { initDashboard } from '../state/initDashboard'; import { notifyApp } from 'app/core/actions'; import { KioskMode, StoreState } from 'app/types'; import { PanelModel } from 'app/features/dashboard/state'; import { PanelInspector } from '../components/Inspector/PanelInspector'; import { SubMenu } from '../components/SubMenu/SubMenu'; import { cleanUpDashboardAndVariables } from '../state/actions'; import { cancelVariables, templateVarsChangedInUrl } from '../../variables/state/actions'; import { findTemplateVarChanges } from '../../variables/utils'; import { dashboardWatcher } from 'app/features/live/dashboard/dashboardWatcher'; import { GrafanaRouteComponentProps } from 'app/core/navigation/types'; import { getTimeSrv } from '../services/TimeSrv'; import { getKioskMode } from 'app/core/navigation/kiosk'; import { GrafanaTheme2, TimeRange, UrlQueryValue } from '@grafana/data'; import { DashboardLoading } from '../components/DashboardLoading/DashboardLoading'; import { DashboardFailed } from '../components/DashboardLoading/DashboardFailed'; import { DashboardPrompt } from '../components/DashboardPrompt/DashboardPrompt'; import classnames from 'classnames'; import { PanelEditExitedEvent } from 'app/types/events'; import { liveTimer } from '../dashgrid/liveTimer'; export interface DashboardPageRouteParams { uid?: string; type?: string; slug?: string; } type DashboardPageRouteSearchParams = { tab?: string; folderId?: string; editPanel?: string; viewPanel?: string; editview?: string; inspect?: string; kiosk?: UrlQueryValue; from?: string; to?: string; refresh?: string; }; export const mapStateToProps = (state: StoreState) => ({ initPhase: state.dashboard.initPhase, isInitSlow: state.dashboard.isInitSlow, initError: state.dashboard.initError, dashboard: state.dashboard.getModel(), }); const mapDispatchToProps = { initDashboard, cleanUpDashboardAndVariables, notifyApp, cancelVariables, templateVarsChangedInUrl, }; const connector = connect(mapStateToProps, mapDispatchToProps); export type Props = Themeable2 & GrafanaRouteComponentProps<DashboardPageRouteParams, DashboardPageRouteSearchParams> & ConnectedProps<typeof connector>; export interface State { editPanel: PanelModel | null; viewPanel: PanelModel | null; scrollTop: number; updateScrollTop?: number; rememberScrollTop: number; showLoadingState: boolean; panelNotFound: boolean; editPanelAccessDenied: boolean; } export class UnthemedDashboardPage extends PureComponent<Props, State> { private forceRouteReloadCounter = 0; state: State = this.getCleanState(); getCleanState(): State { return { editPanel: null, viewPanel: null, showLoadingState: false, scrollTop: 0, rememberScrollTop: 0, panelNotFound: false, editPanelAccessDenied: false, }; } componentDidMount() { this.initDashboard(); this.forceRouteReloadCounter = (this.props.history.location.state as any)?.routeReloadCounter || 0; } componentWillUnmount() { this.closeDashboard(); } closeDashboard() { this.props.cleanUpDashboardAndVariables(); this.setState(this.getCleanState()); } initDashboard() { const { dashboard, match, queryParams } = this.props; if (dashboard) { this.closeDashboard(); } this.props.initDashboard({ urlSlug: match.params.slug, urlUid: match.params.uid, urlType: match.params.type, urlFolderId: queryParams.folderId, routeName: this.props.route.routeName, fixUrl: true, }); // small delay to start live updates setTimeout(this.updateLiveTimer, 250); } componentDidUpdate(prevProps: Props, prevState: State) { const { dashboard, match, templateVarsChangedInUrl } = this.props; const routeReloadCounter = (this.props.history.location.state as any)?.routeReloadCounter; if (!dashboard) { return; } // if we just got dashboard update title if (prevProps.dashboard !== dashboard) { document.title = dashboard.title + ' - ' + Branding.AppTitle; } if ( prevProps.match.params.uid !== match.params.uid || (routeReloadCounter !== undefined && this.forceRouteReloadCounter !== routeReloadCounter) ) { this.initDashboard(); this.forceRouteReloadCounter = routeReloadCounter; return; } if (prevProps.location.search !== this.props.location.search) { const prevUrlParams = prevProps.queryParams; const urlParams = this.props.queryParams; if (urlParams?.from !== prevUrlParams?.from || urlParams?.to !== prevUrlParams?.to) { getTimeSrv().updateTimeRangeFromUrl(); this.updateLiveTimer(); } if (!prevUrlParams?.refresh && urlParams?.refresh) { getTimeSrv().setAutoRefresh(urlParams.refresh); } const templateVarChanges = findTemplateVarChanges(this.props.queryParams, prevProps.queryParams); if (templateVarChanges) { templateVarsChangedInUrl(templateVarChanges); } } // entering edit mode if (this.state.editPanel && !prevState.editPanel) { dashboardWatcher.setEditingState(true); } // leaving edit mode if (!this.state.editPanel && prevState.editPanel) { dashboardWatcher.setEditingState(false); // Some panels need kicked when leaving edit mode this.props.dashboard?.events.publish(new PanelEditExitedEvent(prevState.editPanel.id)); } if (this.state.editPanelAccessDenied) { this.props.notifyApp(createErrorNotification('Permission to edit panel denied')); locationService.partial({ editPanel: null }); } if (this.state.panelNotFound) { this.props.notifyApp(createErrorNotification(`Panel not found`)); locationService.partial({ editPanel: null, viewPanel: null }); } } updateLiveTimer = () => { let tr: TimeRange | undefined = undefined; if (this.props.dashboard?.liveNow) { tr = getTimeSrv().timeRange(); } liveTimer.setLiveTimeRange(tr); }; static getDerivedStateFromProps(props: Props, state: State) { const { dashboard, queryParams } = props; const urlEditPanelId = queryParams.editPanel; const urlViewPanelId = queryParams.viewPanel; if (!dashboard) { return state; } // Entering edit mode if (!state.editPanel && urlEditPanelId) { const panel = dashboard.getPanelByUrlId(urlEditPanelId); if (!panel) { return { ...state, panelNotFound: true }; } if (dashboard.canEditPanel(panel)) { return { ...state, editPanel: panel }; } else { return { ...state, editPanelAccessDenied: true }; } } // Leaving edit mode else if (state.editPanel && !urlEditPanelId) { return { ...state, editPanel: null }; } // Entering view mode if (!state.viewPanel && urlViewPanelId) { const panel = dashboard.getPanelByUrlId(urlViewPanelId); if (!panel) { return { ...state, panelNotFound: urlEditPanelId }; } // This mutable state feels wrong to have in getDerivedStateFromProps // Should move this state out of dashboard in the future dashboard.initViewPanel(panel); return { ...state, viewPanel: panel, rememberScrollTop: state.scrollTop, updateScrollTop: 0, }; } // Leaving view mode else if (state.viewPanel && !urlViewPanelId) { // This mutable state feels wrong to have in getDerivedStateFromProps // Should move this state out of dashboard in the future dashboard.exitViewPanel(state.viewPanel); return { ...state, viewPanel: null, updateScrollTop: state.rememberScrollTop }; } // if we removed url edit state, clear any panel not found state if (state.panelNotFound || (state.editPanelAccessDenied && !urlEditPanelId)) { return { ...state, panelNotFound: false, editPanelAccessDenied: false }; } return state; } setScrollTop = ({ scrollTop }: ScrollbarPosition): void => { this.setState({ scrollTop, updateScrollTop: undefined }); }; onAddPanel = () => { const { dashboard } = this.props; if (!dashboard) { return; } // Return if the "Add panel" exists already if (dashboard.panels.length > 0 && dashboard.panels[0].type === 'add-panel') { return; } dashboard.addPanel({ type: 'add-panel', gridPos: { x: 0, y: 0, w: 12, h: 8 }, title: 'Panel Title', }); // scroll to top after adding panel this.setState({ updateScrollTop: 0 }); }; getInspectPanel() { const { dashboard, queryParams } = this.props; const inspectPanelId = queryParams.inspect; if (!dashboard || !inspectPanelId) { return null; } const inspectPanel = dashboard.getPanelById(parseInt(inspectPanelId, 10)); // cannot inspect panels plugin is not already loaded if (!inspectPanel) { return null; } return inspectPanel; } render() { const { dashboard, isInitSlow, initError, queryParams, theme } = this.props; const { editPanel, viewPanel, scrollTop, updateScrollTop } = this.state; const kioskMode = getKioskMode(queryParams.kiosk); const styles = getStyles(theme, kioskMode); if (!dashboard) { if (isInitSlow) { return <DashboardLoading initPhase={this.props.initPhase} />; } return null; } // Only trigger render when the scroll has moved by 25 const approximateScrollTop = Math.round(scrollTop / 25) * 25; const inspectPanel = this.getInspectPanel(); const containerClassNames = classnames(styles.dashboardContainer, { 'panel-in-fullscreen': viewPanel, }); return ( <div className={containerClassNames}> {kioskMode !== KioskMode.Full && ( <header aria-label={selectors.pages.Dashboard.DashNav.nav}> <DashNav dashboard={dashboard} title={dashboard.title} folderTitle={dashboard.meta.folderTitle} isFullscreen={!!viewPanel} onAddPanel={this.onAddPanel} kioskMode={kioskMode} hideTimePicker={dashboard.timepicker.hidden} /> </header> )} <DashboardPrompt dashboard={dashboard} /> <div className={styles.dashboardScroll}> <CustomScrollbar autoHeightMin="100%" setScrollTop={this.setScrollTop} scrollTop={updateScrollTop} hideHorizontalTrack={true} updateAfterMountMs={500} > <div className={styles.dashboardContent}> {initError && <DashboardFailed />} {!editPanel && kioskMode === KioskMode.Off && ( <section aria-label={selectors.pages.Dashboard.SubMenu.submenu}> <SubMenu dashboard={dashboard} annotations={dashboard.annotations.list} links={dashboard.links} /> </section> )} <DashboardGrid dashboard={dashboard} viewPanel={viewPanel} editPanel={editPanel} scrollTop={approximateScrollTop} /> </div> </CustomScrollbar> </div> {inspectPanel && <PanelInspector dashboard={dashboard} panel={inspectPanel} />} {editPanel && <PanelEditor dashboard={dashboard} sourcePanel={editPanel} tab={this.props.queryParams.tab} />} {queryParams.editview && <DashboardSettings dashboard={dashboard} editview={queryParams.editview} />} </div> ); } } /* * Styles */ export const getStyles = stylesFactory((theme: GrafanaTheme2, kioskMode) => { const contentPadding = kioskMode !== KioskMode.Full ? theme.spacing(0, 2, 2) : theme.spacing(2); return { dashboardContainer: css` width: 100%; height: 100%; display: flex; flex: 1 1 0; flex-direction: column; min-height: 0; `, dashboardScroll: css` width: 100%; flex-grow: 1; min-height: 0; display: flex; `, dashboardContent: css` padding: ${contentPadding}; flex-basis: 100%; flex-grow: 1; `, }; }); export const DashboardPage = withTheme2(UnthemedDashboardPage); DashboardPage.displayName = 'DashboardPage'; export default connector(DashboardPage);
public/app/features/dashboard/containers/DashboardPage.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.994825005531311, 0.027146583423018456, 0.0001653790968703106, 0.0004227076715324074, 0.15054821968078613 ]
{ "id": 9, "code_window": [ " >\n", " <div className={styles.dashboardContent}>\n", " {initError && <DashboardFailed />}\n", " {!editPanel && kioskMode === KioskMode.Off && (\n", " <section aria-label={selectors.pages.Dashboard.SubMenu.submenu}>\n", " <SubMenu dashboard={dashboard} annotations={dashboard.annotations.list} links={dashboard.links} />\n", " </section>\n", " )}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {showSubMenu && (\n" ], "file_path": "public/app/features/dashboard/containers/DashboardPage.tsx", "type": "replace", "edit_start_line_idx": 366 }
package pipeline import ( "context" "errors" "fmt" "strings" "sync" "time" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/spyzhov/ajson" ) type ExactJsonConverterConfig struct { Fields []Field `json:"fields"` } // ExactJsonConverter can convert JSON to a single data.Frame according to // user-defined field configuration and value extraction rules. type ExactJsonConverter struct { config ExactJsonConverterConfig nowTimeFunc func() time.Time } func NewExactJsonConverter(c ExactJsonConverterConfig) *ExactJsonConverter { return &ExactJsonConverter{config: c} } const ConverterTypeJsonExact = "jsonExact" func (c *ExactJsonConverter) Type() string { return ConverterTypeJsonExact } func (c *ExactJsonConverter) Convert(_ context.Context, vars Vars, body []byte) ([]*ChannelFrame, error) { //obj, err := oj.Parse(body) //if err != nil { // return nil, err //} var fields []*data.Field var initGojaOnce sync.Once var gojaRuntime *gojaRuntime for _, f := range c.config.Fields { field := data.NewFieldFromFieldType(f.Type, 1) field.Name = f.Name field.Config = f.Config if strings.HasPrefix(f.Value, "$") { // JSON path. nodes, err := ajson.JSONPath(body, f.Value) if err != nil { return nil, err } if len(nodes) == 0 { field.Set(0, nil) } else if len(nodes) == 1 { val, err := nodes[0].Value() if err != nil { return nil, err } switch f.Type { case data.FieldTypeNullableFloat64: if val == nil { field.Set(0, nil) } else { switch v := val.(type) { case float64: field.SetConcrete(0, v) case int64: field.SetConcrete(0, float64(v)) default: return nil, errors.New("malformed float64 type for: " + f.Name) } } case data.FieldTypeNullableString: v, ok := val.(string) if !ok { return nil, errors.New("malformed string type") } field.SetConcrete(0, v) default: return nil, fmt.Errorf("unsupported field type: %s (%s)", f.Type, f.Name) } } else { return nil, errors.New("too many values") } //x, err := jp.ParseString(f.Value[1:]) //if err != nil { // return nil, err //} //value := x.Get(obj) //if len(value) == 0 { // field.Set(0, nil) //} else if len(value) == 1 { // val := value[0] // switch f.Type { // case data.FieldTypeNullableFloat64: // if val == nil { // field.Set(0, nil) // } else { // switch v := val.(type) { // case float64: // field.SetConcrete(0, v) // case int64: // field.SetConcrete(0, float64(v)) // default: // return nil, errors.New("malformed float64 type for: " + f.Name) // } // } // case data.FieldTypeNullableString: // v, ok := val.(string) // if !ok { // return nil, errors.New("malformed string type") // } // field.SetConcrete(0, v) // default: // return nil, fmt.Errorf("unsupported field type: %s (%s)", f.Type, f.Name) // } //} else { // return nil, errors.New("too many values") //} } else if strings.HasPrefix(f.Value, "{") { // Goja script. script := strings.Trim(f.Value, "{}") var err error initGojaOnce.Do(func() { gojaRuntime, err = getRuntime(body) }) if err != nil { return nil, err } switch f.Type { case data.FieldTypeNullableBool: v, err := gojaRuntime.getBool(script) if err != nil { return nil, err } field.SetConcrete(0, v) case data.FieldTypeNullableFloat64: v, err := gojaRuntime.getFloat64(script) if err != nil { return nil, err } field.SetConcrete(0, v) default: return nil, fmt.Errorf("unsupported field type: %s (%s)", f.Type, f.Name) } } else if f.Value == "#{now}" { // Variable. // TODO: make consistent with Grafana variables? nowTimeFunc := c.nowTimeFunc if nowTimeFunc == nil { nowTimeFunc = time.Now } field.SetConcrete(0, nowTimeFunc()) } labels := map[string]string{} for _, label := range f.Labels { if strings.HasPrefix(label.Value, "$") { nodes, err := ajson.JSONPath(body, label.Value) if err != nil { return nil, err } if len(nodes) == 0 { labels[label.Name] = "" } else if len(nodes) == 1 { value, err := nodes[0].Value() if err != nil { return nil, err } labels[label.Name] = fmt.Sprintf("%v", value) } else { return nil, errors.New("too many values for a label") } //x, err := jp.ParseString(label.Value[1:]) //if err != nil { // return nil, err //} //value := x.Get(obj) //if len(value) == 0 { // labels[label.Name] = "" //} else if len(value) == 1 { // labels[label.Name] = fmt.Sprintf("%v", value[0]) //} else { // return nil, errors.New("too many values for a label") //} } else if strings.HasPrefix(label.Value, "{") { script := strings.Trim(label.Value, "{}") var err error initGojaOnce.Do(func() { gojaRuntime, err = getRuntime(body) }) if err != nil { return nil, err } v, err := gojaRuntime.getString(script) if err != nil { return nil, err } labels[label.Name] = v } else { labels[label.Name] = label.Value } } field.Labels = labels fields = append(fields, field) } frame := data.NewFrame(vars.Path, fields...) return []*ChannelFrame{ {Channel: "", Frame: frame}, }, nil }
pkg/services/live/pipeline/converter_json_exact.go
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001784151536412537, 0.0001728697243379429, 0.00016540670185349882, 0.00017355996533297002, 0.0000036789951991522685 ]
{ "id": 9, "code_window": [ " >\n", " <div className={styles.dashboardContent}>\n", " {initError && <DashboardFailed />}\n", " {!editPanel && kioskMode === KioskMode.Off && (\n", " <section aria-label={selectors.pages.Dashboard.SubMenu.submenu}>\n", " <SubMenu dashboard={dashboard} annotations={dashboard.annotations.list} links={dashboard.links} />\n", " </section>\n", " )}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {showSubMenu && (\n" ], "file_path": "public/app/features/dashboard/containers/DashboardPage.tsx", "type": "replace", "edit_start_line_idx": 366 }
// Copyright (c) 2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import PathElem from './PathElem'; import { simplePath } from './sample-paths.test.resources'; describe('PathElem', () => { const getPath = () => { const path = { focalIdx: 2, }; const members = simplePath.map( ({ operation, service }, i) => new PathElem({ memberIdx: i, operation: { name: operation, service: { name: service, }, }, path, }) ); members[2].visibilityIdx = 0; members[3].visibilityIdx = 1; members[1].visibilityIdx = 2; members[4].visibilityIdx = 3; members[0].visibilityIdx = 4; path.members = members; return path; }; const testMemberIdx = 3; const testOperation = {}; const testPath = { focalIdx: 4, members: ['member0', 'member1', 'member2', 'member3', 'member4', 'member5'], }; const testVisibilityIdx = 105; let pathElem; beforeEach(() => { pathElem = new PathElem({ path: testPath, operation: testOperation, memberIdx: testMemberIdx }); }); it('initializes instance properties', () => { expect(pathElem.memberIdx).toBe(testMemberIdx); expect(pathElem.memberOf).toBe(testPath); expect(pathElem.operation).toBe(testOperation); }); it('calculates distance', () => { expect(pathElem.distance).toBe(-1); }); it('sets visibilityIdx', () => { pathElem.visibilityIdx = testVisibilityIdx; expect(pathElem.visibilityIdx).toBe(testVisibilityIdx); }); it('errors when trying to access unset visibilityIdx', () => { expect(() => pathElem.visibilityIdx).toThrowError(); }); it('errors when trying to override visibilityIdx', () => { pathElem.visibilityIdx = testVisibilityIdx; expect(() => { pathElem.visibilityIdx = testVisibilityIdx; }).toThrowError(); }); it('has externalSideNeighbor if distance is not 0 and it is not external', () => { expect(pathElem.externalSideNeighbor).toBe(testPath.members[testMemberIdx - 1]); }); it('has a null externalSideNeighbor if distance is 0', () => { pathElem = new PathElem({ path: testPath, operation: testOperation, memberIdx: testPath.focalIdx }); expect(pathElem.externalSideNeighbor).toBe(null); }); it('has an undefined externalSideNeighbor if is external', () => { pathElem = new PathElem({ path: testPath, operation: testOperation, memberIdx: 0 }); expect(pathElem.externalSideNeighbor).toBe(undefined); }); it('has focalSideNeighbor if distance is not 0', () => { expect(pathElem.focalSideNeighbor).toBe(testPath.members[testMemberIdx + 1]); }); it('has a null focalSideNeighbor if distance is 0', () => { pathElem = new PathElem({ path: testPath, operation: testOperation, memberIdx: testPath.focalIdx }); expect(pathElem.focalSideNeighbor).toBe(null); }); it('is external if it is first or last PathElem in memberOf.path and not the focalElem', () => { expect(pathElem.isExternal).toBe(false); const firstElem = new PathElem({ path: testPath, operation: testOperation, memberIdx: 0 }); expect(firstElem.isExternal).toBe(true); const lastElem = new PathElem({ path: testPath, operation: testOperation, memberIdx: testPath.members.length - 1, }); expect(lastElem.isExternal).toBe(true); const path = { ...testPath, focalIdx: testPath.members.length - 1, }; const focalElem = new PathElem({ path, operation: testOperation, memberIdx: path.members.length - 1 }); expect(focalElem.isExternal).toBe(false); }); describe('externalPath', () => { const path = getPath(); it('returns array of itself if it is focal elem', () => { const targetPathElem = path.members[path.focalIdx]; expect(targetPathElem.externalPath).toEqual([targetPathElem]); }); it('returns path away from focal elem in correct order for upstream elem', () => { const idx = path.focalIdx - 1; const targetPathElem = path.members[idx]; expect(targetPathElem.externalPath).toEqual(path.members.slice(0, idx + 1)); }); it('returns path away from focal elem in correct order for downstream elem', () => { const idx = path.focalIdx + 1; const targetPathElem = path.members[idx]; expect(targetPathElem.externalPath).toEqual(path.members.slice(idx)); }); }); describe('focalPath', () => { const path = getPath(); it('returns array of itself if it is focal elem', () => { const targetPathElem = path.members[path.focalIdx]; expect(targetPathElem.focalPath).toEqual([targetPathElem]); }); it('returns path to focal elem in correct order for upstream elem', () => { const targetPathElem = path.members[0]; expect(targetPathElem.focalPath).toEqual(path.members.slice(0, path.focalIdx + 1)); }); it('returns path to focal elem in correct order for downstream elem', () => { const idx = path.members.length - 1; const targetPathElem = path.members[idx]; expect(targetPathElem.focalPath).toEqual(path.members.slice(path.focalIdx, idx + 1)); }); }); describe('legibility', () => { const path = getPath(); const targetPathElem = path.members[1]; it('creates consumable JSON', () => { expect(targetPathElem.toJSON()).toMatchSnapshot(); }); it('creates consumable string', () => { expect(targetPathElem.toString()).toBe(JSON.stringify(targetPathElem.toJSON(), null, 2)); }); it('creates informative string tag', () => { expect(Object.prototype.toString.call(targetPathElem)).toEqual( `[object PathElem ${targetPathElem.visibilityIdx}]` ); }); }); });
packages/jaeger-ui-components/src/model/ddg/PathElem.test.js
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001799826859496534, 0.00017627004126552492, 0.0001734627439873293, 0.00017636433767620474, 0.000001421809656676487 ]
{ "id": 9, "code_window": [ " >\n", " <div className={styles.dashboardContent}>\n", " {initError && <DashboardFailed />}\n", " {!editPanel && kioskMode === KioskMode.Off && (\n", " <section aria-label={selectors.pages.Dashboard.SubMenu.submenu}>\n", " <SubMenu dashboard={dashboard} annotations={dashboard.annotations.list} links={dashboard.links} />\n", " </section>\n", " )}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {showSubMenu && (\n" ], "file_path": "public/app/features/dashboard/containers/DashboardPage.tsx", "type": "replace", "edit_start_line_idx": 366 }
package influxdb import ( "testing" "github.com/grafana/grafana-plugin-sdk-go/backend" ) func TestInfluxdbQueryPart(t *testing.T) { tcs := []struct { mode string input string params []string expected string }{ {mode: "field", params: []string{"value"}, input: "value", expected: `"value"`}, {mode: "derivative", params: []string{"10s"}, input: "mean(value)", expected: `derivative(mean(value), 10s)`}, {mode: "bottom", params: []string{"3"}, input: "value", expected: `bottom(value, 3)`}, {mode: "time", params: []string{"$interval"}, input: "", expected: `time($interval)`}, {mode: "time", params: []string{"auto"}, input: "", expected: `time($__interval)`}, {mode: "spread", params: []string{}, input: "value", expected: `spread(value)`}, {mode: "math", params: []string{"/ 100"}, input: "mean(value)", expected: `mean(value) / 100`}, {mode: "alias", params: []string{"test"}, input: "mean(value)", expected: `mean(value) AS "test"`}, {mode: "count", params: []string{}, input: "distinct(value)", expected: `count(distinct(value))`}, {mode: "mode", params: []string{}, input: "value", expected: `mode(value)`}, {mode: "cumulative_sum", params: []string{}, input: "mean(value)", expected: `cumulative_sum(mean(value))`}, {mode: "non_negative_difference", params: []string{}, input: "max(value)", expected: `non_negative_difference(max(value))`}, } queryContext := &backend.QueryDataRequest{} query := &Query{} for _, tc := range tcs { part, err := NewQueryPart(tc.mode, tc.params) if err != nil { t.Errorf("Expected NewQueryPart to not return an error. error: %v", err) } res := part.Render(query, queryContext, tc.input) if res != tc.expected { t.Errorf("expected %v to render into %s", tc, tc.expected) } } }
pkg/tsdb/influxdb/query_part_test.go
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001786534849088639, 0.00017534152721054852, 0.00017040288366843015, 0.00017507605662103742, 0.0000030827493446849985 ]
{ "id": 10, "code_window": [ " >\n", " Variables\n", " </a>\n", " {this.props.idInEditor && (\n", " <span>\n", " <Icon\n", " name=\"angle-right\"\n", " aria-label={selectors.pages.Dashboard.Settings.Variables.Edit.General.modeLabelEdit}\n", " />\n", " Edit\n", " </span>\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Icon name=\"angle-right\" />\n" ], "file_path": "public/app/features/variables/editor/VariableEditorContainer.tsx", "type": "replace", "edit_start_line_idx": 87 }
import React, { HTMLAttributes } from 'react'; import { Label } from './Label'; import { stylesFactory, useTheme2 } from '../../themes'; import { css, cx } from '@emotion/css'; import { GrafanaTheme2 } from '@grafana/data'; import { FieldValidationMessage } from './FieldValidationMessage'; import { getChildId } from '../../utils/children'; export interface FieldProps extends HTMLAttributes<HTMLDivElement> { /** Form input element, i.e Input or Switch */ children: React.ReactElement; /** Label for the field */ label?: React.ReactNode; /** Description of the field */ description?: React.ReactNode; /** Indicates if field is in invalid state */ invalid?: boolean; /** Indicates if field is in loading state */ loading?: boolean; /** Indicates if field is disabled */ disabled?: boolean; /** Indicates if field is required */ required?: boolean; /** Error message to display */ error?: string | null; /** Indicates horizontal layout of the field */ horizontal?: boolean; /** make validation message overflow horizontally. Prevents pushing out adjacent inline components */ validationMessageHorizontalOverflow?: boolean; className?: string; } export const getFieldStyles = stylesFactory((theme: GrafanaTheme2) => { return { field: css` display: flex; flex-direction: column; margin-bottom: ${theme.spacing(2)}; `, fieldHorizontal: css` flex-direction: row; justify-content: space-between; flex-wrap: wrap; `, fieldValidationWrapper: css` margin-top: ${theme.spacing(0.5)}; `, fieldValidationWrapperHorizontal: css` flex: 1 1 100%; `, validationMessageHorizontalOverflow: css` width: 0; overflow-x: visible; & > * { white-space: nowrap; } `, }; }); export const Field: React.FC<FieldProps> = ({ label, description, horizontal, invalid, loading, disabled, required, error, children, className, validationMessageHorizontalOverflow, ...otherProps }) => { const theme = useTheme2(); const styles = getFieldStyles(theme); const inputId = getChildId(children); const labelElement = typeof label === 'string' ? ( <Label htmlFor={inputId} description={description}> {`${label}${required ? ' *' : ''}`} </Label> ) : ( label ); return ( <div className={cx(styles.field, horizontal && styles.fieldHorizontal, className)} {...otherProps}> {labelElement} <div> {React.cloneElement(children, { invalid, disabled, loading })} {invalid && error && !horizontal && ( <div className={cx(styles.fieldValidationWrapper, { [styles.validationMessageHorizontalOverflow]: !!validationMessageHorizontalOverflow, })} > <FieldValidationMessage>{error}</FieldValidationMessage> </div> )} </div> {invalid && error && horizontal && ( <div className={cx(styles.fieldValidationWrapper, styles.fieldValidationWrapperHorizontal, { [styles.validationMessageHorizontalOverflow]: !!validationMessageHorizontalOverflow, })} > <FieldValidationMessage>{error}</FieldValidationMessage> </div> )} </div> ); };
packages/grafana-ui/src/components/Forms/Field.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0017253179103136063, 0.0003009779320564121, 0.0001640086411498487, 0.00017147940525319427, 0.0004294788814149797 ]
{ "id": 10, "code_window": [ " >\n", " Variables\n", " </a>\n", " {this.props.idInEditor && (\n", " <span>\n", " <Icon\n", " name=\"angle-right\"\n", " aria-label={selectors.pages.Dashboard.Settings.Variables.Edit.General.modeLabelEdit}\n", " />\n", " Edit\n", " </span>\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Icon name=\"angle-right\" />\n" ], "file_path": "public/app/features/variables/editor/VariableEditorContainer.tsx", "type": "replace", "edit_start_line_idx": 87 }
import { dateMath, dateTimeParse, isDateTime, TimeZone } from '@grafana/data'; export function isValid(value: string, roundUp?: boolean, timeZone?: TimeZone): boolean { if (isDateTime(value)) { return value.isValid(); } if (dateMath.isMathString(value)) { return dateMath.isValid(value); } const parsed = dateTimeParse(value, { roundUp, timeZone }); return parsed.isValid(); }
packages/grafana-ui/src/components/DateTimePickers/utils.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001714944955892861, 0.00016700202831998467, 0.00016250954649876803, 0.00016700202831998467, 0.000004492474545259029 ]