hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 4, "code_window": [ " {\n", " clearColor = clearColor || this.renderTexture.baseTexture.clearColor;\n", " }\n", " else\n", " {\n", " clearColor = clearColor || this.clearColor;\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " clearColor = clearColor || this.current.baseTexture.clearColor;\n" ], "file_path": "packages/core/src/renderTexture/RenderTextureSystem.js", "type": "replace", "edit_start_line_idx": 144 }
import './Promise'; import './Object.assign'; import './requestAnimationFrame'; import './Math.sign'; import './Number.isInteger'; if (!window.ArrayBuffer) { window.ArrayBuffer = Array; } if (!window.Float32Array) { window.Float32Array = Array; } if (!window.Uint32Array) { window.Uint32Array = Array; } if (!window.Uint16Array) { window.Uint16Array = Array; } if (!window.Uint8Array) { window.Uint8Array = Array; } if (!window.Int32Array) { window.Int32Array = Array; }
packages/polyfill/src/index.js
0
https://github.com/pixijs/pixijs/commit/f2e54200dddb2f78ad1e4f7573aae46dad7d5494
[ 0.00017552067583892494, 0.00017009739531204104, 0.00016605619748588651, 0.00016940635396167636, 0.000003512982175379875 ]
{ "id": 4, "code_window": [ " {\n", " clearColor = clearColor || this.renderTexture.baseTexture.clearColor;\n", " }\n", " else\n", " {\n", " clearColor = clearColor || this.clearColor;\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " clearColor = clearColor || this.current.baseTexture.clearColor;\n" ], "file_path": "packages/core/src/renderTexture/RenderTextureSystem.js", "type": "replace", "edit_start_line_idx": 144 }
import { settings } from '@pixi/settings'; import { Container } from '@pixi/display'; import { Renderer } from '@pixi/core'; /** * Convenience class to create a new PIXI application. * * This class automatically creates the renderer, ticker and root container. * * @example * // Create the application * const app = new PIXI.Application(); * * // Add the view to the DOM * document.body.appendChild(app.view); * * // ex, add display objects * app.stage.addChild(PIXI.Sprite.from('something.png')); * * @class * @memberof PIXI */ export default class Application { /** * @param {object} [options] - The optional renderer parameters. * @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction. * **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set * options.sharedTicker to true in case that it is already started. Stop it by your own. * @param {number} [options.width=800] - The width of the renderers view. * @param {number} [options.height=600] - The height of the renderers view. * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. * @param {boolean} [options.transparent=false] - If the render view is transparent. * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for * resolutions other than 1. * @param {boolean} [options.antialias=false] - Sets antialias * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, enable this if you * need to call toDataUrl on the WebGL context. * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2. * @param {boolean} [options.forceCanvas=false] - Prevents selection of WebGL renderer, even if such is present. * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area * (shown if not transparent). * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or * not before the new render pass. * @param {boolean} [options.forceFXAA=false] - Forces FXAA antialiasing to be used over native. * FXAA is faster, but may not always look as great. **(WebGL only)**. * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" * for devices with dual graphics card. **(WebGL only)**. * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker. * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loaders.shared, `false` to create new Loader. * @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to. */ constructor(options, arg2, arg3, arg4, arg5) { // Support for constructor(width, height, options, noWebGL, useSharedTicker) if (typeof options === 'number') { options = Object.assign({ width: options, height: arg2 || settings.RENDER_OPTIONS.height, forceCanvas: !!arg4, sharedTicker: !!arg5, }, arg3); } // The default options options = Object.assign({ forceCanvas: false, }, options); /** * WebGL renderer if available, otherwise CanvasRenderer. * @member {PIXI.Renderer|PIXI.CanvasRenderer} */ this.renderer = this.createRenderer(options); /** * The root display container that's rendered. * @member {PIXI.Container} */ this.stage = new Container(); // install plugins here Application._plugins.forEach((plugin) => { plugin.init.call(this, options); }); } /** * Register a middleware plugin for the application * @static * @param {PIXI.Application.Plugin} plugin - Plugin being installed */ static registerPlugin(plugin) { Application._plugins.push(plugin); } /** * Create the new renderer, this is here to overridden to support Canvas. * * @protected * @param {Object} [options] See constructor for complete arguments */ createRenderer(options) { return new Renderer(options); } /** * Render the current stage. */ render() { this.renderer.render(this.stage); } /** * Reference to the renderer's canvas element. * @member {HTMLCanvasElement} * @readonly */ get view() { return this.renderer.view; } /** * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen. * @member {PIXI.Rectangle} * @readonly */ get screen() { return this.renderer.screen; } /** * Destroy and don't use after this. * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options * have been set to that value * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy * method called as well. 'stageOptions' will be passed on to those calls. * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set * to true. Should it destroy the texture of the child sprite * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set * to true. Should it destroy the base texture of the child sprite */ destroy(removeView) { // Destroy plugins in the opposite order // which they were constructed const plugins = Application._plugins.slice(0); plugins.reverse(); plugins.forEach((plugin) => { plugin.destroy.call(this); }); this.stage.destroy(); this.stage = null; this.renderer.destroy(removeView); this.renderer = null; this._options = null; } } /** * @memberof PIXI.Application * @typedef {object} Plugin * @property {function} init - Called when Application is constructed, scoped to Application instance. * Passes in `options` as the only argument, which are Application constructor options. * @property {function} destroy - Called when destroying Application, scoped to Application instance */ /** * Collection of installed plugins. * @static * @private * @type {PIXI.Application.Plugin[]} */ Application._plugins = [];
packages/app/src/Application.js
0
https://github.com/pixijs/pixijs/commit/f2e54200dddb2f78ad1e4f7573aae46dad7d5494
[ 0.0001760102022672072, 0.00016761118604335934, 0.0001612952328287065, 0.0001680280256550759, 0.000003589733751141466 ]
{ "id": 0, "code_window": [ "\tprivate inputChangingTimeoutHandle: any;\n", "\t// @ts-ignore (legacy widget - to be replaced with quick input)\n", "\tprivate styles: IQuickOpenStyles;\n", "\t// @ts-ignore (legacy widget - to be replaced with quick input)\n", "\tprivate renderer: Renderer;\n", "\tprivate keyDownSeenSinceShown = false;\n", "\n", "\tconstructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions) {\n", "\t\tsuper();\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 137 }
/*--------------------------------------------------------------------------------------------- * 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!./quickopen'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import { IQuickNavigateConfiguration, IAutoFocus, IEntryRunContext, IModel, Mode, IKeyMods } from 'vs/base/parts/quickopen/common/quickOpen'; import { Filter, Renderer, DataSource, IModelProvider, AccessibilityProvider } from 'vs/base/parts/quickopen/browser/quickOpenViewer'; import { ITree, ContextMenuEvent, IActionProvider, ITreeStyles, ITreeOptions, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree'; import { InputBox, MessageType, IInputBoxStyles, IRange } from 'vs/base/browser/ui/inputbox/inputBox'; import Severity from 'vs/base/common/severity'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { DefaultController, ClickBehavior } from 'vs/base/parts/tree/browser/treeDefaults'; import * as DOM from 'vs/base/browser/dom'; import { KeyCode } from 'vs/base/common/keyCodes'; import { Disposable } from 'vs/base/common/lifecycle'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { StandardMouseEvent, IMouseEvent } from 'vs/base/browser/mouseEvent'; import { IThemable } from 'vs/base/common/styler'; export interface IQuickOpenCallbacks { onOk: () => void; onCancel: () => void; onType: (value: string) => void; onShow?: () => void; onHide?: (reason: HideReason) => void; onFocusLost?: () => boolean /* veto close */; } export interface IQuickOpenOptions extends IQuickOpenStyles { minItemsToShow?: number; maxItemsToShow?: number; inputPlaceHolder?: string; inputAriaLabel?: string; actionProvider?: IActionProvider; keyboardSupport?: boolean; treeCreator?: (container: HTMLElement, configuration: ITreeConfiguration, options?: ITreeOptions) => ITree; } export interface IQuickOpenStyles extends IInputBoxStyles, ITreeStyles { background?: Color; foreground?: Color; borderColor?: Color; pickerGroupForeground?: Color; pickerGroupBorder?: Color; widgetShadow?: Color; progressBarBackground?: Color; } export interface IShowOptions { quickNavigateConfiguration?: IQuickNavigateConfiguration; autoFocus?: IAutoFocus; inputSelection?: IRange; value?: string; } export class QuickOpenController extends DefaultController { onContextMenu(tree: ITree, element: any, event: ContextMenuEvent): boolean { if (platform.isMacintosh) { return this.onLeftClick(tree, element, event); // https://github.com/Microsoft/vscode/issues/1011 } return super.onContextMenu(tree, element, event); } onMouseMiddleClick(tree: ITree, element: any, event: IMouseEvent): boolean { return this.onLeftClick(tree, element, event); } } export const enum HideReason { ELEMENT_SELECTED, FOCUS_LOST, CANCELED } const defaultStyles = { background: Color.fromHex('#1E1E1E'), foreground: Color.fromHex('#CCCCCC'), pickerGroupForeground: Color.fromHex('#0097FB'), pickerGroupBorder: Color.fromHex('#3F3F46'), widgetShadow: Color.fromHex('#000000'), progressBarBackground: Color.fromHex('#0E70C0') }; const DEFAULT_INPUT_ARIA_LABEL = nls.localize('quickOpenAriaLabel', "Quick picker. Type to narrow down results."); export class QuickOpenWidget extends Disposable implements IModelProvider, IThemable { private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private static readonly MAX_ITEMS_HEIGHT = 20 * 22; // Max height of item list below input field private isDisposed: boolean; private options: IQuickOpenOptions; // @ts-ignore (legacy widget - to be replaced with quick input) private element: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private tree: ITree; // @ts-ignore (legacy widget - to be replaced with quick input) private inputBox: InputBox; // @ts-ignore (legacy widget - to be replaced with quick input) private inputContainer: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private helpText: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private resultCount: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private treeContainer: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private progressBar: ProgressBar; // @ts-ignore (legacy widget - to be replaced with quick input) private visible: boolean; // @ts-ignore (legacy widget - to be replaced with quick input) private isLoosingFocus: boolean; private callbacks: IQuickOpenCallbacks; private quickNavigateConfiguration: IQuickNavigateConfiguration | undefined; private container: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private treeElement: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private inputElement: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private layoutDimensions: DOM.Dimension; private model: IModel<any> | null; private inputChangingTimeoutHandle: any; // @ts-ignore (legacy widget - to be replaced with quick input) private styles: IQuickOpenStyles; // @ts-ignore (legacy widget - to be replaced with quick input) private renderer: Renderer; private keyDownSeenSinceShown = false; constructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions) { super(); this.isDisposed = false; this.container = container; this.callbacks = callbacks; this.options = options; this.styles = options || Object.create(null); mixin(this.styles, defaultStyles, false); this.model = null; } getElement(): HTMLElement { return this.element; } getModel(): IModel<any> { return this.model!; } setCallbacks(callbacks: IQuickOpenCallbacks): void { this.callbacks = callbacks; } create(): HTMLElement { // Container this.element = document.createElement('div'); DOM.addClass(this.element, 'monaco-quick-open-widget'); this.container.appendChild(this.element); this._register(DOM.addDisposableListener(this.element, DOM.EventType.CONTEXT_MENU, e => DOM.EventHelper.stop(e, true))); // Do this to fix an issue on Mac where the menu goes into the way this._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, e => this.gainingFocus(), true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, e => this.loosingFocus(e), true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, e => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); if (keyboardEvent.keyCode === KeyCode.Escape) { DOM.EventHelper.stop(e, true); this.hide(HideReason.CANCELED); } else if (keyboardEvent.keyCode === KeyCode.Tab && !keyboardEvent.altKey && !keyboardEvent.ctrlKey && !keyboardEvent.metaKey) { const stops = (e.currentTarget as HTMLElement).querySelectorAll('input, .monaco-tree, .monaco-tree-row.focused .action-label.icon') as NodeListOf<HTMLElement>; if (keyboardEvent.shiftKey && keyboardEvent.target === stops[0]) { DOM.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!keyboardEvent.shiftKey && keyboardEvent.target === stops[stops.length - 1]) { DOM.EventHelper.stop(e, true); stops[0].focus(); } } })); // Progress Bar this.progressBar = this._register(new ProgressBar(this.element, { progressBarBackground: this.styles.progressBarBackground })); this.progressBar.hide(); // Input Field this.inputContainer = document.createElement('div'); DOM.addClass(this.inputContainer, 'quick-open-input'); this.element.appendChild(this.inputContainer); this.inputBox = this._register(new InputBox(this.inputContainer, undefined, { placeholder: this.options.inputPlaceHolder || '', ariaLabel: DEFAULT_INPUT_ARIA_LABEL, inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder })); this.inputElement = this.inputBox.inputElement; this.inputElement.setAttribute('role', 'combobox'); this.inputElement.setAttribute('aria-haspopup', 'false'); this.inputElement.setAttribute('aria-autocomplete', 'list'); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, (e: Event) => this.onType())); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const shouldOpenInBackground = this.shouldOpenInBackground(keyboardEvent); // Do not handle Tab: It is used to navigate between elements without mouse if (keyboardEvent.keyCode === KeyCode.Tab) { return; } // Pass tree navigation keys to the tree but leave focus in input field else if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); // Position cursor at the end of input to allow right arrow (open in background) // to function immediately unless the user has made a selection if (this.inputBox.inputElement.selectionStart === this.inputBox.inputElement.selectionEnd) { this.inputBox.inputElement.selectionStart = this.inputBox.value.length; } } // Select element on Enter or on Arrow-Right if we are at the end of the input else if (keyboardEvent.keyCode === KeyCode.Enter || shouldOpenInBackground) { DOM.EventHelper.stop(e, true); const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus, e, shouldOpenInBackground ? Mode.OPEN_IN_BACKGROUND : Mode.OPEN); } } })); // Result count for screen readers this.resultCount = document.createElement('div'); DOM.addClass(this.resultCount, 'quick-open-result-count'); this.resultCount.setAttribute('aria-live', 'polite'); this.resultCount.setAttribute('aria-atomic', 'true'); this.element.appendChild(this.resultCount); // Tree this.treeContainer = document.createElement('div'); DOM.addClass(this.treeContainer, 'quick-open-tree'); this.element.appendChild(this.treeContainer); const createTree = this.options.treeCreator || ((container, config, opts) => new Tree(container, config, opts)); this.tree = this._register(createTree(this.treeContainer, { dataSource: new DataSource(this), controller: new QuickOpenController({ clickBehavior: ClickBehavior.ON_MOUSE_UP, keyboardSupport: this.options.keyboardSupport }), renderer: (this.renderer = new Renderer(this, this.styles)), filter: new Filter(this), accessibilityProvider: new AccessibilityProvider(this) }, { twistiePixels: 11, indentPixels: 0, alwaysFocused: true, verticalScrollMode: ScrollbarVisibility.Visible, horizontalScrollMode: ScrollbarVisibility.Hidden, ariaLabel: nls.localize('treeAriaLabel', "Quick Picker"), keyboardSupport: this.options.keyboardSupport, preventRootFocus: false })); this.treeElement = this.tree.getHTMLElement(); // Handle Focus and Selection event this._register(this.tree.onDidChangeFocus(event => { this.elementFocused(event.focus, event); })); this._register(this.tree.onDidChangeSelection(event => { if (event.selection && event.selection.length > 0) { const mouseEvent: StandardMouseEvent = event.payload && event.payload.originalEvent instanceof StandardMouseEvent ? event.payload.originalEvent : undefined; const shouldOpenInBackground = mouseEvent ? this.shouldOpenInBackground(mouseEvent) : false; this.elementSelected(event.selection[0], event, shouldOpenInBackground ? Mode.OPEN_IN_BACKGROUND : Mode.OPEN); } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, e => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); // Only handle when in quick navigation mode if (!this.quickNavigateConfiguration) { return; } // Support keyboard navigation in quick navigation mode if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode); } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, e => { const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Only handle when in quick navigation mode if (!this.quickNavigateConfiguration || !this.keyDownSeenSinceShown) { return; } // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigateConfiguration.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed) { const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus, e); } } })); // Support layout if (this.layoutDimensions) { this.layout(this.layoutDimensions); } this.applyStyles(); // Allows focus to switch to next/previous entry after tab into an actionbar item this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); // Only handle when not in quick navigation mode if (this.quickNavigateConfiguration) { return; } if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); this.treeElement.focus(); } })); return this.element; } style(styles: IQuickOpenStyles): void { this.styles = styles; this.applyStyles(); } protected applyStyles(): void { if (this.element) { const foreground = this.styles.foreground ? this.styles.foreground.toString() : null; const background = this.styles.background ? this.styles.background.toString() : ''; const borderColor = this.styles.borderColor ? this.styles.borderColor.toString() : ''; const widgetShadow = this.styles.widgetShadow ? this.styles.widgetShadow.toString() : ''; this.element.style.color = foreground; this.element.style.backgroundColor = background; this.element.style.borderColor = borderColor; this.element.style.borderWidth = borderColor ? '1px' : ''; this.element.style.borderStyle = borderColor ? 'solid' : ''; this.element.style.boxShadow = widgetShadow ? `0 5px 8px ${widgetShadow}` : ''; } if (this.progressBar) { this.progressBar.style({ progressBarBackground: this.styles.progressBarBackground }); } if (this.inputBox) { this.inputBox.style({ inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder }); } if (this.tree && !this.options.treeCreator) { this.tree.style(this.styles); } if (this.renderer) { this.renderer.updateStyles(this.styles); } } private shouldOpenInBackground(e: StandardKeyboardEvent | StandardMouseEvent): boolean { // Keyboard if (e instanceof StandardKeyboardEvent) { if (e.keyCode !== KeyCode.RightArrow) { return false; // only for right arrow } if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return false; // no modifiers allowed } // validate the cursor is at the end of the input and there is no selection, // and if not prevent opening in the background such as the selection can be changed const element = this.inputBox.inputElement; return element.selectionEnd === this.inputBox.value.length && element.selectionStart === element.selectionEnd; } // Mouse return e.middleButton; } private onType(): void { const value = this.inputBox.value; // Adjust help text as needed if present if (this.helpText) { if (value) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Send to callbacks this.callbacks.onType(value); } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void { if (this.isVisible()) { // Transition into quick navigate mode if not yet done if (!this.quickNavigateConfiguration && quickNavigate) { this.quickNavigateConfiguration = quickNavigate; this.tree.domFocus(); } // Navigate this.navigateInTree(next ? KeyCode.DownArrow : KeyCode.UpArrow); } } private navigateInTree(keyCode: KeyCode, isShift?: boolean): void { const model: IModel<any> = this.tree.getInput(); const entries = model ? model.entries : []; const oldFocus = this.tree.getFocus(); // Normal Navigation switch (keyCode) { case KeyCode.DownArrow: this.tree.focusNext(); break; case KeyCode.UpArrow: this.tree.focusPrevious(); break; case KeyCode.PageDown: this.tree.focusNextPage(); break; case KeyCode.PageUp: this.tree.focusPreviousPage(); break; case KeyCode.Tab: if (isShift) { this.tree.focusPrevious(); } else { this.tree.focusNext(); } break; } let newFocus = this.tree.getFocus(); // Support cycle-through navigation if focus did not change if (entries.length > 1 && oldFocus === newFocus) { // Up from no entry or first entry goes down to last if (keyCode === KeyCode.UpArrow || (keyCode === KeyCode.Tab && isShift)) { this.tree.focusLast(); } // Down from last entry goes to up to first else if (keyCode === KeyCode.DownArrow || keyCode === KeyCode.Tab && !isShift) { this.tree.focusFirst(); } } // Reveal newFocus = this.tree.getFocus(); if (newFocus) { this.tree.reveal(newFocus); } } private elementFocused(value: any, event?: any): void { if (!value || !this.isVisible()) { return; } // ARIA const arivaActiveDescendant = this.treeElement.getAttribute('aria-activedescendant'); if (arivaActiveDescendant) { this.inputElement.setAttribute('aria-activedescendant', arivaActiveDescendant); } else { this.inputElement.removeAttribute('aria-activedescendant'); } const context: IEntryRunContext = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; this.model!.runner.run(value, Mode.PREVIEW, context); } private elementSelected(value: any, event?: any, preferredMode?: Mode): void { let hide = true; // Trigger open of element on selection if (this.isVisible()) { let mode = preferredMode || Mode.OPEN; const context: IEntryRunContext = { event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; hide = this.model!.runner.run(value, mode, context); } // Hide if command was run successfully if (hide) { this.hide(HideReason.ELEMENT_SELECTED); } } private extractKeyMods(event: any): IKeyMods { return { ctrlCmd: event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey))), alt: event && (event.altKey || (event.payload && event.payload.originalEvent && event.payload.originalEvent.altKey)) }; } show(prefix: string, options?: IShowOptions): void; show(input: IModel<any>, options?: IShowOptions): void; show(param: any, options?: IShowOptions): void { this.visible = true; this.isLoosingFocus = false; this.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined; this.keyDownSeenSinceShown = false; // Adjust UI for quick navigate mode if (this.quickNavigateConfiguration) { DOM.hide(this.inputContainer); DOM.show(this.element); this.tree.domFocus(); } // Otherwise use normal UI else { DOM.show(this.inputContainer); DOM.show(this.element); this.inputBox.focus(); } // Adjust Help text for IE if (this.helpText) { if (this.quickNavigateConfiguration || types.isString(param)) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Show based on param if (types.isString(param)) { this.doShowWithPrefix(param); } else { if (options && options.value) { this.restoreLastInput(options.value); } this.doShowWithInput(param, options && options.autoFocus ? options.autoFocus : {}); } // Respect selectAll option if (options && options.inputSelection && !this.quickNavigateConfiguration) { this.inputBox.select(options.inputSelection); } if (this.callbacks.onShow) { this.callbacks.onShow(); } } private restoreLastInput(lastInput: string) { this.inputBox.value = lastInput; this.inputBox.select(); this.callbacks.onType(lastInput); } private doShowWithPrefix(prefix: string): void { this.inputBox.value = prefix; this.callbacks.onType(prefix); } private doShowWithInput(input: IModel<any>, autoFocus: IAutoFocus): void { this.setInput(input, autoFocus); } private setInputAndLayout(input: IModel<any>, autoFocus?: IAutoFocus): void { this.treeContainer.style.height = `${this.getHeight(input)}px`; this.tree.setInput(null).then(() => { this.model = input; // ARIA this.inputElement.setAttribute('aria-haspopup', String(input && input.entries && input.entries.length > 0)); return this.tree.setInput(input); }).then(() => { // Indicate entries to tree this.tree.layout(); const entries = input ? input.entries.filter(e => this.isElementVisible(input, e)) : []; this.updateResultCount(entries.length); // Handle auto focus if (entries.length) { this.autoFocus(input, entries, autoFocus); } }); } private isElementVisible<T>(input: IModel<T>, e: T): boolean { if (!input.filter) { return true; } return input.filter.isVisible(e); } private autoFocus(input: IModel<any>, entries: any[], autoFocus: IAutoFocus = {}): void { // First check for auto focus of prefix matches if (autoFocus.autoFocusPrefixMatch) { let caseSensitiveMatch: any; let caseInsensitiveMatch: any; const prefix = autoFocus.autoFocusPrefixMatch; const lowerCasePrefix = prefix.toLowerCase(); for (const entry of entries) { const label = input.dataSource.getLabel(entry) || ''; if (!caseSensitiveMatch && label.indexOf(prefix) === 0) { caseSensitiveMatch = entry; } else if (!caseInsensitiveMatch && label.toLowerCase().indexOf(lowerCasePrefix) === 0) { caseInsensitiveMatch = entry; } if (caseSensitiveMatch && caseInsensitiveMatch) { break; } } const entryToFocus = caseSensitiveMatch || caseInsensitiveMatch; if (entryToFocus) { this.tree.setFocus(entryToFocus); this.tree.reveal(entryToFocus, 0.5); return; } } // Second check for auto focus of first entry if (autoFocus.autoFocusFirstEntry) { this.tree.focusFirst(); this.tree.reveal(this.tree.getFocus()); } // Third check for specific index option else if (typeof autoFocus.autoFocusIndex === 'number') { if (entries.length > autoFocus.autoFocusIndex) { this.tree.focusNth(autoFocus.autoFocusIndex); this.tree.reveal(this.tree.getFocus()); } } // Check for auto focus of second entry else if (autoFocus.autoFocusSecondEntry) { if (entries.length > 1) { this.tree.focusNth(1); } } // Finally check for auto focus of last entry else if (autoFocus.autoFocusLastEntry) { if (entries.length > 1) { this.tree.focusLast(); } } } refresh(input?: IModel<any>, autoFocus?: IAutoFocus): void { if (!this.isVisible()) { return; } if (!input) { input = this.tree.getInput(); } if (!input) { return; } // Apply height & Refresh this.treeContainer.style.height = `${this.getHeight(input)}px`; this.tree.refresh().then(() => { // Indicate entries to tree this.tree.layout(); const entries = input ? input.entries!.filter(e => this.isElementVisible(input!, e)) : []; this.updateResultCount(entries.length); // Handle auto focus if (autoFocus) { if (entries.length) { this.autoFocus(input!, entries, autoFocus); } } }); } private getHeight(input: IModel<any>): number { const renderer = input.renderer; if (!input) { const itemHeight = renderer.getHeight(null); return this.options.minItemsToShow ? this.options.minItemsToShow * itemHeight : 0; } let height = 0; let preferredItemsHeight: number | undefined; if (this.layoutDimensions && this.layoutDimensions.height) { preferredItemsHeight = (this.layoutDimensions.height - 50 /* subtract height of input field (30px) and some spacing (drop shadow) to fit */) * 0.4 /* max 40% of screen */; } if (!preferredItemsHeight || preferredItemsHeight > QuickOpenWidget.MAX_ITEMS_HEIGHT) { preferredItemsHeight = QuickOpenWidget.MAX_ITEMS_HEIGHT; } const entries = input.entries.filter(e => this.isElementVisible(input, e)); const maxEntries = this.options.maxItemsToShow || entries.length; for (let i = 0; i < maxEntries && i < entries.length; i++) { const entryHeight = renderer.getHeight(entries[i]); if (height + entryHeight <= preferredItemsHeight) { height += entryHeight; } else { break; } } return height; } updateResultCount(count: number) { this.resultCount.textContent = nls.localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results", count); } hide(reason?: HideReason): void { if (!this.isVisible()) { return; } this.visible = false; DOM.hide(this.element); this.element.blur(); // Clear input field and clear tree this.inputBox.value = ''; this.tree.setInput(null); // ARIA this.inputElement.setAttribute('aria-haspopup', 'false'); // Reset Tree Height this.treeContainer.style.height = `${this.options.minItemsToShow ? this.options.minItemsToShow * 22 : 0}px`; // Clear any running Progress this.progressBar.stop().hide(); // Clear Focus if (this.tree.isDOMFocused()) { this.tree.domBlur(); } else if (this.inputBox.hasFocus()) { this.inputBox.blur(); } // Callbacks if (reason === HideReason.ELEMENT_SELECTED) { this.callbacks.onOk(); } else { this.callbacks.onCancel(); } if (this.callbacks.onHide) { this.callbacks.onHide(reason!); } } getQuickNavigateConfiguration(): IQuickNavigateConfiguration { return this.quickNavigateConfiguration!; } setPlaceHolder(placeHolder: string): void { if (this.inputBox) { this.inputBox.setPlaceHolder(placeHolder); } } setValue(value: string, selectionOrStableHint?: [number, number] | null): void { if (this.inputBox) { this.inputBox.value = value; if (selectionOrStableHint === null) { // null means stable-selection } else if (Array.isArray(selectionOrStableHint)) { const [start, end] = selectionOrStableHint; this.inputBox.select({ start, end }); } else { this.inputBox.select(); } } } setPassword(isPassword: boolean): void { if (this.inputBox) { this.inputBox.inputElement.type = isPassword ? 'password' : 'text'; } } setInput(input: IModel<any>, autoFocus?: IAutoFocus, ariaLabel?: string): void { if (!this.isVisible()) { return; } // If the input changes, indicate this to the tree if (!!this.getInput()) { this.onInputChanging(); } // Adapt tree height to entries and apply input this.setInputAndLayout(input, autoFocus); // Apply ARIA if (this.inputBox) { this.inputBox.setAriaLabel(ariaLabel || DEFAULT_INPUT_ARIA_LABEL); } } private onInputChanging(): void { if (this.inputChangingTimeoutHandle) { clearTimeout(this.inputChangingTimeoutHandle); this.inputChangingTimeoutHandle = null; } // when the input is changing in quick open, we indicate this as CSS class to the widget // for a certain timeout. this helps reducing some hectic UI updates when input changes quickly DOM.addClass(this.element, 'content-changing'); this.inputChangingTimeoutHandle = setTimeout(() => { DOM.removeClass(this.element, 'content-changing'); }, 500); } getInput(): IModel<any> { return this.tree.getInput(); } showInputDecoration(decoration: Severity): void { if (this.inputBox) { this.inputBox.showMessage({ type: decoration === Severity.Info ? MessageType.INFO : decoration === Severity.Warning ? MessageType.WARNING : MessageType.ERROR, content: '' }); } } clearInputDecoration(): void { if (this.inputBox) { this.inputBox.hideMessage(); } } focus(): void { if (this.isVisible() && this.inputBox) { this.inputBox.focus(); } } accept(): void { if (this.isVisible()) { const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus); } } } getProgressBar(): ProgressBar { return this.progressBar; } getInputBox(): InputBox { return this.inputBox; } setExtraClass(clazz: string | null): void { const previousClass = this.element.getAttribute('quick-open-extra-class'); if (previousClass) { DOM.removeClasses(this.element, previousClass); } if (clazz) { DOM.addClasses(this.element, clazz); this.element.setAttribute('quick-open-extra-class', clazz); } else if (previousClass) { this.element.removeAttribute('quick-open-extra-class'); } } isVisible(): boolean { return this.visible; } layout(dimension: DOM.Dimension): void { this.layoutDimensions = dimension; // Apply to quick open width (height is dynamic by number of items to show) const quickOpenWidth = Math.min(this.layoutDimensions.width * 0.62 /* golden cut */, QuickOpenWidget.MAX_WIDTH); if (this.element) { // quick open this.element.style.width = `${quickOpenWidth}px`; this.element.style.marginLeft = `-${quickOpenWidth / 2}px`; // input field this.inputContainer.style.width = `${quickOpenWidth - 12}px`; } } private gainingFocus(): void { this.isLoosingFocus = false; } private loosingFocus(e: FocusEvent): void { if (!this.isVisible()) { return; } const relatedTarget = e.relatedTarget as HTMLElement; if (!this.quickNavigateConfiguration && DOM.isAncestor(relatedTarget, this.element)) { return; // user clicked somewhere into quick open widget, do not close thereby } this.isLoosingFocus = true; setTimeout(() => { if (!this.isLoosingFocus || this.isDisposed) { return; } const veto = this.callbacks.onFocusLost && this.callbacks.onFocusLost(); if (!veto) { this.hide(HideReason.FOCUS_LOST); } }, 0); } dispose(): void { super.dispose(); this.isDisposed = true; } }
src/vs/base/parts/quickopen/browser/quickOpenWidget.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9990010857582092, 0.106105275452137, 0.00016543698438908905, 0.0001708909694571048, 0.30295324325561523 ]
{ "id": 0, "code_window": [ "\tprivate inputChangingTimeoutHandle: any;\n", "\t// @ts-ignore (legacy widget - to be replaced with quick input)\n", "\tprivate styles: IQuickOpenStyles;\n", "\t// @ts-ignore (legacy widget - to be replaced with quick input)\n", "\tprivate renderer: Renderer;\n", "\tprivate keyDownSeenSinceShown = false;\n", "\n", "\tconstructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions) {\n", "\t\tsuper();\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 137 }
/*--------------------------------------------------------------------------------------------- * 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 dom from 'vs/base/browser/dom'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Color, RGBA } from 'vs/base/common/color'; import { IMarkdownString, MarkdownString, isEmptyMarkdownString, markedStringsEquals } from 'vs/base/common/htmlContent'; import { IDisposable, toDisposable, DisposableStore, combinedDisposable, MutableDisposable } from 'vs/base/common/lifecycle'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { Position } from 'vs/editor/common/core/position'; import { IRange, Range } from 'vs/editor/common/core/range'; import { ModelDecorationOptions } from 'vs/editor/common/model/textModel'; import { DocumentColorProvider, Hover as MarkdownHover, HoverProviderRegistry, IColor } from 'vs/editor/common/modes'; import { getColorPresentations } from 'vs/editor/contrib/colorPicker/color'; import { ColorDetector } from 'vs/editor/contrib/colorPicker/colorDetector'; import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/colorPickerModel'; import { ColorPickerWidget } from 'vs/editor/contrib/colorPicker/colorPickerWidget'; import { getHover } from 'vs/editor/contrib/hover/getHover'; import { HoverOperation, HoverStartMode, IHoverComputer } from 'vs/editor/contrib/hover/hoverOperation'; import { ContentHoverWidget } from 'vs/editor/contrib/hover/hoverWidgets'; import { MarkdownRenderer } from 'vs/editor/contrib/markdown/markdownRenderer'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { coalesce, isNonEmptyArray, asArray } from 'vs/base/common/arrays'; import { IMarker, IMarkerData, MarkerSeverity } from 'vs/platform/markers/common/markers'; import { basename } from 'vs/base/common/resources'; import { IMarkerDecorationsService } from 'vs/editor/common/services/markersDecorationService'; import { onUnexpectedError } from 'vs/base/common/errors'; import { IOpenerService, NullOpenerService } from 'vs/platform/opener/common/opener'; import { MarkerController, NextMarkerAction } from 'vs/editor/contrib/gotoError/gotoError'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async'; import { getCodeActions, CodeActionSet } from 'vs/editor/contrib/codeAction/codeAction'; import { QuickFixAction, QuickFixController } from 'vs/editor/contrib/codeAction/codeActionCommands'; import { CodeActionKind } from 'vs/editor/contrib/codeAction/types'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IIdentifiedSingleEditOperation } from 'vs/editor/common/model'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Constants } from 'vs/base/common/uint'; const $ = dom.$; class ColorHover { constructor( public readonly range: IRange, public readonly color: IColor, public readonly provider: DocumentColorProvider ) { } } class MarkerHover { constructor( public readonly range: IRange, public readonly marker: IMarker, ) { } } type HoverPart = MarkdownHover | ColorHover | MarkerHover; class ModesContentComputer implements IHoverComputer<HoverPart[]> { private readonly _editor: ICodeEditor; private _result: HoverPart[]; private _range?: Range; constructor( editor: ICodeEditor, private readonly _markerDecorationsService: IMarkerDecorationsService ) { this._editor = editor; this._result = []; } setRange(range: Range): void { this._range = range; this._result = []; } clearResult(): void { this._result = []; } computeAsync(token: CancellationToken): Promise<HoverPart[]> { if (!this._editor.hasModel() || !this._range) { return Promise.resolve([]); } const model = this._editor.getModel(); if (!HoverProviderRegistry.has(model)) { return Promise.resolve([]); } return getHover(model, new Position( this._range.startLineNumber, this._range.startColumn ), token); } computeSync(): HoverPart[] { if (!this._editor.hasModel() || !this._range) { return []; } const model = this._editor.getModel(); const lineNumber = this._range.startLineNumber; if (lineNumber > this._editor.getModel().getLineCount()) { // Illegal line number => no results return []; } const colorDetector = ColorDetector.get(this._editor); const maxColumn = model.getLineMaxColumn(lineNumber); const lineDecorations = this._editor.getLineDecorations(lineNumber); let didFindColor = false; const hoverRange = this._range; const result = lineDecorations.map((d): HoverPart | null => { const startColumn = (d.range.startLineNumber === lineNumber) ? d.range.startColumn : 1; const endColumn = (d.range.endLineNumber === lineNumber) ? d.range.endColumn : maxColumn; if (startColumn > hoverRange.startColumn || hoverRange.endColumn > endColumn) { return null; } const range = new Range(hoverRange.startLineNumber, startColumn, hoverRange.startLineNumber, endColumn); const marker = this._markerDecorationsService.getMarker(model, d); if (marker) { return new MarkerHover(range, marker); } const colorData = colorDetector.getColorData(d.range.getStartPosition()); if (!didFindColor && colorData) { didFindColor = true; const { color, range } = colorData.colorInfo; return new ColorHover(range, color, colorData.provider); } else { if (isEmptyMarkdownString(d.options.hoverMessage)) { return null; } const contents: IMarkdownString[] = d.options.hoverMessage ? asArray(d.options.hoverMessage) : []; return { contents, range }; } }); return coalesce(result); } onResult(result: HoverPart[], isFromSynchronousComputation: boolean): void { // Always put synchronous messages before asynchronous ones if (isFromSynchronousComputation) { this._result = result.concat(this._result.sort((a, b) => { if (a instanceof ColorHover) { // sort picker messages at to the top return -1; } else if (b instanceof ColorHover) { return 1; } return 0; })); } else { this._result = this._result.concat(result); } } getResult(): HoverPart[] { return this._result.slice(0); } getResultWithLoadingMessage(): HoverPart[] { return this._result.slice(0).concat([this._getLoadingMessage()]); } private _getLoadingMessage(): HoverPart { return { range: this._range, contents: [new MarkdownString().appendText(nls.localize('modesContentHover.loading', "Loading..."))] }; } } export class ModesContentHoverWidget extends ContentHoverWidget { static readonly ID = 'editor.contrib.modesContentHoverWidget'; private _messages: HoverPart[]; private _lastRange: Range | null; private readonly _computer: ModesContentComputer; private readonly _hoverOperation: HoverOperation<HoverPart[]>; private _highlightDecorations: string[]; private _isChangingDecorations: boolean; private _shouldFocus: boolean; private _colorPicker: ColorPickerWidget | null; private readonly renderDisposable = this._register(new MutableDisposable<IDisposable>()); constructor( editor: ICodeEditor, markerDecorationsService: IMarkerDecorationsService, private readonly _themeService: IThemeService, private readonly _keybindingService: IKeybindingService, private readonly _modeService: IModeService, private readonly _openerService: IOpenerService | null = NullOpenerService, ) { super(ModesContentHoverWidget.ID, editor); this._messages = []; this._lastRange = null; this._computer = new ModesContentComputer(this._editor, markerDecorationsService); this._highlightDecorations = []; this._isChangingDecorations = false; this._shouldFocus = false; this._colorPicker = null; this._hoverOperation = new HoverOperation( this._computer, result => this._withResult(result, true), null, result => this._withResult(result, false), this._editor.getOption(EditorOption.hover).delay ); this._register(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.FOCUS, () => { if (this._colorPicker) { dom.addClass(this.getDomNode(), 'colorpicker-hover'); } })); this._register(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.BLUR, () => { dom.removeClass(this.getDomNode(), 'colorpicker-hover'); })); this._register(editor.onDidChangeConfiguration((e) => { this._hoverOperation.setHoverTime(this._editor.getOption(EditorOption.hover).delay); })); } dispose(): void { this._hoverOperation.cancel(); super.dispose(); } onModelDecorationsChanged(): void { if (this._isChangingDecorations) { return; } 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(); if (!this._colorPicker) { // TODO@Michel ensure that displayed text for other decorations is computed even if color picker is in place this._hoverOperation.start(HoverStartMode.Delayed); } } } startShowingAt(range: Range, mode: HoverStartMode, focus: boolean): void { if (this._lastRange && this._lastRange.equalsRange(range)) { // We have to show the widget at the exact same range as before, so no work is needed return; } this._hoverOperation.cancel(); if (this.isVisible) { // The range might have changed, but the hover is visible // Instead of hiding it completely, filter out messages that are still in the new range and // kick off a new computation if (!this._showAtPosition || this._showAtPosition.lineNumber !== range.startLineNumber) { this.hide(); } else { let filteredMessages: HoverPart[] = []; for (let i = 0, len = this._messages.length; i < len; i++) { const msg = this._messages[i]; const rng = msg.range; if (rng && rng.startColumn <= range.startColumn && rng.endColumn >= range.endColumn) { filteredMessages.push(msg); } } if (filteredMessages.length > 0) { if (hoverContentsEquals(filteredMessages, this._messages)) { return; } this._renderMessages(range, filteredMessages); } else { this.hide(); } } } this._lastRange = range; this._computer.setRange(range); this._shouldFocus = focus; this._hoverOperation.start(mode); } hide(): void { this._lastRange = null; this._hoverOperation.cancel(); super.hide(); this._isChangingDecorations = true; this._highlightDecorations = this._editor.deltaDecorations(this._highlightDecorations, []); this._isChangingDecorations = false; this.renderDisposable.clear(); this._colorPicker = null; } isColorPickerVisible(): boolean { if (this._colorPicker) { return true; } return false; } private _withResult(result: HoverPart[], complete: boolean): void { this._messages = result; if (this._lastRange && this._messages.length > 0) { this._renderMessages(this._lastRange, this._messages); } else if (complete) { this.hide(); } } private _renderMessages(renderRange: Range, messages: HoverPart[]): void { this.renderDisposable.dispose(); this._colorPicker = null; // update column from which to show let renderColumn = Constants.MAX_SAFE_SMALL_INTEGER; let highlightRange: Range | null = messages[0].range ? Range.lift(messages[0].range) : null; let fragment = document.createDocumentFragment(); let isEmptyHoverContent = true; let containColorPicker = false; const markdownDisposeables = new DisposableStore(); const markerMessages: MarkerHover[] = []; messages.forEach((msg) => { if (!msg.range) { return; } renderColumn = Math.min(renderColumn, msg.range.startColumn); highlightRange = highlightRange ? Range.plusRange(highlightRange, msg.range) : Range.lift(msg.range); if (msg instanceof ColorHover) { containColorPicker = true; const { red, green, blue, alpha } = msg.color; const rgba = new RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha); const color = new Color(rgba); if (!this._editor.hasModel()) { return; } const editorModel = this._editor.getModel(); let range = new Range(msg.range.startLineNumber, msg.range.startColumn, msg.range.endLineNumber, msg.range.endColumn); let colorInfo = { range: msg.range, color: msg.color }; // create blank olor picker model and widget first to ensure it's positioned correctly. const model = new ColorPickerModel(color, [], 0); const widget = new ColorPickerWidget(fragment, model, this._editor.getOption(EditorOption.pixelRatio), this._themeService); getColorPresentations(editorModel, colorInfo, msg.provider, CancellationToken.None).then(colorPresentations => { model.colorPresentations = colorPresentations || []; if (!this._editor.hasModel()) { // gone... return; } const originalText = this._editor.getModel().getValueInRange(msg.range); model.guessColorPresentation(color, originalText); const updateEditorModel = () => { let textEdits: IIdentifiedSingleEditOperation[]; let newRange: Range; if (model.presentation.textEdit) { textEdits = [model.presentation.textEdit as IIdentifiedSingleEditOperation]; newRange = new Range( model.presentation.textEdit.range.startLineNumber, model.presentation.textEdit.range.startColumn, model.presentation.textEdit.range.endLineNumber, model.presentation.textEdit.range.endColumn ); newRange = newRange.setEndPosition(newRange.endLineNumber, newRange.startColumn + model.presentation.textEdit.text.length); } else { textEdits = [{ identifier: null, range, text: model.presentation.label, forceMoveMarkers: false }]; newRange = range.setEndPosition(range.endLineNumber, range.startColumn + model.presentation.label.length); } this._editor.pushUndoStop(); this._editor.executeEdits('colorpicker', textEdits); if (model.presentation.additionalTextEdits) { textEdits = [...model.presentation.additionalTextEdits as IIdentifiedSingleEditOperation[]]; this._editor.executeEdits('colorpicker', textEdits); this.hide(); } this._editor.pushUndoStop(); range = newRange; }; const updateColorPresentations = (color: Color) => { return getColorPresentations(editorModel, { range: range, color: { red: color.rgba.r / 255, green: color.rgba.g / 255, blue: color.rgba.b / 255, alpha: color.rgba.a } }, msg.provider, CancellationToken.None).then((colorPresentations) => { model.colorPresentations = colorPresentations || []; }); }; const colorListener = model.onColorFlushed((color: Color) => { updateColorPresentations(color).then(updateEditorModel); }); const colorChangeListener = model.onDidChangeColor(updateColorPresentations); this._colorPicker = widget; this.showAt(range.getStartPosition(), range, this._shouldFocus); this.updateContents(fragment); this._colorPicker.layout(); this.renderDisposable.value = combinedDisposable(colorListener, colorChangeListener, widget, markdownDisposeables); }); } else { if (msg instanceof MarkerHover) { markerMessages.push(msg); isEmptyHoverContent = false; } else { msg.contents .filter(contents => !isEmptyMarkdownString(contents)) .forEach(contents => { const markdownHoverElement = $('div.hover-row.markdown-hover'); const hoverContentsElement = dom.append(markdownHoverElement, $('div.hover-contents')); const renderer = markdownDisposeables.add(new MarkdownRenderer(this._editor, this._modeService, this._openerService)); markdownDisposeables.add(renderer.onDidRenderCodeBlock(() => { hoverContentsElement.className = 'hover-contents code-hover-contents'; this.onContentsChange(); })); const renderedContents = markdownDisposeables.add(renderer.render(contents)); hoverContentsElement.appendChild(renderedContents.element); fragment.appendChild(markdownHoverElement); isEmptyHoverContent = false; }); } } }); if (markerMessages.length) { markerMessages.forEach(msg => fragment.appendChild(this.renderMarkerHover(msg))); const markerHoverForStatusbar = markerMessages.length === 1 ? markerMessages[0] : markerMessages.sort((a, b) => MarkerSeverity.compare(a.marker.severity, b.marker.severity))[0]; fragment.appendChild(this.renderMarkerStatusbar(markerHoverForStatusbar)); } // show if (!containColorPicker && !isEmptyHoverContent) { this.showAt(new Position(renderRange.startLineNumber, renderColumn), highlightRange, this._shouldFocus); this.updateContents(fragment); } this._isChangingDecorations = true; this._highlightDecorations = this._editor.deltaDecorations(this._highlightDecorations, highlightRange ? [{ range: highlightRange, options: ModesContentHoverWidget._DECORATION_OPTIONS }] : []); this._isChangingDecorations = false; } private renderMarkerHover(markerHover: MarkerHover): HTMLElement { const hoverElement = $('div.hover-row'); const markerElement = dom.append(hoverElement, $('div.marker.hover-contents')); const { source, message, code, relatedInformation } = markerHover.marker; this._editor.applyFontInfo(markerElement); const messageElement = dom.append(markerElement, $('span')); messageElement.style.whiteSpace = 'pre-wrap'; messageElement.innerText = message; if (source || code) { const detailsElement = dom.append(markerElement, $('span')); detailsElement.style.opacity = '0.6'; detailsElement.style.paddingLeft = '6px'; detailsElement.innerText = source && code ? `${source}(${code})` : source ? source : `(${code})`; } if (isNonEmptyArray(relatedInformation)) { for (const { message, resource, startLineNumber, startColumn } of relatedInformation) { const relatedInfoContainer = dom.append(markerElement, $('div')); relatedInfoContainer.style.marginTop = '8px'; const a = dom.append(relatedInfoContainer, $('a')); a.innerText = `${basename(resource)}(${startLineNumber}, ${startColumn}): `; a.style.cursor = 'pointer'; a.onclick = e => { e.stopPropagation(); e.preventDefault(); if (this._openerService) { this._openerService.open(resource.with({ fragment: `${startLineNumber},${startColumn}` }), { fromUserGesture: true }).catch(onUnexpectedError); } }; const messageElement = dom.append<HTMLAnchorElement>(relatedInfoContainer, $('span')); messageElement.innerText = message; this._editor.applyFontInfo(messageElement); } } return hoverElement; } private renderMarkerStatusbar(markerHover: MarkerHover): HTMLElement { const hoverElement = $('div.hover-row.status-bar'); const disposables = new DisposableStore(); const actionsElement = dom.append(hoverElement, $('div.actions')); if (markerHover.marker.severity === MarkerSeverity.Error || markerHover.marker.severity === MarkerSeverity.Warning || markerHover.marker.severity === MarkerSeverity.Info) { disposables.add(this.renderAction(actionsElement, { label: nls.localize('peek problem', "Peek Problem"), commandId: NextMarkerAction.ID, run: () => { this.hide(); MarkerController.get(this._editor).show(markerHover.marker); this._editor.focus(); } })); } const quickfixPlaceholderElement = dom.append(actionsElement, $('div')); quickfixPlaceholderElement.style.opacity = '0'; quickfixPlaceholderElement.style.transition = 'opacity 0.2s'; setTimeout(() => quickfixPlaceholderElement.style.opacity = '1', 200); quickfixPlaceholderElement.textContent = nls.localize('checkingForQuickFixes', "Checking for quick fixes..."); disposables.add(toDisposable(() => quickfixPlaceholderElement.remove())); const codeActionsPromise = this.getCodeActions(markerHover.marker); disposables.add(toDisposable(() => codeActionsPromise.cancel())); codeActionsPromise.then(actions => { quickfixPlaceholderElement.style.transition = ''; quickfixPlaceholderElement.style.opacity = '1'; if (!actions.actions.length) { actions.dispose(); quickfixPlaceholderElement.textContent = nls.localize('noQuickFixes', "No quick fixes available"); return; } quickfixPlaceholderElement.remove(); let showing = false; disposables.add(toDisposable(() => { if (!showing) { actions.dispose(); } })); disposables.add(this.renderAction(actionsElement, { label: nls.localize('quick fixes', "Quick Fix..."), commandId: QuickFixAction.Id, run: (target) => { showing = true; const controller = QuickFixController.get(this._editor); const elementPosition = dom.getDomNodePagePosition(target); controller.showCodeActions(actions, { x: elementPosition.left + 6, y: elementPosition.top + elementPosition.height + 6 }); } })); }); this.renderDisposable.value = disposables; return hoverElement; } private getCodeActions(marker: IMarker): CancelablePromise<CodeActionSet> { return createCancelablePromise(cancellationToken => { return getCodeActions( this._editor.getModel()!, new Range(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn), { type: 'manual', filter: { include: CodeActionKind.QuickFix } }, cancellationToken); }); } private renderAction(parent: HTMLElement, actionOptions: { label: string, iconClass?: string, run: (target: HTMLElement) => void, commandId: string }): IDisposable { const actionContainer = dom.append(parent, $('div.action-container')); const action = dom.append(actionContainer, $('a.action')); if (actionOptions.iconClass) { dom.append(action, $(`span.icon.${actionOptions.iconClass}`)); } const label = dom.append(action, $('span')); label.textContent = actionOptions.label; const keybinding = this._keybindingService.lookupKeybinding(actionOptions.commandId); if (keybinding) { label.title = `${actionOptions.label} (${keybinding.getLabel()})`; } return dom.addDisposableListener(actionContainer, dom.EventType.CLICK, e => { e.stopPropagation(); e.preventDefault(); actionOptions.run(actionContainer); }); } private static readonly _DECORATION_OPTIONS = ModelDecorationOptions.register({ className: 'hoverHighlight' }); } function hoverContentsEquals(first: HoverPart[], second: HoverPart[]): boolean { if ((!first && second) || (first && !second) || first.length !== second.length) { return false; } for (let i = 0; i < first.length; i++) { const firstElement = first[i]; const secondElement = second[i]; if (firstElement instanceof MarkerHover && secondElement instanceof MarkerHover) { return IMarkerData.makeKey(firstElement.marker) === IMarkerData.makeKey(secondElement.marker); } if (firstElement instanceof ColorHover || secondElement instanceof ColorHover) { return false; } if (firstElement instanceof MarkerHover || secondElement instanceof MarkerHover) { return false; } if (!markedStringsEquals(firstElement.contents, secondElement.contents)) { return false; } } return true; }
src/vs/editor/contrib/hover/modesContentHover.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0013594415504485369, 0.00020440155640244484, 0.00016488958499394357, 0.0001707638002699241, 0.0001654145453358069 ]
{ "id": 0, "code_window": [ "\tprivate inputChangingTimeoutHandle: any;\n", "\t// @ts-ignore (legacy widget - to be replaced with quick input)\n", "\tprivate styles: IQuickOpenStyles;\n", "\t// @ts-ignore (legacy widget - to be replaced with quick input)\n", "\tprivate renderer: Renderer;\n", "\tprivate keyDownSeenSinceShown = false;\n", "\n", "\tconstructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions) {\n", "\t\tsuper();\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 137 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation'; import { OutputChannel } from 'vs/workbench/services/search/node/ripgrepSearchUtils'; import { RipgrepTextSearchEngine } from 'vs/workbench/services/search/node/ripgrepTextSearchEngine'; import { TextSearchProvider, TextSearchComplete, TextSearchResult, TextSearchQuery, TextSearchOptions } from 'vs/workbench/services/search/common/searchExtTypes'; import { Progress } from 'vs/platform/progress/common/progress'; export class RipgrepSearchProvider implements TextSearchProvider { private inProgress: Set<CancellationTokenSource> = new Set(); constructor(private outputChannel: OutputChannel) { process.once('exit', () => this.dispose()); } provideTextSearchResults(query: TextSearchQuery, options: TextSearchOptions, progress: Progress<TextSearchResult>, token: CancellationToken): Promise<TextSearchComplete> { const engine = new RipgrepTextSearchEngine(this.outputChannel); return this.withToken(token, token => engine.provideTextSearchResults(query, options, progress, token)); } private async withToken<T>(token: CancellationToken, fn: (token: CancellationToken) => Promise<T>): Promise<T> { const merged = mergedTokenSource(token); this.inProgress.add(merged); const result = await fn(merged.token); this.inProgress.delete(merged); return result; } private dispose() { this.inProgress.forEach(engine => engine.cancel()); } } function mergedTokenSource(token: CancellationToken): CancellationTokenSource { const tokenSource = new CancellationTokenSource(); token.onCancellationRequested(() => tokenSource.cancel()); return tokenSource; }
src/vs/workbench/services/search/node/ripgrepSearchProvider.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0005009655724279583, 0.00023695795971434563, 0.0001634949294384569, 0.00017385567480232567, 0.0001320679730270058 ]
{ "id": 0, "code_window": [ "\tprivate inputChangingTimeoutHandle: any;\n", "\t// @ts-ignore (legacy widget - to be replaced with quick input)\n", "\tprivate styles: IQuickOpenStyles;\n", "\t// @ts-ignore (legacy widget - to be replaced with quick input)\n", "\tprivate renderer: Renderer;\n", "\tprivate keyDownSeenSinceShown = false;\n", "\n", "\tconstructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions) {\n", "\t\tsuper();\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 137 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8 3L13 8L8 13L3 8L8 3Z" fill="#848484"/> </svg>
src/vs/workbench/contrib/debug/browser/media/breakpoint-log-disabled.svg
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017151101201307029, 0.00017151101201307029, 0.00017151101201307029, 0.00017151101201307029, 0 ]
{ "id": 1, "code_window": [ "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, e => this.gainingFocus(), true));\n", "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, e => this.loosingFocus(e), true));\n", "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, e => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tif (keyboardEvent.keyCode === KeyCode.Escape) {\n", "\t\t\t\tDOM.EventHelper.stop(e, true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 174 }
/*--------------------------------------------------------------------------------------------- * 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!./quickopen'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import { IQuickNavigateConfiguration, IAutoFocus, IEntryRunContext, IModel, Mode, IKeyMods } from 'vs/base/parts/quickopen/common/quickOpen'; import { Filter, Renderer, DataSource, IModelProvider, AccessibilityProvider } from 'vs/base/parts/quickopen/browser/quickOpenViewer'; import { ITree, ContextMenuEvent, IActionProvider, ITreeStyles, ITreeOptions, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree'; import { InputBox, MessageType, IInputBoxStyles, IRange } from 'vs/base/browser/ui/inputbox/inputBox'; import Severity from 'vs/base/common/severity'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { DefaultController, ClickBehavior } from 'vs/base/parts/tree/browser/treeDefaults'; import * as DOM from 'vs/base/browser/dom'; import { KeyCode } from 'vs/base/common/keyCodes'; import { Disposable } from 'vs/base/common/lifecycle'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { StandardMouseEvent, IMouseEvent } from 'vs/base/browser/mouseEvent'; import { IThemable } from 'vs/base/common/styler'; export interface IQuickOpenCallbacks { onOk: () => void; onCancel: () => void; onType: (value: string) => void; onShow?: () => void; onHide?: (reason: HideReason) => void; onFocusLost?: () => boolean /* veto close */; } export interface IQuickOpenOptions extends IQuickOpenStyles { minItemsToShow?: number; maxItemsToShow?: number; inputPlaceHolder?: string; inputAriaLabel?: string; actionProvider?: IActionProvider; keyboardSupport?: boolean; treeCreator?: (container: HTMLElement, configuration: ITreeConfiguration, options?: ITreeOptions) => ITree; } export interface IQuickOpenStyles extends IInputBoxStyles, ITreeStyles { background?: Color; foreground?: Color; borderColor?: Color; pickerGroupForeground?: Color; pickerGroupBorder?: Color; widgetShadow?: Color; progressBarBackground?: Color; } export interface IShowOptions { quickNavigateConfiguration?: IQuickNavigateConfiguration; autoFocus?: IAutoFocus; inputSelection?: IRange; value?: string; } export class QuickOpenController extends DefaultController { onContextMenu(tree: ITree, element: any, event: ContextMenuEvent): boolean { if (platform.isMacintosh) { return this.onLeftClick(tree, element, event); // https://github.com/Microsoft/vscode/issues/1011 } return super.onContextMenu(tree, element, event); } onMouseMiddleClick(tree: ITree, element: any, event: IMouseEvent): boolean { return this.onLeftClick(tree, element, event); } } export const enum HideReason { ELEMENT_SELECTED, FOCUS_LOST, CANCELED } const defaultStyles = { background: Color.fromHex('#1E1E1E'), foreground: Color.fromHex('#CCCCCC'), pickerGroupForeground: Color.fromHex('#0097FB'), pickerGroupBorder: Color.fromHex('#3F3F46'), widgetShadow: Color.fromHex('#000000'), progressBarBackground: Color.fromHex('#0E70C0') }; const DEFAULT_INPUT_ARIA_LABEL = nls.localize('quickOpenAriaLabel', "Quick picker. Type to narrow down results."); export class QuickOpenWidget extends Disposable implements IModelProvider, IThemable { private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private static readonly MAX_ITEMS_HEIGHT = 20 * 22; // Max height of item list below input field private isDisposed: boolean; private options: IQuickOpenOptions; // @ts-ignore (legacy widget - to be replaced with quick input) private element: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private tree: ITree; // @ts-ignore (legacy widget - to be replaced with quick input) private inputBox: InputBox; // @ts-ignore (legacy widget - to be replaced with quick input) private inputContainer: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private helpText: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private resultCount: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private treeContainer: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private progressBar: ProgressBar; // @ts-ignore (legacy widget - to be replaced with quick input) private visible: boolean; // @ts-ignore (legacy widget - to be replaced with quick input) private isLoosingFocus: boolean; private callbacks: IQuickOpenCallbacks; private quickNavigateConfiguration: IQuickNavigateConfiguration | undefined; private container: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private treeElement: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private inputElement: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private layoutDimensions: DOM.Dimension; private model: IModel<any> | null; private inputChangingTimeoutHandle: any; // @ts-ignore (legacy widget - to be replaced with quick input) private styles: IQuickOpenStyles; // @ts-ignore (legacy widget - to be replaced with quick input) private renderer: Renderer; private keyDownSeenSinceShown = false; constructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions) { super(); this.isDisposed = false; this.container = container; this.callbacks = callbacks; this.options = options; this.styles = options || Object.create(null); mixin(this.styles, defaultStyles, false); this.model = null; } getElement(): HTMLElement { return this.element; } getModel(): IModel<any> { return this.model!; } setCallbacks(callbacks: IQuickOpenCallbacks): void { this.callbacks = callbacks; } create(): HTMLElement { // Container this.element = document.createElement('div'); DOM.addClass(this.element, 'monaco-quick-open-widget'); this.container.appendChild(this.element); this._register(DOM.addDisposableListener(this.element, DOM.EventType.CONTEXT_MENU, e => DOM.EventHelper.stop(e, true))); // Do this to fix an issue on Mac where the menu goes into the way this._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, e => this.gainingFocus(), true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, e => this.loosingFocus(e), true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, e => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); if (keyboardEvent.keyCode === KeyCode.Escape) { DOM.EventHelper.stop(e, true); this.hide(HideReason.CANCELED); } else if (keyboardEvent.keyCode === KeyCode.Tab && !keyboardEvent.altKey && !keyboardEvent.ctrlKey && !keyboardEvent.metaKey) { const stops = (e.currentTarget as HTMLElement).querySelectorAll('input, .monaco-tree, .monaco-tree-row.focused .action-label.icon') as NodeListOf<HTMLElement>; if (keyboardEvent.shiftKey && keyboardEvent.target === stops[0]) { DOM.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!keyboardEvent.shiftKey && keyboardEvent.target === stops[stops.length - 1]) { DOM.EventHelper.stop(e, true); stops[0].focus(); } } })); // Progress Bar this.progressBar = this._register(new ProgressBar(this.element, { progressBarBackground: this.styles.progressBarBackground })); this.progressBar.hide(); // Input Field this.inputContainer = document.createElement('div'); DOM.addClass(this.inputContainer, 'quick-open-input'); this.element.appendChild(this.inputContainer); this.inputBox = this._register(new InputBox(this.inputContainer, undefined, { placeholder: this.options.inputPlaceHolder || '', ariaLabel: DEFAULT_INPUT_ARIA_LABEL, inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder })); this.inputElement = this.inputBox.inputElement; this.inputElement.setAttribute('role', 'combobox'); this.inputElement.setAttribute('aria-haspopup', 'false'); this.inputElement.setAttribute('aria-autocomplete', 'list'); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, (e: Event) => this.onType())); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const shouldOpenInBackground = this.shouldOpenInBackground(keyboardEvent); // Do not handle Tab: It is used to navigate between elements without mouse if (keyboardEvent.keyCode === KeyCode.Tab) { return; } // Pass tree navigation keys to the tree but leave focus in input field else if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); // Position cursor at the end of input to allow right arrow (open in background) // to function immediately unless the user has made a selection if (this.inputBox.inputElement.selectionStart === this.inputBox.inputElement.selectionEnd) { this.inputBox.inputElement.selectionStart = this.inputBox.value.length; } } // Select element on Enter or on Arrow-Right if we are at the end of the input else if (keyboardEvent.keyCode === KeyCode.Enter || shouldOpenInBackground) { DOM.EventHelper.stop(e, true); const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus, e, shouldOpenInBackground ? Mode.OPEN_IN_BACKGROUND : Mode.OPEN); } } })); // Result count for screen readers this.resultCount = document.createElement('div'); DOM.addClass(this.resultCount, 'quick-open-result-count'); this.resultCount.setAttribute('aria-live', 'polite'); this.resultCount.setAttribute('aria-atomic', 'true'); this.element.appendChild(this.resultCount); // Tree this.treeContainer = document.createElement('div'); DOM.addClass(this.treeContainer, 'quick-open-tree'); this.element.appendChild(this.treeContainer); const createTree = this.options.treeCreator || ((container, config, opts) => new Tree(container, config, opts)); this.tree = this._register(createTree(this.treeContainer, { dataSource: new DataSource(this), controller: new QuickOpenController({ clickBehavior: ClickBehavior.ON_MOUSE_UP, keyboardSupport: this.options.keyboardSupport }), renderer: (this.renderer = new Renderer(this, this.styles)), filter: new Filter(this), accessibilityProvider: new AccessibilityProvider(this) }, { twistiePixels: 11, indentPixels: 0, alwaysFocused: true, verticalScrollMode: ScrollbarVisibility.Visible, horizontalScrollMode: ScrollbarVisibility.Hidden, ariaLabel: nls.localize('treeAriaLabel', "Quick Picker"), keyboardSupport: this.options.keyboardSupport, preventRootFocus: false })); this.treeElement = this.tree.getHTMLElement(); // Handle Focus and Selection event this._register(this.tree.onDidChangeFocus(event => { this.elementFocused(event.focus, event); })); this._register(this.tree.onDidChangeSelection(event => { if (event.selection && event.selection.length > 0) { const mouseEvent: StandardMouseEvent = event.payload && event.payload.originalEvent instanceof StandardMouseEvent ? event.payload.originalEvent : undefined; const shouldOpenInBackground = mouseEvent ? this.shouldOpenInBackground(mouseEvent) : false; this.elementSelected(event.selection[0], event, shouldOpenInBackground ? Mode.OPEN_IN_BACKGROUND : Mode.OPEN); } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, e => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); // Only handle when in quick navigation mode if (!this.quickNavigateConfiguration) { return; } // Support keyboard navigation in quick navigation mode if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode); } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, e => { const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Only handle when in quick navigation mode if (!this.quickNavigateConfiguration || !this.keyDownSeenSinceShown) { return; } // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigateConfiguration.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed) { const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus, e); } } })); // Support layout if (this.layoutDimensions) { this.layout(this.layoutDimensions); } this.applyStyles(); // Allows focus to switch to next/previous entry after tab into an actionbar item this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); // Only handle when not in quick navigation mode if (this.quickNavigateConfiguration) { return; } if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); this.treeElement.focus(); } })); return this.element; } style(styles: IQuickOpenStyles): void { this.styles = styles; this.applyStyles(); } protected applyStyles(): void { if (this.element) { const foreground = this.styles.foreground ? this.styles.foreground.toString() : null; const background = this.styles.background ? this.styles.background.toString() : ''; const borderColor = this.styles.borderColor ? this.styles.borderColor.toString() : ''; const widgetShadow = this.styles.widgetShadow ? this.styles.widgetShadow.toString() : ''; this.element.style.color = foreground; this.element.style.backgroundColor = background; this.element.style.borderColor = borderColor; this.element.style.borderWidth = borderColor ? '1px' : ''; this.element.style.borderStyle = borderColor ? 'solid' : ''; this.element.style.boxShadow = widgetShadow ? `0 5px 8px ${widgetShadow}` : ''; } if (this.progressBar) { this.progressBar.style({ progressBarBackground: this.styles.progressBarBackground }); } if (this.inputBox) { this.inputBox.style({ inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder }); } if (this.tree && !this.options.treeCreator) { this.tree.style(this.styles); } if (this.renderer) { this.renderer.updateStyles(this.styles); } } private shouldOpenInBackground(e: StandardKeyboardEvent | StandardMouseEvent): boolean { // Keyboard if (e instanceof StandardKeyboardEvent) { if (e.keyCode !== KeyCode.RightArrow) { return false; // only for right arrow } if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return false; // no modifiers allowed } // validate the cursor is at the end of the input and there is no selection, // and if not prevent opening in the background such as the selection can be changed const element = this.inputBox.inputElement; return element.selectionEnd === this.inputBox.value.length && element.selectionStart === element.selectionEnd; } // Mouse return e.middleButton; } private onType(): void { const value = this.inputBox.value; // Adjust help text as needed if present if (this.helpText) { if (value) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Send to callbacks this.callbacks.onType(value); } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void { if (this.isVisible()) { // Transition into quick navigate mode if not yet done if (!this.quickNavigateConfiguration && quickNavigate) { this.quickNavigateConfiguration = quickNavigate; this.tree.domFocus(); } // Navigate this.navigateInTree(next ? KeyCode.DownArrow : KeyCode.UpArrow); } } private navigateInTree(keyCode: KeyCode, isShift?: boolean): void { const model: IModel<any> = this.tree.getInput(); const entries = model ? model.entries : []; const oldFocus = this.tree.getFocus(); // Normal Navigation switch (keyCode) { case KeyCode.DownArrow: this.tree.focusNext(); break; case KeyCode.UpArrow: this.tree.focusPrevious(); break; case KeyCode.PageDown: this.tree.focusNextPage(); break; case KeyCode.PageUp: this.tree.focusPreviousPage(); break; case KeyCode.Tab: if (isShift) { this.tree.focusPrevious(); } else { this.tree.focusNext(); } break; } let newFocus = this.tree.getFocus(); // Support cycle-through navigation if focus did not change if (entries.length > 1 && oldFocus === newFocus) { // Up from no entry or first entry goes down to last if (keyCode === KeyCode.UpArrow || (keyCode === KeyCode.Tab && isShift)) { this.tree.focusLast(); } // Down from last entry goes to up to first else if (keyCode === KeyCode.DownArrow || keyCode === KeyCode.Tab && !isShift) { this.tree.focusFirst(); } } // Reveal newFocus = this.tree.getFocus(); if (newFocus) { this.tree.reveal(newFocus); } } private elementFocused(value: any, event?: any): void { if (!value || !this.isVisible()) { return; } // ARIA const arivaActiveDescendant = this.treeElement.getAttribute('aria-activedescendant'); if (arivaActiveDescendant) { this.inputElement.setAttribute('aria-activedescendant', arivaActiveDescendant); } else { this.inputElement.removeAttribute('aria-activedescendant'); } const context: IEntryRunContext = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; this.model!.runner.run(value, Mode.PREVIEW, context); } private elementSelected(value: any, event?: any, preferredMode?: Mode): void { let hide = true; // Trigger open of element on selection if (this.isVisible()) { let mode = preferredMode || Mode.OPEN; const context: IEntryRunContext = { event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; hide = this.model!.runner.run(value, mode, context); } // Hide if command was run successfully if (hide) { this.hide(HideReason.ELEMENT_SELECTED); } } private extractKeyMods(event: any): IKeyMods { return { ctrlCmd: event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey))), alt: event && (event.altKey || (event.payload && event.payload.originalEvent && event.payload.originalEvent.altKey)) }; } show(prefix: string, options?: IShowOptions): void; show(input: IModel<any>, options?: IShowOptions): void; show(param: any, options?: IShowOptions): void { this.visible = true; this.isLoosingFocus = false; this.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined; this.keyDownSeenSinceShown = false; // Adjust UI for quick navigate mode if (this.quickNavigateConfiguration) { DOM.hide(this.inputContainer); DOM.show(this.element); this.tree.domFocus(); } // Otherwise use normal UI else { DOM.show(this.inputContainer); DOM.show(this.element); this.inputBox.focus(); } // Adjust Help text for IE if (this.helpText) { if (this.quickNavigateConfiguration || types.isString(param)) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Show based on param if (types.isString(param)) { this.doShowWithPrefix(param); } else { if (options && options.value) { this.restoreLastInput(options.value); } this.doShowWithInput(param, options && options.autoFocus ? options.autoFocus : {}); } // Respect selectAll option if (options && options.inputSelection && !this.quickNavigateConfiguration) { this.inputBox.select(options.inputSelection); } if (this.callbacks.onShow) { this.callbacks.onShow(); } } private restoreLastInput(lastInput: string) { this.inputBox.value = lastInput; this.inputBox.select(); this.callbacks.onType(lastInput); } private doShowWithPrefix(prefix: string): void { this.inputBox.value = prefix; this.callbacks.onType(prefix); } private doShowWithInput(input: IModel<any>, autoFocus: IAutoFocus): void { this.setInput(input, autoFocus); } private setInputAndLayout(input: IModel<any>, autoFocus?: IAutoFocus): void { this.treeContainer.style.height = `${this.getHeight(input)}px`; this.tree.setInput(null).then(() => { this.model = input; // ARIA this.inputElement.setAttribute('aria-haspopup', String(input && input.entries && input.entries.length > 0)); return this.tree.setInput(input); }).then(() => { // Indicate entries to tree this.tree.layout(); const entries = input ? input.entries.filter(e => this.isElementVisible(input, e)) : []; this.updateResultCount(entries.length); // Handle auto focus if (entries.length) { this.autoFocus(input, entries, autoFocus); } }); } private isElementVisible<T>(input: IModel<T>, e: T): boolean { if (!input.filter) { return true; } return input.filter.isVisible(e); } private autoFocus(input: IModel<any>, entries: any[], autoFocus: IAutoFocus = {}): void { // First check for auto focus of prefix matches if (autoFocus.autoFocusPrefixMatch) { let caseSensitiveMatch: any; let caseInsensitiveMatch: any; const prefix = autoFocus.autoFocusPrefixMatch; const lowerCasePrefix = prefix.toLowerCase(); for (const entry of entries) { const label = input.dataSource.getLabel(entry) || ''; if (!caseSensitiveMatch && label.indexOf(prefix) === 0) { caseSensitiveMatch = entry; } else if (!caseInsensitiveMatch && label.toLowerCase().indexOf(lowerCasePrefix) === 0) { caseInsensitiveMatch = entry; } if (caseSensitiveMatch && caseInsensitiveMatch) { break; } } const entryToFocus = caseSensitiveMatch || caseInsensitiveMatch; if (entryToFocus) { this.tree.setFocus(entryToFocus); this.tree.reveal(entryToFocus, 0.5); return; } } // Second check for auto focus of first entry if (autoFocus.autoFocusFirstEntry) { this.tree.focusFirst(); this.tree.reveal(this.tree.getFocus()); } // Third check for specific index option else if (typeof autoFocus.autoFocusIndex === 'number') { if (entries.length > autoFocus.autoFocusIndex) { this.tree.focusNth(autoFocus.autoFocusIndex); this.tree.reveal(this.tree.getFocus()); } } // Check for auto focus of second entry else if (autoFocus.autoFocusSecondEntry) { if (entries.length > 1) { this.tree.focusNth(1); } } // Finally check for auto focus of last entry else if (autoFocus.autoFocusLastEntry) { if (entries.length > 1) { this.tree.focusLast(); } } } refresh(input?: IModel<any>, autoFocus?: IAutoFocus): void { if (!this.isVisible()) { return; } if (!input) { input = this.tree.getInput(); } if (!input) { return; } // Apply height & Refresh this.treeContainer.style.height = `${this.getHeight(input)}px`; this.tree.refresh().then(() => { // Indicate entries to tree this.tree.layout(); const entries = input ? input.entries!.filter(e => this.isElementVisible(input!, e)) : []; this.updateResultCount(entries.length); // Handle auto focus if (autoFocus) { if (entries.length) { this.autoFocus(input!, entries, autoFocus); } } }); } private getHeight(input: IModel<any>): number { const renderer = input.renderer; if (!input) { const itemHeight = renderer.getHeight(null); return this.options.minItemsToShow ? this.options.minItemsToShow * itemHeight : 0; } let height = 0; let preferredItemsHeight: number | undefined; if (this.layoutDimensions && this.layoutDimensions.height) { preferredItemsHeight = (this.layoutDimensions.height - 50 /* subtract height of input field (30px) and some spacing (drop shadow) to fit */) * 0.4 /* max 40% of screen */; } if (!preferredItemsHeight || preferredItemsHeight > QuickOpenWidget.MAX_ITEMS_HEIGHT) { preferredItemsHeight = QuickOpenWidget.MAX_ITEMS_HEIGHT; } const entries = input.entries.filter(e => this.isElementVisible(input, e)); const maxEntries = this.options.maxItemsToShow || entries.length; for (let i = 0; i < maxEntries && i < entries.length; i++) { const entryHeight = renderer.getHeight(entries[i]); if (height + entryHeight <= preferredItemsHeight) { height += entryHeight; } else { break; } } return height; } updateResultCount(count: number) { this.resultCount.textContent = nls.localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results", count); } hide(reason?: HideReason): void { if (!this.isVisible()) { return; } this.visible = false; DOM.hide(this.element); this.element.blur(); // Clear input field and clear tree this.inputBox.value = ''; this.tree.setInput(null); // ARIA this.inputElement.setAttribute('aria-haspopup', 'false'); // Reset Tree Height this.treeContainer.style.height = `${this.options.minItemsToShow ? this.options.minItemsToShow * 22 : 0}px`; // Clear any running Progress this.progressBar.stop().hide(); // Clear Focus if (this.tree.isDOMFocused()) { this.tree.domBlur(); } else if (this.inputBox.hasFocus()) { this.inputBox.blur(); } // Callbacks if (reason === HideReason.ELEMENT_SELECTED) { this.callbacks.onOk(); } else { this.callbacks.onCancel(); } if (this.callbacks.onHide) { this.callbacks.onHide(reason!); } } getQuickNavigateConfiguration(): IQuickNavigateConfiguration { return this.quickNavigateConfiguration!; } setPlaceHolder(placeHolder: string): void { if (this.inputBox) { this.inputBox.setPlaceHolder(placeHolder); } } setValue(value: string, selectionOrStableHint?: [number, number] | null): void { if (this.inputBox) { this.inputBox.value = value; if (selectionOrStableHint === null) { // null means stable-selection } else if (Array.isArray(selectionOrStableHint)) { const [start, end] = selectionOrStableHint; this.inputBox.select({ start, end }); } else { this.inputBox.select(); } } } setPassword(isPassword: boolean): void { if (this.inputBox) { this.inputBox.inputElement.type = isPassword ? 'password' : 'text'; } } setInput(input: IModel<any>, autoFocus?: IAutoFocus, ariaLabel?: string): void { if (!this.isVisible()) { return; } // If the input changes, indicate this to the tree if (!!this.getInput()) { this.onInputChanging(); } // Adapt tree height to entries and apply input this.setInputAndLayout(input, autoFocus); // Apply ARIA if (this.inputBox) { this.inputBox.setAriaLabel(ariaLabel || DEFAULT_INPUT_ARIA_LABEL); } } private onInputChanging(): void { if (this.inputChangingTimeoutHandle) { clearTimeout(this.inputChangingTimeoutHandle); this.inputChangingTimeoutHandle = null; } // when the input is changing in quick open, we indicate this as CSS class to the widget // for a certain timeout. this helps reducing some hectic UI updates when input changes quickly DOM.addClass(this.element, 'content-changing'); this.inputChangingTimeoutHandle = setTimeout(() => { DOM.removeClass(this.element, 'content-changing'); }, 500); } getInput(): IModel<any> { return this.tree.getInput(); } showInputDecoration(decoration: Severity): void { if (this.inputBox) { this.inputBox.showMessage({ type: decoration === Severity.Info ? MessageType.INFO : decoration === Severity.Warning ? MessageType.WARNING : MessageType.ERROR, content: '' }); } } clearInputDecoration(): void { if (this.inputBox) { this.inputBox.hideMessage(); } } focus(): void { if (this.isVisible() && this.inputBox) { this.inputBox.focus(); } } accept(): void { if (this.isVisible()) { const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus); } } } getProgressBar(): ProgressBar { return this.progressBar; } getInputBox(): InputBox { return this.inputBox; } setExtraClass(clazz: string | null): void { const previousClass = this.element.getAttribute('quick-open-extra-class'); if (previousClass) { DOM.removeClasses(this.element, previousClass); } if (clazz) { DOM.addClasses(this.element, clazz); this.element.setAttribute('quick-open-extra-class', clazz); } else if (previousClass) { this.element.removeAttribute('quick-open-extra-class'); } } isVisible(): boolean { return this.visible; } layout(dimension: DOM.Dimension): void { this.layoutDimensions = dimension; // Apply to quick open width (height is dynamic by number of items to show) const quickOpenWidth = Math.min(this.layoutDimensions.width * 0.62 /* golden cut */, QuickOpenWidget.MAX_WIDTH); if (this.element) { // quick open this.element.style.width = `${quickOpenWidth}px`; this.element.style.marginLeft = `-${quickOpenWidth / 2}px`; // input field this.inputContainer.style.width = `${quickOpenWidth - 12}px`; } } private gainingFocus(): void { this.isLoosingFocus = false; } private loosingFocus(e: FocusEvent): void { if (!this.isVisible()) { return; } const relatedTarget = e.relatedTarget as HTMLElement; if (!this.quickNavigateConfiguration && DOM.isAncestor(relatedTarget, this.element)) { return; // user clicked somewhere into quick open widget, do not close thereby } this.isLoosingFocus = true; setTimeout(() => { if (!this.isLoosingFocus || this.isDisposed) { return; } const veto = this.callbacks.onFocusLost && this.callbacks.onFocusLost(); if (!veto) { this.hide(HideReason.FOCUS_LOST); } }, 0); } dispose(): void { super.dispose(); this.isDisposed = true; } }
src/vs/base/parts/quickopen/browser/quickOpenWidget.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9983850717544556, 0.10262148082256317, 0.00016222622070927173, 0.00017037152429111302, 0.29746752977371216 ]
{ "id": 1, "code_window": [ "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, e => this.gainingFocus(), true));\n", "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, e => this.loosingFocus(e), true));\n", "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, e => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tif (keyboardEvent.keyCode === KeyCode.Escape) {\n", "\t\t\t\tDOM.EventHelper.stop(e, true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 174 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IListRenderer } from './list'; import { IDisposable } from 'vs/base/common/lifecycle'; import { $, removeClass } from 'vs/base/browser/dom'; export interface IRow { domNode: HTMLElement | null; templateId: string; templateData: any; } function removeFromParent(element: HTMLElement): void { try { if (element.parentElement) { element.parentElement.removeChild(element); } } catch (e) { // this will throw if this happens due to a blur event, nasty business } } export class RowCache<T> implements IDisposable { private cache = new Map<string, IRow[]>(); constructor(private renderers: Map<string, IListRenderer<T, any>>) { } /** * Returns a row either by creating a new one or reusing * a previously released row which shares the same templateId. */ alloc(templateId: string): IRow { let result = this.getTemplateCache(templateId).pop(); if (!result) { const domNode = $('.monaco-list-row'); const renderer = this.getRenderer(templateId); const templateData = renderer.renderTemplate(domNode); result = { domNode, templateId, templateData }; } return result; } /** * Releases the row for eventual reuse. */ release(row: IRow): void { if (!row) { return; } this.releaseRow(row); } private releaseRow(row: IRow): void { const { domNode, templateId } = row; if (domNode) { removeClass(domNode, 'scrolling'); removeFromParent(domNode); } const cache = this.getTemplateCache(templateId); cache.push(row); } private getTemplateCache(templateId: string): IRow[] { let result = this.cache.get(templateId); if (!result) { result = []; this.cache.set(templateId, result); } return result; } dispose(): void { this.cache.forEach((cachedRows, templateId) => { for (const cachedRow of cachedRows) { const renderer = this.getRenderer(templateId); renderer.disposeTemplate(cachedRow.templateData); cachedRow.domNode = null; cachedRow.templateData = null; } }); this.cache.clear(); } private getRenderer(templateId: string): IListRenderer<T, any> { const renderer = this.renderers.get(templateId); if (!renderer) { throw new Error(`No renderer found for ${templateId}`); } return renderer; } }
src/vs/base/browser/ui/list/rowCache.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0001755897974362597, 0.00017120970005635172, 0.0001652399223530665, 0.00017135785310529172, 0.0000027351056814950425 ]
{ "id": 1, "code_window": [ "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, e => this.gainingFocus(), true));\n", "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, e => this.loosingFocus(e), true));\n", "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, e => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tif (keyboardEvent.keyCode === KeyCode.Escape) {\n", "\t\t\t\tDOM.EventHelper.stop(e, true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 174 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M14.4315 3.3232L5.96151 13.3232L5.1708 13.2874L1.8208 8.5174L2.63915 7.94268L5.61697 12.1827L13.6684 2.67688L14.4315 3.3232Z" fill="#C5C5C5"/> </svg>
src/vs/base/browser/ui/menu/check.svg
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017463756375946105, 0.00017463756375946105, 0.00017463756375946105, 0.00017463756375946105, 0 ]
{ "id": 1, "code_window": [ "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, e => this.gainingFocus(), true));\n", "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, e => this.loosingFocus(e), true));\n", "\t\tthis._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, e => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tif (keyboardEvent.keyCode === KeyCode.Escape) {\n", "\t\t\t\tDOM.EventHelper.stop(e, true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 174 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution'; KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({ layout: { model: 'pc105', layout: 'us', variant: '', options: '', rules: 'evdev', isUSStandard: true }, secondaryLayouts: [ { model: 'pc105', layout: 'cn', variant: '', options: '', rules: 'evdev' }, ], mapping: { Sleep: [], WakeUp: [], KeyA: ['a', 'A', 'a', 'A', 0], KeyB: ['b', 'B', 'b', 'B', 0], KeyC: ['c', 'C', 'c', 'C', 0], KeyD: ['d', 'D', 'd', 'D', 0], KeyE: ['e', 'E', 'e', 'E', 0], KeyF: ['f', 'F', 'f', 'F', 0], KeyG: ['g', 'G', 'g', 'G', 0], KeyH: ['h', 'H', 'h', 'H', 0], KeyI: ['i', 'I', 'i', 'I', 0], KeyJ: ['j', 'J', 'j', 'J', 0], KeyK: ['k', 'K', 'k', 'K', 0], KeyL: ['l', 'L', 'l', 'L', 0], KeyM: ['m', 'M', 'm', 'M', 0], KeyN: ['n', 'N', 'n', 'N', 0], KeyO: ['o', 'O', 'o', 'O', 0], KeyP: ['p', 'P', 'p', 'P', 0], KeyQ: ['q', 'Q', 'q', 'Q', 0], KeyR: ['r', 'R', 'r', 'R', 0], KeyS: ['s', 'S', 's', 'S', 0], KeyT: ['t', 'T', 't', 'T', 0], KeyU: ['u', 'U', 'u', 'U', 0], KeyV: ['v', 'V', 'v', 'V', 0], KeyW: ['w', 'W', 'w', 'W', 0], KeyX: ['x', 'X', 'x', 'X', 0], KeyY: ['y', 'Y', 'y', 'Y', 0], KeyZ: ['z', 'Z', 'z', 'Z', 0], Digit1: ['1', '!', '1', '!', 0], Digit2: ['2', '@', '2', '@', 0], Digit3: ['3', '#', '3', '#', 0], Digit4: ['4', '$', '4', '$', 0], Digit5: ['5', '%', '5', '%', 0], Digit6: ['6', '^', '6', '^', 0], Digit7: ['7', '&', '7', '&', 0], Digit8: ['8', '*', '8', '*', 0], Digit9: ['9', '(', '9', '(', 0], Digit0: ['0', ')', '0', ')', 0], Enter: ['\r', '\r', '\r', '\r', 0], Escape: ['\u001b', '\u001b', '\u001b', '\u001b', 0], Backspace: ['\b', '\b', '\b', '\b', 0], Tab: ['\t', '', '\t', '', 0], Space: [' ', ' ', ' ', ' ', 0], Minus: ['-', '_', '-', '_', 0], Equal: ['=', '+', '=', '+', 0], BracketLeft: ['[', '{', '[', '{', 0], BracketRight: [']', '}', ']', '}', 0], Backslash: ['\\', '|', '\\', '|', 0], Semicolon: [';', ':', ';', ':', 0], Quote: ['\'', '"', '\'', '"', 0], Backquote: ['`', '~', '`', '~', 0], Comma: [',', '<', ',', '<', 0], Period: ['.', '>', '.', '>', 0], Slash: ['/', '?', '/', '?', 0], CapsLock: [], F1: [], F2: [], F3: [], F4: [], F5: [], F6: [], F7: [], F8: [], F9: [], F10: [], F11: [], F12: [], PrintScreen: [], ScrollLock: [], Pause: [], Insert: [], Home: [], PageUp: [], Delete: ['', '', '', '', 0], End: [], PageDown: [], ArrowRight: [], ArrowLeft: [], ArrowDown: [], ArrowUp: [], NumLock: [], NumpadDivide: ['/', '/', '/', '/', 0], NumpadMultiply: ['*', '*', '*', '*', 0], NumpadSubtract: ['-', '-', '-', '-', 0], NumpadAdd: ['+', '+', '+', '+', 0], NumpadEnter: ['\r', '\r', '\r', '\r', 0], Numpad1: ['', '1', '', '1', 0], Numpad2: ['', '2', '', '2', 0], Numpad3: ['', '3', '', '3', 0], Numpad4: ['', '4', '', '4', 0], Numpad5: ['', '5', '', '5', 0], Numpad6: ['', '6', '', '6', 0], Numpad7: ['', '7', '', '7', 0], Numpad8: ['', '8', '', '8', 0], Numpad9: ['', '9', '', '9', 0], Numpad0: ['', '0', '', '0', 0], NumpadDecimal: ['', '.', '', '.', 0], IntlBackslash: ['<', '>', '|', '¦', 0], ContextMenu: [], Power: [], NumpadEqual: ['=', '=', '=', '=', 0], F13: [], F14: [], F15: [], F16: [], F17: [], F18: [], F19: [], F20: [], F21: [], F22: [], F23: [], F24: [], Open: [], Help: [], Select: [], Again: [], Undo: [], Cut: [], Copy: [], Paste: [], Find: [], AudioVolumeMute: [], AudioVolumeUp: [], AudioVolumeDown: [], NumpadComma: ['.', '.', '.', '.', 0], IntlRo: [], KanaMode: [], IntlYen: [], Convert: [], NonConvert: [], Lang1: [], Lang2: [], Lang3: [], Lang4: [], Lang5: [], NumpadParenLeft: ['(', '(', '(', '(', 0], NumpadParenRight: [')', ')', ')', ')', 0], ControlLeft: [], ShiftLeft: [], AltLeft: [], MetaLeft: [], ControlRight: [], ShiftRight: [], AltRight: [], MetaRight: [], BrightnessUp: [], BrightnessDown: [], MediaPlay: [], MediaRecord: [], MediaFastForward: [], MediaRewind: [], MediaTrackNext: [], MediaTrackPrevious: [], MediaStop: [], Eject: [], MediaPlayPause: [], MediaSelect: [], LaunchMail: [], LaunchApp2: [], LaunchApp1: [], SelectTask: [], LaunchScreenSaver: [], BrowserSearch: [], BrowserHome: [], BrowserBack: [], BrowserForward: [], BrowserStop: [], BrowserRefresh: [], BrowserFavorites: [], MailReply: [], MailForward: [], MailSend: [] } });
src/vs/workbench/services/keybinding/browser/keyboardLayouts/en.linux.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017651525558903813, 0.0001717847480904311, 0.00016260564734693617, 0.00017236793064512312, 0.000002960791789519135 ]
{ "id": 2, "code_window": [ "\t\tthis.inputElement.setAttribute('aria-haspopup', 'false');\n", "\t\tthis.inputElement.setAttribute('aria-autocomplete', 'list');\n", "\n", "\t\tthis._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, (e: Event) => this.onType()));\n", "\t\tthis._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tconst shouldOpenInBackground = this.shouldOpenInBackground(keyboardEvent);\n", "\n", "\t\t\t// Do not handle Tab: It is used to navigate between elements without mouse\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 225 }
/*--------------------------------------------------------------------------------------------- * 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/quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { QUICK_INPUT_BACKGROUND, QUICK_INPUT_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerAndGetAmdImageURL } from 'vs/base/common/amd'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-dark.svg')), light: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-light.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; titleBar: HTMLElement; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; filterContainer: HTMLElement; inputBox: QuickInputBox; visibleCountContainer: HTMLElement; visibleCount: CountBadge; countContainer: HTMLElement; count: CountBadge; okContainer: HTMLElement; ok: Button; message: HTMLElement; customButtonContainer: HTMLElement; customButton: Button; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidCustom: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; keyDownSeenSinceShown: boolean; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; customButton?: boolean; }; class QuickInput extends Disposable implements IQuickInput { private _title: string | undefined; private _steps: number | undefined; private _totalSteps: number | undefined; protected visible = false; private _enabled = true; private _contextKey: string | undefined; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private readonly onDidHideEmitter = this._register(new Emitter<void>()); protected readonly visibleDisposables = this._register(new DisposableStore()); private busyDelay: TimeoutTimer | undefined; constructor( protected ui: QuickInputUI ) { super(); } get title() { return this._title; } set title(title: string | undefined) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number | undefined) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number | undefined) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string | undefined) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.add( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.keyDownSeenSinceShown = false; this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables.clear(); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = undefined; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } protected showMessageDecoration(severity: Severity) { this.ui.inputBox.showDecoration(severity); if (severity === Severity.Error) { const styles = this.ui.inputBox.stylesForType(severity); this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : ''; this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : ''; this.ui.message.style.paddingBottom = '4px'; } else { this.ui.message.style.backgroundColor = ''; this.ui.message.style.border = ''; this.ui.message.style.paddingBottom = ''; } } public dispose(): void { this.hide(); super.dispose(); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static readonly INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder: string | undefined; private readonly onDidChangeValueEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private readonly onDidChangeActiveEmitter = this._register(new Emitter<T[]>()); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private readonly onDidChangeSelectionEmitter = this._register(new Emitter<T[]>()); private readonly onDidTriggerItemButtonEmitter = this._register(new Emitter<IQuickPickItemButtonEvent<T>>()); private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _validationMessage: string | undefined; private _ok = false; private _customButton = false; private _customButtonLabel: string | undefined; private _customButtonHover: string | undefined; quickNavigate: IQuickNavigateConfiguration | undefined; get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; onDidCustom = this.onDidCustomEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } get customButton() { return this._customButton; } set customButton(showCustomButton: boolean) { this._customButton = showCustomButton; this.update(); } get customLabel() { return this._customButtonLabel; } set customLabel(label: string | undefined) { this._customButtonLabel = label; this.update(); } get customHover() { return this._customButtonHover; } set customHover(hover: string | undefined) { this._customButtonHover = hover; this.update(); } get ok() { return this._ok; } set ok(showOkButton: boolean) { this._ok = showOkButton; this.update(); } public inputHasFocus(): boolean { return this.visible ? this.ui.inputBox.hasFocus() : false; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); })); this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } })); this.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => { this.ui.keyDownSeenSinceShown = true; switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; } })); this.visibleDisposables.add(this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.onDidCustom(() => { this.onDidCustomEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } })); this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>))); this.visibleDisposables.add(this.registerQuickNavigation()); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true, message: !!this.validationMessage } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true, message: !!this.validationMessage, customButton: this.customButton, ok: this.ok }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } if (this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } else { this.ui.message.textContent = null; this.showMessageDecoration(Severity.Ignore); } this.ui.customButton.label = this.customLabel || ''; this.ui.customButton.element.title = this.customHover || ''; this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); } } class InputBox extends QuickInput implements IInputBox { private static readonly noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _placeholder: string | undefined; private _password = false; private _prompt: string | undefined; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string | undefined; private readonly onDidValueChangeEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string | undefined) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } readonly onDidChangeValue = this.onDidValueChangeEmitter.event; readonly onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); })); this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined))); this.valueSelectionUpdated = true; } super.show(); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.showMessageDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: undefined; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private ui: QuickInputUI | undefined; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: Map<string, IContextKey<boolean>> = new Map(); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts.get(id); if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts.set(id, key); } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { this.contexts.forEach(context => { if (context.get()) { context.reset(); } }); } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private getUI() { if (this.ui) { return this.ui; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; const titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); const extraContainer = dom.append(headerContainer, $('.quick-input-and-message')); const filterContainer = dom.append(extraContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count')); visibleCountContainer.setAttribute('aria-live', 'polite'); visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); const countContainer = dom.append(filterContainer, $('.quick-input-count')); countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); const okContainer = dom.append(headerContainer, $('.quick-input-action')); const ok = new Button(okContainer); attachButtonStyler(ok, this.themeService); ok.label = localize('ok', "OK"); this._register(ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const customButtonContainer = dom.append(headerContainer, $('.quick-input-action')); const customButton = new Button(customButtonContainer); attachButtonStyler(customButton, this.themeService); customButton.label = localize('custom', "Custom"); this._register(customButton.onDidClick(e => { this.onDidCustomEmitter.fire(); })); const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.getUI().ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => { inputBox.setFocus(); })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.getUI().keyDownSeenSinceShown = true; const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.codicon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.getUI().list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, titleBar, title, rightActionBar, checkAll, filterContainer, inputBox, visibleCountContainer, visibleCount, countContainer, count, okContainer, ok, message, customButtonContainer, customButton, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidCustom: this.onDidCustomEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, keyDownSeenSinceShown: false, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); return this.ui; } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { const ui = this.getUI(); return new QuickPick<T>(ui); } createInputBox(): IInputBox { const ui = this.getUI(); return new InputBox(ui); } private show(controller: QuickInput) { const ui = this.getUI(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); ui.leftActionBar.clear(); ui.title.textContent = ''; ui.rightActionBar.clear(); ui.checkAll.checked = false; // ui.inputBox.value = ''; Avoid triggering an event. ui.inputBox.placeholder = ''; ui.inputBox.password = false; ui.inputBox.showDecoration(Severity.Ignore); ui.visibleCount.setCount(0); ui.count.setCount(0); ui.message.textContent = ''; ui.progressBar.stop(); ui.list.setElements([]); ui.list.matchOnDescription = false; ui.list.matchOnDetail = false; ui.list.matchOnLabel = true; ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); ui.container.style.display = ''; this.updateLayout(); ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { const ui = this.getUI(); ui.title.style.display = visibilities.title ? '' : 'none'; ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; ui.countContainer.style.display = visibilities.count ? '' : 'none'; ui.okContainer.style.display = visibilities.ok ? '' : 'none'; ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none'; ui.message.style.display = visibilities.message ? '' : 'none'; ui.list.display(!!visibilities.list); ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { const ui = this.getUI(); this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { ui.inputBox.setAttribute('role', 'combobox'); ui.inputBox.setAttribute('aria-haspopup', 'true'); ui.inputBox.setAttribute('aria-autocomplete', 'list'); ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || ''); } else { ui.inputBox.removeAttribute('role'); ui.inputBox.removeAttribute('aria-haspopup'); ui.inputBox.removeAttribute('aria-autocomplete'); ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.getUI().leftActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } for (const item of this.getUI().rightActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } this.getUI().checkAll.disabled = !enabled; // this.getUI().inputBox.enabled = enabled; Avoid loosing focus. this.getUI().ok.enabled = enabled; this.getUI().list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.getUI().container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.getUI().inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.getUI().list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.getUI().list.isDisplayed()) { this.getUI().list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.ui.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : ''; this.ui.inputBox.style(theme); const quickInputBackground = theme.getColor(QUICK_INPUT_BACKGROUND); this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : ''; const quickInputForeground = theme.getColor(QUICK_INPUT_FOREGROUND); this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : ''; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : ''; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9955647587776184, 0.026515314355492592, 0.0001604724966455251, 0.0001703500165604055, 0.14563213288784027 ]
{ "id": 2, "code_window": [ "\t\tthis.inputElement.setAttribute('aria-haspopup', 'false');\n", "\t\tthis.inputElement.setAttribute('aria-autocomplete', 'list');\n", "\n", "\t\tthis._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, (e: Event) => this.onType()));\n", "\t\tthis._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tconst shouldOpenInBackground = this.shouldOpenInBackground(keyboardEvent);\n", "\n", "\t\t\t// Do not handle Tab: It is used to navigate between elements without mouse\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 225 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .accessibilityHelpWidget { padding: 10px; vertical-align: middle; overflow: auto; }
src/vs/workbench/contrib/codeEditor/browser/accessibility/accessibility.css
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017312762793153524, 0.00016890637925826013, 0.00016468514513690025, 0.00016890637925826013, 0.000004221241397317499 ]
{ "id": 2, "code_window": [ "\t\tthis.inputElement.setAttribute('aria-haspopup', 'false');\n", "\t\tthis.inputElement.setAttribute('aria-autocomplete', 'list');\n", "\n", "\t\tthis._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, (e: Event) => this.onType()));\n", "\t\tthis._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tconst shouldOpenInBackground = this.shouldOpenInBackground(keyboardEvent);\n", "\n", "\t\t\t// Do not handle Tab: It is used to navigate between elements without mouse\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 225 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ExtHostFileSystemEventService } from 'vs/workbench/api/common/extHostFileSystemEventService'; import { IMainContext } from 'vs/workbench/api/common/extHost.protocol'; suite('ExtHostFileSystemEventService', () => { test('FileSystemWatcher ignore events properties are reversed #26851', function () { const protocol: IMainContext = { getProxy: () => { return undefined!; }, set: undefined!, assertRegistered: undefined! }; const watcher1 = new ExtHostFileSystemEventService(protocol, undefined!).createFileSystemWatcher('**/somethingInteresting', false, false, false); assert.equal(watcher1.ignoreChangeEvents, false); assert.equal(watcher1.ignoreCreateEvents, false); assert.equal(watcher1.ignoreDeleteEvents, false); const watcher2 = new ExtHostFileSystemEventService(protocol, undefined!).createFileSystemWatcher('**/somethingBoring', true, true, true); assert.equal(watcher2.ignoreChangeEvents, true); assert.equal(watcher2.ignoreCreateEvents, true); assert.equal(watcher2.ignoreDeleteEvents, true); }); });
src/vs/workbench/test/electron-browser/api/extHostFileSystemEventService.test.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017544721777085215, 0.00017162786389235407, 0.00016640173271298409, 0.00017233125981874764, 0.0000032770669804449426 ]
{ "id": 2, "code_window": [ "\t\tthis.inputElement.setAttribute('aria-haspopup', 'false');\n", "\t\tthis.inputElement.setAttribute('aria-autocomplete', 'list');\n", "\n", "\t\tthis._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, (e: Event) => this.onType()));\n", "\t\tthis._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tconst shouldOpenInBackground = this.shouldOpenInBackground(keyboardEvent);\n", "\n", "\t\t\t// Do not handle Tab: It is used to navigate between elements without mouse\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 225 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .margin-view-overlays .line-numbers { position: absolute; text-align: right; display: inline-block; vertical-align: middle; box-sizing: border-box; cursor: default; height: 100%; } .monaco-editor .relative-current-line-number { text-align: left; display: inline-block; width: 100%; } .monaco-editor .margin-view-overlays .line-numbers { cursor: -webkit-image-set( url('flipped-cursor.svg') 1x, url('flipped-cursor-2x.svg') 2x ) 30 0, default; } .monaco-editor.mac .margin-view-overlays .line-numbers { cursor: -webkit-image-set( url('flipped-cursor-mac.svg') 1x, url('flipped-cursor-mac-2x.svg') 2x ) 24 3, default; } .monaco-editor .margin-view-overlays .line-numbers.lh-odd { margin-top: 1px; }
src/vs/editor/browser/viewParts/lineNumbers/lineNumbers.css
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0001729855575831607, 0.00017050876340363175, 0.00016729009803384542, 0.00017087970627471805, 0.000002047546786343446 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t}));\n", "\n", "\t\tthis._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, e => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\n", "\t\t\t// Only handle when in quick navigation mode\n", "\t\t\tif (!this.quickNavigateConfiguration) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 306 }
/*--------------------------------------------------------------------------------------------- * 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/quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { QUICK_INPUT_BACKGROUND, QUICK_INPUT_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerAndGetAmdImageURL } from 'vs/base/common/amd'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-dark.svg')), light: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-light.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; titleBar: HTMLElement; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; filterContainer: HTMLElement; inputBox: QuickInputBox; visibleCountContainer: HTMLElement; visibleCount: CountBadge; countContainer: HTMLElement; count: CountBadge; okContainer: HTMLElement; ok: Button; message: HTMLElement; customButtonContainer: HTMLElement; customButton: Button; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidCustom: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; keyDownSeenSinceShown: boolean; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; customButton?: boolean; }; class QuickInput extends Disposable implements IQuickInput { private _title: string | undefined; private _steps: number | undefined; private _totalSteps: number | undefined; protected visible = false; private _enabled = true; private _contextKey: string | undefined; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private readonly onDidHideEmitter = this._register(new Emitter<void>()); protected readonly visibleDisposables = this._register(new DisposableStore()); private busyDelay: TimeoutTimer | undefined; constructor( protected ui: QuickInputUI ) { super(); } get title() { return this._title; } set title(title: string | undefined) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number | undefined) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number | undefined) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string | undefined) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.add( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.keyDownSeenSinceShown = false; this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables.clear(); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = undefined; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } protected showMessageDecoration(severity: Severity) { this.ui.inputBox.showDecoration(severity); if (severity === Severity.Error) { const styles = this.ui.inputBox.stylesForType(severity); this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : ''; this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : ''; this.ui.message.style.paddingBottom = '4px'; } else { this.ui.message.style.backgroundColor = ''; this.ui.message.style.border = ''; this.ui.message.style.paddingBottom = ''; } } public dispose(): void { this.hide(); super.dispose(); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static readonly INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder: string | undefined; private readonly onDidChangeValueEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private readonly onDidChangeActiveEmitter = this._register(new Emitter<T[]>()); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private readonly onDidChangeSelectionEmitter = this._register(new Emitter<T[]>()); private readonly onDidTriggerItemButtonEmitter = this._register(new Emitter<IQuickPickItemButtonEvent<T>>()); private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _validationMessage: string | undefined; private _ok = false; private _customButton = false; private _customButtonLabel: string | undefined; private _customButtonHover: string | undefined; quickNavigate: IQuickNavigateConfiguration | undefined; get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; onDidCustom = this.onDidCustomEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } get customButton() { return this._customButton; } set customButton(showCustomButton: boolean) { this._customButton = showCustomButton; this.update(); } get customLabel() { return this._customButtonLabel; } set customLabel(label: string | undefined) { this._customButtonLabel = label; this.update(); } get customHover() { return this._customButtonHover; } set customHover(hover: string | undefined) { this._customButtonHover = hover; this.update(); } get ok() { return this._ok; } set ok(showOkButton: boolean) { this._ok = showOkButton; this.update(); } public inputHasFocus(): boolean { return this.visible ? this.ui.inputBox.hasFocus() : false; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); })); this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } })); this.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => { this.ui.keyDownSeenSinceShown = true; switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; } })); this.visibleDisposables.add(this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.onDidCustom(() => { this.onDidCustomEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } })); this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>))); this.visibleDisposables.add(this.registerQuickNavigation()); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true, message: !!this.validationMessage } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true, message: !!this.validationMessage, customButton: this.customButton, ok: this.ok }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } if (this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } else { this.ui.message.textContent = null; this.showMessageDecoration(Severity.Ignore); } this.ui.customButton.label = this.customLabel || ''; this.ui.customButton.element.title = this.customHover || ''; this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); } } class InputBox extends QuickInput implements IInputBox { private static readonly noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _placeholder: string | undefined; private _password = false; private _prompt: string | undefined; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string | undefined; private readonly onDidValueChangeEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string | undefined) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } readonly onDidChangeValue = this.onDidValueChangeEmitter.event; readonly onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); })); this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined))); this.valueSelectionUpdated = true; } super.show(); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.showMessageDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: undefined; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private ui: QuickInputUI | undefined; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: Map<string, IContextKey<boolean>> = new Map(); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts.get(id); if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts.set(id, key); } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { this.contexts.forEach(context => { if (context.get()) { context.reset(); } }); } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private getUI() { if (this.ui) { return this.ui; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; const titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); const extraContainer = dom.append(headerContainer, $('.quick-input-and-message')); const filterContainer = dom.append(extraContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count')); visibleCountContainer.setAttribute('aria-live', 'polite'); visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); const countContainer = dom.append(filterContainer, $('.quick-input-count')); countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); const okContainer = dom.append(headerContainer, $('.quick-input-action')); const ok = new Button(okContainer); attachButtonStyler(ok, this.themeService); ok.label = localize('ok', "OK"); this._register(ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const customButtonContainer = dom.append(headerContainer, $('.quick-input-action')); const customButton = new Button(customButtonContainer); attachButtonStyler(customButton, this.themeService); customButton.label = localize('custom', "Custom"); this._register(customButton.onDidClick(e => { this.onDidCustomEmitter.fire(); })); const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.getUI().ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => { inputBox.setFocus(); })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.getUI().keyDownSeenSinceShown = true; const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.codicon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.getUI().list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, titleBar, title, rightActionBar, checkAll, filterContainer, inputBox, visibleCountContainer, visibleCount, countContainer, count, okContainer, ok, message, customButtonContainer, customButton, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidCustom: this.onDidCustomEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, keyDownSeenSinceShown: false, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); return this.ui; } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { const ui = this.getUI(); return new QuickPick<T>(ui); } createInputBox(): IInputBox { const ui = this.getUI(); return new InputBox(ui); } private show(controller: QuickInput) { const ui = this.getUI(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); ui.leftActionBar.clear(); ui.title.textContent = ''; ui.rightActionBar.clear(); ui.checkAll.checked = false; // ui.inputBox.value = ''; Avoid triggering an event. ui.inputBox.placeholder = ''; ui.inputBox.password = false; ui.inputBox.showDecoration(Severity.Ignore); ui.visibleCount.setCount(0); ui.count.setCount(0); ui.message.textContent = ''; ui.progressBar.stop(); ui.list.setElements([]); ui.list.matchOnDescription = false; ui.list.matchOnDetail = false; ui.list.matchOnLabel = true; ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); ui.container.style.display = ''; this.updateLayout(); ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { const ui = this.getUI(); ui.title.style.display = visibilities.title ? '' : 'none'; ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; ui.countContainer.style.display = visibilities.count ? '' : 'none'; ui.okContainer.style.display = visibilities.ok ? '' : 'none'; ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none'; ui.message.style.display = visibilities.message ? '' : 'none'; ui.list.display(!!visibilities.list); ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { const ui = this.getUI(); this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { ui.inputBox.setAttribute('role', 'combobox'); ui.inputBox.setAttribute('aria-haspopup', 'true'); ui.inputBox.setAttribute('aria-autocomplete', 'list'); ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || ''); } else { ui.inputBox.removeAttribute('role'); ui.inputBox.removeAttribute('aria-haspopup'); ui.inputBox.removeAttribute('aria-autocomplete'); ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.getUI().leftActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } for (const item of this.getUI().rightActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } this.getUI().checkAll.disabled = !enabled; // this.getUI().inputBox.enabled = enabled; Avoid loosing focus. this.getUI().ok.enabled = enabled; this.getUI().list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.getUI().container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.getUI().inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.getUI().list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.getUI().list.isDisplayed()) { this.getUI().list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.ui.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : ''; this.ui.inputBox.style(theme); const quickInputBackground = theme.getColor(QUICK_INPUT_BACKGROUND); this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : ''; const quickInputForeground = theme.getColor(QUICK_INPUT_FOREGROUND); this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : ''; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : ''; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9988771080970764, 0.033302996307611465, 0.00016196486831177026, 0.000170025450643152, 0.17455719411373138 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t}));\n", "\n", "\t\tthis._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, e => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\n", "\t\t\t// Only handle when in quick navigation mode\n", "\t\t\tif (!this.quickNavigateConfiguration) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 306 }
<svg width="300" height="40" viewBox="0 0 300 40" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M4 26.8575L4.4855 26L9.4855 23H10.5145L15.5145 26L16 26.8575V32.8575L15.5145 33.715L10.5145 36.715H9.4855L4.4855 33.715L4 32.8575V26.8575ZM9.5 35.5575L5 32.8575V27.6998L9.5 30.1543V35.5575ZM10.5 35.5575L15 32.8575V27.6998L10.5 30.1543V35.5575ZM10 23.8575L5.25913 26.702L10 29.2879L14.7409 26.702L10 23.8575Z" fill="#B180D7"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M4 6.85749L4.4855 6L9.4855 3H10.5145L15.5145 6L16 6.85749V12.8575L15.5145 13.715L10.5145 16.715H9.4855L4.4855 13.715L4 12.8575V6.85749ZM9.5 15.5575L5 12.8575V7.69975L9.5 10.1543V15.5575ZM10.5 15.5575L15 12.8575V7.69975L10.5 10.1543V15.5575ZM10 3.85749L5.25913 6.70201L10 9.28794L14.7409 6.70201L10 3.85749Z" fill="#652D90"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M23 28.3944L23.5528 27.5L30.5528 24H31.4472L36.4472 26.5L37 27.3944V31.8944L36.4472 32.7889L29.4472 36.2889H28.5528L23.5528 33.7889L23 32.8944V28.3944ZM28.5 35.1444L24 32.8944V29.1709L28.5 31.2164V35.1444ZM29.5 35.1444L36 31.8944V28.1795L29.5 31.2129V35.1444ZM31 24.8944L24.3373 28.2258L28.9972 30.344L35.6706 27.2297L31 24.8944Z" fill="#75BEFF"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M23 8.39443L23.5528 7.5L30.5528 4H31.4472L36.4472 6.5L37 7.39443V11.8944L36.4472 12.7889L29.4472 16.2889H28.5528L23.5528 13.7889L23 12.8944V8.39443ZM28.5 15.1444L24 12.8944V9.17094L28.5 11.2164V15.1444ZM29.5 15.1444L36 11.8944V8.17954L29.5 11.2129V15.1444ZM31 4.89443L24.3373 8.22579L28.9972 10.344L35.6706 7.22973L31 4.89443Z" fill="#007ACC"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M45.3536 28.6464L44.0607 27.3535L47.3536 24.0607L48.6465 25.3535L45.3536 28.6464ZM47 23L43 27V27.7071L45 29.7071H45.7071L46.8536 28.5606V34.3535L47.3536 34.8535H52.0097V35.3741L53.343 36.7074H54.0501L56.7168 34.0407V33.3336L55.3835 32.0003H54.6763L52.8231 33.8535H47.8536V29.8935H52.0097V30.374L53.343 31.7073H54.0501L56.7168 29.0407V28.3336L55.3835 27.0002H54.6763L52.863 28.8136H47.8536V27.5606L49.7071 25.7071V25L47.7071 23H47ZM53.0703 30.0205L53.6966 30.6467L55.6561 28.6871L55.0299 28.0609L53.0703 30.0205ZM53.0703 35.0205L53.6966 35.6467L55.6561 33.6872L55.0299 33.061L53.0703 35.0205Z" fill="#EE9D28"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M45.3536 8.64642L44.0607 7.35353L47.3536 4.06065L48.6465 5.35354L45.3536 8.64642ZM47 3L43 6.99998V7.70708L45 9.70707H45.7071L46.8536 8.56063V14.3535L47.3536 14.8535H52.0097V15.3741L53.343 16.7074H54.0501L56.7168 14.0407V13.3336L55.3835 12.0003H54.6763L52.8231 13.8535H47.8536V9.89355H52.0097V10.374L53.343 11.7073H54.0501L56.7168 9.04068V8.33357L55.3835 7.00024H54.6763L52.863 8.81356H47.8536V7.56064L49.7071 5.70709V4.99999L47.7071 3H47ZM53.0703 10.0205L53.6966 10.6467L55.6561 8.68713L55.0299 8.0609L53.0703 10.0205ZM53.0703 15.0205L53.6966 15.6467L55.6561 13.6872L55.0299 13.061L53.0703 15.0205Z" fill="#D67E00"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M88 24.9836V24.9718V24H87.9108C87.5974 24 87.2941 24.0616 87.0013 24.1847C86.7082 24.308 86.4494 24.4847 86.2258 24.715C86.0031 24.9442 85.8379 25.195 85.7328 25.4677L85.7323 25.469C85.6338 25.7352 85.5681 26.012 85.5353 26.2992L85.5352 26.3005C85.5068 26.5805 85.4987 26.8684 85.5108 27.1643C85.5227 27.4538 85.5287 27.7433 85.5287 28.0328C85.5287 28.2356 85.4897 28.4259 85.412 28.6051L85.4116 28.606C85.3369 28.783 85.2342 28.9387 85.1032 29.0736C84.9764 29.2041 84.8247 29.3106 84.6467 29.3925C84.4706 29.4695 84.285 29.5082 84.0892 29.5082H84V29.6V30.4V30.4918H84.0892C84.2847 30.4918 84.47 30.5324 84.646 30.6133L84.6474 30.614C84.8246 30.6916 84.9758 30.7976 85.1022 30.9316L85.1041 30.9335C85.2343 31.0637 85.3366 31.2187 85.4113 31.3994L85.412 31.4011C85.4899 31.5805 85.5287 31.7688 85.5287 31.9672C85.5287 32.2567 85.5227 32.5462 85.5108 32.8357C85.4987 33.1316 85.5068 33.4215 85.5352 33.7055L85.5354 33.7072C85.5682 33.9903 85.6339 34.265 85.7323 34.531L85.7328 34.5323C85.8379 34.805 86.0031 35.0558 86.2258 35.285C86.4494 35.5153 86.7082 35.692 87.0013 35.8153C87.2941 35.9384 87.5974 36 87.9108 36H88V35.2V35.0164H87.9108C87.7109 35.0164 87.5235 34.9777 87.3476 34.9008C87.174 34.8191 87.0219 34.7126 86.8909 34.5818C86.7639 34.4469 86.661 34.2911 86.5822 34.1137C86.5084 33.9346 86.4713 33.744 86.4713 33.541C86.4713 33.3127 86.4753 33.0885 86.4832 32.8686C86.4912 32.6411 86.4913 32.4195 86.4832 32.2039C86.4791 31.9825 86.4608 31.7688 86.4282 31.5631C86.3951 31.3502 86.3392 31.1476 86.2604 30.9554C86.1809 30.7616 86.0726 30.5775 85.9362 30.403C85.8235 30.2588 85.6854 30.1246 85.5228 30C85.6854 29.8754 85.8235 29.7412 85.9362 29.597C86.0726 29.4225 86.1809 29.2384 86.2604 29.0446C86.3391 28.8526 86.3951 28.6517 86.4283 28.4428C86.4608 28.2333 86.4791 28.0197 86.4832 27.8022C86.4913 27.5826 86.4913 27.3611 86.4832 27.1375C86.4753 26.9134 86.4713 26.6872 86.4713 26.459C86.4713 26.2602 86.5083 26.0715 86.5824 25.8921C86.6614 25.7103 86.7642 25.5548 86.8909 25.4244C87.0219 25.2894 87.1746 25.1827 87.348 25.1051C87.5238 25.0243 87.7111 24.9836 87.9108 24.9836H88ZM92 35.0164V35.0282V36H92.0892C92.4026 36 92.7059 35.9384 92.9987 35.8153C93.2918 35.692 93.5506 35.5153 93.7742 35.285C93.9969 35.0558 94.1621 34.805 94.2672 34.5323L94.2677 34.531C94.3662 34.2648 94.4319 33.988 94.4647 33.7008L94.4648 33.6995C94.4932 33.4195 94.5013 33.1316 94.4892 32.8357C94.4773 32.5462 94.4713 32.2567 94.4713 31.9672C94.4713 31.7644 94.5103 31.5741 94.588 31.3949L94.5884 31.394C94.6631 31.217 94.7658 31.0613 94.8968 30.9264C95.0236 30.7959 95.1753 30.6894 95.3533 30.6075C95.5294 30.5305 95.715 30.4918 95.9108 30.4918H96V30.4V29.6V29.5082H95.9108C95.7153 29.5082 95.53 29.4676 95.354 29.3867L95.3526 29.386C95.1754 29.3084 95.0242 29.2024 94.8978 29.0684L94.8959 29.0665C94.7657 28.9363 94.6634 28.7813 94.5887 28.6006L94.588 28.5989C94.5101 28.4195 94.4713 28.2312 94.4713 28.0328C94.4713 27.7433 94.4773 27.4538 94.4892 27.1643C94.5013 26.8684 94.4932 26.5785 94.4648 26.2945L94.4646 26.2928C94.4318 26.0097 94.3661 25.735 94.2677 25.469L94.2672 25.4677C94.1621 25.195 93.9969 24.9442 93.7742 24.715C93.5506 24.4847 93.2918 24.308 92.9987 24.1847C92.7059 24.0616 92.4026 24 92.0892 24H92V24.8V24.9836H92.0892C92.2891 24.9836 92.4765 25.0223 92.6524 25.0992C92.826 25.1809 92.9781 25.2874 93.1091 25.4182C93.2361 25.5531 93.339 25.7089 93.4178 25.8863C93.4916 26.0654 93.5287 26.256 93.5287 26.459C93.5287 26.6873 93.5247 26.9115 93.5168 27.1314C93.5088 27.3589 93.5087 27.5805 93.5168 27.7961C93.5209 28.0175 93.5392 28.2312 93.5718 28.4369C93.6049 28.6498 93.6608 28.8524 93.7396 29.0446C93.8191 29.2384 93.9274 29.4225 94.0638 29.597C94.1765 29.7412 94.3146 29.8754 94.4772 30C94.3146 30.1246 94.1765 30.2588 94.0638 30.403C93.9274 30.5775 93.8191 30.7616 93.7396 30.9554C93.6609 31.1474 93.6049 31.3483 93.5717 31.5572C93.5392 31.7667 93.5209 31.9803 93.5168 32.1978C93.5087 32.4174 93.5087 32.6389 93.5168 32.8625C93.5247 33.0866 93.5287 33.3128 93.5287 33.541C93.5287 33.7398 93.4917 33.9285 93.4176 34.1079C93.3386 34.2897 93.2358 34.4452 93.1091 34.5756C92.9781 34.7106 92.8254 34.8173 92.652 34.8949C92.4762 34.9757 92.2889 35.0164 92.0892 35.0164H92Z" fill="#C5C5C5"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M88 4.98361V4.97184V4H87.9108C87.5974 4 87.2941 4.06161 87.0013 4.18473C86.7082 4.30798 86.4494 4.48474 86.2258 4.71498C86.0031 4.94422 85.8379 5.19498 85.7328 5.46766L85.7323 5.46898C85.6338 5.7352 85.5681 6.01201 85.5353 6.29917L85.5352 6.30053C85.5068 6.5805 85.4987 6.86844 85.5108 7.16428C85.5227 7.45379 85.5287 7.74329 85.5287 8.03279C85.5287 8.23556 85.4897 8.42594 85.412 8.60507L85.4116 8.60601C85.3369 8.78296 85.2342 8.93866 85.1032 9.07359C84.9764 9.20405 84.8247 9.31055 84.6467 9.3925C84.4706 9.46954 84.285 9.5082 84.0892 9.5082H84V9.6V10.4V10.4918H84.0892C84.2847 10.4918 84.47 10.5324 84.646 10.6133L84.6474 10.614C84.8246 10.6916 84.9758 10.7976 85.1022 10.9316L85.1041 10.9335C85.2343 11.0637 85.3366 11.2187 85.4113 11.3994L85.412 11.4011C85.4899 11.5805 85.5287 11.7688 85.5287 11.9672C85.5287 12.2567 85.5227 12.5462 85.5108 12.8357C85.4987 13.1316 85.5068 13.4215 85.5352 13.7055L85.5354 13.7072C85.5682 13.9903 85.6339 14.265 85.7323 14.531L85.7328 14.5323C85.8379 14.805 86.0031 15.0558 86.2258 15.285C86.4494 15.5153 86.7082 15.692 87.0013 15.8153C87.2941 15.9384 87.5974 16 87.9108 16H88V15.2V15.0164H87.9108C87.7109 15.0164 87.5235 14.9777 87.3476 14.9008C87.174 14.8191 87.0219 14.7126 86.8909 14.5818C86.7639 14.4469 86.661 14.2911 86.5822 14.1137C86.5084 13.9346 86.4713 13.744 86.4713 13.541C86.4713 13.3127 86.4753 13.0885 86.4832 12.8686C86.4912 12.6411 86.4913 12.4195 86.4832 12.2039C86.4791 11.9825 86.4608 11.7688 86.4282 11.5631C86.3951 11.3502 86.3392 11.1476 86.2604 10.9554C86.1809 10.7616 86.0726 10.5775 85.9362 10.403C85.8235 10.2588 85.6854 10.1246 85.5228 10C85.6854 9.87538 85.8235 9.74119 85.9362 9.59702C86.0726 9.42254 86.1809 9.23843 86.2604 9.04464C86.3391 8.85263 86.3951 8.65175 86.4283 8.44285C86.4608 8.2333 86.4791 8.01973 86.4832 7.80219C86.4913 7.58262 86.4913 7.36105 86.4832 7.13749C86.4753 6.9134 86.4713 6.68725 86.4713 6.45902C86.4713 6.26019 86.5083 6.07152 86.5824 5.89205C86.6614 5.71034 86.7642 5.55475 86.8909 5.42437C87.0219 5.28942 87.1746 5.18275 87.348 5.10513C87.5238 5.02427 87.7111 4.98361 87.9108 4.98361H88ZM92 15.0164V15.0282V16H92.0892C92.4026 16 92.7059 15.9384 92.9987 15.8153C93.2918 15.692 93.5506 15.5153 93.7742 15.285C93.9969 15.0558 94.1621 14.805 94.2672 14.5323L94.2677 14.531C94.3662 14.2648 94.4319 13.988 94.4647 13.7008L94.4648 13.6995C94.4932 13.4195 94.5013 13.1316 94.4892 12.8357C94.4773 12.5462 94.4713 12.2567 94.4713 11.9672C94.4713 11.7644 94.5103 11.5741 94.588 11.3949L94.5884 11.394C94.6631 11.217 94.7658 11.0613 94.8968 10.9264C95.0236 10.7959 95.1753 10.6894 95.3533 10.6075C95.5294 10.5305 95.715 10.4918 95.9108 10.4918H96V10.4V9.6V9.5082H95.9108C95.7153 9.5082 95.53 9.46762 95.354 9.38666L95.3526 9.38604C95.1754 9.30844 95.0242 9.20238 94.8978 9.06839L94.8959 9.06648C94.7657 8.9363 94.6634 8.78129 94.5887 8.60058L94.588 8.59892C94.5101 8.41953 94.4713 8.23117 94.4713 8.03279C94.4713 7.74329 94.4773 7.45379 94.4892 7.16428C94.5013 6.86842 94.4932 6.57848 94.4648 6.29454L94.4646 6.29285C94.4318 6.00971 94.3661 5.73502 94.2677 5.46897L94.2672 5.46766C94.1621 5.19499 93.9969 4.94422 93.7742 4.71498C93.5506 4.48474 93.2918 4.30798 92.9987 4.18473C92.7059 4.06161 92.4026 4 92.0892 4H92V4.8V4.98361H92.0892C92.2891 4.98361 92.4765 5.0223 92.6524 5.09917C92.826 5.18092 92.9781 5.28736 93.1091 5.41823C93.2361 5.55305 93.339 5.70889 93.4178 5.88628C93.4916 6.0654 93.5287 6.25596 93.5287 6.45902C93.5287 6.68727 93.5247 6.91145 93.5168 7.13142C93.5088 7.35894 93.5087 7.58049 93.5168 7.79605C93.5209 8.01754 93.5392 8.23117 93.5718 8.43688C93.6049 8.64976 93.6608 8.85243 93.7396 9.04464C93.8191 9.23843 93.9274 9.42254 94.0638 9.59702C94.1765 9.74119 94.3146 9.87538 94.4772 10C94.3146 10.1246 94.1765 10.2588 94.0638 10.403C93.9274 10.5775 93.8191 10.7616 93.7396 10.9554C93.6609 11.1474 93.6049 11.3483 93.5717 11.5572C93.5392 11.7667 93.5209 11.9803 93.5168 12.1978C93.5087 12.4174 93.5087 12.6389 93.5168 12.8625C93.5247 13.0866 93.5287 13.3128 93.5287 13.541C93.5287 13.7398 93.4917 13.9285 93.4176 14.1079C93.3386 14.2897 93.2358 14.4452 93.1091 14.5756C92.9781 14.7106 92.8254 14.8173 92.652 14.8949C92.4762 14.9757 92.2889 15.0164 92.0892 15.0164H92Z" fill="#424242"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M73.5 27C72.1193 27 71 28.1193 71 29.5C71 30.8807 72.1193 32 73.5 32C74.8807 32 76 30.8807 76 29.5C76 28.1193 74.8807 27 73.5 27ZM70.0354 30C70.2781 31.6961 71.7368 33 73.5 33C75.433 33 77 31.433 77 29.5C77 27.567 75.433 26 73.5 26C71.7368 26 70.2781 27.3039 70.0354 29H66.937C66.715 28.1374 65.9319 27.5 65 27.5C63.8954 27.5 63 28.3954 63 29.5C63 30.6046 63.8954 31.5 65 31.5C65.9319 31.5 66.715 30.8626 66.937 30H70.0354Z" fill="#75BEFF"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M73.5 7C72.1193 7 71 8.11929 71 9.5C71 10.8807 72.1193 12 73.5 12C74.8807 12 76 10.8807 76 9.5C76 8.11929 74.8807 7 73.5 7ZM70.0354 10C70.2781 11.6961 71.7368 13 73.5 13C75.433 13 77 11.433 77 9.5C77 7.567 75.433 6 73.5 6C71.7368 6 70.2781 7.30385 70.0354 9H66.937C66.715 8.13739 65.9319 7.5 65 7.5C63.8954 7.5 63 8.39543 63 9.5C63 10.6046 63.8954 11.5 65 11.5C65.9319 11.5 66.715 10.8626 66.937 10H70.0354Z" fill="#007ACC"/> <path d="M104.807 36.9754C104.571 36.9721 104.338 36.9211 104.122 36.8254C103.907 36.7297 103.712 36.5913 103.552 36.4186C103.239 36.1334 103.044 35.7408 103.008 35.3189C102.966 34.8828 103.093 34.4473 103.361 34.1013C104.568 32.8289 106.947 30.4494 108.678 28.7548C108.31 27.7589 108.327 26.6613 108.726 25.6774C109.055 24.8588 109.639 24.1681 110.391 23.7081C110.982 23.3171 111.66 23.0794 112.366 23.0167C113.071 22.954 113.781 23.0682 114.431 23.3489L115.048 23.6162L112.182 26.5674L113.437 27.8258L116.381 24.9489L116.648 25.5679C116.874 26.0898 116.993 26.6512 117 27.2196C117.006 27.788 116.9 28.3521 116.687 28.8791C116.476 29.4003 116.162 29.8737 115.765 30.2712C115.539 30.4917 115.29 30.6865 115.022 30.8522C114.467 31.2228 113.832 31.4564 113.17 31.5338C112.507 31.6112 111.835 31.5303 111.21 31.2976C110.112 32.4113 107.371 35.1704 105.891 36.5522C105.594 36.8219 105.208 36.9726 104.807 36.9754ZM112.745 23.928C112.087 23.9264 111.444 24.1202 110.896 24.4848C110.683 24.6152 110.484 24.769 110.305 24.9433C109.828 25.4242 109.509 26.0395 109.392 26.7067C109.274 27.3739 109.364 28.061 109.648 28.6759L109.783 28.9729L109.55 29.2003C107.812 30.8967 105.281 33.4201 104.065 34.7045C103.956 34.8658 103.91 35.0608 103.934 35.2535C103.959 35.4463 104.052 35.6238 104.197 35.7532C104.28 35.8462 104.382 35.9211 104.495 35.9731C104.596 36.0184 104.704 36.043 104.814 36.0455C104.981 36.0413 105.14 35.977 105.264 35.8646C106.837 34.3964 109.876 31.3264 110.768 30.4243L110.997 30.1933L111.292 30.3278C111.806 30.5673 112.373 30.6698 112.938 30.6255C113.503 30.5811 114.047 30.3913 114.517 30.0745C114.731 29.9426 114.93 29.7869 115.109 29.6105C115.418 29.3015 115.663 28.9337 115.829 28.5287C115.994 28.1237 116.077 27.6897 116.072 27.2523C116.072 27.0366 116.05 26.8215 116.008 26.6101L113.431 29.1251L110.879 26.5776L113.394 23.9883C113.18 23.9467 112.963 23.9265 112.745 23.928Z" fill="#C5C5C5"/> <path d="M104.807 16.9754C104.571 16.9721 104.338 16.9211 104.122 16.8254C103.907 16.7297 103.712 16.5913 103.552 16.4186C103.239 16.1334 103.044 15.7408 103.008 15.3189C102.966 14.8828 103.093 14.4473 103.361 14.1013C104.568 12.8289 106.947 10.4494 108.678 8.75479C108.31 7.75887 108.327 6.66127 108.726 5.67739C109.055 4.85876 109.639 4.16805 110.391 3.70807C110.982 3.31706 111.66 3.07944 112.366 3.01673C113.071 2.95402 113.781 3.06819 114.431 3.34892L115.048 3.6162L112.182 6.56738L113.437 7.82582L116.381 4.94887L116.648 5.56788C116.874 6.08976 116.993 6.65119 117 7.21961C117.006 7.78802 116.9 8.35211 116.687 8.87915C116.476 9.40029 116.162 9.87368 115.765 10.2712C115.539 10.4917 115.29 10.6865 115.022 10.8522C114.467 11.2228 113.832 11.4564 113.17 11.5338C112.507 11.6112 111.835 11.5303 111.21 11.2976C110.112 12.4113 107.371 15.1704 105.891 16.5522C105.594 16.8219 105.208 16.9726 104.807 16.9754ZM112.745 3.92802C112.087 3.92637 111.444 4.12018 110.896 4.48485C110.683 4.6152 110.484 4.76897 110.305 4.9433C109.828 5.42423 109.509 6.03953 109.392 6.70669C109.274 7.37385 109.364 8.06098 109.648 8.67591L109.783 8.97288L109.55 9.20025C107.812 10.8967 105.281 13.4201 104.065 14.7045C103.956 14.8658 103.91 15.0608 103.934 15.2535C103.959 15.4463 104.052 15.6238 104.197 15.7532C104.28 15.8462 104.382 15.9211 104.495 15.9731C104.596 16.0184 104.704 16.043 104.814 16.0455C104.981 16.0413 105.14 15.977 105.264 15.8646C106.837 14.3964 109.876 11.3264 110.768 10.4243L110.997 10.1933L111.292 10.3278C111.806 10.5673 112.373 10.6698 112.938 10.6255C113.503 10.5811 114.047 10.3913 114.517 10.0745C114.731 9.9426 114.93 9.78694 115.109 9.61045C115.418 9.30153 115.663 8.93374 115.829 8.52874C115.994 8.12375 116.077 7.68974 116.072 7.25228C116.072 7.03662 116.05 6.82148 116.008 6.61007L113.431 9.12508L110.879 6.57759L113.394 3.98834C113.18 3.94674 112.963 3.92653 112.745 3.92802Z" fill="#424242"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M149 25L150 24H156L157 25V30L156 31H152V30H156V25H150V28H149V25ZM150 29L151 30V31V35L150 36H144L143 35V30L144 29H149H150ZM150 30V31V35H144V30H149H150ZM151.414 29L151 28.5858V28H155V29H151.414ZM151 26H155V27H151V26ZM149 32H145V33H149V32Z" fill="#75BEFF"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M149 5L150 4H156L157 5V10L156 11H152V10H156V5H150V8H149V5ZM150 9L151 10V11V15L150 16H144L143 15V10L144 9H149H150ZM150 10V11V15H144V10H149H150ZM151.414 9L151 8.58579V8H155V9H151.414ZM151 6H155V7H151V6ZM149 12H145V13H149V12Z" fill="#007ACC"/> <path d="M177 6H172V5H177V6ZM176 9H174V10H176V9ZM172 9H163V10H172V9ZM174 15H163V16H174V15ZM169 12H163V13H169V12ZM177 12H172V13H177V12ZM170 4V7H163V4H170ZM169 5H164V6H169V5Z" fill="#C5C5C5"/> <path d="M177 26H172V25H177V26ZM176 29H174V30H176V29ZM172 29H163V30H172V29ZM174 35H163V36H174V35ZM169 32H163V33H169V32ZM177 32H172V33H177V32ZM170 24V27H163V24H170ZM169 25H164V26H169V25Z" fill="#424242"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M209.223 32.933C209.549 33.1254 209.922 33.2231 210.3 33.215C210.638 33.2218 210.973 33.1492 211.277 33.003C211.582 32.8567 211.848 32.6409 212.054 32.373C212.509 31.7652 212.74 31.0187 212.708 30.26C212.741 29.5862 212.537 28.9221 212.132 28.383C211.936 28.1416 211.686 27.9496 211.402 27.8223C211.118 27.695 210.809 27.636 210.498 27.65C210.075 27.647 209.66 27.7608 209.298 27.979C209.183 28.0481 209.075 28.1278 208.975 28.217V25.475H207.984V33.1H208.979V32.756C209.055 32.8217 209.137 32.8809 209.223 32.933ZM209.85 28.7001C210.036 28.621 210.238 28.5868 210.44 28.6C210.613 28.5945 210.784 28.6305 210.94 28.705C211.096 28.7795 211.232 28.8902 211.336 29.028C211.593 29.3905 211.718 29.8295 211.693 30.273C211.72 30.7975 211.58 31.317 211.293 31.757C211.188 31.9153 211.045 32.0447 210.878 32.1335C210.71 32.2223 210.523 32.2675 210.333 32.265C210.149 32.2732 209.966 32.24 209.797 32.1678C209.628 32.0956 209.478 31.9863 209.357 31.848C209.102 31.5596 208.965 31.1851 208.975 30.8V30.2C208.963 29.7833 209.103 29.3765 209.368 29.055C209.499 28.9006 209.664 28.7791 209.85 28.7001ZM205.289 27.675C204.97 27.6793 204.654 27.734 204.352 27.837C204.064 27.9229 203.793 28.0583 203.552 28.237L203.452 28.314V29.514L203.875 29.155C204.246 28.8048 204.731 28.6015 205.241 28.583C205.366 28.5716 205.492 28.5915 205.607 28.6407C205.722 28.6899 205.824 28.767 205.902 28.865C206.052 29.0971 206.132 29.3675 206.133 29.644L204.9 29.825C204.394 29.8778 203.915 30.0777 203.522 30.4C203.367 30.5518 203.243 30.7327 203.158 30.9324C203.073 31.132 203.028 31.3464 203.026 31.5634C203.024 31.7804 203.065 31.9957 203.146 32.1969C203.228 32.3981 203.348 32.5813 203.5 32.736C203.669 32.8904 203.866 33.01 204.081 33.0879C204.296 33.1659 204.525 33.2005 204.753 33.19C205.147 33.1931 205.533 33.0774 205.86 32.858C205.962 32.7897 206.057 32.7131 206.146 32.629V33.073H207.087V29.715C207.121 29.1742 206.954 28.6399 206.618 28.215C206.45 28.0329 206.243 27.89 206.014 27.7967C205.784 27.7034 205.537 27.6618 205.289 27.675ZM206.146 30.716C206.166 31.1343 206.026 31.5446 205.755 31.864C205.637 32.0005 205.49 32.1092 205.325 32.1821C205.16 32.2551 204.98 32.2906 204.8 32.286C204.69 32.2945 204.58 32.2812 204.476 32.2469C204.372 32.2125 204.275 32.1579 204.192 32.086C204.061 31.9346 203.989 31.7409 203.989 31.5405C203.989 31.3401 204.061 31.1464 204.192 30.995C204.473 30.8213 204.792 30.7184 205.122 30.695L206.142 30.547L206.146 30.716ZM214.459 33.0325C214.766 33.1638 215.098 33.2261 215.432 33.215C215.927 33.227 216.415 33.1006 216.842 32.85L216.965 32.775L216.978 32.768V31.615L216.532 31.935C216.216 32.1592 215.836 32.2747 215.448 32.264C215.25 32.2719 215.052 32.2342 214.87 32.1538C214.689 32.0733 214.528 31.9523 214.4 31.8C214.114 31.4245 213.973 30.9591 214 30.488C213.974 29.9873 214.135 29.4948 214.453 29.107C214.593 28.9411 214.77 28.8091 214.968 28.7213C215.167 28.6335 215.383 28.592 215.6 28.6C215.944 28.5984 216.281 28.6953 216.571 28.879L217 29.144V27.97L216.831 27.897C216.463 27.7343 216.064 27.6502 215.661 27.65C215.3 27.6399 214.941 27.7076 214.608 27.8486C214.275 27.9896 213.976 28.2005 213.732 28.467C213.226 29.0268 212.958 29.7619 212.985 30.516C212.957 31.2235 213.196 31.9157 213.654 32.455C213.877 32.704 214.152 32.9012 214.459 33.0325Z" fill="#C5C5C5"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M209.223 12.933C209.549 13.1254 209.922 13.2231 210.3 13.215C210.638 13.2218 210.973 13.1492 211.277 13.003C211.582 12.8567 211.848 12.6409 212.054 12.373C212.509 11.7652 212.74 11.0187 212.708 10.26C212.741 9.58622 212.537 8.9221 212.132 8.38298C211.936 8.14161 211.686 7.94957 211.402 7.82228C211.118 7.69498 210.809 7.63597 210.498 7.64997C210.075 7.64699 209.66 7.76085 209.298 7.97898C209.183 8.04807 209.075 8.12775 208.975 8.21698V5.47498H207.984V13.1H208.979V12.756C209.055 12.8217 209.137 12.8809 209.223 12.933ZM209.85 8.70006C210.036 8.62105 210.238 8.58677 210.44 8.59998C210.613 8.59452 210.784 8.63054 210.94 8.70501C211.096 8.77948 211.232 8.89023 211.336 9.02798C211.593 9.39053 211.718 9.82951 211.693 10.273C211.72 10.7975 211.58 11.317 211.293 11.757C211.188 11.9153 211.045 12.0447 210.878 12.1335C210.71 12.2223 210.523 12.2675 210.333 12.265C210.149 12.2732 209.966 12.24 209.797 12.1678C209.628 12.0956 209.478 11.9863 209.357 11.848C209.102 11.5596 208.965 11.1851 208.975 10.8V10.2C208.963 9.78332 209.103 9.3765 209.368 9.05498C209.499 8.90064 209.664 8.77908 209.85 8.70006ZM205.289 7.67499C204.97 7.67933 204.654 7.734 204.352 7.83699C204.064 7.92293 203.793 8.05828 203.552 8.23699L203.452 8.31399V9.51399L203.875 9.15499C204.246 8.80478 204.731 8.60146 205.241 8.58299C205.366 8.57164 205.492 8.59147 205.607 8.64068C205.722 8.6899 205.824 8.76697 205.902 8.86499C206.052 9.0971 206.132 9.36754 206.133 9.64399L204.9 9.82499C204.394 9.87781 203.915 10.0777 203.522 10.4C203.367 10.5518 203.243 10.7327 203.158 10.9324C203.073 11.132 203.028 11.3464 203.026 11.5634C203.024 11.7804 203.065 11.9957 203.146 12.1969C203.228 12.3981 203.348 12.5813 203.5 12.736C203.669 12.8904 203.866 13.01 204.081 13.0879C204.296 13.1659 204.525 13.2005 204.753 13.19C205.147 13.1931 205.533 13.0774 205.86 12.858C205.962 12.7897 206.057 12.7131 206.146 12.629V13.073H207.087V9.71499C207.121 9.17422 206.954 8.63988 206.618 8.21499C206.45 8.03285 206.243 7.89003 206.014 7.7967C205.784 7.70336 205.537 7.66181 205.289 7.67499ZM206.146 10.716C206.166 11.1343 206.026 11.5446 205.755 11.864C205.637 12.0005 205.49 12.1092 205.325 12.1821C205.16 12.2551 204.98 12.2906 204.8 12.286C204.69 12.2945 204.58 12.2812 204.476 12.2469C204.372 12.2125 204.275 12.1579 204.192 12.086C204.061 11.9346 203.989 11.7409 203.989 11.5405C203.989 11.3401 204.061 11.1464 204.192 10.995C204.473 10.8213 204.792 10.7184 205.122 10.695L206.142 10.547L206.146 10.716ZM214.459 13.0325C214.766 13.1638 215.098 13.2261 215.432 13.215C215.927 13.227 216.415 13.1006 216.842 12.85L216.965 12.775L216.978 12.768V11.615L216.532 11.935C216.216 12.1592 215.836 12.2747 215.448 12.264C215.25 12.2719 215.052 12.2342 214.87 12.1538C214.689 12.0733 214.528 11.9523 214.4 11.8C214.114 11.4245 213.973 10.9591 214 10.488C213.974 9.98732 214.135 9.49475 214.453 9.10704C214.593 8.94105 214.77 8.80914 214.968 8.7213C215.167 8.63346 215.383 8.592 215.6 8.60004C215.944 8.59844 216.281 8.69525 216.571 8.87904L217 9.14404V7.97004L216.831 7.89704C216.463 7.73432 216.064 7.6502 215.661 7.65004C215.3 7.63991 214.941 7.70762 214.608 7.84859C214.275 7.98956 213.976 8.20048 213.732 8.46704C213.226 9.02683 212.958 9.76186 212.985 10.516C212.957 11.2235 213.196 11.9157 213.654 12.455C213.877 12.704 214.152 12.9012 214.459 13.0325Z" fill="#424242"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M266 3L265 4V16L266 17H275L276 16V7L275.707 6.29289L272.707 3.29289L272 3H266ZM266 16V4L271 4V8H275V16H266ZM275 7L272 4V7L275 7Z" fill="#424242"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M266 23L265 24V36L266 37H275L276 36V27L275.707 26.2929L272.707 23.2929L272 23H266ZM266 36V24L271 24V28H275V36H266ZM275 27L272 24V27L275 27Z" fill="#C5C5C5"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M130 24L129 25V28H130V25H136V30H132V31H136L137 30V25L136 24H130ZM131 30L130 29H129H124L123 30V35L124 36H130L131 35V31V30ZM130 31V30H129H124V35H130V31ZM131 28.5858L131.414 29H135V28H131V28.5858ZM135 26H131V27H135V26ZM129 31H125V32H129V31ZM125 33H129V34H125V33Z" fill="#EE9D28"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M130 4L129 5V8H130V5H136V10H132V11H136L137 10V5L136 4H130ZM131 10L130 9H129H124L123 10V15L124 16H130L131 15V11V10ZM130 11V10H129H124V15H130V11ZM131 8.58579L131.414 9H135V8H131V8.58579ZM135 6H131V7H135V6ZM129 11H125V12H129V11ZM125 13H129V14H125V13Z" fill="#D67E00"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M246 3L245 4V16L246 17H254L255 16V4L254 3H246ZM246 5V4H254V16H246V15H248V14H246V12H250V11H246V9H248V8H246V6H250V5H246Z" fill="#424242"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M246 23L245 24V36L246 37H254L255 36V24L254 23H246ZM246 25V24H254V36H246V35H248V34H246V32H250V31H246V29H248V28H246V26H250V25H246Z" fill="#C5C5C5"/> </svg>
src/vs/editor/standalone/browser/quickOpen/symbol-sprite.svg
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0014096341328695416, 0.0008682275074534118, 0.0004255325475241989, 0.0007695158128626645, 0.000407776067731902 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t}));\n", "\n", "\t\tthis._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, e => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\n", "\t\t\t// Only handle when in quick navigation mode\n", "\t\t\tif (!this.quickNavigateConfiguration) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 306 }
{ "extends": "../shared.tsconfig.json", "compilerOptions": { "outDir": "./out" }, "include": [ "src/**/*" ] }
extensions/vscode-api-tests/tsconfig.json
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0001737055426929146, 0.0001737055426929146, 0.0001737055426929146, 0.0001737055426929146, 0 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t}));\n", "\n", "\t\tthis._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, e => {\n", "\t\t\tthis.keyDownSeenSinceShown = true;\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\n", "\t\t\t// Only handle when in quick navigation mode\n", "\t\t\tif (!this.quickNavigateConfiguration) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 306 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { IDisposable, dispose, ReferenceCollection } from 'vs/base/common/lifecycle'; class Disposable implements IDisposable { isDisposed = false; dispose() { this.isDisposed = true; } } suite('Lifecycle', () => { test('dispose single disposable', () => { const disposable = new Disposable(); assert(!disposable.isDisposed); dispose(disposable); assert(disposable.isDisposed); }); test('dispose disposable array', () => { const disposable = new Disposable(); const disposable2 = new Disposable(); assert(!disposable.isDisposed); assert(!disposable2.isDisposed); dispose([disposable, disposable2]); assert(disposable.isDisposed); assert(disposable2.isDisposed); }); test('dispose disposables', () => { const disposable = new Disposable(); const disposable2 = new Disposable(); assert(!disposable.isDisposed); assert(!disposable2.isDisposed); dispose(disposable); dispose(disposable2); assert(disposable.isDisposed); assert(disposable2.isDisposed); }); }); suite('Reference Collection', () => { class Collection extends ReferenceCollection<number> { private _count = 0; get count() { return this._count; } protected createReferencedObject(key: string): number { this._count++; return key.length; } protected destroyReferencedObject(key: string, object: number): void { this._count--; } } test('simple', () => { const collection = new Collection(); const ref1 = collection.acquire('test'); assert(ref1); assert.equal(ref1.object, 4); assert.equal(collection.count, 1); ref1.dispose(); assert.equal(collection.count, 0); const ref2 = collection.acquire('test'); const ref3 = collection.acquire('test'); assert.equal(ref2.object, ref3.object); assert.equal(collection.count, 1); const ref4 = collection.acquire('monkey'); assert.equal(ref4.object, 6); assert.equal(collection.count, 2); ref2.dispose(); assert.equal(collection.count, 2); ref3.dispose(); assert.equal(collection.count, 1); ref4.dispose(); assert.equal(collection.count, 0); }); });
src/vs/base/test/common/lifecycle.test.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00044884689850732684, 0.0002028433227678761, 0.00016558912466280162, 0.00017402351659256965, 0.000087040476500988 ]
{ "id": 4, "code_window": [ "\t\tthis._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, e => {\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tconst keyCode = keyboardEvent.keyCode;\n", "\n", "\t\t\t// Only handle when in quick navigation mode\n", "\t\t\tif (!this.quickNavigateConfiguration || !this.keyDownSeenSinceShown) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!this.quickNavigateConfiguration) {\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 327 }
/*--------------------------------------------------------------------------------------------- * 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!./quickopen'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import { IQuickNavigateConfiguration, IAutoFocus, IEntryRunContext, IModel, Mode, IKeyMods } from 'vs/base/parts/quickopen/common/quickOpen'; import { Filter, Renderer, DataSource, IModelProvider, AccessibilityProvider } from 'vs/base/parts/quickopen/browser/quickOpenViewer'; import { ITree, ContextMenuEvent, IActionProvider, ITreeStyles, ITreeOptions, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree'; import { InputBox, MessageType, IInputBoxStyles, IRange } from 'vs/base/browser/ui/inputbox/inputBox'; import Severity from 'vs/base/common/severity'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { DefaultController, ClickBehavior } from 'vs/base/parts/tree/browser/treeDefaults'; import * as DOM from 'vs/base/browser/dom'; import { KeyCode } from 'vs/base/common/keyCodes'; import { Disposable } from 'vs/base/common/lifecycle'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { StandardMouseEvent, IMouseEvent } from 'vs/base/browser/mouseEvent'; import { IThemable } from 'vs/base/common/styler'; export interface IQuickOpenCallbacks { onOk: () => void; onCancel: () => void; onType: (value: string) => void; onShow?: () => void; onHide?: (reason: HideReason) => void; onFocusLost?: () => boolean /* veto close */; } export interface IQuickOpenOptions extends IQuickOpenStyles { minItemsToShow?: number; maxItemsToShow?: number; inputPlaceHolder?: string; inputAriaLabel?: string; actionProvider?: IActionProvider; keyboardSupport?: boolean; treeCreator?: (container: HTMLElement, configuration: ITreeConfiguration, options?: ITreeOptions) => ITree; } export interface IQuickOpenStyles extends IInputBoxStyles, ITreeStyles { background?: Color; foreground?: Color; borderColor?: Color; pickerGroupForeground?: Color; pickerGroupBorder?: Color; widgetShadow?: Color; progressBarBackground?: Color; } export interface IShowOptions { quickNavigateConfiguration?: IQuickNavigateConfiguration; autoFocus?: IAutoFocus; inputSelection?: IRange; value?: string; } export class QuickOpenController extends DefaultController { onContextMenu(tree: ITree, element: any, event: ContextMenuEvent): boolean { if (platform.isMacintosh) { return this.onLeftClick(tree, element, event); // https://github.com/Microsoft/vscode/issues/1011 } return super.onContextMenu(tree, element, event); } onMouseMiddleClick(tree: ITree, element: any, event: IMouseEvent): boolean { return this.onLeftClick(tree, element, event); } } export const enum HideReason { ELEMENT_SELECTED, FOCUS_LOST, CANCELED } const defaultStyles = { background: Color.fromHex('#1E1E1E'), foreground: Color.fromHex('#CCCCCC'), pickerGroupForeground: Color.fromHex('#0097FB'), pickerGroupBorder: Color.fromHex('#3F3F46'), widgetShadow: Color.fromHex('#000000'), progressBarBackground: Color.fromHex('#0E70C0') }; const DEFAULT_INPUT_ARIA_LABEL = nls.localize('quickOpenAriaLabel', "Quick picker. Type to narrow down results."); export class QuickOpenWidget extends Disposable implements IModelProvider, IThemable { private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private static readonly MAX_ITEMS_HEIGHT = 20 * 22; // Max height of item list below input field private isDisposed: boolean; private options: IQuickOpenOptions; // @ts-ignore (legacy widget - to be replaced with quick input) private element: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private tree: ITree; // @ts-ignore (legacy widget - to be replaced with quick input) private inputBox: InputBox; // @ts-ignore (legacy widget - to be replaced with quick input) private inputContainer: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private helpText: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private resultCount: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private treeContainer: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private progressBar: ProgressBar; // @ts-ignore (legacy widget - to be replaced with quick input) private visible: boolean; // @ts-ignore (legacy widget - to be replaced with quick input) private isLoosingFocus: boolean; private callbacks: IQuickOpenCallbacks; private quickNavigateConfiguration: IQuickNavigateConfiguration | undefined; private container: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private treeElement: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private inputElement: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private layoutDimensions: DOM.Dimension; private model: IModel<any> | null; private inputChangingTimeoutHandle: any; // @ts-ignore (legacy widget - to be replaced with quick input) private styles: IQuickOpenStyles; // @ts-ignore (legacy widget - to be replaced with quick input) private renderer: Renderer; private keyDownSeenSinceShown = false; constructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions) { super(); this.isDisposed = false; this.container = container; this.callbacks = callbacks; this.options = options; this.styles = options || Object.create(null); mixin(this.styles, defaultStyles, false); this.model = null; } getElement(): HTMLElement { return this.element; } getModel(): IModel<any> { return this.model!; } setCallbacks(callbacks: IQuickOpenCallbacks): void { this.callbacks = callbacks; } create(): HTMLElement { // Container this.element = document.createElement('div'); DOM.addClass(this.element, 'monaco-quick-open-widget'); this.container.appendChild(this.element); this._register(DOM.addDisposableListener(this.element, DOM.EventType.CONTEXT_MENU, e => DOM.EventHelper.stop(e, true))); // Do this to fix an issue on Mac where the menu goes into the way this._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, e => this.gainingFocus(), true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, e => this.loosingFocus(e), true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, e => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); if (keyboardEvent.keyCode === KeyCode.Escape) { DOM.EventHelper.stop(e, true); this.hide(HideReason.CANCELED); } else if (keyboardEvent.keyCode === KeyCode.Tab && !keyboardEvent.altKey && !keyboardEvent.ctrlKey && !keyboardEvent.metaKey) { const stops = (e.currentTarget as HTMLElement).querySelectorAll('input, .monaco-tree, .monaco-tree-row.focused .action-label.icon') as NodeListOf<HTMLElement>; if (keyboardEvent.shiftKey && keyboardEvent.target === stops[0]) { DOM.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!keyboardEvent.shiftKey && keyboardEvent.target === stops[stops.length - 1]) { DOM.EventHelper.stop(e, true); stops[0].focus(); } } })); // Progress Bar this.progressBar = this._register(new ProgressBar(this.element, { progressBarBackground: this.styles.progressBarBackground })); this.progressBar.hide(); // Input Field this.inputContainer = document.createElement('div'); DOM.addClass(this.inputContainer, 'quick-open-input'); this.element.appendChild(this.inputContainer); this.inputBox = this._register(new InputBox(this.inputContainer, undefined, { placeholder: this.options.inputPlaceHolder || '', ariaLabel: DEFAULT_INPUT_ARIA_LABEL, inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder })); this.inputElement = this.inputBox.inputElement; this.inputElement.setAttribute('role', 'combobox'); this.inputElement.setAttribute('aria-haspopup', 'false'); this.inputElement.setAttribute('aria-autocomplete', 'list'); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, (e: Event) => this.onType())); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const shouldOpenInBackground = this.shouldOpenInBackground(keyboardEvent); // Do not handle Tab: It is used to navigate between elements without mouse if (keyboardEvent.keyCode === KeyCode.Tab) { return; } // Pass tree navigation keys to the tree but leave focus in input field else if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); // Position cursor at the end of input to allow right arrow (open in background) // to function immediately unless the user has made a selection if (this.inputBox.inputElement.selectionStart === this.inputBox.inputElement.selectionEnd) { this.inputBox.inputElement.selectionStart = this.inputBox.value.length; } } // Select element on Enter or on Arrow-Right if we are at the end of the input else if (keyboardEvent.keyCode === KeyCode.Enter || shouldOpenInBackground) { DOM.EventHelper.stop(e, true); const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus, e, shouldOpenInBackground ? Mode.OPEN_IN_BACKGROUND : Mode.OPEN); } } })); // Result count for screen readers this.resultCount = document.createElement('div'); DOM.addClass(this.resultCount, 'quick-open-result-count'); this.resultCount.setAttribute('aria-live', 'polite'); this.resultCount.setAttribute('aria-atomic', 'true'); this.element.appendChild(this.resultCount); // Tree this.treeContainer = document.createElement('div'); DOM.addClass(this.treeContainer, 'quick-open-tree'); this.element.appendChild(this.treeContainer); const createTree = this.options.treeCreator || ((container, config, opts) => new Tree(container, config, opts)); this.tree = this._register(createTree(this.treeContainer, { dataSource: new DataSource(this), controller: new QuickOpenController({ clickBehavior: ClickBehavior.ON_MOUSE_UP, keyboardSupport: this.options.keyboardSupport }), renderer: (this.renderer = new Renderer(this, this.styles)), filter: new Filter(this), accessibilityProvider: new AccessibilityProvider(this) }, { twistiePixels: 11, indentPixels: 0, alwaysFocused: true, verticalScrollMode: ScrollbarVisibility.Visible, horizontalScrollMode: ScrollbarVisibility.Hidden, ariaLabel: nls.localize('treeAriaLabel', "Quick Picker"), keyboardSupport: this.options.keyboardSupport, preventRootFocus: false })); this.treeElement = this.tree.getHTMLElement(); // Handle Focus and Selection event this._register(this.tree.onDidChangeFocus(event => { this.elementFocused(event.focus, event); })); this._register(this.tree.onDidChangeSelection(event => { if (event.selection && event.selection.length > 0) { const mouseEvent: StandardMouseEvent = event.payload && event.payload.originalEvent instanceof StandardMouseEvent ? event.payload.originalEvent : undefined; const shouldOpenInBackground = mouseEvent ? this.shouldOpenInBackground(mouseEvent) : false; this.elementSelected(event.selection[0], event, shouldOpenInBackground ? Mode.OPEN_IN_BACKGROUND : Mode.OPEN); } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, e => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); // Only handle when in quick navigation mode if (!this.quickNavigateConfiguration) { return; } // Support keyboard navigation in quick navigation mode if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode); } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, e => { const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Only handle when in quick navigation mode if (!this.quickNavigateConfiguration || !this.keyDownSeenSinceShown) { return; } // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigateConfiguration.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed) { const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus, e); } } })); // Support layout if (this.layoutDimensions) { this.layout(this.layoutDimensions); } this.applyStyles(); // Allows focus to switch to next/previous entry after tab into an actionbar item this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); // Only handle when not in quick navigation mode if (this.quickNavigateConfiguration) { return; } if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); this.treeElement.focus(); } })); return this.element; } style(styles: IQuickOpenStyles): void { this.styles = styles; this.applyStyles(); } protected applyStyles(): void { if (this.element) { const foreground = this.styles.foreground ? this.styles.foreground.toString() : null; const background = this.styles.background ? this.styles.background.toString() : ''; const borderColor = this.styles.borderColor ? this.styles.borderColor.toString() : ''; const widgetShadow = this.styles.widgetShadow ? this.styles.widgetShadow.toString() : ''; this.element.style.color = foreground; this.element.style.backgroundColor = background; this.element.style.borderColor = borderColor; this.element.style.borderWidth = borderColor ? '1px' : ''; this.element.style.borderStyle = borderColor ? 'solid' : ''; this.element.style.boxShadow = widgetShadow ? `0 5px 8px ${widgetShadow}` : ''; } if (this.progressBar) { this.progressBar.style({ progressBarBackground: this.styles.progressBarBackground }); } if (this.inputBox) { this.inputBox.style({ inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder }); } if (this.tree && !this.options.treeCreator) { this.tree.style(this.styles); } if (this.renderer) { this.renderer.updateStyles(this.styles); } } private shouldOpenInBackground(e: StandardKeyboardEvent | StandardMouseEvent): boolean { // Keyboard if (e instanceof StandardKeyboardEvent) { if (e.keyCode !== KeyCode.RightArrow) { return false; // only for right arrow } if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return false; // no modifiers allowed } // validate the cursor is at the end of the input and there is no selection, // and if not prevent opening in the background such as the selection can be changed const element = this.inputBox.inputElement; return element.selectionEnd === this.inputBox.value.length && element.selectionStart === element.selectionEnd; } // Mouse return e.middleButton; } private onType(): void { const value = this.inputBox.value; // Adjust help text as needed if present if (this.helpText) { if (value) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Send to callbacks this.callbacks.onType(value); } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void { if (this.isVisible()) { // Transition into quick navigate mode if not yet done if (!this.quickNavigateConfiguration && quickNavigate) { this.quickNavigateConfiguration = quickNavigate; this.tree.domFocus(); } // Navigate this.navigateInTree(next ? KeyCode.DownArrow : KeyCode.UpArrow); } } private navigateInTree(keyCode: KeyCode, isShift?: boolean): void { const model: IModel<any> = this.tree.getInput(); const entries = model ? model.entries : []; const oldFocus = this.tree.getFocus(); // Normal Navigation switch (keyCode) { case KeyCode.DownArrow: this.tree.focusNext(); break; case KeyCode.UpArrow: this.tree.focusPrevious(); break; case KeyCode.PageDown: this.tree.focusNextPage(); break; case KeyCode.PageUp: this.tree.focusPreviousPage(); break; case KeyCode.Tab: if (isShift) { this.tree.focusPrevious(); } else { this.tree.focusNext(); } break; } let newFocus = this.tree.getFocus(); // Support cycle-through navigation if focus did not change if (entries.length > 1 && oldFocus === newFocus) { // Up from no entry or first entry goes down to last if (keyCode === KeyCode.UpArrow || (keyCode === KeyCode.Tab && isShift)) { this.tree.focusLast(); } // Down from last entry goes to up to first else if (keyCode === KeyCode.DownArrow || keyCode === KeyCode.Tab && !isShift) { this.tree.focusFirst(); } } // Reveal newFocus = this.tree.getFocus(); if (newFocus) { this.tree.reveal(newFocus); } } private elementFocused(value: any, event?: any): void { if (!value || !this.isVisible()) { return; } // ARIA const arivaActiveDescendant = this.treeElement.getAttribute('aria-activedescendant'); if (arivaActiveDescendant) { this.inputElement.setAttribute('aria-activedescendant', arivaActiveDescendant); } else { this.inputElement.removeAttribute('aria-activedescendant'); } const context: IEntryRunContext = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; this.model!.runner.run(value, Mode.PREVIEW, context); } private elementSelected(value: any, event?: any, preferredMode?: Mode): void { let hide = true; // Trigger open of element on selection if (this.isVisible()) { let mode = preferredMode || Mode.OPEN; const context: IEntryRunContext = { event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; hide = this.model!.runner.run(value, mode, context); } // Hide if command was run successfully if (hide) { this.hide(HideReason.ELEMENT_SELECTED); } } private extractKeyMods(event: any): IKeyMods { return { ctrlCmd: event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey))), alt: event && (event.altKey || (event.payload && event.payload.originalEvent && event.payload.originalEvent.altKey)) }; } show(prefix: string, options?: IShowOptions): void; show(input: IModel<any>, options?: IShowOptions): void; show(param: any, options?: IShowOptions): void { this.visible = true; this.isLoosingFocus = false; this.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined; this.keyDownSeenSinceShown = false; // Adjust UI for quick navigate mode if (this.quickNavigateConfiguration) { DOM.hide(this.inputContainer); DOM.show(this.element); this.tree.domFocus(); } // Otherwise use normal UI else { DOM.show(this.inputContainer); DOM.show(this.element); this.inputBox.focus(); } // Adjust Help text for IE if (this.helpText) { if (this.quickNavigateConfiguration || types.isString(param)) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Show based on param if (types.isString(param)) { this.doShowWithPrefix(param); } else { if (options && options.value) { this.restoreLastInput(options.value); } this.doShowWithInput(param, options && options.autoFocus ? options.autoFocus : {}); } // Respect selectAll option if (options && options.inputSelection && !this.quickNavigateConfiguration) { this.inputBox.select(options.inputSelection); } if (this.callbacks.onShow) { this.callbacks.onShow(); } } private restoreLastInput(lastInput: string) { this.inputBox.value = lastInput; this.inputBox.select(); this.callbacks.onType(lastInput); } private doShowWithPrefix(prefix: string): void { this.inputBox.value = prefix; this.callbacks.onType(prefix); } private doShowWithInput(input: IModel<any>, autoFocus: IAutoFocus): void { this.setInput(input, autoFocus); } private setInputAndLayout(input: IModel<any>, autoFocus?: IAutoFocus): void { this.treeContainer.style.height = `${this.getHeight(input)}px`; this.tree.setInput(null).then(() => { this.model = input; // ARIA this.inputElement.setAttribute('aria-haspopup', String(input && input.entries && input.entries.length > 0)); return this.tree.setInput(input); }).then(() => { // Indicate entries to tree this.tree.layout(); const entries = input ? input.entries.filter(e => this.isElementVisible(input, e)) : []; this.updateResultCount(entries.length); // Handle auto focus if (entries.length) { this.autoFocus(input, entries, autoFocus); } }); } private isElementVisible<T>(input: IModel<T>, e: T): boolean { if (!input.filter) { return true; } return input.filter.isVisible(e); } private autoFocus(input: IModel<any>, entries: any[], autoFocus: IAutoFocus = {}): void { // First check for auto focus of prefix matches if (autoFocus.autoFocusPrefixMatch) { let caseSensitiveMatch: any; let caseInsensitiveMatch: any; const prefix = autoFocus.autoFocusPrefixMatch; const lowerCasePrefix = prefix.toLowerCase(); for (const entry of entries) { const label = input.dataSource.getLabel(entry) || ''; if (!caseSensitiveMatch && label.indexOf(prefix) === 0) { caseSensitiveMatch = entry; } else if (!caseInsensitiveMatch && label.toLowerCase().indexOf(lowerCasePrefix) === 0) { caseInsensitiveMatch = entry; } if (caseSensitiveMatch && caseInsensitiveMatch) { break; } } const entryToFocus = caseSensitiveMatch || caseInsensitiveMatch; if (entryToFocus) { this.tree.setFocus(entryToFocus); this.tree.reveal(entryToFocus, 0.5); return; } } // Second check for auto focus of first entry if (autoFocus.autoFocusFirstEntry) { this.tree.focusFirst(); this.tree.reveal(this.tree.getFocus()); } // Third check for specific index option else if (typeof autoFocus.autoFocusIndex === 'number') { if (entries.length > autoFocus.autoFocusIndex) { this.tree.focusNth(autoFocus.autoFocusIndex); this.tree.reveal(this.tree.getFocus()); } } // Check for auto focus of second entry else if (autoFocus.autoFocusSecondEntry) { if (entries.length > 1) { this.tree.focusNth(1); } } // Finally check for auto focus of last entry else if (autoFocus.autoFocusLastEntry) { if (entries.length > 1) { this.tree.focusLast(); } } } refresh(input?: IModel<any>, autoFocus?: IAutoFocus): void { if (!this.isVisible()) { return; } if (!input) { input = this.tree.getInput(); } if (!input) { return; } // Apply height & Refresh this.treeContainer.style.height = `${this.getHeight(input)}px`; this.tree.refresh().then(() => { // Indicate entries to tree this.tree.layout(); const entries = input ? input.entries!.filter(e => this.isElementVisible(input!, e)) : []; this.updateResultCount(entries.length); // Handle auto focus if (autoFocus) { if (entries.length) { this.autoFocus(input!, entries, autoFocus); } } }); } private getHeight(input: IModel<any>): number { const renderer = input.renderer; if (!input) { const itemHeight = renderer.getHeight(null); return this.options.minItemsToShow ? this.options.minItemsToShow * itemHeight : 0; } let height = 0; let preferredItemsHeight: number | undefined; if (this.layoutDimensions && this.layoutDimensions.height) { preferredItemsHeight = (this.layoutDimensions.height - 50 /* subtract height of input field (30px) and some spacing (drop shadow) to fit */) * 0.4 /* max 40% of screen */; } if (!preferredItemsHeight || preferredItemsHeight > QuickOpenWidget.MAX_ITEMS_HEIGHT) { preferredItemsHeight = QuickOpenWidget.MAX_ITEMS_HEIGHT; } const entries = input.entries.filter(e => this.isElementVisible(input, e)); const maxEntries = this.options.maxItemsToShow || entries.length; for (let i = 0; i < maxEntries && i < entries.length; i++) { const entryHeight = renderer.getHeight(entries[i]); if (height + entryHeight <= preferredItemsHeight) { height += entryHeight; } else { break; } } return height; } updateResultCount(count: number) { this.resultCount.textContent = nls.localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results", count); } hide(reason?: HideReason): void { if (!this.isVisible()) { return; } this.visible = false; DOM.hide(this.element); this.element.blur(); // Clear input field and clear tree this.inputBox.value = ''; this.tree.setInput(null); // ARIA this.inputElement.setAttribute('aria-haspopup', 'false'); // Reset Tree Height this.treeContainer.style.height = `${this.options.minItemsToShow ? this.options.minItemsToShow * 22 : 0}px`; // Clear any running Progress this.progressBar.stop().hide(); // Clear Focus if (this.tree.isDOMFocused()) { this.tree.domBlur(); } else if (this.inputBox.hasFocus()) { this.inputBox.blur(); } // Callbacks if (reason === HideReason.ELEMENT_SELECTED) { this.callbacks.onOk(); } else { this.callbacks.onCancel(); } if (this.callbacks.onHide) { this.callbacks.onHide(reason!); } } getQuickNavigateConfiguration(): IQuickNavigateConfiguration { return this.quickNavigateConfiguration!; } setPlaceHolder(placeHolder: string): void { if (this.inputBox) { this.inputBox.setPlaceHolder(placeHolder); } } setValue(value: string, selectionOrStableHint?: [number, number] | null): void { if (this.inputBox) { this.inputBox.value = value; if (selectionOrStableHint === null) { // null means stable-selection } else if (Array.isArray(selectionOrStableHint)) { const [start, end] = selectionOrStableHint; this.inputBox.select({ start, end }); } else { this.inputBox.select(); } } } setPassword(isPassword: boolean): void { if (this.inputBox) { this.inputBox.inputElement.type = isPassword ? 'password' : 'text'; } } setInput(input: IModel<any>, autoFocus?: IAutoFocus, ariaLabel?: string): void { if (!this.isVisible()) { return; } // If the input changes, indicate this to the tree if (!!this.getInput()) { this.onInputChanging(); } // Adapt tree height to entries and apply input this.setInputAndLayout(input, autoFocus); // Apply ARIA if (this.inputBox) { this.inputBox.setAriaLabel(ariaLabel || DEFAULT_INPUT_ARIA_LABEL); } } private onInputChanging(): void { if (this.inputChangingTimeoutHandle) { clearTimeout(this.inputChangingTimeoutHandle); this.inputChangingTimeoutHandle = null; } // when the input is changing in quick open, we indicate this as CSS class to the widget // for a certain timeout. this helps reducing some hectic UI updates when input changes quickly DOM.addClass(this.element, 'content-changing'); this.inputChangingTimeoutHandle = setTimeout(() => { DOM.removeClass(this.element, 'content-changing'); }, 500); } getInput(): IModel<any> { return this.tree.getInput(); } showInputDecoration(decoration: Severity): void { if (this.inputBox) { this.inputBox.showMessage({ type: decoration === Severity.Info ? MessageType.INFO : decoration === Severity.Warning ? MessageType.WARNING : MessageType.ERROR, content: '' }); } } clearInputDecoration(): void { if (this.inputBox) { this.inputBox.hideMessage(); } } focus(): void { if (this.isVisible() && this.inputBox) { this.inputBox.focus(); } } accept(): void { if (this.isVisible()) { const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus); } } } getProgressBar(): ProgressBar { return this.progressBar; } getInputBox(): InputBox { return this.inputBox; } setExtraClass(clazz: string | null): void { const previousClass = this.element.getAttribute('quick-open-extra-class'); if (previousClass) { DOM.removeClasses(this.element, previousClass); } if (clazz) { DOM.addClasses(this.element, clazz); this.element.setAttribute('quick-open-extra-class', clazz); } else if (previousClass) { this.element.removeAttribute('quick-open-extra-class'); } } isVisible(): boolean { return this.visible; } layout(dimension: DOM.Dimension): void { this.layoutDimensions = dimension; // Apply to quick open width (height is dynamic by number of items to show) const quickOpenWidth = Math.min(this.layoutDimensions.width * 0.62 /* golden cut */, QuickOpenWidget.MAX_WIDTH); if (this.element) { // quick open this.element.style.width = `${quickOpenWidth}px`; this.element.style.marginLeft = `-${quickOpenWidth / 2}px`; // input field this.inputContainer.style.width = `${quickOpenWidth - 12}px`; } } private gainingFocus(): void { this.isLoosingFocus = false; } private loosingFocus(e: FocusEvent): void { if (!this.isVisible()) { return; } const relatedTarget = e.relatedTarget as HTMLElement; if (!this.quickNavigateConfiguration && DOM.isAncestor(relatedTarget, this.element)) { return; // user clicked somewhere into quick open widget, do not close thereby } this.isLoosingFocus = true; setTimeout(() => { if (!this.isLoosingFocus || this.isDisposed) { return; } const veto = this.callbacks.onFocusLost && this.callbacks.onFocusLost(); if (!veto) { this.hide(HideReason.FOCUS_LOST); } }, 0); } dispose(): void { super.dispose(); this.isDisposed = true; } }
src/vs/base/parts/quickopen/browser/quickOpenWidget.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9991820454597473, 0.19078566133975983, 0.00015943583275657147, 0.00017389110871590674, 0.3873937726020813 ]
{ "id": 4, "code_window": [ "\t\tthis._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, e => {\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tconst keyCode = keyboardEvent.keyCode;\n", "\n", "\t\t\t// Only handle when in quick navigation mode\n", "\t\t\tif (!this.quickNavigateConfiguration || !this.keyDownSeenSinceShown) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!this.quickNavigateConfiguration) {\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 327 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAction, IActionViewItem } from 'vs/base/common/actions'; export interface IComposite { /** * Returns the unique identifier of this composite. */ getId(): string; /** * Returns the name of this composite to show in the title area. */ getTitle(): string | undefined; /** * Returns the primary actions of the composite. */ getActions(): ReadonlyArray<IAction>; /** * Returns the secondary actions of the composite. */ getSecondaryActions(): ReadonlyArray<IAction>; /** * Returns an array of actions to show in the context menu of the composite */ getContextMenuActions(): ReadonlyArray<IAction>; /** * Returns the action item for a specific action. */ getActionViewItem(action: IAction): IActionViewItem | undefined; /** * Returns the underlying control of this composite. */ getControl(): ICompositeControl | undefined; /** * Asks the underlying control to focus. */ focus(): void; } /** * Marker interface for the composite control */ export interface ICompositeControl { }
src/vs/workbench/common/composite.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0001769005903042853, 0.00017262932669837028, 0.00016405369387939572, 0.00017421680968254805, 0.000004164511210547062 ]
{ "id": 4, "code_window": [ "\t\tthis._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, e => {\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tconst keyCode = keyboardEvent.keyCode;\n", "\n", "\t\t\t// Only handle when in quick navigation mode\n", "\t\t\tif (!this.quickNavigateConfiguration || !this.keyDownSeenSinceShown) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!this.quickNavigateConfiguration) {\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 327 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { URI as uri } from 'vs/base/common/uri'; import severity from 'vs/base/common/severity'; import { DebugModel, Expression, StackFrame, Thread } from 'vs/workbench/contrib/debug/common/debugModel'; import * as sinon from 'sinon'; import { MockRawSession } from 'vs/workbench/contrib/debug/test/common/mockDebug'; import { Source } from 'vs/workbench/contrib/debug/common/debugSource'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { SimpleReplElement, RawObjectReplElement, ReplEvaluationInput, ReplModel } from 'vs/workbench/contrib/debug/common/replModel'; import { IBreakpointUpdateData, IDebugSessionOptions } from 'vs/workbench/contrib/debug/common/debug'; import { NullOpenerService } from 'vs/platform/opener/common/opener'; function createMockSession(model: DebugModel, name = 'mockSession', options?: IDebugSessionOptions): DebugSession { return new DebugSession({ resolved: { name, type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, options, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, NullOpenerService); } suite('Debug - Model', () => { let model: DebugModel; let rawSession: MockRawSession; setup(() => { model = new DebugModel([], [], [], [], [], <any>{ isDirty: (e: any) => false }); rawSession = new MockRawSession(); }); // Breakpoints test('breakpoints simple', () => { const modelUri = uri.file('/myfolder/myfile.js'); model.addBreakpoints(modelUri, [{ lineNumber: 5, enabled: true }, { lineNumber: 10, enabled: false }]); assert.equal(model.areBreakpointsActivated(), true); assert.equal(model.getBreakpoints().length, 2); model.removeBreakpoints(model.getBreakpoints()); assert.equal(model.getBreakpoints().length, 0); }); test('breakpoints toggling', () => { const modelUri = uri.file('/myfolder/myfile.js'); model.addBreakpoints(modelUri, [{ lineNumber: 5, enabled: true }, { lineNumber: 10, enabled: false }]); model.addBreakpoints(modelUri, [{ lineNumber: 12, enabled: true, condition: 'fake condition' }]); assert.equal(model.getBreakpoints().length, 3); const bp = model.getBreakpoints().pop(); if (bp) { model.removeBreakpoints([bp]); } assert.equal(model.getBreakpoints().length, 2); model.setBreakpointsActivated(false); assert.equal(model.areBreakpointsActivated(), false); model.setBreakpointsActivated(true); assert.equal(model.areBreakpointsActivated(), true); }); test('breakpoints two files', () => { const modelUri1 = uri.file('/myfolder/my file first.js'); const modelUri2 = uri.file('/secondfolder/second/second file.js'); model.addBreakpoints(modelUri1, [{ lineNumber: 5, enabled: true }, { lineNumber: 10, enabled: false }]); model.addBreakpoints(modelUri2, [{ lineNumber: 1, enabled: true }, { lineNumber: 2, enabled: true }, { lineNumber: 3, enabled: false }]); assert.equal(model.getBreakpoints().length, 5); const bp = model.getBreakpoints()[0]; const update = new Map<string, IBreakpointUpdateData>(); update.set(bp.getId(), { lineNumber: 100 }); model.updateBreakpoints(update); assert.equal(bp.lineNumber, 100); model.enableOrDisableAllBreakpoints(false); model.getBreakpoints().forEach(bp => { assert.equal(bp.enabled, false); }); model.setEnablement(bp, true); assert.equal(bp.enabled, true); model.removeBreakpoints(model.getBreakpoints({ uri: modelUri1 })); assert.equal(model.getBreakpoints().length, 3); }); test('breakpoints conditions', () => { const modelUri1 = uri.file('/myfolder/my file first.js'); model.addBreakpoints(modelUri1, [{ lineNumber: 5, condition: 'i < 5', hitCondition: '17' }, { lineNumber: 10, condition: 'j < 3' }]); const breakpoints = model.getBreakpoints(); assert.equal(breakpoints[0].condition, 'i < 5'); assert.equal(breakpoints[0].hitCondition, '17'); assert.equal(breakpoints[1].condition, 'j < 3'); assert.equal(!!breakpoints[1].hitCondition, false); assert.equal(model.getBreakpoints().length, 2); model.removeBreakpoints(model.getBreakpoints()); assert.equal(model.getBreakpoints().length, 0); }); test('function breakpoints', () => { model.addFunctionBreakpoint('foo', '1'); model.addFunctionBreakpoint('bar', '2'); model.renameFunctionBreakpoint('1', 'fooUpdated'); model.renameFunctionBreakpoint('2', 'barUpdated'); const functionBps = model.getFunctionBreakpoints(); assert.equal(functionBps[0].name, 'fooUpdated'); assert.equal(functionBps[1].name, 'barUpdated'); model.removeFunctionBreakpoints(); assert.equal(model.getFunctionBreakpoints().length, 0); }); test('breakpoints multiple sessions', () => { const modelUri = uri.file('/myfolder/myfile.js'); const breakpoints = model.addBreakpoints(modelUri, [{ lineNumber: 5, enabled: true, condition: 'x > 5' }, { lineNumber: 10, enabled: false }]); const session = createMockSession(model); const data = new Map<string, DebugProtocol.Breakpoint>(); assert.equal(breakpoints[0].lineNumber, 5); assert.equal(breakpoints[1].lineNumber, 10); data.set(breakpoints[0].getId(), { verified: false, line: 10 }); data.set(breakpoints[1].getId(), { verified: true, line: 50 }); model.setBreakpointSessionData(session.getId(), {}, data); assert.equal(breakpoints[0].lineNumber, 5); assert.equal(breakpoints[1].lineNumber, 50); const session2 = createMockSession(model); const data2 = new Map<string, DebugProtocol.Breakpoint>(); data2.set(breakpoints[0].getId(), { verified: true, line: 100 }); data2.set(breakpoints[1].getId(), { verified: true, line: 500 }); model.setBreakpointSessionData(session2.getId(), {}, data2); // Breakpoint is verified only once, show that line assert.equal(breakpoints[0].lineNumber, 100); // Breakpoint is verified two times, show the original line assert.equal(breakpoints[1].lineNumber, 10); model.setBreakpointSessionData(session.getId(), {}, undefined); // No more double session verification assert.equal(breakpoints[0].lineNumber, 100); assert.equal(breakpoints[1].lineNumber, 500); assert.equal(breakpoints[0].supported, false); const data3 = new Map<string, DebugProtocol.Breakpoint>(); data3.set(breakpoints[0].getId(), { verified: true, line: 500 }); model.setBreakpointSessionData(session2.getId(), { supportsConditionalBreakpoints: true }, data2); assert.equal(breakpoints[0].supported, true); }); // Threads test('threads simple', () => { const threadId = 1; const threadName = 'firstThread'; const session = createMockSession(model); model.addSession(session); assert.equal(model.getSessions(true).length, 1); model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId, name: threadName }] }); assert.equal(session.getThread(threadId)!.name, threadName); model.clearThreads(session.getId(), true); assert.equal(session.getThread(threadId), undefined); assert.equal(model.getSessions(true).length, 1); }); test('threads multiple wtih allThreadsStopped', () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread1 = session.getThread(threadId1)!; const thread2 = session.getThread(threadId2)!; // at the beginning, callstacks are obtainable but not available assert.equal(session.getAllThreads().length, 2); assert.equal(thread1.name, threadName1); assert.equal(thread1.stopped, true); assert.equal(thread1.getCallStack().length, 0); assert.equal(thread1.stoppedDetails!.reason, stoppedReason); assert.equal(thread2.name, threadName2); assert.equal(thread2.stopped, true); assert.equal(thread2.getCallStack().length, 0); assert.equal(thread2.stoppedDetails!.reason, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter thread1.fetchCallStack().then(() => { assert.notEqual(thread1.getCallStack().length, 0); }); thread2.fetchCallStack().then(() => { assert.notEqual(thread2.getCallStack().length, 0); }); // calling multiple times getCallStack doesn't result in multiple calls // to the debug adapter thread1.fetchCallStack().then(() => { return thread2.fetchCallStack(); }); // clearing the callstack results in the callstack not being available thread1.clearCallStack(); assert.equal(thread1.stopped, true); assert.equal(thread1.getCallStack().length, 0); thread2.clearCallStack(); assert.equal(thread2.stopped, true); assert.equal(thread2.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.equal(session.getThread(threadId1), undefined); assert.equal(session.getThread(threadId2), undefined); assert.equal(session.getAllThreads().length, 0); }); test('threads mutltiple without allThreadsStopped', () => { const sessionStub = sinon.spy(rawSession, 'stackTrace'); const stoppedThreadId = 1; const stoppedThreadName = 'stoppedThread'; const runningThreadId = 2; const runningThreadName = 'runningThread'; const stoppedReason = 'breakpoint'; const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; // Add the threads model.rawUpdate({ sessionId: session.getId(), threads: [{ id: stoppedThreadId, name: stoppedThreadName }] }); // Stopped event with only one thread stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: 1, name: stoppedThreadName }, { id: runningThreadId, name: runningThreadName }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: false } }); const stoppedThread = session.getThread(stoppedThreadId)!; const runningThread = session.getThread(runningThreadId)!; // the callstack for the stopped thread is obtainable but not available // the callstack for the running thread is not obtainable nor available assert.equal(stoppedThread.name, stoppedThreadName); assert.equal(stoppedThread.stopped, true); assert.equal(session.getAllThreads().length, 2); assert.equal(stoppedThread.getCallStack().length, 0); assert.equal(stoppedThread.stoppedDetails!.reason, stoppedReason); assert.equal(runningThread.name, runningThreadName); assert.equal(runningThread.stopped, false); assert.equal(runningThread.getCallStack().length, 0); assert.equal(runningThread.stoppedDetails, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter stoppedThread.fetchCallStack().then(() => { assert.notEqual(stoppedThread.getCallStack().length, 0); assert.equal(runningThread.getCallStack().length, 0); assert.equal(sessionStub.callCount, 1); }); // calling getCallStack on the running thread returns empty array // and does not return in a request for the callstack in the debug // adapter runningThread.fetchCallStack().then(() => { assert.equal(runningThread.getCallStack().length, 0); assert.equal(sessionStub.callCount, 1); }); // clearing the callstack results in the callstack not being available stoppedThread.clearCallStack(); assert.equal(stoppedThread.stopped, true); assert.equal(stoppedThread.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.equal(session.getThread(stoppedThreadId), undefined); assert.equal(session.getThread(runningThreadId), undefined); assert.equal(session.getAllThreads().length, 0); }); // Expressions function assertWatchExpressions(watchExpressions: Expression[], expectedName: string) { assert.equal(watchExpressions.length, 2); watchExpressions.forEach(we => { assert.equal(we.available, false); assert.equal(we.reference, 0); assert.equal(we.name, expectedName); }); } test('watch expressions', () => { assert.equal(model.getWatchExpressions().length, 0); model.addWatchExpression('console'); model.addWatchExpression('console'); let watchExpressions = model.getWatchExpressions(); assertWatchExpressions(watchExpressions, 'console'); model.renameWatchExpression(watchExpressions[0].getId(), 'new_name'); model.renameWatchExpression(watchExpressions[1].getId(), 'new_name'); assertWatchExpressions(model.getWatchExpressions(), 'new_name'); assertWatchExpressions(model.getWatchExpressions(), 'new_name'); model.addWatchExpression('mockExpression'); model.moveWatchExpression(model.getWatchExpressions()[2].getId(), 1); watchExpressions = model.getWatchExpressions(); assert.equal(watchExpressions[0].name, 'new_name'); assert.equal(watchExpressions[1].name, 'mockExpression'); assert.equal(watchExpressions[2].name, 'new_name'); model.removeWatchExpressions(); assert.equal(model.getWatchExpressions().length, 0); }); test('repl expressions', () => { const session = createMockSession(model); assert.equal(session.getReplElements().length, 0); model.addSession(session); session['raw'] = <any>rawSession; const thread = new Thread(session, 'mockthread', 1); const stackFrame = new StackFrame(thread, 1, <any>undefined, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1); const replModel = new ReplModel(); replModel.addReplExpression(session, stackFrame, 'myVariable').then(); replModel.addReplExpression(session, stackFrame, 'myVariable').then(); replModel.addReplExpression(session, stackFrame, 'myVariable').then(); assert.equal(replModel.getReplElements().length, 3); replModel.getReplElements().forEach(re => { assert.equal((<ReplEvaluationInput>re).value, 'myVariable'); }); replModel.removeReplExpressions(); assert.equal(replModel.getReplElements().length, 0); }); test('stack frame get specific source name', () => { const session = createMockSession(model); model.addSession(session); let firstStackFrame: StackFrame; let secondStackFrame: StackFrame; const thread = new class extends Thread { public getCallStack(): StackFrame[] { return [firstStackFrame, secondStackFrame]; } }(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId'); const secondSource = new Source({ name: 'internalModule.js', path: 'z/x/c/d/internalModule.js', sourceReference: 11, }, 'aDebugSessionId'); firstStackFrame = new StackFrame(thread, 1, firstSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1); secondStackFrame = new StackFrame(thread, 1, secondSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1); assert.equal(firstStackFrame.getSpecificSourceName(), '.../b/c/d/internalModule.js'); assert.equal(secondStackFrame.getSpecificSourceName(), '.../x/c/d/internalModule.js'); }); test('stack frame toString()', () => { const session = createMockSession(model); const thread = new Thread(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId'); const stackFrame = new StackFrame(thread, 1, firstSource, 'app', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1); assert.equal(stackFrame.toString(), 'app (internalModule.js:1)'); const secondSource = new Source(undefined, 'aDebugSessionId'); const stackFrame2 = new StackFrame(thread, 2, secondSource, 'module', 'normal', { startLineNumber: undefined!, startColumn: undefined!, endLineNumber: undefined!, endColumn: undefined! }, 2); assert.equal(stackFrame2.toString(), 'module'); }); test('debug child sessions are added in correct order', () => { const session = createMockSession(model); model.addSession(session); const secondSession = createMockSession(model, 'mockSession2'); model.addSession(secondSession); const firstChild = createMockSession(model, 'firstChild', { parentSession: session }); model.addSession(firstChild); const secondChild = createMockSession(model, 'secondChild', { parentSession: session }); model.addSession(secondChild); const thirdSession = createMockSession(model, 'mockSession3'); model.addSession(thirdSession); const anotherChild = createMockSession(model, 'secondChild', { parentSession: secondSession }); model.addSession(anotherChild); const sessions = model.getSessions(); assert.equal(sessions[0].getId(), session.getId()); assert.equal(sessions[1].getId(), firstChild.getId()); assert.equal(sessions[2].getId(), secondChild.getId()); assert.equal(sessions[3].getId(), secondSession.getId()); assert.equal(sessions[4].getId(), anotherChild.getId()); assert.equal(sessions[5].getId(), thirdSession.getId()); }); // Repl output test('repl output', () => { const session = createMockSession(model); const repl = new ReplModel(); repl.appendToRepl(session, 'first line\n', severity.Error); repl.appendToRepl(session, 'second line ', severity.Error); repl.appendToRepl(session, 'third line ', severity.Error); repl.appendToRepl(session, 'fourth line', severity.Error); let elements = <SimpleReplElement[]>repl.getReplElements(); assert.equal(elements.length, 2); assert.equal(elements[0].value, 'first line\n'); assert.equal(elements[0].severity, severity.Error); assert.equal(elements[1].value, 'second line third line fourth line'); assert.equal(elements[1].severity, severity.Error); repl.appendToRepl(session, '1', severity.Warning); elements = <SimpleReplElement[]>repl.getReplElements(); assert.equal(elements.length, 3); assert.equal(elements[2].value, '1'); assert.equal(elements[2].severity, severity.Warning); const keyValueObject = { 'key1': 2, 'key2': 'value' }; repl.appendToRepl(session, new RawObjectReplElement('fakeid', 'fake', keyValueObject), severity.Info); const element = <RawObjectReplElement>repl.getReplElements()[3]; assert.equal(element.value, 'Object'); assert.deepEqual(element.valueObj, keyValueObject); repl.removeReplExpressions(); assert.equal(repl.getReplElements().length, 0); repl.appendToRepl(session, '1\n', severity.Info); repl.appendToRepl(session, '2', severity.Info); repl.appendToRepl(session, '3\n4', severity.Info); repl.appendToRepl(session, '5\n', severity.Info); repl.appendToRepl(session, '6', severity.Info); elements = <SimpleReplElement[]>repl.getReplElements(); assert.equal(elements.length, 3); assert.equal(elements[0], '1\n'); assert.equal(elements[1], '23\n45\n'); assert.equal(elements[2], '6'); }); test('repl merging', () => { // 'mergeWithParent' should be ignored when there is no parent. const parent = createMockSession(model, 'parent', { repl: 'mergeWithParent' }); const child1 = createMockSession(model, 'child1', { parentSession: parent, repl: 'separate' }); const child2 = createMockSession(model, 'child2', { parentSession: parent, repl: 'mergeWithParent' }); const grandChild = createMockSession(model, 'grandChild', { parentSession: child2, repl: 'mergeWithParent' }); const child3 = createMockSession(model, 'child3', { parentSession: parent }); let parentChanges = 0; parent.onDidChangeReplElements(() => ++parentChanges); parent.appendToRepl('1\n', severity.Info); assert.equal(parentChanges, 1); assert.equal(parent.getReplElements().length, 1); assert.equal(child1.getReplElements().length, 0); assert.equal(child2.getReplElements().length, 1); assert.equal(grandChild.getReplElements().length, 1); assert.equal(child3.getReplElements().length, 0); grandChild.appendToRepl('1\n', severity.Info); assert.equal(parentChanges, 2); assert.equal(parent.getReplElements().length, 2); assert.equal(child1.getReplElements().length, 0); assert.equal(child2.getReplElements().length, 2); assert.equal(grandChild.getReplElements().length, 2); assert.equal(child3.getReplElements().length, 0); child3.appendToRepl('1\n', severity.Info); assert.equal(parentChanges, 2); assert.equal(parent.getReplElements().length, 2); assert.equal(child1.getReplElements().length, 0); assert.equal(child2.getReplElements().length, 2); assert.equal(grandChild.getReplElements().length, 2); assert.equal(child3.getReplElements().length, 1); child1.appendToRepl('1\n', severity.Info); assert.equal(parentChanges, 2); assert.equal(parent.getReplElements().length, 2); assert.equal(child1.getReplElements().length, 1); assert.equal(child2.getReplElements().length, 2); assert.equal(grandChild.getReplElements().length, 2); assert.equal(child3.getReplElements().length, 1); }); });
src/vs/workbench/contrib/debug/test/browser/debugModel.test.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0001782412000466138, 0.0001748290378600359, 0.00016979708743747324, 0.00017493547056801617, 0.000001990997816392337 ]
{ "id": 4, "code_window": [ "\t\tthis._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, e => {\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n", "\t\t\tconst keyCode = keyboardEvent.keyCode;\n", "\n", "\t\t\t// Only handle when in quick navigation mode\n", "\t\t\tif (!this.quickNavigateConfiguration || !this.keyDownSeenSinceShown) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!this.quickNavigateConfiguration) {\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 327 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as ts from 'typescript'; import * as Lint from 'tslint'; import * as fs from 'fs'; export class Rule extends Lint.Rules.AbstractRule { public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithWalker(new TranslationRemindRuleWalker(sourceFile, this.getOptions())); } } class TranslationRemindRuleWalker extends Lint.RuleWalker { private static NLS_MODULE: string = 'vs/nls'; constructor(file: ts.SourceFile, opts: Lint.IOptions) { super(file, opts); } protected visitImportDeclaration(node: ts.ImportDeclaration): void { const declaration = node.moduleSpecifier.getText(); if (declaration !== `'${TranslationRemindRuleWalker.NLS_MODULE}'`) { return; } this.visitImportLikeDeclaration(node); } protected visitImportEqualsDeclaration(node: ts.ImportEqualsDeclaration): void { const reference = node.moduleReference.getText(); if (reference !== `require('${TranslationRemindRuleWalker.NLS_MODULE}')`) { return; } this.visitImportLikeDeclaration(node); } private visitImportLikeDeclaration(node: ts.ImportDeclaration | ts.ImportEqualsDeclaration) { const currentFile = node.getSourceFile().fileName; const matchService = currentFile.match(/vs\/workbench\/services\/\w+/); const matchPart = currentFile.match(/vs\/workbench\/contrib\/\w+/); if (!matchService && !matchPart) { return; } const resource = matchService ? matchService[0] : matchPart![0]; let resourceDefined = false; let json; try { json = fs.readFileSync('./build/lib/i18n.resources.json', 'utf8'); } catch (e) { console.error('[translation-remind rule]: File with resources to pull from Transifex was not found. Aborting translation resource check for newly defined workbench part/service.'); return; } const workbenchResources = JSON.parse(json).workbench; workbenchResources.forEach((existingResource: any) => { if (existingResource.name === resource) { resourceDefined = true; return; } }); if (!resourceDefined) { this.addFailureAtNode(node, `Please add '${resource}' to ./build/lib/i18n.resources.json file to use translations here.`); } } }
build/lib/tslint/translationRemindRule.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017672272224444896, 0.00017419086361769587, 0.00017100658442359418, 0.00017397810006514192, 0.0000015739365153422114 ]
{ "id": 5, "code_window": [ "\tshow(param: any, options?: IShowOptions): void {\n", "\t\tthis.visible = true;\n", "\t\tthis.isLoosingFocus = false;\n", "\t\tthis.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined;\n", "\t\tthis.keyDownSeenSinceShown = false;\n", "\n", "\t\t// Adjust UI for quick navigate mode\n", "\t\tif (this.quickNavigateConfiguration) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 602 }
/*--------------------------------------------------------------------------------------------- * 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/quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { QUICK_INPUT_BACKGROUND, QUICK_INPUT_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerAndGetAmdImageURL } from 'vs/base/common/amd'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-dark.svg')), light: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-light.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; titleBar: HTMLElement; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; filterContainer: HTMLElement; inputBox: QuickInputBox; visibleCountContainer: HTMLElement; visibleCount: CountBadge; countContainer: HTMLElement; count: CountBadge; okContainer: HTMLElement; ok: Button; message: HTMLElement; customButtonContainer: HTMLElement; customButton: Button; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidCustom: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; keyDownSeenSinceShown: boolean; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; customButton?: boolean; }; class QuickInput extends Disposable implements IQuickInput { private _title: string | undefined; private _steps: number | undefined; private _totalSteps: number | undefined; protected visible = false; private _enabled = true; private _contextKey: string | undefined; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private readonly onDidHideEmitter = this._register(new Emitter<void>()); protected readonly visibleDisposables = this._register(new DisposableStore()); private busyDelay: TimeoutTimer | undefined; constructor( protected ui: QuickInputUI ) { super(); } get title() { return this._title; } set title(title: string | undefined) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number | undefined) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number | undefined) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string | undefined) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.add( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.keyDownSeenSinceShown = false; this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables.clear(); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = undefined; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } protected showMessageDecoration(severity: Severity) { this.ui.inputBox.showDecoration(severity); if (severity === Severity.Error) { const styles = this.ui.inputBox.stylesForType(severity); this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : ''; this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : ''; this.ui.message.style.paddingBottom = '4px'; } else { this.ui.message.style.backgroundColor = ''; this.ui.message.style.border = ''; this.ui.message.style.paddingBottom = ''; } } public dispose(): void { this.hide(); super.dispose(); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static readonly INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder: string | undefined; private readonly onDidChangeValueEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private readonly onDidChangeActiveEmitter = this._register(new Emitter<T[]>()); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private readonly onDidChangeSelectionEmitter = this._register(new Emitter<T[]>()); private readonly onDidTriggerItemButtonEmitter = this._register(new Emitter<IQuickPickItemButtonEvent<T>>()); private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _validationMessage: string | undefined; private _ok = false; private _customButton = false; private _customButtonLabel: string | undefined; private _customButtonHover: string | undefined; quickNavigate: IQuickNavigateConfiguration | undefined; get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; onDidCustom = this.onDidCustomEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } get customButton() { return this._customButton; } set customButton(showCustomButton: boolean) { this._customButton = showCustomButton; this.update(); } get customLabel() { return this._customButtonLabel; } set customLabel(label: string | undefined) { this._customButtonLabel = label; this.update(); } get customHover() { return this._customButtonHover; } set customHover(hover: string | undefined) { this._customButtonHover = hover; this.update(); } get ok() { return this._ok; } set ok(showOkButton: boolean) { this._ok = showOkButton; this.update(); } public inputHasFocus(): boolean { return this.visible ? this.ui.inputBox.hasFocus() : false; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); })); this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } })); this.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => { this.ui.keyDownSeenSinceShown = true; switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; } })); this.visibleDisposables.add(this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.onDidCustom(() => { this.onDidCustomEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } })); this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>))); this.visibleDisposables.add(this.registerQuickNavigation()); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true, message: !!this.validationMessage } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true, message: !!this.validationMessage, customButton: this.customButton, ok: this.ok }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } if (this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } else { this.ui.message.textContent = null; this.showMessageDecoration(Severity.Ignore); } this.ui.customButton.label = this.customLabel || ''; this.ui.customButton.element.title = this.customHover || ''; this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); } } class InputBox extends QuickInput implements IInputBox { private static readonly noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _placeholder: string | undefined; private _password = false; private _prompt: string | undefined; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string | undefined; private readonly onDidValueChangeEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string | undefined) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } readonly onDidChangeValue = this.onDidValueChangeEmitter.event; readonly onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); })); this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined))); this.valueSelectionUpdated = true; } super.show(); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.showMessageDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: undefined; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private ui: QuickInputUI | undefined; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: Map<string, IContextKey<boolean>> = new Map(); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts.get(id); if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts.set(id, key); } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { this.contexts.forEach(context => { if (context.get()) { context.reset(); } }); } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private getUI() { if (this.ui) { return this.ui; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; const titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); const extraContainer = dom.append(headerContainer, $('.quick-input-and-message')); const filterContainer = dom.append(extraContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count')); visibleCountContainer.setAttribute('aria-live', 'polite'); visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); const countContainer = dom.append(filterContainer, $('.quick-input-count')); countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); const okContainer = dom.append(headerContainer, $('.quick-input-action')); const ok = new Button(okContainer); attachButtonStyler(ok, this.themeService); ok.label = localize('ok', "OK"); this._register(ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const customButtonContainer = dom.append(headerContainer, $('.quick-input-action')); const customButton = new Button(customButtonContainer); attachButtonStyler(customButton, this.themeService); customButton.label = localize('custom', "Custom"); this._register(customButton.onDidClick(e => { this.onDidCustomEmitter.fire(); })); const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.getUI().ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => { inputBox.setFocus(); })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.getUI().keyDownSeenSinceShown = true; const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.codicon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.getUI().list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, titleBar, title, rightActionBar, checkAll, filterContainer, inputBox, visibleCountContainer, visibleCount, countContainer, count, okContainer, ok, message, customButtonContainer, customButton, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidCustom: this.onDidCustomEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, keyDownSeenSinceShown: false, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); return this.ui; } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { const ui = this.getUI(); return new QuickPick<T>(ui); } createInputBox(): IInputBox { const ui = this.getUI(); return new InputBox(ui); } private show(controller: QuickInput) { const ui = this.getUI(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); ui.leftActionBar.clear(); ui.title.textContent = ''; ui.rightActionBar.clear(); ui.checkAll.checked = false; // ui.inputBox.value = ''; Avoid triggering an event. ui.inputBox.placeholder = ''; ui.inputBox.password = false; ui.inputBox.showDecoration(Severity.Ignore); ui.visibleCount.setCount(0); ui.count.setCount(0); ui.message.textContent = ''; ui.progressBar.stop(); ui.list.setElements([]); ui.list.matchOnDescription = false; ui.list.matchOnDetail = false; ui.list.matchOnLabel = true; ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); ui.container.style.display = ''; this.updateLayout(); ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { const ui = this.getUI(); ui.title.style.display = visibilities.title ? '' : 'none'; ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; ui.countContainer.style.display = visibilities.count ? '' : 'none'; ui.okContainer.style.display = visibilities.ok ? '' : 'none'; ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none'; ui.message.style.display = visibilities.message ? '' : 'none'; ui.list.display(!!visibilities.list); ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { const ui = this.getUI(); this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { ui.inputBox.setAttribute('role', 'combobox'); ui.inputBox.setAttribute('aria-haspopup', 'true'); ui.inputBox.setAttribute('aria-autocomplete', 'list'); ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || ''); } else { ui.inputBox.removeAttribute('role'); ui.inputBox.removeAttribute('aria-haspopup'); ui.inputBox.removeAttribute('aria-autocomplete'); ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.getUI().leftActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } for (const item of this.getUI().rightActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } this.getUI().checkAll.disabled = !enabled; // this.getUI().inputBox.enabled = enabled; Avoid loosing focus. this.getUI().ok.enabled = enabled; this.getUI().list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.getUI().container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.getUI().inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.getUI().list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.getUI().list.isDisplayed()) { this.getUI().list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.ui.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : ''; this.ui.inputBox.style(theme); const quickInputBackground = theme.getColor(QUICK_INPUT_BACKGROUND); this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : ''; const quickInputForeground = theme.getColor(QUICK_INPUT_FOREGROUND); this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : ''; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : ''; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9768163561820984, 0.012439697980880737, 0.00016375329869333655, 0.00017261221364606172, 0.08571913093328476 ]
{ "id": 5, "code_window": [ "\tshow(param: any, options?: IShowOptions): void {\n", "\t\tthis.visible = true;\n", "\t\tthis.isLoosingFocus = false;\n", "\t\tthis.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined;\n", "\t\tthis.keyDownSeenSinceShown = false;\n", "\n", "\t\t// Adjust UI for quick navigate mode\n", "\t\tif (this.quickNavigateConfiguration) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 602 }
// A launch configuration that compiles the extension and then opens it inside a new window // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 { "version": "0.2.0", "configurations": [ { "name": "Extension", "type": "extensionHost", "request": "launch", "runtimeExecutable": "${execPath}", "args": [ "--extensionDevelopmentPath=${workspaceFolder}", "--remote=test+test" ], "outFiles": [ "${workspaceFolder}/out/**/*.js" ] } ] }
extensions/vscode-test-resolver/.vscode/launch.json
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017699641466606408, 0.0001744777400745079, 0.00017143366858363152, 0.00017500310786999762, 0.0000023011666598904412 ]
{ "id": 5, "code_window": [ "\tshow(param: any, options?: IShowOptions): void {\n", "\t\tthis.visible = true;\n", "\t\tthis.isLoosingFocus = false;\n", "\t\tthis.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined;\n", "\t\tthis.keyDownSeenSinceShown = false;\n", "\n", "\t\t// Adjust UI for quick navigate mode\n", "\t\tif (this.quickNavigateConfiguration) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 602 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import * as nls from 'vscode-nls'; import { TypeScriptVersion, TypeScriptVersionProvider } from './versionProvider'; const localize = nls.loadMessageBundle(); const useWorkspaceTsdkStorageKey = 'typescript.useWorkspaceTsdk'; interface MyQuickPickItem extends vscode.QuickPickItem { id: MessageAction; version?: TypeScriptVersion; } enum MessageAction { useLocal, useBundled, learnMore, } export class TypeScriptVersionPicker { private _currentVersion: TypeScriptVersion; public constructor( private readonly versionProvider: TypeScriptVersionProvider, private readonly workspaceState: vscode.Memento ) { this._currentVersion = this.versionProvider.defaultVersion; if (this.useWorkspaceTsdkSetting) { const localVersion = this.versionProvider.localVersion; if (localVersion) { this._currentVersion = localVersion; } } } public get useWorkspaceTsdkSetting(): boolean { return this.workspaceState.get<boolean>(useWorkspaceTsdkStorageKey, false); } public get currentVersion(): TypeScriptVersion { return this._currentVersion; } public useBundledVersion(): void { this._currentVersion = this.versionProvider.bundledVersion; } public async show(firstRun?: boolean): Promise<{ oldVersion?: TypeScriptVersion, newVersion?: TypeScriptVersion }> { const pickOptions: MyQuickPickItem[] = []; const shippedVersion = this.versionProvider.defaultVersion; pickOptions.push({ label: (!this.useWorkspaceTsdkSetting ? '• ' : '') + localize('useVSCodeVersionOption', "Use VS Code's Version"), description: shippedVersion.displayName, detail: shippedVersion.pathLabel, id: MessageAction.useBundled, }); for (const version of this.versionProvider.localVersions) { pickOptions.push({ label: (this.useWorkspaceTsdkSetting && this.currentVersion.path === version.path ? '• ' : '') + localize('useWorkspaceVersionOption', "Use Workspace Version"), description: version.displayName, detail: version.pathLabel, id: MessageAction.useLocal, version }); } pickOptions.push({ label: localize('learnMore', 'Learn More'), description: '', id: MessageAction.learnMore }); const selected = await vscode.window.showQuickPick<MyQuickPickItem>(pickOptions, { placeHolder: localize( 'selectTsVersion', "Select the TypeScript version used for JavaScript and TypeScript language features"), ignoreFocusOut: firstRun, }); if (!selected) { return { oldVersion: this.currentVersion }; } switch (selected.id) { case MessageAction.useLocal: await this.workspaceState.update(useWorkspaceTsdkStorageKey, true); if (selected.version) { const tsConfig = vscode.workspace.getConfiguration('typescript'); await tsConfig.update('tsdk', selected.version.pathLabel, false); const previousVersion = this.currentVersion; this._currentVersion = selected.version; return { oldVersion: previousVersion, newVersion: selected.version }; } return { oldVersion: this.currentVersion }; case MessageAction.useBundled: await this.workspaceState.update(useWorkspaceTsdkStorageKey, false); const previousVersion = this.currentVersion; this._currentVersion = shippedVersion; return { oldVersion: previousVersion, newVersion: shippedVersion }; case MessageAction.learnMore: vscode.env.openExternal(vscode.Uri.parse('https://go.microsoft.com/fwlink/?linkid=839919')); return { oldVersion: this.currentVersion }; default: return { oldVersion: this.currentVersion }; } } }
extensions/typescript-language-features/src/utils/versionPicker.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0009685164550319314, 0.00023455599148292094, 0.0001682391739450395, 0.0001750199735397473, 0.0002119008859153837 ]
{ "id": 5, "code_window": [ "\tshow(param: any, options?: IShowOptions): void {\n", "\t\tthis.visible = true;\n", "\t\tthis.isLoosingFocus = false;\n", "\t\tthis.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined;\n", "\t\tthis.keyDownSeenSinceShown = false;\n", "\n", "\t\t// Adjust UI for quick navigate mode\n", "\t\tif (this.quickNavigateConfiguration) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenWidget.ts", "type": "replace", "edit_start_line_idx": 602 }
{ "comments": { "blockComment": ["/*", "*/"], "lineComment": "//" }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ { "open": "{", "close": "}", "notIn": ["string", "comment"] }, { "open": "[", "close": "]", "notIn": ["string", "comment"] }, { "open": "(", "close": ")", "notIn": ["string", "comment"] }, { "open": "\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "'", "close": "'", "notIn": ["string", "comment"] } ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"] ], "folding": { "markers": { "start": "^\\s*\\/\\*\\s*#region\\b\\s*(.*?)\\s*\\*\\/", "end": "^\\s*\\/\\*\\s*#endregion\\b.*\\*\\/" } } }
extensions/scss/language-configuration.json
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017635172116570175, 0.00017324276268482208, 0.00016844527272041887, 0.00017408700659871101, 0.000003176059408360743 ]
{ "id": 6, "code_window": [ "\tonDidCustom: Event<void>;\n", "\tonDidTriggerButton: Event<IQuickInputButton>;\n", "\tignoreFocusOut: boolean;\n", "\tkeyMods: Writeable<IKeyMods>;\n", "\tkeyDownSeenSinceShown: boolean;\n", "\tisScreenReaderOptimized(): boolean;\n", "\tshow(controller: QuickInput): void;\n", "\tsetVisibilities(visibilities: Visibilities): void;\n", "\tsetComboboxAccessibility(enabled: boolean): void;\n", "\tsetEnabled(enabled: boolean): void;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 86 }
/*--------------------------------------------------------------------------------------------- * 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/quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { QUICK_INPUT_BACKGROUND, QUICK_INPUT_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerAndGetAmdImageURL } from 'vs/base/common/amd'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-dark.svg')), light: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-light.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; titleBar: HTMLElement; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; filterContainer: HTMLElement; inputBox: QuickInputBox; visibleCountContainer: HTMLElement; visibleCount: CountBadge; countContainer: HTMLElement; count: CountBadge; okContainer: HTMLElement; ok: Button; message: HTMLElement; customButtonContainer: HTMLElement; customButton: Button; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidCustom: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; keyDownSeenSinceShown: boolean; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; customButton?: boolean; }; class QuickInput extends Disposable implements IQuickInput { private _title: string | undefined; private _steps: number | undefined; private _totalSteps: number | undefined; protected visible = false; private _enabled = true; private _contextKey: string | undefined; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private readonly onDidHideEmitter = this._register(new Emitter<void>()); protected readonly visibleDisposables = this._register(new DisposableStore()); private busyDelay: TimeoutTimer | undefined; constructor( protected ui: QuickInputUI ) { super(); } get title() { return this._title; } set title(title: string | undefined) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number | undefined) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number | undefined) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string | undefined) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.add( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.keyDownSeenSinceShown = false; this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables.clear(); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = undefined; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } protected showMessageDecoration(severity: Severity) { this.ui.inputBox.showDecoration(severity); if (severity === Severity.Error) { const styles = this.ui.inputBox.stylesForType(severity); this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : ''; this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : ''; this.ui.message.style.paddingBottom = '4px'; } else { this.ui.message.style.backgroundColor = ''; this.ui.message.style.border = ''; this.ui.message.style.paddingBottom = ''; } } public dispose(): void { this.hide(); super.dispose(); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static readonly INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder: string | undefined; private readonly onDidChangeValueEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private readonly onDidChangeActiveEmitter = this._register(new Emitter<T[]>()); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private readonly onDidChangeSelectionEmitter = this._register(new Emitter<T[]>()); private readonly onDidTriggerItemButtonEmitter = this._register(new Emitter<IQuickPickItemButtonEvent<T>>()); private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _validationMessage: string | undefined; private _ok = false; private _customButton = false; private _customButtonLabel: string | undefined; private _customButtonHover: string | undefined; quickNavigate: IQuickNavigateConfiguration | undefined; get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; onDidCustom = this.onDidCustomEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } get customButton() { return this._customButton; } set customButton(showCustomButton: boolean) { this._customButton = showCustomButton; this.update(); } get customLabel() { return this._customButtonLabel; } set customLabel(label: string | undefined) { this._customButtonLabel = label; this.update(); } get customHover() { return this._customButtonHover; } set customHover(hover: string | undefined) { this._customButtonHover = hover; this.update(); } get ok() { return this._ok; } set ok(showOkButton: boolean) { this._ok = showOkButton; this.update(); } public inputHasFocus(): boolean { return this.visible ? this.ui.inputBox.hasFocus() : false; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); })); this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } })); this.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => { this.ui.keyDownSeenSinceShown = true; switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; } })); this.visibleDisposables.add(this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.onDidCustom(() => { this.onDidCustomEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } })); this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>))); this.visibleDisposables.add(this.registerQuickNavigation()); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true, message: !!this.validationMessage } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true, message: !!this.validationMessage, customButton: this.customButton, ok: this.ok }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } if (this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } else { this.ui.message.textContent = null; this.showMessageDecoration(Severity.Ignore); } this.ui.customButton.label = this.customLabel || ''; this.ui.customButton.element.title = this.customHover || ''; this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); } } class InputBox extends QuickInput implements IInputBox { private static readonly noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _placeholder: string | undefined; private _password = false; private _prompt: string | undefined; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string | undefined; private readonly onDidValueChangeEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string | undefined) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } readonly onDidChangeValue = this.onDidValueChangeEmitter.event; readonly onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); })); this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined))); this.valueSelectionUpdated = true; } super.show(); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.showMessageDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: undefined; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private ui: QuickInputUI | undefined; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: Map<string, IContextKey<boolean>> = new Map(); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts.get(id); if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts.set(id, key); } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { this.contexts.forEach(context => { if (context.get()) { context.reset(); } }); } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private getUI() { if (this.ui) { return this.ui; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; const titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); const extraContainer = dom.append(headerContainer, $('.quick-input-and-message')); const filterContainer = dom.append(extraContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count')); visibleCountContainer.setAttribute('aria-live', 'polite'); visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); const countContainer = dom.append(filterContainer, $('.quick-input-count')); countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); const okContainer = dom.append(headerContainer, $('.quick-input-action')); const ok = new Button(okContainer); attachButtonStyler(ok, this.themeService); ok.label = localize('ok', "OK"); this._register(ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const customButtonContainer = dom.append(headerContainer, $('.quick-input-action')); const customButton = new Button(customButtonContainer); attachButtonStyler(customButton, this.themeService); customButton.label = localize('custom', "Custom"); this._register(customButton.onDidClick(e => { this.onDidCustomEmitter.fire(); })); const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.getUI().ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => { inputBox.setFocus(); })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.getUI().keyDownSeenSinceShown = true; const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.codicon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.getUI().list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, titleBar, title, rightActionBar, checkAll, filterContainer, inputBox, visibleCountContainer, visibleCount, countContainer, count, okContainer, ok, message, customButtonContainer, customButton, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidCustom: this.onDidCustomEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, keyDownSeenSinceShown: false, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); return this.ui; } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { const ui = this.getUI(); return new QuickPick<T>(ui); } createInputBox(): IInputBox { const ui = this.getUI(); return new InputBox(ui); } private show(controller: QuickInput) { const ui = this.getUI(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); ui.leftActionBar.clear(); ui.title.textContent = ''; ui.rightActionBar.clear(); ui.checkAll.checked = false; // ui.inputBox.value = ''; Avoid triggering an event. ui.inputBox.placeholder = ''; ui.inputBox.password = false; ui.inputBox.showDecoration(Severity.Ignore); ui.visibleCount.setCount(0); ui.count.setCount(0); ui.message.textContent = ''; ui.progressBar.stop(); ui.list.setElements([]); ui.list.matchOnDescription = false; ui.list.matchOnDetail = false; ui.list.matchOnLabel = true; ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); ui.container.style.display = ''; this.updateLayout(); ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { const ui = this.getUI(); ui.title.style.display = visibilities.title ? '' : 'none'; ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; ui.countContainer.style.display = visibilities.count ? '' : 'none'; ui.okContainer.style.display = visibilities.ok ? '' : 'none'; ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none'; ui.message.style.display = visibilities.message ? '' : 'none'; ui.list.display(!!visibilities.list); ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { const ui = this.getUI(); this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { ui.inputBox.setAttribute('role', 'combobox'); ui.inputBox.setAttribute('aria-haspopup', 'true'); ui.inputBox.setAttribute('aria-autocomplete', 'list'); ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || ''); } else { ui.inputBox.removeAttribute('role'); ui.inputBox.removeAttribute('aria-haspopup'); ui.inputBox.removeAttribute('aria-autocomplete'); ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.getUI().leftActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } for (const item of this.getUI().rightActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } this.getUI().checkAll.disabled = !enabled; // this.getUI().inputBox.enabled = enabled; Avoid loosing focus. this.getUI().ok.enabled = enabled; this.getUI().list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.getUI().container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.getUI().inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.getUI().list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.getUI().list.isDisplayed()) { this.getUI().list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.ui.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : ''; this.ui.inputBox.style(theme); const quickInputBackground = theme.getColor(QUICK_INPUT_BACKGROUND); this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : ''; const quickInputForeground = theme.getColor(QUICK_INPUT_FOREGROUND); this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : ''; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : ''; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9990746974945068, 0.09541488438844681, 0.00016307891928590834, 0.00017502957780379802, 0.2743259370326996 ]
{ "id": 6, "code_window": [ "\tonDidCustom: Event<void>;\n", "\tonDidTriggerButton: Event<IQuickInputButton>;\n", "\tignoreFocusOut: boolean;\n", "\tkeyMods: Writeable<IKeyMods>;\n", "\tkeyDownSeenSinceShown: boolean;\n", "\tisScreenReaderOptimized(): boolean;\n", "\tshow(controller: QuickInput): void;\n", "\tsetVisibilities(visibilities: Visibilities): void;\n", "\tsetComboboxAccessibility(enabled: boolean): void;\n", "\tsetEnabled(enabled: boolean): void;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 86 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as sinon from 'sinon'; import { IExtensionManagementService, DidUninstallExtensionEvent, ILocalExtension, DidInstallExtensionEvent } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IExtensionEnablementService, EnablementState, IExtensionManagementServerService } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { ExtensionEnablementService } from 'vs/workbench/services/extensionManagement/common/extensionEnablementService'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { Emitter } from 'vs/base/common/event'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IStorageService, InMemoryStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IExtensionContributions, ExtensionType, IExtension } from 'vs/platform/extensions/common/extensions'; import { isUndefinedOrNull } from 'vs/base/common/types'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { URI } from 'vs/base/common/uri'; import { Schemas } from 'vs/base/common/network'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { assign } from 'vs/base/common/objects'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { productService } from 'vs/workbench/test/workbenchTestServices'; function storageService(instantiationService: TestInstantiationService): IStorageService { let service = instantiationService.get(IStorageService); if (!service) { let workspaceContextService = instantiationService.get(IWorkspaceContextService); if (!workspaceContextService) { workspaceContextService = instantiationService.stub(IWorkspaceContextService, <IWorkspaceContextService>{ getWorkbenchState: () => WorkbenchState.FOLDER, }); } service = instantiationService.stub(IStorageService, new InMemoryStorageService()); } return service; } export class TestExtensionEnablementService extends ExtensionEnablementService { constructor(instantiationService: TestInstantiationService) { const extensionManagementService = instantiationService.get(IExtensionManagementService) || instantiationService.stub(IExtensionManagementService, { onDidInstallExtension: new Emitter<DidInstallExtensionEvent>().event, onDidUninstallExtension: new Emitter<DidUninstallExtensionEvent>().event } as IExtensionManagementService); const extensionManagementServerService = instantiationService.get(IExtensionManagementServerService) || instantiationService.stub(IExtensionManagementServerService, <IExtensionManagementServerService>{ localExtensionManagementServer: { extensionManagementService } }); super( storageService(instantiationService), instantiationService.get(IWorkspaceContextService), instantiationService.get(IWorkbenchEnvironmentService) || instantiationService.stub(IWorkbenchEnvironmentService, { configuration: Object.create(null) } as IWorkbenchEnvironmentService), extensionManagementService, instantiationService.get(IConfigurationService), extensionManagementServerService, productService ); } public reset(): void { let extensions = this._getDisabledExtensions(StorageScope.GLOBAL); for (const e of this._getDisabledExtensions(StorageScope.WORKSPACE)) { if (!extensions.some(r => areSameExtensions(r, e))) { extensions.push(e); } } const workspaceEnabledExtensions = this._getEnabledExtensions(StorageScope.WORKSPACE); if (workspaceEnabledExtensions.length) { extensions = extensions.filter(r => !workspaceEnabledExtensions.some(e => areSameExtensions(e, r))); } extensions.forEach(d => this.setEnablement([aLocalExtension(d.id)], EnablementState.EnabledGlobally)); } } suite('ExtensionEnablementService Test', () => { let instantiationService: TestInstantiationService; let testObject: IExtensionEnablementService; const didUninstallEvent = new Emitter<DidUninstallExtensionEvent>(); setup(() => { instantiationService = new TestInstantiationService(); instantiationService.stub(IConfigurationService, new TestConfigurationService()); instantiationService.stub(IExtensionManagementService, { onDidUninstallExtension: didUninstallEvent.event, getInstalled: () => Promise.resolve([] as ILocalExtension[]) } as IExtensionManagementService); instantiationService.stub(IExtensionManagementServerService, <IExtensionManagementServerService>{ localExtensionManagementServer: { extensionManagementService: instantiationService.get(IExtensionManagementService) } }); testObject = new TestExtensionEnablementService(instantiationService); }); teardown(() => { (<ExtensionEnablementService>testObject).dispose(); }); test('test disable an extension globally', async () => { const extension = aLocalExtension('pub.a'); await testObject.setEnablement([extension], EnablementState.DisabledGlobally); assert.ok(!testObject.isEnabled(extension)); assert.equal(testObject.getEnablementState(extension), EnablementState.DisabledGlobally); }); test('test disable an extension globally should return truthy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(value => assert.ok(value)); }); test('test disable an extension globally triggers the change event', () => { const target = sinon.spy(); testObject.onEnablementChanged(target); return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => { assert.ok(target.calledOnce); assert.deepEqual((<IExtension>target.args[0][0][0]).identifier, { id: 'pub.a' }); }); }); test('test disable an extension globally again should return a falsy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally)) .then(value => assert.ok(!value[0])); }); test('test state of globally disabled extension', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.DisabledGlobally)); }); test('test state of globally enabled extension', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledGlobally)) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.EnabledGlobally)); }); test('test disable an extension for workspace', async () => { const extension = aLocalExtension('pub.a'); await testObject.setEnablement([extension], EnablementState.DisabledWorkspace); assert.ok(!testObject.isEnabled(extension)); assert.equal(testObject.getEnablementState(extension), EnablementState.DisabledWorkspace); }); test('test disable an extension for workspace returns a truthy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(value => assert.ok(value)); }); test('test disable an extension for workspace again should return a falsy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace)) .then(value => assert.ok(!value[0])); }); test('test state of workspace disabled extension', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.DisabledWorkspace)); }); test('test state of workspace and globally disabled extension', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace)) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.DisabledWorkspace)); }); test('test state of workspace enabled extension', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledWorkspace)) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.EnabledWorkspace)); }); test('test state of globally disabled and workspace enabled extension', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace)) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledWorkspace)) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.EnabledWorkspace)); }); test('test state of an extension when disabled for workspace from workspace enabled', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledWorkspace)) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace)) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.DisabledWorkspace)); }); test('test state of an extension when disabled globally from workspace enabled', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledWorkspace)) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally)) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.DisabledGlobally)); }); test('test state of an extension when disabled globally from workspace disabled', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally)) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.DisabledGlobally)); }); test('test state of an extension when enabled globally from workspace enabled', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledWorkspace)) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledGlobally)) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.EnabledGlobally)); }); test('test state of an extension when enabled globally from workspace disabled', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledGlobally)) .then(() => assert.equal(testObject.getEnablementState(aLocalExtension('pub.a')), EnablementState.EnabledGlobally)); }); test('test disable an extension for workspace and then globally', async () => { const extension = aLocalExtension('pub.a'); await testObject.setEnablement([extension], EnablementState.DisabledWorkspace); await testObject.setEnablement([extension], EnablementState.DisabledGlobally); assert.ok(!testObject.isEnabled(extension)); assert.equal(testObject.getEnablementState(extension), EnablementState.DisabledGlobally); }); test('test disable an extension for workspace and then globally return a truthy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally)) .then(value => assert.ok(value)); }); test('test disable an extension for workspace and then globally trigger the change event', () => { const target = sinon.spy(); return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.onEnablementChanged(target)) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally)) .then(() => { assert.ok(target.calledOnce); assert.deepEqual((<IExtension>target.args[0][0][0]).identifier, { id: 'pub.a' }); }); }); test('test disable an extension globally and then for workspace', async () => { const extension = aLocalExtension('pub.a'); await testObject.setEnablement([extension], EnablementState.DisabledGlobally); await testObject.setEnablement([extension], EnablementState.DisabledWorkspace); assert.ok(!testObject.isEnabled(extension)); assert.equal(testObject.getEnablementState(extension), EnablementState.DisabledWorkspace); }); test('test disable an extension globally and then for workspace return a truthy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace)) .then(value => assert.ok(value)); }); test('test disable an extension globally and then for workspace triggers the change event', () => { const target = sinon.spy(); return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => testObject.onEnablementChanged(target)) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace)) .then(() => { assert.ok(target.calledOnce); assert.deepEqual((<IExtension>target.args[0][0][0]).identifier, { id: 'pub.a' }); }); }); test('test disable an extension for workspace when there is no workspace throws error', () => { instantiationService.stub(IWorkspaceContextService, 'getWorkbenchState', WorkbenchState.EMPTY); return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => assert.fail('should throw an error'), error => assert.ok(error)); }); test('test enable an extension globally', async () => { const extension = aLocalExtension('pub.a'); await testObject.setEnablement([extension], EnablementState.DisabledGlobally); await testObject.setEnablement([extension], EnablementState.EnabledGlobally); assert.ok(testObject.isEnabled(extension)); assert.equal(testObject.getEnablementState(extension), EnablementState.EnabledGlobally); }); test('test enable an extension globally return truthy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledGlobally)) .then(value => assert.ok(value)); }); test('test enable an extension globally triggers change event', () => { const target = sinon.spy(); return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => testObject.onEnablementChanged(target)) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledGlobally)) .then(() => { assert.ok(target.calledOnce); assert.deepEqual((<IExtension>target.args[0][0][0]).identifier, { id: 'pub.a' }); }); }); test('test enable an extension globally when already enabled return falsy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledGlobally) .then(value => assert.ok(!value[0])); }); test('test enable an extension for workspace', async () => { const extension = aLocalExtension('pub.a'); await testObject.setEnablement([extension], EnablementState.DisabledWorkspace); await testObject.setEnablement([extension], EnablementState.EnabledWorkspace); assert.ok(testObject.isEnabled(extension)); assert.equal(testObject.getEnablementState(extension), EnablementState.EnabledWorkspace); }); test('test enable an extension for workspace return truthy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledWorkspace)) .then(value => assert.ok(value)); }); test('test enable an extension for workspace triggers change event', () => { const target = sinon.spy(); return testObject.setEnablement([aLocalExtension('pub.b')], EnablementState.DisabledWorkspace) .then(() => testObject.onEnablementChanged(target)) .then(() => testObject.setEnablement([aLocalExtension('pub.b')], EnablementState.EnabledWorkspace)) .then(() => { assert.ok(target.calledOnce); assert.deepEqual((<IExtension>target.args[0][0][0]).identifier, { id: 'pub.b' }); }); }); test('test enable an extension for workspace when already enabled return truthy promise', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.EnabledWorkspace) .then(value => assert.ok(value)); }); test('test enable an extension for workspace when disabled in workspace and gloablly', async () => { const extension = aLocalExtension('pub.a'); await testObject.setEnablement([extension], EnablementState.DisabledWorkspace); await testObject.setEnablement([extension], EnablementState.DisabledGlobally); await testObject.setEnablement([extension], EnablementState.EnabledWorkspace); assert.ok(testObject.isEnabled(extension)); assert.equal(testObject.getEnablementState(extension), EnablementState.EnabledWorkspace); }); test('test enable an extension globally when disabled in workspace and gloablly', async () => { const extension = aLocalExtension('pub.a'); await testObject.setEnablement([extension], EnablementState.EnabledWorkspace); await testObject.setEnablement([extension], EnablementState.DisabledWorkspace); await testObject.setEnablement([extension], EnablementState.DisabledGlobally); await testObject.setEnablement([extension], EnablementState.EnabledGlobally); assert.ok(testObject.isEnabled(extension)); assert.equal(testObject.getEnablementState(extension), EnablementState.EnabledGlobally); }); test('test remove an extension from disablement list when uninstalled', async () => { const extension = aLocalExtension('pub.a'); await testObject.setEnablement([extension], EnablementState.DisabledWorkspace); await testObject.setEnablement([extension], EnablementState.DisabledGlobally); didUninstallEvent.fire({ identifier: { id: 'pub.a' } }); assert.ok(testObject.isEnabled(extension)); assert.equal(testObject.getEnablementState(extension), EnablementState.EnabledGlobally); }); test('test isEnabled return false extension is disabled globally', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledGlobally) .then(() => assert.ok(!testObject.isEnabled(aLocalExtension('pub.a')))); }); test('test isEnabled return false extension is disabled in workspace', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => assert.ok(!testObject.isEnabled(aLocalExtension('pub.a')))); }); test('test isEnabled return true extension is not disabled', () => { return testObject.setEnablement([aLocalExtension('pub.a')], EnablementState.DisabledWorkspace) .then(() => testObject.setEnablement([aLocalExtension('pub.c')], EnablementState.DisabledGlobally)) .then(() => assert.ok(testObject.isEnabled(aLocalExtension('pub.b')))); }); test('test canChangeEnablement return false for language packs', () => { assert.equal(testObject.canChangeEnablement(aLocalExtension('pub.a', { localizations: [{ languageId: 'gr', translations: [{ id: 'vscode', path: 'path' }] }] })), false); }); test('test canChangeEnablement return false when extensions are disabled in environment', () => { instantiationService.stub(IWorkbenchEnvironmentService, { disableExtensions: true } as IWorkbenchEnvironmentService); testObject = new TestExtensionEnablementService(instantiationService); assert.equal(testObject.canChangeEnablement(aLocalExtension('pub.a')), false); }); test('test canChangeEnablement return false when the extension is disabled in environment', () => { instantiationService.stub(IWorkbenchEnvironmentService, { disableExtensions: ['pub.a'] } as IWorkbenchEnvironmentService); testObject = new TestExtensionEnablementService(instantiationService); assert.equal(testObject.canChangeEnablement(aLocalExtension('pub.a')), false); }); test('test canChangeEnablement return true for system extensions when extensions are disabled in environment', () => { instantiationService.stub(IWorkbenchEnvironmentService, { disableExtensions: true } as IWorkbenchEnvironmentService); testObject = new TestExtensionEnablementService(instantiationService); const extension = aLocalExtension('pub.a', undefined, ExtensionType.System); assert.equal(testObject.canChangeEnablement(extension), true); }); test('test canChangeEnablement return false for system extension when extension is disabled in environment', () => { instantiationService.stub(IWorkbenchEnvironmentService, { disableExtensions: ['pub.a'] } as IWorkbenchEnvironmentService); testObject = new TestExtensionEnablementService(instantiationService); const extension = aLocalExtension('pub.a', undefined, ExtensionType.System); assert.ok(!testObject.canChangeEnablement(extension)); }); test('test extension is disabled when disabled in enviroment', async () => { const extension = aLocalExtension('pub.a'); instantiationService.stub(IWorkbenchEnvironmentService, { disableExtensions: ['pub.a'] } as IWorkbenchEnvironmentService); instantiationService.stub(IExtensionManagementService, { onDidUninstallExtension: didUninstallEvent.event, getInstalled: () => Promise.resolve([extension, aLocalExtension('pub.b')]) } as IExtensionManagementService); testObject = new TestExtensionEnablementService(instantiationService); assert.ok(!testObject.isEnabled(extension)); assert.deepEqual(testObject.getEnablementState(extension), EnablementState.DisabledByEnvironemt); }); test('test local workspace extension is disabled by kind', async () => { instantiationService.stub(IExtensionManagementServerService, aMultiExtensionManagementServerService(instantiationService)); const localWorkspaceExtension = aLocalExtension2('pub.a', { extensionKind: 'workspace' }, { location: URI.file(`pub.a`) }); testObject = new TestExtensionEnablementService(instantiationService); assert.ok(!testObject.isEnabled(localWorkspaceExtension)); assert.deepEqual(testObject.getEnablementState(localWorkspaceExtension), EnablementState.DisabledByExtensionKind); }); test('test local ui extension is not disabled by kind', async () => { instantiationService.stub(IExtensionManagementServerService, aMultiExtensionManagementServerService(instantiationService)); const localWorkspaceExtension = aLocalExtension2('pub.a', { extensionKind: 'ui' }, { location: URI.file(`pub.a`) }); testObject = new TestExtensionEnablementService(instantiationService); assert.ok(testObject.isEnabled(localWorkspaceExtension)); assert.deepEqual(testObject.getEnablementState(localWorkspaceExtension), EnablementState.EnabledGlobally); }); test('test canChangeEnablement return false when the local workspace extension is disabled by kind', () => { instantiationService.stub(IExtensionManagementServerService, aMultiExtensionManagementServerService(instantiationService)); const localWorkspaceExtension = aLocalExtension2('pub.a', { extensionKind: 'workspace' }, { location: URI.file(`pub.a`) }); testObject = new TestExtensionEnablementService(instantiationService); assert.equal(testObject.canChangeEnablement(localWorkspaceExtension), false); }); test('test canChangeEnablement return true for local ui extension', () => { instantiationService.stub(IExtensionManagementServerService, aMultiExtensionManagementServerService(instantiationService)); const localWorkspaceExtension = aLocalExtension2('pub.a', { extensionKind: 'ui' }, { location: URI.file(`pub.a`) }); testObject = new TestExtensionEnablementService(instantiationService); assert.equal(testObject.canChangeEnablement(localWorkspaceExtension), true); }); test('test remote ui extension is disabled by kind', async () => { instantiationService.stub(IExtensionManagementServerService, aMultiExtensionManagementServerService(instantiationService)); const localWorkspaceExtension = aLocalExtension2('pub.a', { extensionKind: 'ui' }, { location: URI.file(`pub.a`).with({ scheme: Schemas.vscodeRemote }) }); testObject = new TestExtensionEnablementService(instantiationService); assert.ok(testObject.isEnabled(localWorkspaceExtension)); assert.deepEqual(testObject.getEnablementState(localWorkspaceExtension), EnablementState.EnabledGlobally); }); test('test remote workspace extension is not disabled by kind', async () => { instantiationService.stub(IExtensionManagementServerService, aMultiExtensionManagementServerService(instantiationService)); const localWorkspaceExtension = aLocalExtension2('pub.a', { extensionKind: 'workspace' }, { location: URI.file(`pub.a`).with({ scheme: Schemas.vscodeRemote }) }); testObject = new TestExtensionEnablementService(instantiationService); assert.ok(testObject.isEnabled(localWorkspaceExtension)); assert.deepEqual(testObject.getEnablementState(localWorkspaceExtension), EnablementState.EnabledGlobally); }); test('test canChangeEnablement return false when the remote ui extension is disabled by kind', () => { instantiationService.stub(IExtensionManagementServerService, aMultiExtensionManagementServerService(instantiationService)); const localWorkspaceExtension = aLocalExtension2('pub.a', { extensionKind: 'ui' }, { location: URI.file(`pub.a`).with({ scheme: Schemas.vscodeRemote }) }); testObject = new TestExtensionEnablementService(instantiationService); assert.equal(testObject.canChangeEnablement(localWorkspaceExtension), true); }); test('test canChangeEnablement return true for remote workspace extension', () => { instantiationService.stub(IExtensionManagementServerService, aMultiExtensionManagementServerService(instantiationService)); const localWorkspaceExtension = aLocalExtension2('pub.a', { extensionKind: 'workspace' }, { location: URI.file(`pub.a`).with({ scheme: Schemas.vscodeRemote }) }); testObject = new TestExtensionEnablementService(instantiationService); assert.equal(testObject.canChangeEnablement(localWorkspaceExtension), true); }); }); function aMultiExtensionManagementServerService(instantiationService: TestInstantiationService): IExtensionManagementServerService { const localExtensionManagementServer = { authority: 'vscode-local', label: 'local', extensionManagementService: instantiationService.get(IExtensionManagementService) }; const remoteExtensionManagementServer = { authority: 'vscode-remote', label: 'remote', extensionManagementService: instantiationService.get(IExtensionManagementService) }; return { _serviceBrand: undefined, localExtensionManagementServer, remoteExtensionManagementServer, getExtensionManagementServer: (location: URI) => { if (location.scheme === Schemas.file) { return localExtensionManagementServer; } if (location.scheme === REMOTE_HOST_SCHEME) { return remoteExtensionManagementServer; } return null; } }; } function aLocalExtension(id: string, contributes?: IExtensionContributions, type?: ExtensionType): ILocalExtension { return aLocalExtension2(id, contributes ? { contributes } : {}, isUndefinedOrNull(type) ? {} : { type }); } function aLocalExtension2(id: string, manifest: any = {}, properties: any = {}): ILocalExtension { const [publisher, name] = id.split('.'); properties = assign({ identifier: { id }, galleryIdentifier: { id, uuid: undefined }, type: ExtensionType.User }, properties); manifest = assign({ name, publisher }, manifest); return <ILocalExtension>Object.create({ manifest, ...properties }); }
src/vs/workbench/services/extensionManagement/test/electron-browser/extensionEnablementService.test.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017724029021337628, 0.00017334948643110693, 0.00016496553143952042, 0.00017371399735566229, 0.000002377503051320673 ]
{ "id": 6, "code_window": [ "\tonDidCustom: Event<void>;\n", "\tonDidTriggerButton: Event<IQuickInputButton>;\n", "\tignoreFocusOut: boolean;\n", "\tkeyMods: Writeable<IKeyMods>;\n", "\tkeyDownSeenSinceShown: boolean;\n", "\tisScreenReaderOptimized(): boolean;\n", "\tshow(controller: QuickInput): void;\n", "\tsetVisibilities(visibilities: Visibilities): void;\n", "\tsetComboboxAccessibility(enabled: boolean): void;\n", "\tsetEnabled(enabled: boolean): void;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 86 }
{ "registrations": [], "version": 1 }
extensions/git-ui/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017335361917503178, 0.00017335361917503178, 0.00017335361917503178, 0.00017335361917503178, 0 ]
{ "id": 6, "code_window": [ "\tonDidCustom: Event<void>;\n", "\tonDidTriggerButton: Event<IQuickInputButton>;\n", "\tignoreFocusOut: boolean;\n", "\tkeyMods: Writeable<IKeyMods>;\n", "\tkeyDownSeenSinceShown: boolean;\n", "\tisScreenReaderOptimized(): boolean;\n", "\tshow(controller: QuickInput): void;\n", "\tsetVisibilities(visibilities: Visibilities): void;\n", "\tsetComboboxAccessibility(enabled: boolean): void;\n", "\tsetEnabled(enabled: boolean): void;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 86 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const cp = require('child_process'); const fs = require('fs'); const path = require('path'); /** * @param {string} location */ function updateGrammar(location) { const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; const result = cp.spawnSync(npm, ['run', 'update-grammar'], { cwd: location, stdio: 'inherit' }); if (result.error || result.status !== 0) { process.exit(1); } } const allExtensionFolders = fs.readdirSync('extensions'); const extensions = allExtensionFolders.filter(e => { try { let packageJSON = JSON.parse(fs.readFileSync(path.join('extensions', e, 'package.json')).toString()); return packageJSON && packageJSON.scripts && packageJSON.scripts['update-grammar']; } catch (e) { return false; } }); console.log(`Updating ${extensions.length} grammars...`); extensions.forEach(extension => updateGrammar(`extensions/${extension}`)); // run integration tests if (process.platform === 'win32') { cp.spawn('.\\scripts\\test-integration.bat', [], { env: process.env, stdio: 'inherit' }); } else { cp.spawn('/bin/bash', ['./scripts/test-integration.sh'], { env: process.env, stdio: 'inherit' }); }
build/npm/update-all-grammars.js
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017834678874351084, 0.0001749226648826152, 0.00017049470625352114, 0.00017449060396756977, 0.0000028321110221440904 ]
{ "id": 7, "code_window": [ "\t\t\t\t\tthis.onDidTriggerButtonEmitter.fire(button);\n", "\t\t\t\t}\n", "\t\t\t}),\n", "\t\t);\n", "\t\tthis.ui.keyDownSeenSinceShown = false;\n", "\t\tthis.ui.show(this);\n", "\t\tthis.visible = true;\n", "\t\tthis.update();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * 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/quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { QUICK_INPUT_BACKGROUND, QUICK_INPUT_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerAndGetAmdImageURL } from 'vs/base/common/amd'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-dark.svg')), light: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-light.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; titleBar: HTMLElement; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; filterContainer: HTMLElement; inputBox: QuickInputBox; visibleCountContainer: HTMLElement; visibleCount: CountBadge; countContainer: HTMLElement; count: CountBadge; okContainer: HTMLElement; ok: Button; message: HTMLElement; customButtonContainer: HTMLElement; customButton: Button; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidCustom: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; keyDownSeenSinceShown: boolean; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; customButton?: boolean; }; class QuickInput extends Disposable implements IQuickInput { private _title: string | undefined; private _steps: number | undefined; private _totalSteps: number | undefined; protected visible = false; private _enabled = true; private _contextKey: string | undefined; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private readonly onDidHideEmitter = this._register(new Emitter<void>()); protected readonly visibleDisposables = this._register(new DisposableStore()); private busyDelay: TimeoutTimer | undefined; constructor( protected ui: QuickInputUI ) { super(); } get title() { return this._title; } set title(title: string | undefined) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number | undefined) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number | undefined) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string | undefined) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.add( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.keyDownSeenSinceShown = false; this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables.clear(); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = undefined; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } protected showMessageDecoration(severity: Severity) { this.ui.inputBox.showDecoration(severity); if (severity === Severity.Error) { const styles = this.ui.inputBox.stylesForType(severity); this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : ''; this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : ''; this.ui.message.style.paddingBottom = '4px'; } else { this.ui.message.style.backgroundColor = ''; this.ui.message.style.border = ''; this.ui.message.style.paddingBottom = ''; } } public dispose(): void { this.hide(); super.dispose(); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static readonly INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder: string | undefined; private readonly onDidChangeValueEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private readonly onDidChangeActiveEmitter = this._register(new Emitter<T[]>()); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private readonly onDidChangeSelectionEmitter = this._register(new Emitter<T[]>()); private readonly onDidTriggerItemButtonEmitter = this._register(new Emitter<IQuickPickItemButtonEvent<T>>()); private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _validationMessage: string | undefined; private _ok = false; private _customButton = false; private _customButtonLabel: string | undefined; private _customButtonHover: string | undefined; quickNavigate: IQuickNavigateConfiguration | undefined; get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; onDidCustom = this.onDidCustomEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } get customButton() { return this._customButton; } set customButton(showCustomButton: boolean) { this._customButton = showCustomButton; this.update(); } get customLabel() { return this._customButtonLabel; } set customLabel(label: string | undefined) { this._customButtonLabel = label; this.update(); } get customHover() { return this._customButtonHover; } set customHover(hover: string | undefined) { this._customButtonHover = hover; this.update(); } get ok() { return this._ok; } set ok(showOkButton: boolean) { this._ok = showOkButton; this.update(); } public inputHasFocus(): boolean { return this.visible ? this.ui.inputBox.hasFocus() : false; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); })); this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } })); this.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => { this.ui.keyDownSeenSinceShown = true; switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; } })); this.visibleDisposables.add(this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.onDidCustom(() => { this.onDidCustomEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } })); this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>))); this.visibleDisposables.add(this.registerQuickNavigation()); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true, message: !!this.validationMessage } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true, message: !!this.validationMessage, customButton: this.customButton, ok: this.ok }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } if (this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } else { this.ui.message.textContent = null; this.showMessageDecoration(Severity.Ignore); } this.ui.customButton.label = this.customLabel || ''; this.ui.customButton.element.title = this.customHover || ''; this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); } } class InputBox extends QuickInput implements IInputBox { private static readonly noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _placeholder: string | undefined; private _password = false; private _prompt: string | undefined; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string | undefined; private readonly onDidValueChangeEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string | undefined) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } readonly onDidChangeValue = this.onDidValueChangeEmitter.event; readonly onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); })); this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined))); this.valueSelectionUpdated = true; } super.show(); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.showMessageDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: undefined; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private ui: QuickInputUI | undefined; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: Map<string, IContextKey<boolean>> = new Map(); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts.get(id); if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts.set(id, key); } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { this.contexts.forEach(context => { if (context.get()) { context.reset(); } }); } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private getUI() { if (this.ui) { return this.ui; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; const titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); const extraContainer = dom.append(headerContainer, $('.quick-input-and-message')); const filterContainer = dom.append(extraContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count')); visibleCountContainer.setAttribute('aria-live', 'polite'); visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); const countContainer = dom.append(filterContainer, $('.quick-input-count')); countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); const okContainer = dom.append(headerContainer, $('.quick-input-action')); const ok = new Button(okContainer); attachButtonStyler(ok, this.themeService); ok.label = localize('ok', "OK"); this._register(ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const customButtonContainer = dom.append(headerContainer, $('.quick-input-action')); const customButton = new Button(customButtonContainer); attachButtonStyler(customButton, this.themeService); customButton.label = localize('custom', "Custom"); this._register(customButton.onDidClick(e => { this.onDidCustomEmitter.fire(); })); const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.getUI().ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => { inputBox.setFocus(); })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.getUI().keyDownSeenSinceShown = true; const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.codicon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.getUI().list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, titleBar, title, rightActionBar, checkAll, filterContainer, inputBox, visibleCountContainer, visibleCount, countContainer, count, okContainer, ok, message, customButtonContainer, customButton, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidCustom: this.onDidCustomEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, keyDownSeenSinceShown: false, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); return this.ui; } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { const ui = this.getUI(); return new QuickPick<T>(ui); } createInputBox(): IInputBox { const ui = this.getUI(); return new InputBox(ui); } private show(controller: QuickInput) { const ui = this.getUI(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); ui.leftActionBar.clear(); ui.title.textContent = ''; ui.rightActionBar.clear(); ui.checkAll.checked = false; // ui.inputBox.value = ''; Avoid triggering an event. ui.inputBox.placeholder = ''; ui.inputBox.password = false; ui.inputBox.showDecoration(Severity.Ignore); ui.visibleCount.setCount(0); ui.count.setCount(0); ui.message.textContent = ''; ui.progressBar.stop(); ui.list.setElements([]); ui.list.matchOnDescription = false; ui.list.matchOnDetail = false; ui.list.matchOnLabel = true; ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); ui.container.style.display = ''; this.updateLayout(); ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { const ui = this.getUI(); ui.title.style.display = visibilities.title ? '' : 'none'; ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; ui.countContainer.style.display = visibilities.count ? '' : 'none'; ui.okContainer.style.display = visibilities.ok ? '' : 'none'; ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none'; ui.message.style.display = visibilities.message ? '' : 'none'; ui.list.display(!!visibilities.list); ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { const ui = this.getUI(); this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { ui.inputBox.setAttribute('role', 'combobox'); ui.inputBox.setAttribute('aria-haspopup', 'true'); ui.inputBox.setAttribute('aria-autocomplete', 'list'); ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || ''); } else { ui.inputBox.removeAttribute('role'); ui.inputBox.removeAttribute('aria-haspopup'); ui.inputBox.removeAttribute('aria-autocomplete'); ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.getUI().leftActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } for (const item of this.getUI().rightActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } this.getUI().checkAll.disabled = !enabled; // this.getUI().inputBox.enabled = enabled; Avoid loosing focus. this.getUI().ok.enabled = enabled; this.getUI().list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.getUI().container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.getUI().inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.getUI().list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.getUI().list.isDisplayed()) { this.getUI().list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.ui.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : ''; this.ui.inputBox.style(theme); const quickInputBackground = theme.getColor(QUICK_INPUT_BACKGROUND); this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : ''; const quickInputForeground = theme.getColor(QUICK_INPUT_FOREGROUND); this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : ''; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : ''; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9922985434532166, 0.009851419366896152, 0.00016364420298486948, 0.00017305748770013452, 0.08040659129619598 ]
{ "id": 7, "code_window": [ "\t\t\t\t\tthis.onDidTriggerButtonEmitter.fire(button);\n", "\t\t\t\t}\n", "\t\t\t}),\n", "\t\t);\n", "\t\tthis.ui.keyDownSeenSinceShown = false;\n", "\t\tthis.ui.show(this);\n", "\t\tthis.visible = true;\n", "\t\tthis.update();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 219 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M8 1c-3.865 0-7 3.135-7 7s3.135 7 7 7 7-3.135 7-7-3.135-7-7-7zm1 12h-2v-7h2v7zm0-8h-2v-2h2v2z" fill="#1BA1E2"/><path d="M7 6h2v7h-2v-7zm0-1h2v-2h-2v2z" fill="#fff"/></svg>
src/vs/workbench/contrib/feedback/browser/media/info.svg
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00016989426512736827, 0.00016989426512736827, 0.00016989426512736827, 0.00016989426512736827, 0 ]
{ "id": 7, "code_window": [ "\t\t\t\t\tthis.onDidTriggerButtonEmitter.fire(button);\n", "\t\t\t\t}\n", "\t\t\t}),\n", "\t\t);\n", "\t\tthis.ui.keyDownSeenSinceShown = false;\n", "\t\tthis.ui.show(this);\n", "\t\tthis.visible = true;\n", "\t\tthis.update();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 219 }
[ { "c": "@", "t": "source.batchfile keyword.operator.at.batchfile", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": "echo", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "off", "t": "source.batchfile keyword.other.special-method.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": "setlocal", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": "title", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " VSCode Dev", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "pushd", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "%", "t": "source.batchfile punctuation.definition.variable.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "~dp0", "t": "source.batchfile variable.parameter.batchfile", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": "\\..", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "::", "t": "source.batchfile comment.line.colon.batchfile punctuation.definition.comment.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " Node modules", "t": "source.batchfile comment.line.colon.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "if", "t": "source.batchfile keyword.control.conditional.batchfile", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "not", "t": "source.batchfile keyword.operator.logical.batchfile", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "exist", "t": "source.batchfile keyword.other.special-method.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " node_modules ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "call", "t": "source.batchfile keyword.control.statement.batchfile", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " .\\scripts\\npm.bat install", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "::", "t": "source.batchfile comment.line.colon.batchfile punctuation.definition.comment.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " Get electron", "t": "source.batchfile comment.line.colon.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "node .\\node_modules\\gulp\\bin\\gulp.js electron", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "::", "t": "source.batchfile comment.line.colon.batchfile punctuation.definition.comment.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " Build", "t": "source.batchfile comment.line.colon.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "if", "t": "source.batchfile keyword.control.conditional.batchfile", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "not", "t": "source.batchfile keyword.operator.logical.batchfile", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "exist", "t": "source.batchfile keyword.other.special-method.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " out node .\\node_modules\\gulp\\bin\\gulp.js compile", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "::", "t": "source.batchfile comment.line.colon.batchfile punctuation.definition.comment.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " Configuration", "t": "source.batchfile comment.line.colon.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "set", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "NODE_ENV", "t": "source.batchfile variable.other.readwrite.batchfile", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": "=", "t": "source.batchfile keyword.operator.assignment.batchfile", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": "development", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "call", "t": "source.batchfile keyword.control.statement.batchfile", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "echo", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "%%", "t": "source.batchfile constant.character.escape.batchfile", "r": { "dark_plus": "constant.character.escape: #D7BA7D", "light_plus": "constant.character.escape: #FF0000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "constant.character: #569CD6" } }, { "c": "LINE:rem +=", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "%%", "t": "source.batchfile constant.character.escape.batchfile", "r": { "dark_plus": "constant.character.escape: #D7BA7D", "light_plus": "constant.character.escape: #FF0000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "constant.character: #569CD6" } }, { "c": "popd", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": "endlocal", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } } ]
extensions/bat/test/colorize-results/test_bat.json
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017586191825103015, 0.0001734325778670609, 0.0001705199247226119, 0.0001736326958052814, 0.0000012653700878217933 ]
{ "id": 7, "code_window": [ "\t\t\t\t\tthis.onDidTriggerButtonEmitter.fire(button);\n", "\t\t\t\t}\n", "\t\t\t}),\n", "\t\t);\n", "\t\tthis.ui.keyDownSeenSinceShown = false;\n", "\t\tthis.ui.show(this);\n", "\t\tthis.visible = true;\n", "\t\tthis.update();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { Direction, getRelativeLocation, Orientation, SerializableGrid, ISerializableView, IViewDeserializer, GridNode, Sizing, isGridBranchNode, sanitizeGridNodeDescriptor, GridNodeDescriptor, createSerializedGrid, Grid } from 'vs/base/browser/ui/grid/grid'; import { TestView, nodesToArrays } from './util'; import { deepClone } from 'vs/base/common/objects'; // Simple example: // // +-----+---------------+ // | 4 | 2 | // +-----+---------+-----+ // | 1 | | // +---------------+ 3 | // | 5 | | // +---------------+-----+ // // V // +-H // | +-4 // | +-2 // +-H // +-V // | +-1 // | +-5 // +-3 suite('Grid', function () { let container: HTMLElement; setup(function () { container = document.createElement('div'); container.style.position = 'absolute'; container.style.width = `${800}px`; container.style.height = `${600}px`; }); test('getRelativeLocation', () => { assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [0], Direction.Up), [0]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [0], Direction.Down), [1]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [0], Direction.Left), [0, 0]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [0], Direction.Right), [0, 1]); assert.deepEqual(getRelativeLocation(Orientation.HORIZONTAL, [0], Direction.Up), [0, 0]); assert.deepEqual(getRelativeLocation(Orientation.HORIZONTAL, [0], Direction.Down), [0, 1]); assert.deepEqual(getRelativeLocation(Orientation.HORIZONTAL, [0], Direction.Left), [0]); assert.deepEqual(getRelativeLocation(Orientation.HORIZONTAL, [0], Direction.Right), [1]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [4], Direction.Up), [4]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [4], Direction.Down), [5]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [4], Direction.Left), [4, 0]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [4], Direction.Right), [4, 1]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [0, 0], Direction.Up), [0, 0, 0]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [0, 0], Direction.Down), [0, 0, 1]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [0, 0], Direction.Left), [0, 0]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [0, 0], Direction.Right), [0, 1]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [1, 2], Direction.Up), [1, 2, 0]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [1, 2], Direction.Down), [1, 2, 1]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [1, 2], Direction.Left), [1, 2]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [1, 2], Direction.Right), [1, 3]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [1, 2, 3], Direction.Up), [1, 2, 3]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [1, 2, 3], Direction.Down), [1, 2, 4]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [1, 2, 3], Direction.Left), [1, 2, 3, 0]); assert.deepEqual(getRelativeLocation(Orientation.VERTICAL, [1, 2, 3], Direction.Right), [1, 2, 3, 1]); }); test('empty', () => { const view1 = new TestView(100, Number.MAX_VALUE, 100, Number.MAX_VALUE); const gridview = new Grid(view1); container.appendChild(gridview.element); gridview.layout(800, 600); assert.deepEqual(view1.size, [800, 600]); }); test('two views vertically', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); assert.deepEqual(view1.size, [800, 600]); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, 200, view1, Direction.Up); assert.deepEqual(view1.size, [800, 400]); assert.deepEqual(view2.size, [800, 200]); }); test('two views horizontally', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); assert.deepEqual(view1.size, [800, 600]); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, 300, view1, Direction.Right); assert.deepEqual(view1.size, [500, 600]); assert.deepEqual(view2.size, [300, 600]); }); test('simple layout', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); assert.deepEqual(view1.size, [800, 600]); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, 200, view1, Direction.Up); assert.deepEqual(view1.size, [800, 400]); assert.deepEqual(view2.size, [800, 200]); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, 200, view1, Direction.Right); assert.deepEqual(view1.size, [600, 400]); assert.deepEqual(view2.size, [800, 200]); assert.deepEqual(view3.size, [200, 400]); const view4 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, 200, view2, Direction.Left); assert.deepEqual(view1.size, [600, 400]); assert.deepEqual(view2.size, [600, 200]); assert.deepEqual(view3.size, [200, 400]); assert.deepEqual(view4.size, [200, 200]); const view5 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, 100, view1, Direction.Down); assert.deepEqual(view1.size, [600, 300]); assert.deepEqual(view2.size, [600, 200]); assert.deepEqual(view3.size, [200, 400]); assert.deepEqual(view4.size, [200, 200]); assert.deepEqual(view5.size, [600, 100]); }); test('another simple layout with automatic size distribution', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); assert.deepEqual(view1.size, [800, 600]); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Distribute, view1, Direction.Left); assert.deepEqual(view1.size, [400, 600]); assert.deepEqual(view2.size, [400, 600]); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Distribute, view1, Direction.Right); assert.deepEqual(view1.size, [266, 600]); assert.deepEqual(view2.size, [266, 600]); assert.deepEqual(view3.size, [268, 600]); const view4 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, Sizing.Distribute, view2, Direction.Down); assert.deepEqual(view1.size, [266, 600]); assert.deepEqual(view2.size, [266, 300]); assert.deepEqual(view3.size, [268, 600]); assert.deepEqual(view4.size, [266, 300]); const view5 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, Sizing.Distribute, view3, Direction.Up); assert.deepEqual(view1.size, [266, 600]); assert.deepEqual(view2.size, [266, 300]); assert.deepEqual(view3.size, [268, 300]); assert.deepEqual(view4.size, [266, 300]); assert.deepEqual(view5.size, [268, 300]); const view6 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view6, Sizing.Distribute, view3, Direction.Down); assert.deepEqual(view1.size, [266, 600]); assert.deepEqual(view2.size, [266, 300]); assert.deepEqual(view3.size, [268, 200]); assert.deepEqual(view4.size, [266, 300]); assert.deepEqual(view5.size, [268, 200]); assert.deepEqual(view6.size, [268, 200]); }); test('another simple layout with split size distribution', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); assert.deepEqual(view1.size, [800, 600]); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Split, view1, Direction.Left); assert.deepEqual(view1.size, [400, 600]); assert.deepEqual(view2.size, [400, 600]); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Split, view1, Direction.Right); assert.deepEqual(view1.size, [200, 600]); assert.deepEqual(view2.size, [400, 600]); assert.deepEqual(view3.size, [200, 600]); const view4 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, Sizing.Split, view2, Direction.Down); assert.deepEqual(view1.size, [200, 600]); assert.deepEqual(view2.size, [400, 300]); assert.deepEqual(view3.size, [200, 600]); assert.deepEqual(view4.size, [400, 300]); const view5 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, Sizing.Split, view3, Direction.Up); assert.deepEqual(view1.size, [200, 600]); assert.deepEqual(view2.size, [400, 300]); assert.deepEqual(view3.size, [200, 300]); assert.deepEqual(view4.size, [400, 300]); assert.deepEqual(view5.size, [200, 300]); const view6 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view6, Sizing.Split, view3, Direction.Down); assert.deepEqual(view1.size, [200, 600]); assert.deepEqual(view2.size, [400, 300]); assert.deepEqual(view3.size, [200, 150]); assert.deepEqual(view4.size, [400, 300]); assert.deepEqual(view5.size, [200, 300]); assert.deepEqual(view6.size, [200, 150]); }); test('3/2 layout with split', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); assert.deepEqual(view1.size, [800, 600]); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Split, view1, Direction.Down); assert.deepEqual(view1.size, [800, 300]); assert.deepEqual(view2.size, [800, 300]); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Split, view2, Direction.Right); assert.deepEqual(view1.size, [800, 300]); assert.deepEqual(view2.size, [400, 300]); assert.deepEqual(view3.size, [400, 300]); const view4 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, Sizing.Split, view1, Direction.Right); assert.deepEqual(view1.size, [400, 300]); assert.deepEqual(view2.size, [400, 300]); assert.deepEqual(view3.size, [400, 300]); assert.deepEqual(view4.size, [400, 300]); const view5 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, Sizing.Split, view1, Direction.Right); assert.deepEqual(view1.size, [200, 300]); assert.deepEqual(view2.size, [400, 300]); assert.deepEqual(view3.size, [400, 300]); assert.deepEqual(view4.size, [400, 300]); assert.deepEqual(view5.size, [200, 300]); }); test('sizing should be correct after branch demotion #50564', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Split, view1, Direction.Right); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Split, view2, Direction.Down); const view4 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, Sizing.Split, view2, Direction.Right); assert.deepEqual(view1.size, [400, 600]); assert.deepEqual(view2.size, [200, 300]); assert.deepEqual(view3.size, [400, 300]); assert.deepEqual(view4.size, [200, 300]); grid.removeView(view3); assert.deepEqual(view1.size, [400, 600]); assert.deepEqual(view2.size, [200, 600]); assert.deepEqual(view4.size, [200, 600]); }); test('sizing should be correct after branch demotion #50675', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Distribute, view1, Direction.Down); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Distribute, view2, Direction.Down); const view4 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, Sizing.Distribute, view3, Direction.Right); assert.deepEqual(view1.size, [800, 200]); assert.deepEqual(view2.size, [800, 200]); assert.deepEqual(view3.size, [400, 200]); assert.deepEqual(view4.size, [400, 200]); grid.removeView(view3, Sizing.Distribute); assert.deepEqual(view1.size, [800, 200]); assert.deepEqual(view2.size, [800, 200]); assert.deepEqual(view4.size, [800, 200]); }); test('getNeighborViews should work on single view layout', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); assert.deepEqual(grid.getNeighborViews(view1, Direction.Up), []); assert.deepEqual(grid.getNeighborViews(view1, Direction.Right), []); assert.deepEqual(grid.getNeighborViews(view1, Direction.Down), []); assert.deepEqual(grid.getNeighborViews(view1, Direction.Left), []); assert.deepEqual(grid.getNeighborViews(view1, Direction.Up, true), [view1]); assert.deepEqual(grid.getNeighborViews(view1, Direction.Right, true), [view1]); assert.deepEqual(grid.getNeighborViews(view1, Direction.Down, true), [view1]); assert.deepEqual(grid.getNeighborViews(view1, Direction.Left, true), [view1]); }); test('getNeighborViews should work on simple layout', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Distribute, view1, Direction.Down); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Distribute, view2, Direction.Down); assert.deepEqual(grid.getNeighborViews(view1, Direction.Up), []); assert.deepEqual(grid.getNeighborViews(view1, Direction.Right), []); assert.deepEqual(grid.getNeighborViews(view1, Direction.Down), [view2]); assert.deepEqual(grid.getNeighborViews(view1, Direction.Left), []); assert.deepEqual(grid.getNeighborViews(view1, Direction.Up, true), [view3]); assert.deepEqual(grid.getNeighborViews(view1, Direction.Right, true), [view1]); assert.deepEqual(grid.getNeighborViews(view1, Direction.Down, true), [view2]); assert.deepEqual(grid.getNeighborViews(view1, Direction.Left, true), [view1]); assert.deepEqual(grid.getNeighborViews(view2, Direction.Up), [view1]); assert.deepEqual(grid.getNeighborViews(view2, Direction.Right), []); assert.deepEqual(grid.getNeighborViews(view2, Direction.Down), [view3]); assert.deepEqual(grid.getNeighborViews(view2, Direction.Left), []); assert.deepEqual(grid.getNeighborViews(view2, Direction.Up, true), [view1]); assert.deepEqual(grid.getNeighborViews(view2, Direction.Right, true), [view2]); assert.deepEqual(grid.getNeighborViews(view2, Direction.Down, true), [view3]); assert.deepEqual(grid.getNeighborViews(view2, Direction.Left, true), [view2]); assert.deepEqual(grid.getNeighborViews(view3, Direction.Up), [view2]); assert.deepEqual(grid.getNeighborViews(view3, Direction.Right), []); assert.deepEqual(grid.getNeighborViews(view3, Direction.Down), []); assert.deepEqual(grid.getNeighborViews(view3, Direction.Left), []); assert.deepEqual(grid.getNeighborViews(view3, Direction.Up, true), [view2]); assert.deepEqual(grid.getNeighborViews(view3, Direction.Right, true), [view3]); assert.deepEqual(grid.getNeighborViews(view3, Direction.Down, true), [view1]); assert.deepEqual(grid.getNeighborViews(view3, Direction.Left, true), [view3]); }); test('getNeighborViews should work on a complex layout', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Distribute, view1, Direction.Down); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Distribute, view2, Direction.Down); const view4 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, Sizing.Distribute, view2, Direction.Right); const view5 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, Sizing.Distribute, view4, Direction.Down); assert.deepEqual(grid.getNeighborViews(view1, Direction.Up), []); assert.deepEqual(grid.getNeighborViews(view1, Direction.Right), []); assert.deepEqual(grid.getNeighborViews(view1, Direction.Down), [view2, view4]); assert.deepEqual(grid.getNeighborViews(view1, Direction.Left), []); assert.deepEqual(grid.getNeighborViews(view2, Direction.Up), [view1]); assert.deepEqual(grid.getNeighborViews(view2, Direction.Right), [view4, view5]); assert.deepEqual(grid.getNeighborViews(view2, Direction.Down), [view3]); assert.deepEqual(grid.getNeighborViews(view2, Direction.Left), []); assert.deepEqual(grid.getNeighborViews(view4, Direction.Up), [view1]); assert.deepEqual(grid.getNeighborViews(view4, Direction.Right), []); assert.deepEqual(grid.getNeighborViews(view4, Direction.Down), [view5]); assert.deepEqual(grid.getNeighborViews(view4, Direction.Left), [view2]); assert.deepEqual(grid.getNeighborViews(view5, Direction.Up), [view4]); assert.deepEqual(grid.getNeighborViews(view5, Direction.Right), []); assert.deepEqual(grid.getNeighborViews(view5, Direction.Down), [view3]); assert.deepEqual(grid.getNeighborViews(view5, Direction.Left), [view2]); assert.deepEqual(grid.getNeighborViews(view3, Direction.Up), [view2, view5]); assert.deepEqual(grid.getNeighborViews(view3, Direction.Right), []); assert.deepEqual(grid.getNeighborViews(view3, Direction.Down), []); assert.deepEqual(grid.getNeighborViews(view3, Direction.Left), []); }); test('getNeighborViews should work on another simple layout', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Distribute, view1, Direction.Right); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Distribute, view2, Direction.Down); const view4 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, Sizing.Distribute, view2, Direction.Right); assert.deepEqual(grid.getNeighborViews(view4, Direction.Up), []); assert.deepEqual(grid.getNeighborViews(view4, Direction.Right), []); assert.deepEqual(grid.getNeighborViews(view4, Direction.Down), [view3]); assert.deepEqual(grid.getNeighborViews(view4, Direction.Left), [view2]); }); test('getNeighborViews should only return immediate neighbors', function () { const view1 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new Grid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Distribute, view1, Direction.Right); const view3 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Distribute, view2, Direction.Down); const view4 = new TestView(50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, Sizing.Distribute, view2, Direction.Right); assert.deepEqual(grid.getNeighborViews(view1, Direction.Right), [view2, view3]); }); }); class TestSerializableView extends TestView implements ISerializableView { constructor( readonly name: string, minimumWidth: number, maximumWidth: number, minimumHeight: number, maximumHeight: number ) { super(minimumWidth, maximumWidth, minimumHeight, maximumHeight); } toJSON() { return { name: this.name }; } } class TestViewDeserializer implements IViewDeserializer<TestSerializableView> { private views = new Map<string, TestSerializableView>(); fromJSON(json: any): TestSerializableView { const view = new TestSerializableView(json.name, 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); this.views.set(json.name, view); return view; } getView(id: string): TestSerializableView { const view = this.views.get(id); if (!view) { throw new Error('Unknown view'); } return view; } } function nodesToNames(node: GridNode<TestSerializableView>): any { if (isGridBranchNode(node)) { return node.children.map(nodesToNames); } else { return node.view.name; } } suite('SerializableGrid', function () { let container: HTMLElement; setup(function () { container = document.createElement('div'); container.style.position = 'absolute'; container.style.width = `${800}px`; container.style.height = `${600}px`; }); test('serialize empty', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const actual = grid.serialize(); assert.deepEqual(actual, { orientation: 0, width: 800, height: 600, root: { type: 'branch', data: [ { type: 'leaf', data: { name: 'view1', }, size: 600 } ], size: 800 } }); }); test('serialize simple layout', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestSerializableView('view2', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, 200, view1, Direction.Up); const view3 = new TestSerializableView('view3', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, 200, view1, Direction.Right); const view4 = new TestSerializableView('view4', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, 200, view2, Direction.Left); const view5 = new TestSerializableView('view5', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, 100, view1, Direction.Down); assert.deepEqual(grid.serialize(), { orientation: 0, width: 800, height: 600, root: { type: 'branch', data: [ { type: 'branch', data: [ { type: 'leaf', data: { name: 'view4' }, size: 200 }, { type: 'leaf', data: { name: 'view2' }, size: 600 } ], size: 200 }, { type: 'branch', data: [ { type: 'branch', data: [ { type: 'leaf', data: { name: 'view1' }, size: 300 }, { type: 'leaf', data: { name: 'view5' }, size: 100 } ], size: 600 }, { type: 'leaf', data: { name: 'view3' }, size: 200 } ], size: 400 } ], size: 800 } }); }); test('deserialize empty', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const json = grid.serialize(); grid.dispose(); const deserializer = new TestViewDeserializer(); const grid2 = SerializableGrid.deserialize(json, deserializer); grid2.layout(800, 600); assert.deepEqual(nodesToNames(grid2.getViews()), ['view1']); }); test('deserialize simple layout', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestSerializableView('view2', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, 200, view1, Direction.Up); const view3 = new TestSerializableView('view3', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, 200, view1, Direction.Right); const view4 = new TestSerializableView('view4', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, 200, view2, Direction.Left); const view5 = new TestSerializableView('view5', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, 100, view1, Direction.Down); const json = grid.serialize(); grid.dispose(); const deserializer = new TestViewDeserializer(); const grid2 = SerializableGrid.deserialize(json, deserializer); const view1Copy = deserializer.getView('view1'); const view2Copy = deserializer.getView('view2'); const view3Copy = deserializer.getView('view3'); const view4Copy = deserializer.getView('view4'); const view5Copy = deserializer.getView('view5'); assert.deepEqual(nodesToArrays(grid2.getViews()), [[view4Copy, view2Copy], [[view1Copy, view5Copy], view3Copy]]); grid2.layout(800, 600); assert.deepEqual(view1Copy.size, [600, 300]); assert.deepEqual(view2Copy.size, [600, 200]); assert.deepEqual(view3Copy.size, [200, 400]); assert.deepEqual(view4Copy.size, [200, 200]); assert.deepEqual(view5Copy.size, [600, 100]); }); test('deserialize simple layout with scaling', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestSerializableView('view2', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, 200, view1, Direction.Up); const view3 = new TestSerializableView('view3', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, 200, view1, Direction.Right); const view4 = new TestSerializableView('view4', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, 200, view2, Direction.Left); const view5 = new TestSerializableView('view5', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, 100, view1, Direction.Down); const json = grid.serialize(); grid.dispose(); const deserializer = new TestViewDeserializer(); const grid2 = SerializableGrid.deserialize(json, deserializer); const view1Copy = deserializer.getView('view1'); const view2Copy = deserializer.getView('view2'); const view3Copy = deserializer.getView('view3'); const view4Copy = deserializer.getView('view4'); const view5Copy = deserializer.getView('view5'); grid2.layout(400, 800); // [/2, *4/3] assert.deepEqual(view1Copy.size, [300, 400]); assert.deepEqual(view2Copy.size, [300, 267]); assert.deepEqual(view3Copy.size, [100, 533]); assert.deepEqual(view4Copy.size, [100, 267]); assert.deepEqual(view5Copy.size, [300, 133]); }); test('deserialize 4 view layout (ben issue #2)', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestSerializableView('view2', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Split, view1, Direction.Down); const view3 = new TestSerializableView('view3', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Split, view2, Direction.Down); const view4 = new TestSerializableView('view4', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, Sizing.Split, view3, Direction.Right); const json = grid.serialize(); grid.dispose(); const deserializer = new TestViewDeserializer(); const grid2 = SerializableGrid.deserialize(json, deserializer); const view1Copy = deserializer.getView('view1'); const view2Copy = deserializer.getView('view2'); const view3Copy = deserializer.getView('view3'); const view4Copy = deserializer.getView('view4'); grid2.layout(800, 600); assert.deepEqual(view1Copy.size, [800, 300]); assert.deepEqual(view2Copy.size, [800, 150]); assert.deepEqual(view3Copy.size, [400, 150]); assert.deepEqual(view4Copy.size, [400, 150]); }); test('deserialize 2 view layout (ben issue #3)', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestSerializableView('view2', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Split, view1, Direction.Right); const json = grid.serialize(); grid.dispose(); const deserializer = new TestViewDeserializer(); const grid2 = SerializableGrid.deserialize(json, deserializer); const view1Copy = deserializer.getView('view1'); const view2Copy = deserializer.getView('view2'); grid2.layout(800, 600); assert.deepEqual(view1Copy.size, [400, 600]); assert.deepEqual(view2Copy.size, [400, 600]); }); test('deserialize simple view layout #50609', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestSerializableView('view2', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, Sizing.Split, view1, Direction.Right); const view3 = new TestSerializableView('view3', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, Sizing.Split, view2, Direction.Down); grid.removeView(view1, Sizing.Split); const json = grid.serialize(); grid.dispose(); const deserializer = new TestViewDeserializer(); const grid2 = SerializableGrid.deserialize(json, deserializer); const view2Copy = deserializer.getView('view2'); const view3Copy = deserializer.getView('view3'); grid2.layout(800, 600); assert.deepEqual(view2Copy.size, [800, 300]); assert.deepEqual(view3Copy.size, [800, 300]); }); test('sanitizeGridNodeDescriptor', () => { const nodeDescriptor = { groups: [{ size: 0.2 }, { size: 0.2 }, { size: 0.6, groups: [{}, {}] }] }; const nodeDescriptorCopy = deepClone<GridNodeDescriptor>(nodeDescriptor); sanitizeGridNodeDescriptor(nodeDescriptorCopy); assert.deepEqual(nodeDescriptorCopy, { groups: [{ size: 0.2 }, { size: 0.2 }, { size: 0.6, groups: [{ size: 0.5 }, { size: 0.5 }] }] }); }); test('createSerializedGrid', () => { const gridDescriptor = { orientation: Orientation.VERTICAL, groups: [{ size: 0.2 }, { size: 0.2 }, { size: 0.6, groups: [{}, {}] }] }; const serializedGrid = createSerializedGrid(gridDescriptor); assert.deepEqual(serializedGrid, { root: { type: 'branch', size: undefined, data: [ { type: 'leaf', size: 0.2, data: null }, { type: 'leaf', size: 0.2, data: null }, { type: 'branch', size: 0.6, data: [ { type: 'leaf', size: 0.5, data: null }, { type: 'leaf', size: 0.5, data: null } ] } ] }, orientation: Orientation.VERTICAL, width: 1, height: 1 }); }); test('serialize should store visibility and previous size', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestSerializableView('view2', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, 200, view1, Direction.Up); const view3 = new TestSerializableView('view3', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, 200, view1, Direction.Right); const view4 = new TestSerializableView('view4', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, 200, view2, Direction.Left); const view5 = new TestSerializableView('view5', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, 100, view1, Direction.Down); assert.deepEqual(view1.size, [600, 300]); assert.deepEqual(view2.size, [600, 200]); assert.deepEqual(view3.size, [200, 400]); assert.deepEqual(view4.size, [200, 200]); assert.deepEqual(view5.size, [600, 100]); grid.setViewVisible(view5, false); assert.deepEqual(view1.size, [600, 400]); assert.deepEqual(view2.size, [600, 200]); assert.deepEqual(view3.size, [200, 400]); assert.deepEqual(view4.size, [200, 200]); assert.deepEqual(view5.size, [600, 0]); grid.setViewVisible(view5, true); assert.deepEqual(view1.size, [600, 300]); assert.deepEqual(view2.size, [600, 200]); assert.deepEqual(view3.size, [200, 400]); assert.deepEqual(view4.size, [200, 200]); assert.deepEqual(view5.size, [600, 100]); grid.setViewVisible(view5, false); assert.deepEqual(view1.size, [600, 400]); assert.deepEqual(view2.size, [600, 200]); assert.deepEqual(view3.size, [200, 400]); assert.deepEqual(view4.size, [200, 200]); assert.deepEqual(view5.size, [600, 0]); grid.setViewVisible(view5, false); const json = grid.serialize(); assert.deepEqual(json, { orientation: 0, width: 800, height: 600, root: { type: 'branch', data: [ { type: 'branch', data: [ { type: 'leaf', data: { name: 'view4' }, size: 200 }, { type: 'leaf', data: { name: 'view2' }, size: 600 } ], size: 200 }, { type: 'branch', data: [ { type: 'branch', data: [ { type: 'leaf', data: { name: 'view1' }, size: 400 }, { type: 'leaf', data: { name: 'view5' }, size: 100, visible: false } ], size: 600 }, { type: 'leaf', data: { name: 'view3' }, size: 200 } ], size: 400 } ], size: 800 } }); grid.dispose(); const deserializer = new TestViewDeserializer(); const grid2 = SerializableGrid.deserialize(json, deserializer); const view1Copy = deserializer.getView('view1'); const view2Copy = deserializer.getView('view2'); const view3Copy = deserializer.getView('view3'); const view4Copy = deserializer.getView('view4'); const view5Copy = deserializer.getView('view5'); assert.deepEqual(nodesToArrays(grid2.getViews()), [[view4Copy, view2Copy], [[view1Copy, view5Copy], view3Copy]]); grid2.layout(800, 600); assert.deepEqual(view1Copy.size, [600, 400]); assert.deepEqual(view2Copy.size, [600, 200]); assert.deepEqual(view3Copy.size, [200, 400]); assert.deepEqual(view4Copy.size, [200, 200]); assert.deepEqual(view5Copy.size, [600, 0]); assert.deepEqual(grid2.isViewVisible(view1Copy), true); assert.deepEqual(grid2.isViewVisible(view2Copy), true); assert.deepEqual(grid2.isViewVisible(view3Copy), true); assert.deepEqual(grid2.isViewVisible(view4Copy), true); assert.deepEqual(grid2.isViewVisible(view5Copy), false); grid2.setViewVisible(view5Copy, true); assert.deepEqual(view1Copy.size, [600, 300]); assert.deepEqual(view2Copy.size, [600, 200]); assert.deepEqual(view3Copy.size, [200, 400]); assert.deepEqual(view4Copy.size, [200, 200]); assert.deepEqual(view5Copy.size, [600, 100]); assert.deepEqual(grid2.isViewVisible(view1Copy), true); assert.deepEqual(grid2.isViewVisible(view2Copy), true); assert.deepEqual(grid2.isViewVisible(view3Copy), true); assert.deepEqual(grid2.isViewVisible(view4Copy), true); assert.deepEqual(grid2.isViewVisible(view5Copy), true); }); test('serialize should store visibility and previous size even for first leaf', function () { const view1 = new TestSerializableView('view1', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); const grid = new SerializableGrid(view1); container.appendChild(grid.element); grid.layout(800, 600); const view2 = new TestSerializableView('view2', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view2, 200, view1, Direction.Up); const view3 = new TestSerializableView('view3', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view3, 200, view1, Direction.Right); const view4 = new TestSerializableView('view4', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view4, 200, view2, Direction.Left); const view5 = new TestSerializableView('view5', 50, Number.MAX_VALUE, 50, Number.MAX_VALUE); grid.addView(view5, 100, view1, Direction.Down); assert.deepEqual(view1.size, [600, 300]); assert.deepEqual(view2.size, [600, 200]); assert.deepEqual(view3.size, [200, 400]); assert.deepEqual(view4.size, [200, 200]); assert.deepEqual(view5.size, [600, 100]); grid.setViewVisible(view4, false); assert.deepEqual(view1.size, [600, 300]); assert.deepEqual(view2.size, [800, 200]); assert.deepEqual(view3.size, [200, 400]); assert.deepEqual(view4.size, [0, 200]); assert.deepEqual(view5.size, [600, 100]); const json = grid.serialize(); assert.deepEqual(json, { orientation: 0, width: 800, height: 600, root: { type: 'branch', data: [ { type: 'branch', data: [ { type: 'leaf', data: { name: 'view4' }, size: 200, visible: false }, { type: 'leaf', data: { name: 'view2' }, size: 800 } ], size: 200 }, { type: 'branch', data: [ { type: 'branch', data: [ { type: 'leaf', data: { name: 'view1' }, size: 300 }, { type: 'leaf', data: { name: 'view5' }, size: 100 } ], size: 600 }, { type: 'leaf', data: { name: 'view3' }, size: 200 } ], size: 400 } ], size: 800 } }); grid.dispose(); const deserializer = new TestViewDeserializer(); const grid2 = SerializableGrid.deserialize(json, deserializer); const view1Copy = deserializer.getView('view1'); const view2Copy = deserializer.getView('view2'); const view3Copy = deserializer.getView('view3'); const view4Copy = deserializer.getView('view4'); const view5Copy = deserializer.getView('view5'); assert.deepEqual(nodesToArrays(grid2.getViews()), [[view4Copy, view2Copy], [[view1Copy, view5Copy], view3Copy]]); grid2.layout(800, 600); assert.deepEqual(view1Copy.size, [600, 300]); assert.deepEqual(view2Copy.size, [800, 200]); assert.deepEqual(view3Copy.size, [200, 400]); assert.deepEqual(view4Copy.size, [0, 200]); assert.deepEqual(view5Copy.size, [600, 100]); assert.deepEqual(grid2.isViewVisible(view1Copy), true); assert.deepEqual(grid2.isViewVisible(view2Copy), true); assert.deepEqual(grid2.isViewVisible(view3Copy), true); assert.deepEqual(grid2.isViewVisible(view4Copy), false); assert.deepEqual(grid2.isViewVisible(view5Copy), true); grid2.setViewVisible(view4Copy, true); assert.deepEqual(view1Copy.size, [600, 300]); assert.deepEqual(view2Copy.size, [600, 200]); assert.deepEqual(view3Copy.size, [200, 400]); assert.deepEqual(view4Copy.size, [200, 200]); assert.deepEqual(view5Copy.size, [600, 100]); assert.deepEqual(grid2.isViewVisible(view1Copy), true); assert.deepEqual(grid2.isViewVisible(view2Copy), true); assert.deepEqual(grid2.isViewVisible(view3Copy), true); assert.deepEqual(grid2.isViewVisible(view4Copy), true); assert.deepEqual(grid2.isViewVisible(view5Copy), true); }); });
src/vs/base/test/browser/ui/grid/grid.test.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017662282334640622, 0.00017290031246375293, 0.00016642124683130533, 0.00017323729116469622, 0.000002106680767610669 ]
{ "id": 8, "code_window": [ "\t\t\t\t\tthis.ui.list.clearFocus();\n", "\t\t\t\t}\n", "\t\t\t}));\n", "\t\t\tthis.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => {\n", "\t\t\t\tthis.ui.keyDownSeenSinceShown = true;\n", "\t\t\t\tswitch (event.keyCode) {\n", "\t\t\t\t\tcase KeyCode.DownArrow:\n", "\t\t\t\t\t\tthis.ui.list.focus('Next');\n", "\t\t\t\t\t\tif (this.canSelectMany) {\n", "\t\t\t\t\t\t\tthis.ui.list.domFocus();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 558 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { QUICK_INPUT_BACKGROUND, QUICK_INPUT_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerAndGetAmdImageURL } from 'vs/base/common/amd'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-dark.svg')), light: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-light.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; titleBar: HTMLElement; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; filterContainer: HTMLElement; inputBox: QuickInputBox; visibleCountContainer: HTMLElement; visibleCount: CountBadge; countContainer: HTMLElement; count: CountBadge; okContainer: HTMLElement; ok: Button; message: HTMLElement; customButtonContainer: HTMLElement; customButton: Button; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidCustom: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; keyDownSeenSinceShown: boolean; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; customButton?: boolean; }; class QuickInput extends Disposable implements IQuickInput { private _title: string | undefined; private _steps: number | undefined; private _totalSteps: number | undefined; protected visible = false; private _enabled = true; private _contextKey: string | undefined; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private readonly onDidHideEmitter = this._register(new Emitter<void>()); protected readonly visibleDisposables = this._register(new DisposableStore()); private busyDelay: TimeoutTimer | undefined; constructor( protected ui: QuickInputUI ) { super(); } get title() { return this._title; } set title(title: string | undefined) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number | undefined) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number | undefined) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string | undefined) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.add( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.keyDownSeenSinceShown = false; this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables.clear(); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = undefined; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } protected showMessageDecoration(severity: Severity) { this.ui.inputBox.showDecoration(severity); if (severity === Severity.Error) { const styles = this.ui.inputBox.stylesForType(severity); this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : ''; this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : ''; this.ui.message.style.paddingBottom = '4px'; } else { this.ui.message.style.backgroundColor = ''; this.ui.message.style.border = ''; this.ui.message.style.paddingBottom = ''; } } public dispose(): void { this.hide(); super.dispose(); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static readonly INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder: string | undefined; private readonly onDidChangeValueEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private readonly onDidChangeActiveEmitter = this._register(new Emitter<T[]>()); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private readonly onDidChangeSelectionEmitter = this._register(new Emitter<T[]>()); private readonly onDidTriggerItemButtonEmitter = this._register(new Emitter<IQuickPickItemButtonEvent<T>>()); private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _validationMessage: string | undefined; private _ok = false; private _customButton = false; private _customButtonLabel: string | undefined; private _customButtonHover: string | undefined; quickNavigate: IQuickNavigateConfiguration | undefined; get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; onDidCustom = this.onDidCustomEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } get customButton() { return this._customButton; } set customButton(showCustomButton: boolean) { this._customButton = showCustomButton; this.update(); } get customLabel() { return this._customButtonLabel; } set customLabel(label: string | undefined) { this._customButtonLabel = label; this.update(); } get customHover() { return this._customButtonHover; } set customHover(hover: string | undefined) { this._customButtonHover = hover; this.update(); } get ok() { return this._ok; } set ok(showOkButton: boolean) { this._ok = showOkButton; this.update(); } public inputHasFocus(): boolean { return this.visible ? this.ui.inputBox.hasFocus() : false; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); })); this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } })); this.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => { this.ui.keyDownSeenSinceShown = true; switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; } })); this.visibleDisposables.add(this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.onDidCustom(() => { this.onDidCustomEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } })); this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>))); this.visibleDisposables.add(this.registerQuickNavigation()); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true, message: !!this.validationMessage } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true, message: !!this.validationMessage, customButton: this.customButton, ok: this.ok }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } if (this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } else { this.ui.message.textContent = null; this.showMessageDecoration(Severity.Ignore); } this.ui.customButton.label = this.customLabel || ''; this.ui.customButton.element.title = this.customHover || ''; this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); } } class InputBox extends QuickInput implements IInputBox { private static readonly noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _placeholder: string | undefined; private _password = false; private _prompt: string | undefined; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string | undefined; private readonly onDidValueChangeEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string | undefined) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } readonly onDidChangeValue = this.onDidValueChangeEmitter.event; readonly onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); })); this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined))); this.valueSelectionUpdated = true; } super.show(); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.showMessageDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: undefined; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private ui: QuickInputUI | undefined; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: Map<string, IContextKey<boolean>> = new Map(); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts.get(id); if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts.set(id, key); } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { this.contexts.forEach(context => { if (context.get()) { context.reset(); } }); } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private getUI() { if (this.ui) { return this.ui; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; const titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); const extraContainer = dom.append(headerContainer, $('.quick-input-and-message')); const filterContainer = dom.append(extraContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count')); visibleCountContainer.setAttribute('aria-live', 'polite'); visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); const countContainer = dom.append(filterContainer, $('.quick-input-count')); countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); const okContainer = dom.append(headerContainer, $('.quick-input-action')); const ok = new Button(okContainer); attachButtonStyler(ok, this.themeService); ok.label = localize('ok', "OK"); this._register(ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const customButtonContainer = dom.append(headerContainer, $('.quick-input-action')); const customButton = new Button(customButtonContainer); attachButtonStyler(customButton, this.themeService); customButton.label = localize('custom', "Custom"); this._register(customButton.onDidClick(e => { this.onDidCustomEmitter.fire(); })); const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.getUI().ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => { inputBox.setFocus(); })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.getUI().keyDownSeenSinceShown = true; const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.codicon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.getUI().list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, titleBar, title, rightActionBar, checkAll, filterContainer, inputBox, visibleCountContainer, visibleCount, countContainer, count, okContainer, ok, message, customButtonContainer, customButton, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidCustom: this.onDidCustomEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, keyDownSeenSinceShown: false, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); return this.ui; } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { const ui = this.getUI(); return new QuickPick<T>(ui); } createInputBox(): IInputBox { const ui = this.getUI(); return new InputBox(ui); } private show(controller: QuickInput) { const ui = this.getUI(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); ui.leftActionBar.clear(); ui.title.textContent = ''; ui.rightActionBar.clear(); ui.checkAll.checked = false; // ui.inputBox.value = ''; Avoid triggering an event. ui.inputBox.placeholder = ''; ui.inputBox.password = false; ui.inputBox.showDecoration(Severity.Ignore); ui.visibleCount.setCount(0); ui.count.setCount(0); ui.message.textContent = ''; ui.progressBar.stop(); ui.list.setElements([]); ui.list.matchOnDescription = false; ui.list.matchOnDetail = false; ui.list.matchOnLabel = true; ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); ui.container.style.display = ''; this.updateLayout(); ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { const ui = this.getUI(); ui.title.style.display = visibilities.title ? '' : 'none'; ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; ui.countContainer.style.display = visibilities.count ? '' : 'none'; ui.okContainer.style.display = visibilities.ok ? '' : 'none'; ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none'; ui.message.style.display = visibilities.message ? '' : 'none'; ui.list.display(!!visibilities.list); ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { const ui = this.getUI(); this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { ui.inputBox.setAttribute('role', 'combobox'); ui.inputBox.setAttribute('aria-haspopup', 'true'); ui.inputBox.setAttribute('aria-autocomplete', 'list'); ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || ''); } else { ui.inputBox.removeAttribute('role'); ui.inputBox.removeAttribute('aria-haspopup'); ui.inputBox.removeAttribute('aria-autocomplete'); ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.getUI().leftActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } for (const item of this.getUI().rightActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } this.getUI().checkAll.disabled = !enabled; // this.getUI().inputBox.enabled = enabled; Avoid loosing focus. this.getUI().ok.enabled = enabled; this.getUI().list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.getUI().container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.getUI().inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.getUI().list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.getUI().list.isDisplayed()) { this.getUI().list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.ui.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : ''; this.ui.inputBox.style(theme); const quickInputBackground = theme.getColor(QUICK_INPUT_BACKGROUND); this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : ''; const quickInputForeground = theme.getColor(QUICK_INPUT_FOREGROUND); this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : ''; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : ''; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.993096649646759, 0.02195892669260502, 0.00016121449880301952, 0.0001705713802948594, 0.13246679306030273 ]
{ "id": 8, "code_window": [ "\t\t\t\t\tthis.ui.list.clearFocus();\n", "\t\t\t\t}\n", "\t\t\t}));\n", "\t\t\tthis.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => {\n", "\t\t\t\tthis.ui.keyDownSeenSinceShown = true;\n", "\t\t\t\tswitch (event.keyCode) {\n", "\t\t\t\t\tcase KeyCode.DownArrow:\n", "\t\t\t\t\t\tthis.ui.list.focus('Next');\n", "\t\t\t\t\t\tif (this.canSelectMany) {\n", "\t\t\t\t\t\t\tthis.ui.list.domFocus();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 558 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { RGBA8 } from 'vs/editor/common/core/rgba'; import { Constants, getCharIndex } from './minimapCharSheet'; export class MinimapCharRenderer { _minimapCharRendererBrand: void; private readonly charDataNormal: Uint8ClampedArray; private readonly charDataLight: Uint8ClampedArray; constructor(charData: Uint8ClampedArray, public readonly scale: number) { this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15); this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60); } private static soften(input: Uint8ClampedArray, ratio: number): Uint8ClampedArray { let result = new Uint8ClampedArray(input.length); for (let i = 0, len = input.length; i < len; i++) { result[i] = input[i] * ratio; } return result; } public renderChar( target: ImageData, dx: number, dy: number, chCode: number, color: RGBA8, backgroundColor: RGBA8, useLighterFont: boolean ): void { const charWidth = Constants.BASE_CHAR_WIDTH * this.scale; const charHeight = Constants.BASE_CHAR_HEIGHT * this.scale; if (dx + charWidth > target.width || dy + charHeight > target.height) { console.warn('bad render request outside image data'); return; } const charData = useLighterFont ? this.charDataLight : this.charDataNormal; const charIndex = getCharIndex(chCode); const destWidth = target.width * Constants.RGBA_CHANNELS_CNT; const backgroundR = backgroundColor.r; const backgroundG = backgroundColor.g; const backgroundB = backgroundColor.b; const deltaR = color.r - backgroundR; const deltaG = color.g - backgroundG; const deltaB = color.b - backgroundB; const dest = target.data; let sourceOffset = charIndex * charWidth * charHeight; let row = dy * destWidth + dx * Constants.RGBA_CHANNELS_CNT; for (let y = 0; y < charHeight; y++) { let column = row; for (let x = 0; x < charWidth; x++) { const c = charData[sourceOffset++] / 255; dest[column++] = backgroundR + deltaR * c; dest[column++] = backgroundG + deltaG * c; dest[column++] = backgroundB + deltaB * c; column++; } row += destWidth; } } public blockRenderChar( target: ImageData, dx: number, dy: number, color: RGBA8, backgroundColor: RGBA8, useLighterFont: boolean ): void { const charWidth = Constants.BASE_CHAR_WIDTH * this.scale; const charHeight = Constants.BASE_CHAR_HEIGHT * this.scale; if (dx + charWidth > target.width || dy + charHeight > target.height) { console.warn('bad render request outside image data'); return; } const destWidth = target.width * Constants.RGBA_CHANNELS_CNT; const c = 0.5; const backgroundR = backgroundColor.r; const backgroundG = backgroundColor.g; const backgroundB = backgroundColor.b; const deltaR = color.r - backgroundR; const deltaG = color.g - backgroundG; const deltaB = color.b - backgroundB; const colorR = backgroundR + deltaR * c; const colorG = backgroundG + deltaG * c; const colorB = backgroundB + deltaB * c; const dest = target.data; let row = dy * destWidth + dx * Constants.RGBA_CHANNELS_CNT; for (let y = 0; y < charHeight; y++) { let column = row; for (let x = 0; x < charWidth; x++) { dest[column++] = colorR; dest[column++] = colorG; dest[column++] = colorB; column++; } row += destWidth; } } }
src/vs/editor/browser/viewParts/minimap/minimapCharRenderer.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017369925626553595, 0.00017073990602511913, 0.0001678462722338736, 0.00017075924552045763, 0.0000017151975271190167 ]
{ "id": 8, "code_window": [ "\t\t\t\t\tthis.ui.list.clearFocus();\n", "\t\t\t\t}\n", "\t\t\t}));\n", "\t\t\tthis.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => {\n", "\t\t\t\tthis.ui.keyDownSeenSinceShown = true;\n", "\t\t\t\tswitch (event.keyCode) {\n", "\t\t\t\t\tcase KeyCode.DownArrow:\n", "\t\t\t\t\t\tthis.ui.list.focus('Next');\n", "\t\t\t\t\t\tif (this.canSelectMany) {\n", "\t\t\t\t\t\t\tthis.ui.list.domFocus();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 558 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./textAreaHandler'; import * as nls from 'vs/nls'; import * as browser from 'vs/base/browser/browser'; import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import * as platform from 'vs/base/common/platform'; import * as strings from 'vs/base/common/strings'; import { Configuration } from 'vs/editor/browser/config/configuration'; import { CopyOptions, ICompositionData, IPasteData, ITextAreaInputHost, TextAreaInput, ClipboardDataToCopy } from 'vs/editor/browser/controller/textAreaInput'; import { ISimpleModel, ITypeData, PagedScreenReaderStrategy, TextAreaState } from 'vs/editor/browser/controller/textAreaState'; import { ViewController } from 'vs/editor/browser/view/viewController'; import { PartFingerprint, PartFingerprints, ViewPart } from 'vs/editor/browser/view/viewPart'; import { LineNumbersOverlay } from 'vs/editor/browser/viewParts/lineNumbers/lineNumbers'; import { Margin } from 'vs/editor/browser/viewParts/margin/margin'; import { RenderLineNumbersType, EditorOption, IComputedEditorOptions } from 'vs/editor/common/config/editorOptions'; import { BareFontInfo } from 'vs/editor/common/config/fontInfo'; import { WordCharacterClass, getMapForWordSeparators } from 'vs/editor/common/controller/wordCharacterClassifier'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { EndOfLinePreference } from 'vs/editor/common/model'; import { RenderingContext, RestrictedRenderingContext, HorizontalPosition } from 'vs/editor/common/view/renderingContext'; import { ViewContext } from 'vs/editor/common/view/viewContext'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; export interface ITextAreaHandlerHelper { visibleRangeForPositionRelativeToEditor(lineNumber: number, column: number): HorizontalPosition | null; } class VisibleTextAreaData { _visibleTextAreaBrand: void; public readonly top: number; public readonly left: number; public readonly width: number; constructor(top: number, left: number, width: number) { this.top = top; this.left = left; this.width = width; } public setWidth(width: number): VisibleTextAreaData { return new VisibleTextAreaData(this.top, this.left, width); } } const canUseZeroSizeTextarea = (browser.isEdgeOrIE || browser.isFirefox); export class TextAreaHandler extends ViewPart { private readonly _viewController: ViewController; private readonly _viewHelper: ITextAreaHandlerHelper; private _scrollLeft: number; private _scrollTop: number; private _accessibilitySupport: AccessibilitySupport; private _contentLeft: number; private _contentWidth: number; private _contentHeight: number; private _fontInfo: BareFontInfo; private _lineHeight: number; private _emptySelectionClipboard: boolean; private _copyWithSyntaxHighlighting: boolean; /** * Defined only when the text area is visible (composition case). */ private _visibleTextArea: VisibleTextAreaData | null; private _selections: Selection[]; public readonly textArea: FastDomNode<HTMLTextAreaElement>; public readonly textAreaCover: FastDomNode<HTMLElement>; private readonly _textAreaInput: TextAreaInput; constructor(context: ViewContext, viewController: ViewController, viewHelper: ITextAreaHandlerHelper) { super(context); this._viewController = viewController; this._viewHelper = viewHelper; this._scrollLeft = 0; this._scrollTop = 0; const options = this._context.configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this._accessibilitySupport = options.get(EditorOption.accessibilitySupport); this._contentLeft = layoutInfo.contentLeft; this._contentWidth = layoutInfo.contentWidth; this._contentHeight = layoutInfo.contentHeight; this._fontInfo = options.get(EditorOption.fontInfo); this._lineHeight = options.get(EditorOption.lineHeight); this._emptySelectionClipboard = options.get(EditorOption.emptySelectionClipboard); this._copyWithSyntaxHighlighting = options.get(EditorOption.copyWithSyntaxHighlighting); this._visibleTextArea = null; this._selections = [new Selection(1, 1, 1, 1)]; // Text Area (The focus will always be in the textarea when the cursor is blinking) this.textArea = createFastDomNode(document.createElement('textarea')); PartFingerprints.write(this.textArea, PartFingerprint.TextArea); this.textArea.setClassName('inputarea'); this.textArea.setAttribute('wrap', 'off'); this.textArea.setAttribute('autocorrect', 'off'); this.textArea.setAttribute('autocapitalize', 'off'); this.textArea.setAttribute('autocomplete', 'off'); this.textArea.setAttribute('spellcheck', 'false'); this.textArea.setAttribute('aria-label', this._getAriaLabel(options)); this.textArea.setAttribute('role', 'textbox'); this.textArea.setAttribute('aria-multiline', 'true'); this.textArea.setAttribute('aria-haspopup', 'false'); this.textArea.setAttribute('aria-autocomplete', 'both'); if (platform.isWeb && options.get(EditorOption.readOnly)) { this.textArea.setAttribute('readonly', 'true'); } this.textAreaCover = createFastDomNode(document.createElement('div')); this.textAreaCover.setPosition('absolute'); const simpleModel: ISimpleModel = { getLineCount: (): number => { return this._context.model.getLineCount(); }, getLineMaxColumn: (lineNumber: number): number => { return this._context.model.getLineMaxColumn(lineNumber); }, getValueInRange: (range: Range, eol: EndOfLinePreference): string => { return this._context.model.getValueInRange(range, eol); } }; const textAreaInputHost: ITextAreaInputHost = { getDataToCopy: (generateHTML: boolean): ClipboardDataToCopy => { const rawTextToCopy = this._context.model.getPlainTextToCopy(this._selections, this._emptySelectionClipboard, platform.isWindows); const newLineCharacter = this._context.model.getEOL(); const isFromEmptySelection = (this._emptySelectionClipboard && this._selections.length === 1 && this._selections[0].isEmpty()); const multicursorText = (Array.isArray(rawTextToCopy) ? rawTextToCopy : null); const text = (Array.isArray(rawTextToCopy) ? rawTextToCopy.join(newLineCharacter) : rawTextToCopy); let html: string | null | undefined = undefined; if (generateHTML) { if (CopyOptions.forceCopyWithSyntaxHighlighting || (this._copyWithSyntaxHighlighting && text.length < 65536)) { html = this._context.model.getHTMLToCopy(this._selections, this._emptySelectionClipboard); } } return { isFromEmptySelection, multicursorText, text, html }; }, getScreenReaderContent: (currentState: TextAreaState): TextAreaState => { if (browser.isIPad) { // Do not place anything in the textarea for the iPad return TextAreaState.EMPTY; } if (this._accessibilitySupport === AccessibilitySupport.Disabled) { // We know for a fact that a screen reader is not attached // On OSX, we write the character before the cursor to allow for "long-press" composition // Also on OSX, we write the word before the cursor to allow for the Accessibility Keyboard to give good hints if (platform.isMacintosh) { const selection = this._selections[0]; if (selection.isEmpty()) { const position = selection.getStartPosition(); let textBefore = this._getWordBeforePosition(position); if (textBefore.length === 0) { textBefore = this._getCharacterBeforePosition(position); } if (textBefore.length > 0) { return new TextAreaState(textBefore, textBefore.length, textBefore.length, position, position); } } } return TextAreaState.EMPTY; } return PagedScreenReaderStrategy.fromEditorSelection(currentState, simpleModel, this._selections[0], this._accessibilitySupport === AccessibilitySupport.Unknown); }, deduceModelPosition: (viewAnchorPosition: Position, deltaOffset: number, lineFeedCnt: number): Position => { return this._context.model.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt); } }; this._textAreaInput = this._register(new TextAreaInput(textAreaInputHost, this.textArea)); this._register(this._textAreaInput.onKeyDown((e: IKeyboardEvent) => { this._viewController.emitKeyDown(e); })); this._register(this._textAreaInput.onKeyUp((e: IKeyboardEvent) => { this._viewController.emitKeyUp(e); })); this._register(this._textAreaInput.onPaste((e: IPasteData) => { let pasteOnNewLine = false; let multicursorText: string[] | null = null; if (e.metadata) { pasteOnNewLine = (this._emptySelectionClipboard && !!e.metadata.isFromEmptySelection); multicursorText = (typeof e.metadata.multicursorText !== 'undefined' ? e.metadata.multicursorText : null); } this._viewController.paste('keyboard', e.text, pasteOnNewLine, multicursorText); })); this._register(this._textAreaInput.onCut(() => { this._viewController.cut('keyboard'); })); this._register(this._textAreaInput.onType((e: ITypeData) => { if (e.replaceCharCnt) { this._viewController.replacePreviousChar('keyboard', e.text, e.replaceCharCnt); } else { this._viewController.type('keyboard', e.text); } })); this._register(this._textAreaInput.onSelectionChangeRequest((modelSelection: Selection) => { this._viewController.setSelection('keyboard', modelSelection); })); this._register(this._textAreaInput.onCompositionStart(() => { const lineNumber = this._selections[0].startLineNumber; const column = this._selections[0].startColumn; this._context.privateViewEventBus.emit(new viewEvents.ViewRevealRangeRequestEvent( 'keyboard', new Range(lineNumber, column, lineNumber, column), viewEvents.VerticalRevealType.Simple, true, ScrollType.Immediate )); // Find range pixel position const visibleRange = this._viewHelper.visibleRangeForPositionRelativeToEditor(lineNumber, column); if (visibleRange) { this._visibleTextArea = new VisibleTextAreaData( this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber), visibleRange.left, canUseZeroSizeTextarea ? 0 : 1 ); this._render(); } // Show the textarea this.textArea.setClassName('inputarea ime-input'); this._viewController.compositionStart('keyboard'); })); this._register(this._textAreaInput.onCompositionUpdate((e: ICompositionData) => { if (browser.isEdgeOrIE) { // Due to isEdgeOrIE (where the textarea was not cleared initially) // we cannot assume the text consists only of the composited text this._visibleTextArea = this._visibleTextArea!.setWidth(0); } else { // adjust width by its size this._visibleTextArea = this._visibleTextArea!.setWidth(measureText(e.data, this._fontInfo)); } this._render(); })); this._register(this._textAreaInput.onCompositionEnd(() => { this._visibleTextArea = null; this._render(); this.textArea.setClassName('inputarea'); this._viewController.compositionEnd('keyboard'); })); this._register(this._textAreaInput.onFocus(() => { this._context.privateViewEventBus.emit(new viewEvents.ViewFocusChangedEvent(true)); })); this._register(this._textAreaInput.onBlur(() => { this._context.privateViewEventBus.emit(new viewEvents.ViewFocusChangedEvent(false)); })); } public dispose(): void { super.dispose(); } private _getWordBeforePosition(position: Position): string { const lineContent = this._context.model.getLineContent(position.lineNumber); const wordSeparators = getMapForWordSeparators(this._context.configuration.options.get(EditorOption.wordSeparators)); let column = position.column; let distance = 0; while (column > 1) { const charCode = lineContent.charCodeAt(column - 2); const charClass = wordSeparators.get(charCode); if (charClass !== WordCharacterClass.Regular || distance > 50) { return lineContent.substring(column - 1, position.column - 1); } distance++; column--; } return lineContent.substring(0, position.column - 1); } private _getCharacterBeforePosition(position: Position): string { if (position.column > 1) { const lineContent = this._context.model.getLineContent(position.lineNumber); const charBefore = lineContent.charAt(position.column - 2); if (!strings.isHighSurrogate(charBefore.charCodeAt(0))) { return charBefore; } } return ''; } private _getAriaLabel(options: IComputedEditorOptions): string { const accessibilitySupport = options.get(EditorOption.accessibilitySupport); if (accessibilitySupport === AccessibilitySupport.Disabled) { return nls.localize('accessibilityOffAriaLabel', "The editor is not accessible at this time. Press Alt+F1 for options."); } return options.get(EditorOption.ariaLabel); } // --- begin event handlers public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { const options = this._context.configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this._accessibilitySupport = options.get(EditorOption.accessibilitySupport); this._contentLeft = layoutInfo.contentLeft; this._contentWidth = layoutInfo.contentWidth; this._contentHeight = layoutInfo.contentHeight; this._fontInfo = options.get(EditorOption.fontInfo); this._lineHeight = options.get(EditorOption.lineHeight); this._emptySelectionClipboard = options.get(EditorOption.emptySelectionClipboard); this._copyWithSyntaxHighlighting = options.get(EditorOption.copyWithSyntaxHighlighting); this.textArea.setAttribute('aria-label', this._getAriaLabel(options)); if (platform.isWeb && e.hasChanged(EditorOption.readOnly)) { if (options.get(EditorOption.readOnly)) { this.textArea.setAttribute('readonly', 'true'); } else { this.textArea.removeAttribute('readonly'); } } if (e.hasChanged(EditorOption.accessibilitySupport)) { this._textAreaInput.writeScreenReaderContent('strategy changed'); } return true; } public onCursorStateChanged(e: viewEvents.ViewCursorStateChangedEvent): boolean { this._selections = e.selections.slice(0); this._textAreaInput.writeScreenReaderContent('selection changed'); return true; } public onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean { // true for inline decorations that can end up relayouting text return true; } public onFlushed(e: viewEvents.ViewFlushedEvent): boolean { return true; } public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean { return true; } public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean { return true; } public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean { return true; } public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean { this._scrollLeft = e.scrollLeft; this._scrollTop = e.scrollTop; return true; } public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean { return true; } // --- end event handlers // --- begin view API public isFocused(): boolean { return this._textAreaInput.isFocused(); } public focusTextArea(): void { this._textAreaInput.focusTextArea(); } public refreshFocusState() { this._textAreaInput.refreshFocusState(); } // --- end view API private _primaryCursorVisibleRange: HorizontalPosition | null = null; public prepareRender(ctx: RenderingContext): void { const primaryCursorPosition = new Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn); this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(primaryCursorPosition); } public render(ctx: RestrictedRenderingContext): void { this._textAreaInput.writeScreenReaderContent('render'); this._render(); } private _render(): void { if (this._visibleTextArea) { // The text area is visible for composition reasons this._renderInsideEditor( this._visibleTextArea.top - this._scrollTop, this._contentLeft + this._visibleTextArea.left - this._scrollLeft, this._visibleTextArea.width, this._lineHeight ); return; } if (!this._primaryCursorVisibleRange) { // The primary cursor is outside the viewport => place textarea to the top left this._renderAtTopLeft(); return; } const left = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft; if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) { // cursor is outside the viewport this._renderAtTopLeft(); return; } const top = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop; if (top < 0 || top > this._contentHeight) { // cursor is outside the viewport this._renderAtTopLeft(); return; } // The primary cursor is in the viewport (at least vertically) => place textarea on the cursor if (platform.isMacintosh) { // For the popup emoji input, we will make the text area as high as the line height // We will also make the fontSize and lineHeight the correct dimensions to help with the placement of these pickers this._renderInsideEditor( top, left, canUseZeroSizeTextarea ? 0 : 1, this._lineHeight ); return; } this._renderInsideEditor( top, left, canUseZeroSizeTextarea ? 0 : 1, canUseZeroSizeTextarea ? 0 : 1 ); } private _renderInsideEditor(top: number, left: number, width: number, height: number): void { const ta = this.textArea; const tac = this.textAreaCover; Configuration.applyFontInfo(ta, this._fontInfo); ta.setTop(top); ta.setLeft(left); ta.setWidth(width); ta.setHeight(height); tac.setTop(0); tac.setLeft(0); tac.setWidth(0); tac.setHeight(0); } private _renderAtTopLeft(): void { const ta = this.textArea; const tac = this.textAreaCover; Configuration.applyFontInfo(ta, this._fontInfo); ta.setTop(0); ta.setLeft(0); tac.setTop(0); tac.setLeft(0); if (canUseZeroSizeTextarea) { ta.setWidth(0); ta.setHeight(0); tac.setWidth(0); tac.setHeight(0); return; } // (in WebKit the textarea is 1px by 1px because it cannot handle input to a 0x0 textarea) // specifically, when doing Korean IME, setting the textarea to 0x0 breaks IME badly. ta.setWidth(1); ta.setHeight(1); tac.setWidth(1); tac.setHeight(1); const options = this._context.configuration.options; if (options.get(EditorOption.glyphMargin)) { tac.setClassName('monaco-editor-background textAreaCover ' + Margin.OUTER_CLASS_NAME); } else { if (options.get(EditorOption.lineNumbers).renderType !== RenderLineNumbersType.Off) { tac.setClassName('monaco-editor-background textAreaCover ' + LineNumbersOverlay.CLASS_NAME); } else { tac.setClassName('monaco-editor-background textAreaCover'); } } } } function measureText(text: string, fontInfo: BareFontInfo): number { // adjust width by its size const canvasElem = <HTMLCanvasElement>document.createElement('canvas'); const context = canvasElem.getContext('2d')!; context.font = createFontString(fontInfo); const metrics = context.measureText(text); if (browser.isFirefox) { return metrics.width + 2; // +2 for Japanese... } else { return metrics.width; } } function createFontString(bareFontInfo: BareFontInfo): string { return doCreateFontString('normal', bareFontInfo.fontWeight, bareFontInfo.fontSize, bareFontInfo.lineHeight, bareFontInfo.fontFamily); } function doCreateFontString(fontStyle: string, fontWeight: string, fontSize: number, lineHeight: number, fontFamily: string): string { // The full font syntax is: // style | variant | weight | stretch | size/line-height | fontFamily // (https://developer.mozilla.org/en-US/docs/Web/CSS/font) // But it appears Edge and IE11 cannot properly parse `stretch`. return `${fontStyle} normal ${fontWeight} ${fontSize}px / ${lineHeight}px ${fontFamily}`; }
src/vs/editor/browser/controller/textAreaHandler.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0003918400325346738, 0.00017240781744476408, 0.00016135399346239865, 0.00016849907115101814, 0.000029758391974610277 ]
{ "id": 8, "code_window": [ "\t\t\t\t\tthis.ui.list.clearFocus();\n", "\t\t\t\t}\n", "\t\t\t}));\n", "\t\t\tthis.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => {\n", "\t\t\t\tthis.ui.keyDownSeenSinceShown = true;\n", "\t\t\t\tswitch (event.keyCode) {\n", "\t\t\t\t\tcase KeyCode.DownArrow:\n", "\t\t\t\t\t\tthis.ui.list.focus('Next');\n", "\t\t\t\t\t\tif (this.canSelectMany) {\n", "\t\t\t\t\t\t\tthis.ui.list.domFocus();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 558 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M12.2376 8L9.9282 12H5.3094L3 8L5.3094 4H9.9282L12.2376 8Z" fill="#848484"/> </svg>
src/vs/workbench/contrib/debug/browser/media/breakpoint-data-disabled.svg
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017132436914835125, 0.00017132436914835125, 0.00017132436914835125, 0.00017132436914835125, 0 ]
{ "id": 9, "code_window": [ "\n", "\tprivate registerQuickNavigation() {\n", "\t\treturn dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => {\n", "\t\t\tif (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (this.canSelectMany || !this.quickNavigate) {\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 657 }
/*--------------------------------------------------------------------------------------------- * 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!./quickopen'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import { IQuickNavigateConfiguration, IAutoFocus, IEntryRunContext, IModel, Mode, IKeyMods } from 'vs/base/parts/quickopen/common/quickOpen'; import { Filter, Renderer, DataSource, IModelProvider, AccessibilityProvider } from 'vs/base/parts/quickopen/browser/quickOpenViewer'; import { ITree, ContextMenuEvent, IActionProvider, ITreeStyles, ITreeOptions, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree'; import { InputBox, MessageType, IInputBoxStyles, IRange } from 'vs/base/browser/ui/inputbox/inputBox'; import Severity from 'vs/base/common/severity'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { DefaultController, ClickBehavior } from 'vs/base/parts/tree/browser/treeDefaults'; import * as DOM from 'vs/base/browser/dom'; import { KeyCode } from 'vs/base/common/keyCodes'; import { Disposable } from 'vs/base/common/lifecycle'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { StandardMouseEvent, IMouseEvent } from 'vs/base/browser/mouseEvent'; import { IThemable } from 'vs/base/common/styler'; export interface IQuickOpenCallbacks { onOk: () => void; onCancel: () => void; onType: (value: string) => void; onShow?: () => void; onHide?: (reason: HideReason) => void; onFocusLost?: () => boolean /* veto close */; } export interface IQuickOpenOptions extends IQuickOpenStyles { minItemsToShow?: number; maxItemsToShow?: number; inputPlaceHolder?: string; inputAriaLabel?: string; actionProvider?: IActionProvider; keyboardSupport?: boolean; treeCreator?: (container: HTMLElement, configuration: ITreeConfiguration, options?: ITreeOptions) => ITree; } export interface IQuickOpenStyles extends IInputBoxStyles, ITreeStyles { background?: Color; foreground?: Color; borderColor?: Color; pickerGroupForeground?: Color; pickerGroupBorder?: Color; widgetShadow?: Color; progressBarBackground?: Color; } export interface IShowOptions { quickNavigateConfiguration?: IQuickNavigateConfiguration; autoFocus?: IAutoFocus; inputSelection?: IRange; value?: string; } export class QuickOpenController extends DefaultController { onContextMenu(tree: ITree, element: any, event: ContextMenuEvent): boolean { if (platform.isMacintosh) { return this.onLeftClick(tree, element, event); // https://github.com/Microsoft/vscode/issues/1011 } return super.onContextMenu(tree, element, event); } onMouseMiddleClick(tree: ITree, element: any, event: IMouseEvent): boolean { return this.onLeftClick(tree, element, event); } } export const enum HideReason { ELEMENT_SELECTED, FOCUS_LOST, CANCELED } const defaultStyles = { background: Color.fromHex('#1E1E1E'), foreground: Color.fromHex('#CCCCCC'), pickerGroupForeground: Color.fromHex('#0097FB'), pickerGroupBorder: Color.fromHex('#3F3F46'), widgetShadow: Color.fromHex('#000000'), progressBarBackground: Color.fromHex('#0E70C0') }; const DEFAULT_INPUT_ARIA_LABEL = nls.localize('quickOpenAriaLabel', "Quick picker. Type to narrow down results."); export class QuickOpenWidget extends Disposable implements IModelProvider, IThemable { private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private static readonly MAX_ITEMS_HEIGHT = 20 * 22; // Max height of item list below input field private isDisposed: boolean; private options: IQuickOpenOptions; // @ts-ignore (legacy widget - to be replaced with quick input) private element: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private tree: ITree; // @ts-ignore (legacy widget - to be replaced with quick input) private inputBox: InputBox; // @ts-ignore (legacy widget - to be replaced with quick input) private inputContainer: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private helpText: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private resultCount: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private treeContainer: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private progressBar: ProgressBar; // @ts-ignore (legacy widget - to be replaced with quick input) private visible: boolean; // @ts-ignore (legacy widget - to be replaced with quick input) private isLoosingFocus: boolean; private callbacks: IQuickOpenCallbacks; private quickNavigateConfiguration: IQuickNavigateConfiguration | undefined; private container: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private treeElement: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private inputElement: HTMLElement; // @ts-ignore (legacy widget - to be replaced with quick input) private layoutDimensions: DOM.Dimension; private model: IModel<any> | null; private inputChangingTimeoutHandle: any; // @ts-ignore (legacy widget - to be replaced with quick input) private styles: IQuickOpenStyles; // @ts-ignore (legacy widget - to be replaced with quick input) private renderer: Renderer; private keyDownSeenSinceShown = false; constructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions) { super(); this.isDisposed = false; this.container = container; this.callbacks = callbacks; this.options = options; this.styles = options || Object.create(null); mixin(this.styles, defaultStyles, false); this.model = null; } getElement(): HTMLElement { return this.element; } getModel(): IModel<any> { return this.model!; } setCallbacks(callbacks: IQuickOpenCallbacks): void { this.callbacks = callbacks; } create(): HTMLElement { // Container this.element = document.createElement('div'); DOM.addClass(this.element, 'monaco-quick-open-widget'); this.container.appendChild(this.element); this._register(DOM.addDisposableListener(this.element, DOM.EventType.CONTEXT_MENU, e => DOM.EventHelper.stop(e, true))); // Do this to fix an issue on Mac where the menu goes into the way this._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, e => this.gainingFocus(), true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, e => this.loosingFocus(e), true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, e => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); if (keyboardEvent.keyCode === KeyCode.Escape) { DOM.EventHelper.stop(e, true); this.hide(HideReason.CANCELED); } else if (keyboardEvent.keyCode === KeyCode.Tab && !keyboardEvent.altKey && !keyboardEvent.ctrlKey && !keyboardEvent.metaKey) { const stops = (e.currentTarget as HTMLElement).querySelectorAll('input, .monaco-tree, .monaco-tree-row.focused .action-label.icon') as NodeListOf<HTMLElement>; if (keyboardEvent.shiftKey && keyboardEvent.target === stops[0]) { DOM.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!keyboardEvent.shiftKey && keyboardEvent.target === stops[stops.length - 1]) { DOM.EventHelper.stop(e, true); stops[0].focus(); } } })); // Progress Bar this.progressBar = this._register(new ProgressBar(this.element, { progressBarBackground: this.styles.progressBarBackground })); this.progressBar.hide(); // Input Field this.inputContainer = document.createElement('div'); DOM.addClass(this.inputContainer, 'quick-open-input'); this.element.appendChild(this.inputContainer); this.inputBox = this._register(new InputBox(this.inputContainer, undefined, { placeholder: this.options.inputPlaceHolder || '', ariaLabel: DEFAULT_INPUT_ARIA_LABEL, inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder })); this.inputElement = this.inputBox.inputElement; this.inputElement.setAttribute('role', 'combobox'); this.inputElement.setAttribute('aria-haspopup', 'false'); this.inputElement.setAttribute('aria-autocomplete', 'list'); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, (e: Event) => this.onType())); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const shouldOpenInBackground = this.shouldOpenInBackground(keyboardEvent); // Do not handle Tab: It is used to navigate between elements without mouse if (keyboardEvent.keyCode === KeyCode.Tab) { return; } // Pass tree navigation keys to the tree but leave focus in input field else if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); // Position cursor at the end of input to allow right arrow (open in background) // to function immediately unless the user has made a selection if (this.inputBox.inputElement.selectionStart === this.inputBox.inputElement.selectionEnd) { this.inputBox.inputElement.selectionStart = this.inputBox.value.length; } } // Select element on Enter or on Arrow-Right if we are at the end of the input else if (keyboardEvent.keyCode === KeyCode.Enter || shouldOpenInBackground) { DOM.EventHelper.stop(e, true); const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus, e, shouldOpenInBackground ? Mode.OPEN_IN_BACKGROUND : Mode.OPEN); } } })); // Result count for screen readers this.resultCount = document.createElement('div'); DOM.addClass(this.resultCount, 'quick-open-result-count'); this.resultCount.setAttribute('aria-live', 'polite'); this.resultCount.setAttribute('aria-atomic', 'true'); this.element.appendChild(this.resultCount); // Tree this.treeContainer = document.createElement('div'); DOM.addClass(this.treeContainer, 'quick-open-tree'); this.element.appendChild(this.treeContainer); const createTree = this.options.treeCreator || ((container, config, opts) => new Tree(container, config, opts)); this.tree = this._register(createTree(this.treeContainer, { dataSource: new DataSource(this), controller: new QuickOpenController({ clickBehavior: ClickBehavior.ON_MOUSE_UP, keyboardSupport: this.options.keyboardSupport }), renderer: (this.renderer = new Renderer(this, this.styles)), filter: new Filter(this), accessibilityProvider: new AccessibilityProvider(this) }, { twistiePixels: 11, indentPixels: 0, alwaysFocused: true, verticalScrollMode: ScrollbarVisibility.Visible, horizontalScrollMode: ScrollbarVisibility.Hidden, ariaLabel: nls.localize('treeAriaLabel', "Quick Picker"), keyboardSupport: this.options.keyboardSupport, preventRootFocus: false })); this.treeElement = this.tree.getHTMLElement(); // Handle Focus and Selection event this._register(this.tree.onDidChangeFocus(event => { this.elementFocused(event.focus, event); })); this._register(this.tree.onDidChangeSelection(event => { if (event.selection && event.selection.length > 0) { const mouseEvent: StandardMouseEvent = event.payload && event.payload.originalEvent instanceof StandardMouseEvent ? event.payload.originalEvent : undefined; const shouldOpenInBackground = mouseEvent ? this.shouldOpenInBackground(mouseEvent) : false; this.elementSelected(event.selection[0], event, shouldOpenInBackground ? Mode.OPEN_IN_BACKGROUND : Mode.OPEN); } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, e => { this.keyDownSeenSinceShown = true; const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); // Only handle when in quick navigation mode if (!this.quickNavigateConfiguration) { return; } // Support keyboard navigation in quick navigation mode if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode); } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, e => { const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Only handle when in quick navigation mode if (!this.quickNavigateConfiguration || !this.keyDownSeenSinceShown) { return; } // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigateConfiguration.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed) { const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus, e); } } })); // Support layout if (this.layoutDimensions) { this.layout(this.layoutDimensions); } this.applyStyles(); // Allows focus to switch to next/previous entry after tab into an actionbar item this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); // Only handle when not in quick navigation mode if (this.quickNavigateConfiguration) { return; } if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) { DOM.EventHelper.stop(e, true); this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); this.treeElement.focus(); } })); return this.element; } style(styles: IQuickOpenStyles): void { this.styles = styles; this.applyStyles(); } protected applyStyles(): void { if (this.element) { const foreground = this.styles.foreground ? this.styles.foreground.toString() : null; const background = this.styles.background ? this.styles.background.toString() : ''; const borderColor = this.styles.borderColor ? this.styles.borderColor.toString() : ''; const widgetShadow = this.styles.widgetShadow ? this.styles.widgetShadow.toString() : ''; this.element.style.color = foreground; this.element.style.backgroundColor = background; this.element.style.borderColor = borderColor; this.element.style.borderWidth = borderColor ? '1px' : ''; this.element.style.borderStyle = borderColor ? 'solid' : ''; this.element.style.boxShadow = widgetShadow ? `0 5px 8px ${widgetShadow}` : ''; } if (this.progressBar) { this.progressBar.style({ progressBarBackground: this.styles.progressBarBackground }); } if (this.inputBox) { this.inputBox.style({ inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder }); } if (this.tree && !this.options.treeCreator) { this.tree.style(this.styles); } if (this.renderer) { this.renderer.updateStyles(this.styles); } } private shouldOpenInBackground(e: StandardKeyboardEvent | StandardMouseEvent): boolean { // Keyboard if (e instanceof StandardKeyboardEvent) { if (e.keyCode !== KeyCode.RightArrow) { return false; // only for right arrow } if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return false; // no modifiers allowed } // validate the cursor is at the end of the input and there is no selection, // and if not prevent opening in the background such as the selection can be changed const element = this.inputBox.inputElement; return element.selectionEnd === this.inputBox.value.length && element.selectionStart === element.selectionEnd; } // Mouse return e.middleButton; } private onType(): void { const value = this.inputBox.value; // Adjust help text as needed if present if (this.helpText) { if (value) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Send to callbacks this.callbacks.onType(value); } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void { if (this.isVisible()) { // Transition into quick navigate mode if not yet done if (!this.quickNavigateConfiguration && quickNavigate) { this.quickNavigateConfiguration = quickNavigate; this.tree.domFocus(); } // Navigate this.navigateInTree(next ? KeyCode.DownArrow : KeyCode.UpArrow); } } private navigateInTree(keyCode: KeyCode, isShift?: boolean): void { const model: IModel<any> = this.tree.getInput(); const entries = model ? model.entries : []; const oldFocus = this.tree.getFocus(); // Normal Navigation switch (keyCode) { case KeyCode.DownArrow: this.tree.focusNext(); break; case KeyCode.UpArrow: this.tree.focusPrevious(); break; case KeyCode.PageDown: this.tree.focusNextPage(); break; case KeyCode.PageUp: this.tree.focusPreviousPage(); break; case KeyCode.Tab: if (isShift) { this.tree.focusPrevious(); } else { this.tree.focusNext(); } break; } let newFocus = this.tree.getFocus(); // Support cycle-through navigation if focus did not change if (entries.length > 1 && oldFocus === newFocus) { // Up from no entry or first entry goes down to last if (keyCode === KeyCode.UpArrow || (keyCode === KeyCode.Tab && isShift)) { this.tree.focusLast(); } // Down from last entry goes to up to first else if (keyCode === KeyCode.DownArrow || keyCode === KeyCode.Tab && !isShift) { this.tree.focusFirst(); } } // Reveal newFocus = this.tree.getFocus(); if (newFocus) { this.tree.reveal(newFocus); } } private elementFocused(value: any, event?: any): void { if (!value || !this.isVisible()) { return; } // ARIA const arivaActiveDescendant = this.treeElement.getAttribute('aria-activedescendant'); if (arivaActiveDescendant) { this.inputElement.setAttribute('aria-activedescendant', arivaActiveDescendant); } else { this.inputElement.removeAttribute('aria-activedescendant'); } const context: IEntryRunContext = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; this.model!.runner.run(value, Mode.PREVIEW, context); } private elementSelected(value: any, event?: any, preferredMode?: Mode): void { let hide = true; // Trigger open of element on selection if (this.isVisible()) { let mode = preferredMode || Mode.OPEN; const context: IEntryRunContext = { event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; hide = this.model!.runner.run(value, mode, context); } // Hide if command was run successfully if (hide) { this.hide(HideReason.ELEMENT_SELECTED); } } private extractKeyMods(event: any): IKeyMods { return { ctrlCmd: event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey))), alt: event && (event.altKey || (event.payload && event.payload.originalEvent && event.payload.originalEvent.altKey)) }; } show(prefix: string, options?: IShowOptions): void; show(input: IModel<any>, options?: IShowOptions): void; show(param: any, options?: IShowOptions): void { this.visible = true; this.isLoosingFocus = false; this.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined; this.keyDownSeenSinceShown = false; // Adjust UI for quick navigate mode if (this.quickNavigateConfiguration) { DOM.hide(this.inputContainer); DOM.show(this.element); this.tree.domFocus(); } // Otherwise use normal UI else { DOM.show(this.inputContainer); DOM.show(this.element); this.inputBox.focus(); } // Adjust Help text for IE if (this.helpText) { if (this.quickNavigateConfiguration || types.isString(param)) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Show based on param if (types.isString(param)) { this.doShowWithPrefix(param); } else { if (options && options.value) { this.restoreLastInput(options.value); } this.doShowWithInput(param, options && options.autoFocus ? options.autoFocus : {}); } // Respect selectAll option if (options && options.inputSelection && !this.quickNavigateConfiguration) { this.inputBox.select(options.inputSelection); } if (this.callbacks.onShow) { this.callbacks.onShow(); } } private restoreLastInput(lastInput: string) { this.inputBox.value = lastInput; this.inputBox.select(); this.callbacks.onType(lastInput); } private doShowWithPrefix(prefix: string): void { this.inputBox.value = prefix; this.callbacks.onType(prefix); } private doShowWithInput(input: IModel<any>, autoFocus: IAutoFocus): void { this.setInput(input, autoFocus); } private setInputAndLayout(input: IModel<any>, autoFocus?: IAutoFocus): void { this.treeContainer.style.height = `${this.getHeight(input)}px`; this.tree.setInput(null).then(() => { this.model = input; // ARIA this.inputElement.setAttribute('aria-haspopup', String(input && input.entries && input.entries.length > 0)); return this.tree.setInput(input); }).then(() => { // Indicate entries to tree this.tree.layout(); const entries = input ? input.entries.filter(e => this.isElementVisible(input, e)) : []; this.updateResultCount(entries.length); // Handle auto focus if (entries.length) { this.autoFocus(input, entries, autoFocus); } }); } private isElementVisible<T>(input: IModel<T>, e: T): boolean { if (!input.filter) { return true; } return input.filter.isVisible(e); } private autoFocus(input: IModel<any>, entries: any[], autoFocus: IAutoFocus = {}): void { // First check for auto focus of prefix matches if (autoFocus.autoFocusPrefixMatch) { let caseSensitiveMatch: any; let caseInsensitiveMatch: any; const prefix = autoFocus.autoFocusPrefixMatch; const lowerCasePrefix = prefix.toLowerCase(); for (const entry of entries) { const label = input.dataSource.getLabel(entry) || ''; if (!caseSensitiveMatch && label.indexOf(prefix) === 0) { caseSensitiveMatch = entry; } else if (!caseInsensitiveMatch && label.toLowerCase().indexOf(lowerCasePrefix) === 0) { caseInsensitiveMatch = entry; } if (caseSensitiveMatch && caseInsensitiveMatch) { break; } } const entryToFocus = caseSensitiveMatch || caseInsensitiveMatch; if (entryToFocus) { this.tree.setFocus(entryToFocus); this.tree.reveal(entryToFocus, 0.5); return; } } // Second check for auto focus of first entry if (autoFocus.autoFocusFirstEntry) { this.tree.focusFirst(); this.tree.reveal(this.tree.getFocus()); } // Third check for specific index option else if (typeof autoFocus.autoFocusIndex === 'number') { if (entries.length > autoFocus.autoFocusIndex) { this.tree.focusNth(autoFocus.autoFocusIndex); this.tree.reveal(this.tree.getFocus()); } } // Check for auto focus of second entry else if (autoFocus.autoFocusSecondEntry) { if (entries.length > 1) { this.tree.focusNth(1); } } // Finally check for auto focus of last entry else if (autoFocus.autoFocusLastEntry) { if (entries.length > 1) { this.tree.focusLast(); } } } refresh(input?: IModel<any>, autoFocus?: IAutoFocus): void { if (!this.isVisible()) { return; } if (!input) { input = this.tree.getInput(); } if (!input) { return; } // Apply height & Refresh this.treeContainer.style.height = `${this.getHeight(input)}px`; this.tree.refresh().then(() => { // Indicate entries to tree this.tree.layout(); const entries = input ? input.entries!.filter(e => this.isElementVisible(input!, e)) : []; this.updateResultCount(entries.length); // Handle auto focus if (autoFocus) { if (entries.length) { this.autoFocus(input!, entries, autoFocus); } } }); } private getHeight(input: IModel<any>): number { const renderer = input.renderer; if (!input) { const itemHeight = renderer.getHeight(null); return this.options.minItemsToShow ? this.options.minItemsToShow * itemHeight : 0; } let height = 0; let preferredItemsHeight: number | undefined; if (this.layoutDimensions && this.layoutDimensions.height) { preferredItemsHeight = (this.layoutDimensions.height - 50 /* subtract height of input field (30px) and some spacing (drop shadow) to fit */) * 0.4 /* max 40% of screen */; } if (!preferredItemsHeight || preferredItemsHeight > QuickOpenWidget.MAX_ITEMS_HEIGHT) { preferredItemsHeight = QuickOpenWidget.MAX_ITEMS_HEIGHT; } const entries = input.entries.filter(e => this.isElementVisible(input, e)); const maxEntries = this.options.maxItemsToShow || entries.length; for (let i = 0; i < maxEntries && i < entries.length; i++) { const entryHeight = renderer.getHeight(entries[i]); if (height + entryHeight <= preferredItemsHeight) { height += entryHeight; } else { break; } } return height; } updateResultCount(count: number) { this.resultCount.textContent = nls.localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results", count); } hide(reason?: HideReason): void { if (!this.isVisible()) { return; } this.visible = false; DOM.hide(this.element); this.element.blur(); // Clear input field and clear tree this.inputBox.value = ''; this.tree.setInput(null); // ARIA this.inputElement.setAttribute('aria-haspopup', 'false'); // Reset Tree Height this.treeContainer.style.height = `${this.options.minItemsToShow ? this.options.minItemsToShow * 22 : 0}px`; // Clear any running Progress this.progressBar.stop().hide(); // Clear Focus if (this.tree.isDOMFocused()) { this.tree.domBlur(); } else if (this.inputBox.hasFocus()) { this.inputBox.blur(); } // Callbacks if (reason === HideReason.ELEMENT_SELECTED) { this.callbacks.onOk(); } else { this.callbacks.onCancel(); } if (this.callbacks.onHide) { this.callbacks.onHide(reason!); } } getQuickNavigateConfiguration(): IQuickNavigateConfiguration { return this.quickNavigateConfiguration!; } setPlaceHolder(placeHolder: string): void { if (this.inputBox) { this.inputBox.setPlaceHolder(placeHolder); } } setValue(value: string, selectionOrStableHint?: [number, number] | null): void { if (this.inputBox) { this.inputBox.value = value; if (selectionOrStableHint === null) { // null means stable-selection } else if (Array.isArray(selectionOrStableHint)) { const [start, end] = selectionOrStableHint; this.inputBox.select({ start, end }); } else { this.inputBox.select(); } } } setPassword(isPassword: boolean): void { if (this.inputBox) { this.inputBox.inputElement.type = isPassword ? 'password' : 'text'; } } setInput(input: IModel<any>, autoFocus?: IAutoFocus, ariaLabel?: string): void { if (!this.isVisible()) { return; } // If the input changes, indicate this to the tree if (!!this.getInput()) { this.onInputChanging(); } // Adapt tree height to entries and apply input this.setInputAndLayout(input, autoFocus); // Apply ARIA if (this.inputBox) { this.inputBox.setAriaLabel(ariaLabel || DEFAULT_INPUT_ARIA_LABEL); } } private onInputChanging(): void { if (this.inputChangingTimeoutHandle) { clearTimeout(this.inputChangingTimeoutHandle); this.inputChangingTimeoutHandle = null; } // when the input is changing in quick open, we indicate this as CSS class to the widget // for a certain timeout. this helps reducing some hectic UI updates when input changes quickly DOM.addClass(this.element, 'content-changing'); this.inputChangingTimeoutHandle = setTimeout(() => { DOM.removeClass(this.element, 'content-changing'); }, 500); } getInput(): IModel<any> { return this.tree.getInput(); } showInputDecoration(decoration: Severity): void { if (this.inputBox) { this.inputBox.showMessage({ type: decoration === Severity.Info ? MessageType.INFO : decoration === Severity.Warning ? MessageType.WARNING : MessageType.ERROR, content: '' }); } } clearInputDecoration(): void { if (this.inputBox) { this.inputBox.hideMessage(); } } focus(): void { if (this.isVisible() && this.inputBox) { this.inputBox.focus(); } } accept(): void { if (this.isVisible()) { const focus = this.tree.getFocus(); if (focus) { this.elementSelected(focus); } } } getProgressBar(): ProgressBar { return this.progressBar; } getInputBox(): InputBox { return this.inputBox; } setExtraClass(clazz: string | null): void { const previousClass = this.element.getAttribute('quick-open-extra-class'); if (previousClass) { DOM.removeClasses(this.element, previousClass); } if (clazz) { DOM.addClasses(this.element, clazz); this.element.setAttribute('quick-open-extra-class', clazz); } else if (previousClass) { this.element.removeAttribute('quick-open-extra-class'); } } isVisible(): boolean { return this.visible; } layout(dimension: DOM.Dimension): void { this.layoutDimensions = dimension; // Apply to quick open width (height is dynamic by number of items to show) const quickOpenWidth = Math.min(this.layoutDimensions.width * 0.62 /* golden cut */, QuickOpenWidget.MAX_WIDTH); if (this.element) { // quick open this.element.style.width = `${quickOpenWidth}px`; this.element.style.marginLeft = `-${quickOpenWidth / 2}px`; // input field this.inputContainer.style.width = `${quickOpenWidth - 12}px`; } } private gainingFocus(): void { this.isLoosingFocus = false; } private loosingFocus(e: FocusEvent): void { if (!this.isVisible()) { return; } const relatedTarget = e.relatedTarget as HTMLElement; if (!this.quickNavigateConfiguration && DOM.isAncestor(relatedTarget, this.element)) { return; // user clicked somewhere into quick open widget, do not close thereby } this.isLoosingFocus = true; setTimeout(() => { if (!this.isLoosingFocus || this.isDisposed) { return; } const veto = this.callbacks.onFocusLost && this.callbacks.onFocusLost(); if (!veto) { this.hide(HideReason.FOCUS_LOST); } }, 0); } dispose(): void { super.dispose(); this.isDisposed = true; } }
src/vs/base/parts/quickopen/browser/quickOpenWidget.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9986169338226318, 0.1312379539012909, 0.0001638596731936559, 0.00017068471061065793, 0.3267502784729004 ]
{ "id": 9, "code_window": [ "\n", "\tprivate registerQuickNavigation() {\n", "\t\treturn dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => {\n", "\t\t\tif (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (this.canSelectMany || !this.quickNavigate) {\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 657 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions, IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { ISettingsMergeService } from 'vs/platform/userDataSync/common/userDataSync'; import { Registry } from 'vs/platform/registry/common/platform'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { ISharedProcessService } from 'vs/platform/ipc/electron-browser/sharedProcessService'; import { SettingsMergeChannel } from 'vs/platform/userDataSync/common/settingsSyncIpc'; class UserDataSyncServicesContribution implements IWorkbenchContribution { constructor( @ISettingsMergeService settingsMergeService: ISettingsMergeService, @ISharedProcessService sharedProcessService: ISharedProcessService, ) { sharedProcessService.registerChannel('settingsMerge', new SettingsMergeChannel(settingsMergeService)); } } const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench); workbenchRegistry.registerWorkbenchContribution(UserDataSyncServicesContribution, LifecyclePhase.Starting);
src/vs/workbench/contrib/userDataSync/electron-browser/userDataSync.contribution.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.0001741289161145687, 0.0001723253371892497, 0.0001710202923277393, 0.00017182677402161062, 0.0000013171438695280813 ]
{ "id": 9, "code_window": [ "\n", "\tprivate registerQuickNavigation() {\n", "\t\treturn dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => {\n", "\t\t\tif (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (this.canSelectMany || !this.quickNavigate) {\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 657 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { TextModel } from 'vs/editor/common/model/textModel'; import { computeRanges } from 'vs/editor/contrib/folding/indentRangeProvider'; import { FoldingMarkers } from 'vs/editor/common/modes/languageConfiguration'; import { MAX_FOLDING_REGIONS } from 'vs/editor/contrib/folding/foldingRanges'; let markers: FoldingMarkers = { start: /^\s*#region\b/, end: /^\s*#endregion\b/ }; suite('FoldingRanges', () => { test('test max folding regions', () => { let lines: string[] = []; let nRegions = MAX_FOLDING_REGIONS; for (let i = 0; i < nRegions; i++) { lines.push('#region'); } for (let i = 0; i < nRegions; i++) { lines.push('#endregion'); } let model = TextModel.createFromString(lines.join('\n')); let actual = computeRanges(model, false, markers, MAX_FOLDING_REGIONS); assert.equal(actual.length, nRegions, 'len'); for (let i = 0; i < nRegions; i++) { assert.equal(actual.getStartLineNumber(i), i + 1, 'start' + i); assert.equal(actual.getEndLineNumber(i), nRegions * 2 - i, 'end' + i); assert.equal(actual.getParentIndex(i), i - 1, 'parent' + i); } }); test('findRange', () => { let lines = [ /* 1*/ '#region', /* 2*/ '#endregion', /* 3*/ 'class A {', /* 4*/ ' void foo() {', /* 5*/ ' if (true) {', /* 6*/ ' return;', /* 7*/ ' }', /* 8*/ '', /* 9*/ ' if (true) {', /* 10*/ ' return;', /* 11*/ ' }', /* 12*/ ' }', /* 13*/ '}']; let textModel = TextModel.createFromString(lines.join('\n')); try { let actual = computeRanges(textModel, false, markers); // let r0 = r(1, 2); // let r1 = r(3, 12); // let r2 = r(4, 11); // let r3 = r(5, 6); // let r4 = r(9, 10); assert.equal(actual.findRange(1), 0, '1'); assert.equal(actual.findRange(2), 0, '2'); assert.equal(actual.findRange(3), 1, '3'); assert.equal(actual.findRange(4), 2, '4'); assert.equal(actual.findRange(5), 3, '5'); assert.equal(actual.findRange(6), 3, '6'); assert.equal(actual.findRange(7), 2, '7'); assert.equal(actual.findRange(8), 2, '8'); assert.equal(actual.findRange(9), 4, '9'); assert.equal(actual.findRange(10), 4, '10'); assert.equal(actual.findRange(11), 2, '11'); assert.equal(actual.findRange(12), 1, '12'); assert.equal(actual.findRange(13), -1, '13'); } finally { textModel.dispose(); } }); test('setCollapsed', () => { let lines: string[] = []; let nRegions = 500; for (let i = 0; i < nRegions; i++) { lines.push('#region'); } for (let i = 0; i < nRegions; i++) { lines.push('#endregion'); } let model = TextModel.createFromString(lines.join('\n')); let actual = computeRanges(model, false, markers, MAX_FOLDING_REGIONS); assert.equal(actual.length, nRegions, 'len'); for (let i = 0; i < nRegions; i++) { actual.setCollapsed(i, i % 3 === 0); } for (let i = 0; i < nRegions; i++) { assert.equal(actual.isCollapsed(i), i % 3 === 0, 'line' + i); } }); });
src/vs/editor/contrib/folding/test/foldingRanges.test.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017594863311387599, 0.00017219177971128374, 0.00016577442875131965, 0.00017261090397369117, 0.000002728405661400757 ]
{ "id": 9, "code_window": [ "\n", "\tprivate registerQuickNavigation() {\n", "\t\treturn dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => {\n", "\t\t\tif (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n", "\t\t\tconst keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (this.canSelectMany || !this.quickNavigate) {\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 657 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as crypto from 'crypto'; import { IFileService, IResolveFileResult, IFileStat } from 'vs/platform/files/common/files'; import { IWorkspaceContextService, WorkbenchState, IWorkspace } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IWindowConfiguration } from 'vs/platform/windows/common/windows'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { INotificationService, NeverShowAgainScope, INeverShowAgainOptions } from 'vs/platform/notification/common/notification'; import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput'; import { ITextFileService, ITextFileContent } from 'vs/workbench/services/textfile/common/textfiles'; import { URI } from 'vs/base/common/uri'; import { Schemas } from 'vs/base/common/network'; import { hasWorkspaceFileExtension } from 'vs/platform/workspaces/common/workspaces'; import { localize } from 'vs/nls'; import Severity from 'vs/base/common/severity'; import { joinPath } from 'vs/base/common/resources'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IWorkspaceTagsService, Tags } from 'vs/workbench/contrib/tags/common/workspaceTags'; import { getHashedRemotesFromConfig } from 'vs/workbench/contrib/tags/electron-browser/workspaceTags'; import { IProductService } from 'vs/platform/product/common/productService'; const ModulesToLookFor = [ // Packages that suggest a node server 'express', 'sails', 'koa', 'hapi', 'socket.io', 'restify', // JS frameworks 'react', 'react-native', 'rnpm-plugin-windows', '@angular/core', '@ionic', 'vue', 'tns-core-modules', // Other interesting packages 'aws-sdk', 'aws-amplify', 'azure', 'azure-storage', 'firebase', '@google-cloud/common', 'heroku-cli', //Office and Sharepoint packages '@microsoft/office-js', '@microsoft/office-js-helpers', '@types/office-js', '@types/office-runtime', 'office-ui-fabric-react', '@uifabric/icons', '@uifabric/merge-styles', '@uifabric/styling', '@uifabric/experiments', '@uifabric/utilities', '@microsoft/rush', 'lerna', 'just-task', 'beachball' ]; const PyModulesToLookFor = [ 'azure', 'azure-storage-common', 'azure-storage-blob', 'azure-storage-file', 'azure-storage-queue', 'azure-shell', 'azure-cosmos', 'azure-devtools', 'azure-elasticluster', 'azure-eventgrid', 'azure-functions', 'azure-graphrbac', 'azure-keyvault', 'azure-loganalytics', 'azure-monitor', 'azure-servicebus', 'azure-servicefabric', 'azure-storage', 'azure-translator', 'azure-iothub-device-client', 'adal', 'pydocumentdb', 'botbuilder-core', 'botbuilder-schema', 'botframework-connector' ]; export class WorkspaceTagsService implements IWorkspaceTagsService { _serviceBrand: undefined; private _tags: Tags | undefined; constructor( @IFileService private readonly fileService: IFileService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IProductService private readonly productService: IProductService, @IHostService private readonly hostService: IHostService, @INotificationService private readonly notificationService: INotificationService, @IQuickInputService private readonly quickInputService: IQuickInputService, @ITextFileService private readonly textFileService: ITextFileService ) { } async getTags(): Promise<Tags> { if (!this._tags) { this._tags = await this.resolveWorkspaceTags(this.environmentService.configuration, rootFiles => this.handleWorkspaceFiles(rootFiles)); } return this._tags; } getTelemetryWorkspaceId(workspace: IWorkspace, state: WorkbenchState): string | undefined { function createHash(uri: URI): string { return crypto.createHash('sha1').update(uri.scheme === Schemas.file ? uri.fsPath : uri.toString()).digest('hex'); } let workspaceId: string | undefined; switch (state) { case WorkbenchState.EMPTY: workspaceId = undefined; break; case WorkbenchState.FOLDER: workspaceId = createHash(workspace.folders[0].uri); break; case WorkbenchState.WORKSPACE: if (workspace.configuration) { workspaceId = createHash(workspace.configuration); } } return workspaceId; } getHashedRemotesFromUri(workspaceUri: URI, stripEndingDotGit: boolean = false): Promise<string[]> { const path = workspaceUri.path; const uri = workspaceUri.with({ path: `${path !== '/' ? path : ''}/.git/config` }); return this.fileService.exists(uri).then(exists => { if (!exists) { return []; } return this.textFileService.read(uri, { acceptTextOnly: true }).then( content => getHashedRemotesFromConfig(content.value, stripEndingDotGit), err => [] // ignore missing or binary file ); }); } /* __GDPR__FRAGMENT__ "WorkspaceTags" : { "workbench.filesToOpenOrCreate" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workbench.filesToDiff" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "workspace.roots" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.empty" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.grunt" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.gulp" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.jake" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.tsconfig" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.jsconfig" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.config.xml" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.vsc.extension" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.asp<NUMBER>" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.sln" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.unity" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.express" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.sails" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.koa" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.hapi" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.socket.io" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.restify" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.rnpm-plugin-windows" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.react" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@angular/core" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.vue" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.aws-sdk" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.aws-amplify-sdk" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.azure" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.azure-storage" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@google-cloud/common" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.firebase" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.heroku-cli" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@microsoft/office-js" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@microsoft/office-js-helpers" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@types/office-js" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@types/office-runtime" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.office-ui-fabric-react" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@uifabric/icons" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@uifabric/merge-styles" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@uifabric/styling" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@uifabric/experiments" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@uifabric/utilities" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.@microsoft/rush" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.lerna" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.just-task" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.npm.beachball" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.bower" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.yeoman.code.ext" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.cordova.high" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.cordova.low" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.xamarin.android" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.xamarin.ios" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.android.cpp" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.reactNative" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.ionic" : { "classification" : "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": "true" }, "workspace.nativeScript" : { "classification" : "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": "true" }, "workspace.java.pom" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.requirements" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.requirements.star" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.Pipfile" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.conda" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.any-azure" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-storage-common" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-storage-blob" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-storage-file" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-storage-queue" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-mgmt" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-shell" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.pulumi-azure" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-cosmos" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-devtools" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-elasticluster" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-eventgrid" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-functions" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-graphrbac" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-keyvault" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-loganalytics" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-monitor" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-servicebus" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-servicefabric" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-storage" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-translator" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-iothub-device-client" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-ml" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.azure-cognitiveservices" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.adal" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.pydocumentdb" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.botbuilder-core" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.botbuilder-schema" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "workspace.py.botframework-connector" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ private resolveWorkspaceTags(configuration: IWindowConfiguration, participant?: (rootFiles: string[]) => void): Promise<Tags> { const tags: Tags = Object.create(null); const state = this.contextService.getWorkbenchState(); const workspace = this.contextService.getWorkspace(); tags['workspace.id'] = this.getTelemetryWorkspaceId(workspace, state); const { filesToOpenOrCreate, filesToDiff } = configuration; tags['workbench.filesToOpenOrCreate'] = filesToOpenOrCreate && filesToOpenOrCreate.length || 0; tags['workbench.filesToDiff'] = filesToDiff && filesToDiff.length || 0; const isEmpty = state === WorkbenchState.EMPTY; tags['workspace.roots'] = isEmpty ? 0 : workspace.folders.length; tags['workspace.empty'] = isEmpty; const folders = !isEmpty ? workspace.folders.map(folder => folder.uri) : this.productService.quality !== 'stable' && this.findFolders(configuration); if (!folders || !folders.length || !this.fileService) { return Promise.resolve(tags); } return this.fileService.resolveAll(folders.map(resource => ({ resource }))).then((files: IResolveFileResult[]) => { const names = (<IFileStat[]>[]).concat(...files.map(result => result.success ? (result.stat!.children || []) : [])).map(c => c.name); const nameSet = names.reduce((s, n) => s.add(n.toLowerCase()), new Set()); if (participant) { participant(names); } tags['workspace.grunt'] = nameSet.has('gruntfile.js'); tags['workspace.gulp'] = nameSet.has('gulpfile.js'); tags['workspace.jake'] = nameSet.has('jakefile.js'); tags['workspace.tsconfig'] = nameSet.has('tsconfig.json'); tags['workspace.jsconfig'] = nameSet.has('jsconfig.json'); tags['workspace.config.xml'] = nameSet.has('config.xml'); tags['workspace.vsc.extension'] = nameSet.has('vsc-extension-quickstart.md'); tags['workspace.ASP5'] = nameSet.has('project.json') && this.searchArray(names, /^.+\.cs$/i); tags['workspace.sln'] = this.searchArray(names, /^.+\.sln$|^.+\.csproj$/i); tags['workspace.unity'] = nameSet.has('assets') && nameSet.has('library') && nameSet.has('projectsettings'); tags['workspace.npm'] = nameSet.has('package.json') || nameSet.has('node_modules'); tags['workspace.bower'] = nameSet.has('bower.json') || nameSet.has('bower_components'); tags['workspace.java.pom'] = nameSet.has('pom.xml'); tags['workspace.yeoman.code.ext'] = nameSet.has('vsc-extension-quickstart.md'); tags['workspace.py.requirements'] = nameSet.has('requirements.txt'); tags['workspace.py.requirements.star'] = this.searchArray(names, /^(.*)requirements(.*)\.txt$/i); tags['workspace.py.Pipfile'] = nameSet.has('pipfile'); tags['workspace.py.conda'] = this.searchArray(names, /^environment(\.yml$|\.yaml$)/i); const mainActivity = nameSet.has('mainactivity.cs') || nameSet.has('mainactivity.fs'); const appDelegate = nameSet.has('appdelegate.cs') || nameSet.has('appdelegate.fs'); const androidManifest = nameSet.has('androidmanifest.xml'); const platforms = nameSet.has('platforms'); const plugins = nameSet.has('plugins'); const www = nameSet.has('www'); const properties = nameSet.has('properties'); const resources = nameSet.has('resources'); const jni = nameSet.has('jni'); if (tags['workspace.config.xml'] && !tags['workspace.language.cs'] && !tags['workspace.language.vb'] && !tags['workspace.language.aspx']) { if (platforms && plugins && www) { tags['workspace.cordova.high'] = true; } else { tags['workspace.cordova.low'] = true; } } if (tags['workspace.config.xml'] && !tags['workspace.language.cs'] && !tags['workspace.language.vb'] && !tags['workspace.language.aspx']) { if (nameSet.has('ionic.config.json')) { tags['workspace.ionic'] = true; } } if (mainActivity && properties && resources) { tags['workspace.xamarin.android'] = true; } if (appDelegate && resources) { tags['workspace.xamarin.ios'] = true; } if (androidManifest && jni) { tags['workspace.android.cpp'] = true; } function getFilePromises(filename: string, fileService: IFileService, textFileService: ITextFileService, contentHandler: (content: ITextFileContent) => void): Promise<void>[] { return !nameSet.has(filename) ? [] : (folders as URI[]).map(workspaceUri => { const uri = workspaceUri.with({ path: `${workspaceUri.path !== '/' ? workspaceUri.path : ''}/${filename}` }); return fileService.exists(uri).then(exists => { if (!exists) { return undefined; } return textFileService.read(uri, { acceptTextOnly: true }).then(contentHandler); }, err => { // Ignore missing file }); }); } function addPythonTags(packageName: string): void { if (PyModulesToLookFor.indexOf(packageName) > -1) { tags['workspace.py.' + packageName] = true; } // cognitive services has a lot of tiny packages. e.g. 'azure-cognitiveservices-search-autosuggest' if (packageName.indexOf('azure-cognitiveservices') > -1) { tags['workspace.py.azure-cognitiveservices'] = true; } if (packageName.indexOf('azure-mgmt') > -1) { tags['workspace.py.azure-mgmt'] = true; } if (packageName.indexOf('azure-ml') > -1) { tags['workspace.py.azure-ml'] = true; } if (!tags['workspace.py.any-azure']) { tags['workspace.py.any-azure'] = /azure/i.test(packageName); } } const requirementsTxtPromises = getFilePromises('requirements.txt', this.fileService, this.textFileService, content => { const dependencies: string[] = content.value.split(/\r\n|\r|\n/); for (let dependency of dependencies) { // Dependencies in requirements.txt can have 3 formats: `foo==3.1, foo>=3.1, foo` const format1 = dependency.split('=='); const format2 = dependency.split('>='); const packageName = (format1.length === 2 ? format1[0] : format2[0]).trim(); addPythonTags(packageName); } }); const pipfilePromises = getFilePromises('pipfile', this.fileService, this.textFileService, content => { let dependencies: string[] = content.value.split(/\r\n|\r|\n/); // We're only interested in the '[packages]' section of the Pipfile dependencies = dependencies.slice(dependencies.indexOf('[packages]') + 1); for (let dependency of dependencies) { if (dependency.trim().indexOf('[') > -1) { break; } // All dependencies in Pipfiles follow the format: `<package> = <version, or git repo, or something else>` if (dependency.indexOf('=') === -1) { continue; } const packageName = dependency.split('=')[0].trim(); addPythonTags(packageName); } }); const packageJsonPromises = getFilePromises('package.json', this.fileService, this.textFileService, content => { try { const packageJsonContents = JSON.parse(content.value); let dependencies = packageJsonContents['dependencies']; let devDependencies = packageJsonContents['devDependencies']; for (let module of ModulesToLookFor) { if ('react-native' === module) { if ((dependencies && dependencies[module]) || (devDependencies && devDependencies[module])) { tags['workspace.reactNative'] = true; } } else if ('tns-core-modules' === module) { if ((dependencies && dependencies[module]) || (devDependencies && devDependencies[module])) { tags['workspace.nativescript'] = true; } } else { if ((dependencies && dependencies[module]) || (devDependencies && devDependencies[module])) { tags['workspace.npm.' + module] = true; } } } } catch (e) { // Ignore errors when resolving file or parsing file contents } }); return Promise.all([...packageJsonPromises, ...requirementsTxtPromises, ...pipfilePromises]).then(() => tags); }); } private handleWorkspaceFiles(rootFiles: string[]): void { const state = this.contextService.getWorkbenchState(); const workspace = this.contextService.getWorkspace(); // Handle top-level workspace files for local single folder workspace if (state === WorkbenchState.FOLDER) { const workspaceFiles = rootFiles.filter(hasWorkspaceFileExtension); if (workspaceFiles.length > 0) { this.doHandleWorkspaceFiles(workspace.folders[0].uri, workspaceFiles); } } } private doHandleWorkspaceFiles(folder: URI, workspaces: string[]): void { const neverShowAgain: INeverShowAgainOptions = { id: 'workspaces.dontPromptToOpen', scope: NeverShowAgainScope.WORKSPACE, isSecondary: true }; // Prompt to open one workspace if (workspaces.length === 1) { const workspaceFile = workspaces[0]; this.notificationService.prompt(Severity.Info, localize('workspaceFound', "This folder contains a workspace file '{0}'. Do you want to open it? [Learn more]({1}) about workspace files.", workspaceFile, 'https://go.microsoft.com/fwlink/?linkid=2025315'), [{ label: localize('openWorkspace', "Open Workspace"), run: () => this.hostService.openWindow([{ workspaceUri: joinPath(folder, workspaceFile) }]) }], { neverShowAgain }); } // Prompt to select a workspace from many else if (workspaces.length > 1) { this.notificationService.prompt(Severity.Info, localize('workspacesFound', "This folder contains multiple workspace files. Do you want to open one? [Learn more]({0}) about workspace files.", 'https://go.microsoft.com/fwlink/?linkid=2025315'), [{ label: localize('selectWorkspace', "Select Workspace"), run: () => { this.quickInputService.pick( workspaces.map(workspace => ({ label: workspace } as IQuickPickItem)), { placeHolder: localize('selectToOpen', "Select a workspace to open") }).then(pick => { if (pick) { this.hostService.openWindow([{ workspaceUri: joinPath(folder, pick.label) }]); } }); } }], { neverShowAgain }); } } private findFolders(configuration: IWindowConfiguration): URI[] | undefined { const folder = this.findFolder(configuration); return folder && [folder]; } private findFolder({ filesToOpenOrCreate, filesToDiff }: IWindowConfiguration): URI | undefined { if (filesToOpenOrCreate && filesToOpenOrCreate.length) { return this.parentURI(filesToOpenOrCreate[0].fileUri); } else if (filesToDiff && filesToDiff.length) { return this.parentURI(filesToDiff[0].fileUri); } return undefined; } private parentURI(uri: URI | undefined): URI | undefined { if (!uri) { return undefined; } const path = uri.path; const i = path.lastIndexOf('/'); return i !== -1 ? uri.with({ path: path.substr(0, i) }) : undefined; } private searchArray(arr: string[], regEx: RegExp): boolean | undefined { return arr.some(v => v.search(regEx) > -1) || undefined; } } registerSingleton(IWorkspaceTagsService, WorkspaceTagsService, true);
src/vs/workbench/contrib/tags/electron-browser/workspaceTagsService.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017523253336548805, 0.00017087679589167237, 0.00016667073941789567, 0.0001710375800030306, 0.000002100825440720655 ]
{ "id": 10, "code_window": [ "\t\t}));\n", "\t\tthis._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => {\n", "\t\t\tinputBox.setFocus();\n", "\t\t}));\n", "\t\tthis._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {\n", "\t\t\tthis.getUI().keyDownSeenSinceShown = true;\n", "\t\t\tconst event = new StandardKeyboardEvent(e);\n", "\t\t\tswitch (event.keyCode) {\n", "\t\t\t\tcase KeyCode.Enter:\n", "\t\t\t\t\tdom.EventHelper.stop(e, true);\n", "\t\t\t\t\tthis.onDidAcceptEmitter.fire();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 1116 }
/*--------------------------------------------------------------------------------------------- * 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/quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { QUICK_INPUT_BACKGROUND, QUICK_INPUT_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerAndGetAmdImageURL } from 'vs/base/common/amd'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-dark.svg')), light: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-light.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; titleBar: HTMLElement; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; filterContainer: HTMLElement; inputBox: QuickInputBox; visibleCountContainer: HTMLElement; visibleCount: CountBadge; countContainer: HTMLElement; count: CountBadge; okContainer: HTMLElement; ok: Button; message: HTMLElement; customButtonContainer: HTMLElement; customButton: Button; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidCustom: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; keyDownSeenSinceShown: boolean; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; customButton?: boolean; }; class QuickInput extends Disposable implements IQuickInput { private _title: string | undefined; private _steps: number | undefined; private _totalSteps: number | undefined; protected visible = false; private _enabled = true; private _contextKey: string | undefined; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private readonly onDidHideEmitter = this._register(new Emitter<void>()); protected readonly visibleDisposables = this._register(new DisposableStore()); private busyDelay: TimeoutTimer | undefined; constructor( protected ui: QuickInputUI ) { super(); } get title() { return this._title; } set title(title: string | undefined) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number | undefined) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number | undefined) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string | undefined) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.add( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.keyDownSeenSinceShown = false; this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables.clear(); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = undefined; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } protected showMessageDecoration(severity: Severity) { this.ui.inputBox.showDecoration(severity); if (severity === Severity.Error) { const styles = this.ui.inputBox.stylesForType(severity); this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : ''; this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : ''; this.ui.message.style.paddingBottom = '4px'; } else { this.ui.message.style.backgroundColor = ''; this.ui.message.style.border = ''; this.ui.message.style.paddingBottom = ''; } } public dispose(): void { this.hide(); super.dispose(); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static readonly INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder: string | undefined; private readonly onDidChangeValueEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private readonly onDidChangeActiveEmitter = this._register(new Emitter<T[]>()); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private readonly onDidChangeSelectionEmitter = this._register(new Emitter<T[]>()); private readonly onDidTriggerItemButtonEmitter = this._register(new Emitter<IQuickPickItemButtonEvent<T>>()); private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _validationMessage: string | undefined; private _ok = false; private _customButton = false; private _customButtonLabel: string | undefined; private _customButtonHover: string | undefined; quickNavigate: IQuickNavigateConfiguration | undefined; get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; onDidCustom = this.onDidCustomEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } get customButton() { return this._customButton; } set customButton(showCustomButton: boolean) { this._customButton = showCustomButton; this.update(); } get customLabel() { return this._customButtonLabel; } set customLabel(label: string | undefined) { this._customButtonLabel = label; this.update(); } get customHover() { return this._customButtonHover; } set customHover(hover: string | undefined) { this._customButtonHover = hover; this.update(); } get ok() { return this._ok; } set ok(showOkButton: boolean) { this._ok = showOkButton; this.update(); } public inputHasFocus(): boolean { return this.visible ? this.ui.inputBox.hasFocus() : false; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); })); this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } })); this.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => { this.ui.keyDownSeenSinceShown = true; switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; } })); this.visibleDisposables.add(this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.onDidCustom(() => { this.onDidCustomEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } })); this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>))); this.visibleDisposables.add(this.registerQuickNavigation()); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true, message: !!this.validationMessage } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true, message: !!this.validationMessage, customButton: this.customButton, ok: this.ok }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } if (this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } else { this.ui.message.textContent = null; this.showMessageDecoration(Severity.Ignore); } this.ui.customButton.label = this.customLabel || ''; this.ui.customButton.element.title = this.customHover || ''; this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); } } class InputBox extends QuickInput implements IInputBox { private static readonly noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _placeholder: string | undefined; private _password = false; private _prompt: string | undefined; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string | undefined; private readonly onDidValueChangeEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string | undefined) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } readonly onDidChangeValue = this.onDidValueChangeEmitter.event; readonly onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); })); this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined))); this.valueSelectionUpdated = true; } super.show(); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.showMessageDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: undefined; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private ui: QuickInputUI | undefined; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: Map<string, IContextKey<boolean>> = new Map(); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts.get(id); if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts.set(id, key); } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { this.contexts.forEach(context => { if (context.get()) { context.reset(); } }); } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private getUI() { if (this.ui) { return this.ui; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; const titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); const extraContainer = dom.append(headerContainer, $('.quick-input-and-message')); const filterContainer = dom.append(extraContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count')); visibleCountContainer.setAttribute('aria-live', 'polite'); visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); const countContainer = dom.append(filterContainer, $('.quick-input-count')); countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); const okContainer = dom.append(headerContainer, $('.quick-input-action')); const ok = new Button(okContainer); attachButtonStyler(ok, this.themeService); ok.label = localize('ok', "OK"); this._register(ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const customButtonContainer = dom.append(headerContainer, $('.quick-input-action')); const customButton = new Button(customButtonContainer); attachButtonStyler(customButton, this.themeService); customButton.label = localize('custom', "Custom"); this._register(customButton.onDidClick(e => { this.onDidCustomEmitter.fire(); })); const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.getUI().ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => { inputBox.setFocus(); })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.getUI().keyDownSeenSinceShown = true; const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.codicon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.getUI().list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, titleBar, title, rightActionBar, checkAll, filterContainer, inputBox, visibleCountContainer, visibleCount, countContainer, count, okContainer, ok, message, customButtonContainer, customButton, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidCustom: this.onDidCustomEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, keyDownSeenSinceShown: false, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); return this.ui; } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { const ui = this.getUI(); return new QuickPick<T>(ui); } createInputBox(): IInputBox { const ui = this.getUI(); return new InputBox(ui); } private show(controller: QuickInput) { const ui = this.getUI(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); ui.leftActionBar.clear(); ui.title.textContent = ''; ui.rightActionBar.clear(); ui.checkAll.checked = false; // ui.inputBox.value = ''; Avoid triggering an event. ui.inputBox.placeholder = ''; ui.inputBox.password = false; ui.inputBox.showDecoration(Severity.Ignore); ui.visibleCount.setCount(0); ui.count.setCount(0); ui.message.textContent = ''; ui.progressBar.stop(); ui.list.setElements([]); ui.list.matchOnDescription = false; ui.list.matchOnDetail = false; ui.list.matchOnLabel = true; ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); ui.container.style.display = ''; this.updateLayout(); ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { const ui = this.getUI(); ui.title.style.display = visibilities.title ? '' : 'none'; ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; ui.countContainer.style.display = visibilities.count ? '' : 'none'; ui.okContainer.style.display = visibilities.ok ? '' : 'none'; ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none'; ui.message.style.display = visibilities.message ? '' : 'none'; ui.list.display(!!visibilities.list); ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { const ui = this.getUI(); this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { ui.inputBox.setAttribute('role', 'combobox'); ui.inputBox.setAttribute('aria-haspopup', 'true'); ui.inputBox.setAttribute('aria-autocomplete', 'list'); ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || ''); } else { ui.inputBox.removeAttribute('role'); ui.inputBox.removeAttribute('aria-haspopup'); ui.inputBox.removeAttribute('aria-autocomplete'); ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.getUI().leftActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } for (const item of this.getUI().rightActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } this.getUI().checkAll.disabled = !enabled; // this.getUI().inputBox.enabled = enabled; Avoid loosing focus. this.getUI().ok.enabled = enabled; this.getUI().list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.getUI().container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.getUI().inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.getUI().list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.getUI().list.isDisplayed()) { this.getUI().list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.ui.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : ''; this.ui.inputBox.style(theme); const quickInputBackground = theme.getColor(QUICK_INPUT_BACKGROUND); this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : ''; const quickInputForeground = theme.getColor(QUICK_INPUT_FOREGROUND); this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : ''; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : ''; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.9982636570930481, 0.019974585622549057, 0.00016163547115866095, 0.00017108168685808778, 0.12118476629257202 ]
{ "id": 10, "code_window": [ "\t\t}));\n", "\t\tthis._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => {\n", "\t\t\tinputBox.setFocus();\n", "\t\t}));\n", "\t\tthis._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {\n", "\t\t\tthis.getUI().keyDownSeenSinceShown = true;\n", "\t\t\tconst event = new StandardKeyboardEvent(e);\n", "\t\t\tswitch (event.keyCode) {\n", "\t\t\t\tcase KeyCode.Enter:\n", "\t\t\t\t\tdom.EventHelper.stop(e, true);\n", "\t\t\t\t\tthis.onDidAcceptEmitter.fire();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 1116 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M13 3.5V6H15.151L15.634 6.629L13 13.629L12.516 14L8.74284 14C8.99647 13.6929 9.2174 13.3578 9.4003 13L12.133 13L14.5 7H8.74284C8.52467 6.73583 8.2823 6.49238 8.01914 6.27304L8.14602 6.146L8.50002 6H12V4H6.5L6.146 3.854L5.293 3H1V6.25716C0.62057 6.57052 0.283885 6.93379 0 7.33692V2.5L0.5 2H5.5L5.854 2.146L6.707 3H12.5L13 3.5Z" fill="#424242"/> <path d="M6 10.5C6 11.3284 5.32843 12 4.5 12C3.67157 12 3 11.3284 3 10.5C3 9.67157 3.67157 9 4.5 9C5.32843 9 6 9.67157 6 10.5Z" fill="#424242"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M8 10.5C8 12.433 6.433 14 4.5 14C2.567 14 1 12.433 1 10.5C1 8.567 2.567 7 4.5 7C6.433 7 8 8.567 8 10.5ZM4.5 13C5.88071 13 7 11.8807 7 10.5C7 9.11929 5.88071 8 4.5 8C3.11929 8 2 9.11929 2 10.5C2 11.8807 3.11929 13 4.5 13Z" fill="#424242"/> </svg>
extensions/theme-defaults/fileicons/images/root-folder-open-light.svg
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00019556671031750739, 0.00019556671031750739, 0.00019556671031750739, 0.00019556671031750739, 0 ]
{ "id": 10, "code_window": [ "\t\t}));\n", "\t\tthis._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => {\n", "\t\t\tinputBox.setFocus();\n", "\t\t}));\n", "\t\tthis._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {\n", "\t\t\tthis.getUI().keyDownSeenSinceShown = true;\n", "\t\t\tconst event = new StandardKeyboardEvent(e);\n", "\t\t\tswitch (event.keyCode) {\n", "\t\t\t\tcase KeyCode.Enter:\n", "\t\t\t\t\tdom.EventHelper.stop(e, true);\n", "\t\t\t\t\tthis.onDidAcceptEmitter.fire();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 1116 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M14.4315 3.3232L5.96154 13.3232L5.17083 13.2874L1.82083 8.5174L2.63918 7.94268L5.617 12.1827L13.6685 2.67688L14.4315 3.3232Z" fill="#424242"/> </svg>
src/vs/workbench/contrib/files/browser/media/check-light.svg
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017249521624762565, 0.00017249521624762565, 0.00017249521624762565, 0.00017249521624762565, 0 ]
{ "id": 10, "code_window": [ "\t\t}));\n", "\t\tthis._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => {\n", "\t\t\tinputBox.setFocus();\n", "\t\t}));\n", "\t\tthis._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {\n", "\t\t\tthis.getUI().keyDownSeenSinceShown = true;\n", "\t\t\tconst event = new StandardKeyboardEvent(e);\n", "\t\t\tswitch (event.keyCode) {\n", "\t\t\t\tcase KeyCode.Enter:\n", "\t\t\t\t\tdom.EventHelper.stop(e, true);\n", "\t\t\t\t\tthis.onDidAcceptEmitter.fire();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 1116 }
{ "type": "object", "properties": { "registrations": { "type": "array", "items": { "type": "object", "properties": { "component": { "oneOf": [ { "type": "object", "required": [ "type", "git" ], "properties": { "type": { "type": "string", "enum": [ "git" ] }, "git": { "type": "object", "required": [ "name", "repositoryUrl", "commitHash" ], "properties": { "name": { "type": "string" }, "repositoryUrl": { "type": "string" }, "commitHash": { "type": "string" } } } } }, { "type": "object", "required": [ "type", "npm" ], "properties": { "type": { "type": "string", "enum": [ "npm" ] }, "npm": { "type": "object", "required": [ "name", "version" ], "properties": { "name": { "type": "string" }, "version": { "type": "string" } } } } }, { "type": "object", "required": [ "type", "other" ], "properties": { "type": { "type": "string", "enum": [ "other" ] }, "other": { "type": "object", "required": [ "name", "downloadUrl", "version" ], "properties": { "name": { "type": "string" }, "downloadUrl": { "type": "string" }, "version": { "type": "string" } } } } } ] }, "repositoryUrl": { "type": "string", "description": "The git url of the component" }, "version": { "type": "string", "description": "The version of the component" }, "license": { "type": "string", "description": "The name of the license" }, "developmentDependency": { "type": "boolean", "description": "This component is inlined in the vscode repo and **is not shipped**." }, "isOnlyProductionDependency": { "type": "boolean", "description": "This component is shipped and **is not inlined in the vscode repo**." }, "licenseDetail": { "type": "array", "items": { "type": "string" }, "description": "The license text" } } } } } }
.vscode/cgmanifest.schema.json
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017400426440872252, 0.0001707747724140063, 0.00016636888904031366, 0.00017099044634960592, 0.000002245426003355533 ]
{ "id": 11, "code_window": [ "\t\t\tonDidAccept: this.onDidAcceptEmitter.event,\n", "\t\t\tonDidCustom: this.onDidCustomEmitter.event,\n", "\t\t\tonDidTriggerButton: this.onDidTriggerButtonEmitter.event,\n", "\t\t\tignoreFocusOut: false,\n", "\t\t\tkeyMods: this.keyMods,\n", "\t\t\tkeyDownSeenSinceShown: false,\n", "\t\t\tisScreenReaderOptimized: () => this.isScreenReaderOptimized(),\n", "\t\t\tshow: controller => this.show(controller),\n", "\t\t\thide: () => this.hide(),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 1178 }
/*--------------------------------------------------------------------------------------------- * 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/quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { QUICK_INPUT_BACKGROUND, QUICK_INPUT_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerAndGetAmdImageURL } from 'vs/base/common/amd'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-dark.svg')), light: URI.parse(registerAndGetAmdImageURL('vs/workbench/browser/parts/quickinput/media/arrow-left-light.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; titleBar: HTMLElement; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; filterContainer: HTMLElement; inputBox: QuickInputBox; visibleCountContainer: HTMLElement; visibleCount: CountBadge; countContainer: HTMLElement; count: CountBadge; okContainer: HTMLElement; ok: Button; message: HTMLElement; customButtonContainer: HTMLElement; customButton: Button; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidCustom: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; keyDownSeenSinceShown: boolean; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; customButton?: boolean; }; class QuickInput extends Disposable implements IQuickInput { private _title: string | undefined; private _steps: number | undefined; private _totalSteps: number | undefined; protected visible = false; private _enabled = true; private _contextKey: string | undefined; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private readonly onDidHideEmitter = this._register(new Emitter<void>()); protected readonly visibleDisposables = this._register(new DisposableStore()); private busyDelay: TimeoutTimer | undefined; constructor( protected ui: QuickInputUI ) { super(); } get title() { return this._title; } set title(title: string | undefined) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number | undefined) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number | undefined) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string | undefined) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.add( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.keyDownSeenSinceShown = false; this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables.clear(); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = undefined; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } protected showMessageDecoration(severity: Severity) { this.ui.inputBox.showDecoration(severity); if (severity === Severity.Error) { const styles = this.ui.inputBox.stylesForType(severity); this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : ''; this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : ''; this.ui.message.style.paddingBottom = '4px'; } else { this.ui.message.style.backgroundColor = ''; this.ui.message.style.border = ''; this.ui.message.style.paddingBottom = ''; } } public dispose(): void { this.hide(); super.dispose(); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static readonly INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder: string | undefined; private readonly onDidChangeValueEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private readonly onDidChangeActiveEmitter = this._register(new Emitter<T[]>()); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private readonly onDidChangeSelectionEmitter = this._register(new Emitter<T[]>()); private readonly onDidTriggerItemButtonEmitter = this._register(new Emitter<IQuickPickItemButtonEvent<T>>()); private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _validationMessage: string | undefined; private _ok = false; private _customButton = false; private _customButtonLabel: string | undefined; private _customButtonHover: string | undefined; quickNavigate: IQuickNavigateConfiguration | undefined; get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; onDidCustom = this.onDidCustomEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } get customButton() { return this._customButton; } set customButton(showCustomButton: boolean) { this._customButton = showCustomButton; this.update(); } get customLabel() { return this._customButtonLabel; } set customLabel(label: string | undefined) { this._customButtonLabel = label; this.update(); } get customHover() { return this._customButtonHover; } set customHover(hover: string | undefined) { this._customButtonHover = hover; this.update(); } get ok() { return this._ok; } set ok(showOkButton: boolean) { this._ok = showOkButton; this.update(); } public inputHasFocus(): boolean { return this.visible ? this.ui.inputBox.hasFocus() : false; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); })); this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } })); this.visibleDisposables.add(this.ui.inputBox.onKeyDown(event => { this.ui.keyDownSeenSinceShown = true; switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; } })); this.visibleDisposables.add(this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.onDidCustom(() => { this.onDidCustomEmitter.fire(undefined); })); this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } })); this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); })); this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>))); this.visibleDisposables.add(this.registerQuickNavigation()); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate || !this.ui.keyDownSeenSinceShown) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true, message: !!this.validationMessage } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true, message: !!this.validationMessage, customButton: this.customButton, ok: this.ok }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } if (this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } else { this.ui.message.textContent = null; this.showMessageDecoration(Severity.Ignore); } this.ui.customButton.label = this.customLabel || ''; this.ui.customButton.element.title = this.customHover || ''; this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); } } class InputBox extends QuickInput implements IInputBox { private static readonly noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]> | undefined; private valueSelectionUpdated = true; private _placeholder: string | undefined; private _password = false; private _prompt: string | undefined; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string | undefined; private readonly onDidValueChangeEmitter = this._register(new Emitter<string>()); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string | undefined) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string | undefined) { this._validationMessage = validationMessage; this.update(); } readonly onDidChangeValue = this.onDidValueChangeEmitter.event; readonly onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.add( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); })); this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined))); this.valueSelectionUpdated = true; } super.show(); } protected update() { if (!this.visible) { return; } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); super.update(); if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.showMessageDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.showMessageDecoration(Severity.Error); } } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: undefined; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private ui: QuickInputUI | undefined; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: Map<string, IContextKey<boolean>> = new Map(); private readonly onDidAcceptEmitter = this._register(new Emitter<void>()); private readonly onDidCustomEmitter = this._register(new Emitter<void>()); private readonly onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts.get(id); if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts.set(id, key); } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { this.contexts.forEach(context => { if (context.get()) { context.reset(); } }); } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private getUI() { if (this.ui) { return this.ui; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; const titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); const extraContainer = dom.append(headerContainer, $('.quick-input-and-message')); const filterContainer = dom.append(extraContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count')); visibleCountContainer.setAttribute('aria-live', 'polite'); visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); const countContainer = dom.append(filterContainer, $('.quick-input-count')); countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); const okContainer = dom.append(headerContainer, $('.quick-input-action')); const ok = new Button(okContainer); attachButtonStyler(ok, this.themeService); ok.label = localize('ok', "OK"); this._register(ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const customButtonContainer = dom.append(headerContainer, $('.quick-input-action')); const customButton = new Button(customButtonContainer); attachButtonStyler(customButton, this.themeService); customButton.label = localize('custom', "Custom"); this._register(customButton.onDidClick(e => { this.onDidCustomEmitter.fire(); })); const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.getUI().ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e: FocusEvent) => { inputBox.setFocus(); })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { this.getUI().keyDownSeenSinceShown = true; const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.codicon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.getUI().list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, titleBar, title, rightActionBar, checkAll, filterContainer, inputBox, visibleCountContainer, visibleCount, countContainer, count, okContainer, ok, message, customButtonContainer, customButton, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidCustom: this.onDidCustomEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, keyDownSeenSinceShown: false, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); return this.ui; } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { const ui = this.getUI(); return new QuickPick<T>(ui); } createInputBox(): IInputBox { const ui = this.getUI(); return new InputBox(ui); } private show(controller: QuickInput) { const ui = this.getUI(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); ui.leftActionBar.clear(); ui.title.textContent = ''; ui.rightActionBar.clear(); ui.checkAll.checked = false; // ui.inputBox.value = ''; Avoid triggering an event. ui.inputBox.placeholder = ''; ui.inputBox.password = false; ui.inputBox.showDecoration(Severity.Ignore); ui.visibleCount.setCount(0); ui.count.setCount(0); ui.message.textContent = ''; ui.progressBar.stop(); ui.list.setElements([]); ui.list.matchOnDescription = false; ui.list.matchOnDetail = false; ui.list.matchOnLabel = true; ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); ui.container.style.display = ''; this.updateLayout(); ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { const ui = this.getUI(); ui.title.style.display = visibilities.title ? '' : 'none'; ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; ui.countContainer.style.display = visibilities.count ? '' : 'none'; ui.okContainer.style.display = visibilities.ok ? '' : 'none'; ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none'; ui.message.style.display = visibilities.message ? '' : 'none'; ui.list.display(!!visibilities.list); ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { const ui = this.getUI(); this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { ui.inputBox.setAttribute('role', 'combobox'); ui.inputBox.setAttribute('aria-haspopup', 'true'); ui.inputBox.setAttribute('aria-autocomplete', 'list'); ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || ''); } else { ui.inputBox.removeAttribute('role'); ui.inputBox.removeAttribute('aria-haspopup'); ui.inputBox.removeAttribute('aria-autocomplete'); ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.getUI().leftActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } for (const item of this.getUI().rightActionBar.viewItems) { (item as ActionViewItem).getAction().enabled = enabled; } this.getUI().checkAll.disabled = !enabled; // this.getUI().inputBox.enabled = enabled; Avoid loosing focus. this.getUI().ok.enabled = enabled; this.getUI().list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.getUI().container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.getUI().inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.getUI().list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.getUI().list.isDisplayed()) { this.getUI().list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.ui.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : ''; this.ui.inputBox.style(theme); const quickInputBackground = theme.getColor(QUICK_INPUT_BACKGROUND); this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : ''; const quickInputForeground = theme.getColor(QUICK_INPUT_FOREGROUND); this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : ''; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : ''; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.12010044604539871, 0.002659020945429802, 0.00016287084145005792, 0.00017072248738259077, 0.010892380960285664 ]
{ "id": 11, "code_window": [ "\t\t\tonDidAccept: this.onDidAcceptEmitter.event,\n", "\t\t\tonDidCustom: this.onDidCustomEmitter.event,\n", "\t\t\tonDidTriggerButton: this.onDidTriggerButtonEmitter.event,\n", "\t\t\tignoreFocusOut: false,\n", "\t\t\tkeyMods: this.keyMods,\n", "\t\t\tkeyDownSeenSinceShown: false,\n", "\t\t\tisScreenReaderOptimized: () => this.isScreenReaderOptimized(),\n", "\t\t\tshow: controller => this.show(controller),\n", "\t\t\thide: () => this.hide(),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 1178 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { CharCode } from 'vs/base/common/charCode'; import * as platform from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Range } from 'vs/editor/common/core/range'; import { createStringBuilder } from 'vs/editor/common/core/stringBuilder'; import { DefaultEndOfLine } from 'vs/editor/common/model'; import { TextModel, createTextBuffer } from 'vs/editor/common/model/textModel'; import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl'; import { ITextResourcePropertiesService } from 'vs/editor/common/services/resourceConfiguration'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; const GENERATE_TESTS = false; suite('ModelService', () => { let modelService: ModelServiceImpl; setup(() => { const configService = new TestConfigurationService(); configService.setUserConfiguration('files', { 'eol': '\n' }); configService.setUserConfiguration('files', { 'eol': '\r\n' }, URI.file(platform.isWindows ? 'c:\\myroot' : '/myroot')); modelService = new ModelServiceImpl(configService, new TestTextResourcePropertiesService(configService)); }); teardown(() => { modelService.dispose(); }); test('EOL setting respected depending on root', () => { const model1 = modelService.createModel('farboo', null); const model2 = modelService.createModel('farboo', null, URI.file(platform.isWindows ? 'c:\\myroot\\myfile.txt' : '/myroot/myfile.txt')); const model3 = modelService.createModel('farboo', null, URI.file(platform.isWindows ? 'c:\\other\\myfile.txt' : '/other/myfile.txt')); assert.equal(model1.getOptions().defaultEOL, DefaultEndOfLine.LF); assert.equal(model2.getOptions().defaultEOL, DefaultEndOfLine.CRLF); assert.equal(model3.getOptions().defaultEOL, DefaultEndOfLine.LF); }); test('_computeEdits no change', function () { const model = TextModel.createFromString( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n') ); const textBuffer = createTextBuffer( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n'), DefaultEndOfLine.LF ); const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepEqual(actual, []); }); test('_computeEdits first line changed', function () { const model = TextModel.createFromString( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n') ); const textBuffer = createTextBuffer( [ 'This is line One', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n'), DefaultEndOfLine.LF ); const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepEqual(actual, [ EditOperation.replaceMove(new Range(1, 1, 2, 1), 'This is line One\n') ]); }); test('_computeEdits EOL changed', function () { const model = TextModel.createFromString( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n') ); const textBuffer = createTextBuffer( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\r\n'), DefaultEndOfLine.LF ); const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepEqual(actual, []); }); test('_computeEdits EOL and other change 1', function () { const model = TextModel.createFromString( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n') ); const textBuffer = createTextBuffer( [ 'This is line One', //16 'and this is line number two', //27 'It is followed by #3', //20 'and finished with the fourth.', //29 ].join('\r\n'), DefaultEndOfLine.LF ); const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepEqual(actual, [ EditOperation.replaceMove( new Range(1, 1, 4, 1), [ 'This is line One', 'and this is line number two', 'It is followed by #3', '' ].join('\r\n') ) ]); }); test('_computeEdits EOL and other change 2', function () { const model = TextModel.createFromString( [ 'package main', // 1 'func foo() {', // 2 '}' // 3 ].join('\n') ); const textBuffer = createTextBuffer( [ 'package main', // 1 'func foo() {', // 2 '}', // 3 '' ].join('\r\n'), DefaultEndOfLine.LF ); const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepEqual(actual, [ EditOperation.replaceMove(new Range(3, 2, 3, 2), '\r\n') ]); }); test('generated1', () => { const file1 = ['pram', 'okctibad', 'pjuwtemued', 'knnnm', 'u', '']; const file2 = ['tcnr', 'rxwlicro', 'vnzy', '', '', 'pjzcogzur', 'ptmxyp', 'dfyshia', 'pee', 'ygg']; assertComputeEdits(file1, file2); }); test('generated2', () => { const file1 = ['', 'itls', 'hrilyhesv', '']; const file2 = ['vdl', '', 'tchgz', 'bhx', 'nyl']; assertComputeEdits(file1, file2); }); test('generated3', () => { const file1 = ['ubrbrcv', 'wv', 'xodspybszt', 's', 'wednjxm', 'fklajt', 'fyfc', 'lvejgge', 'rtpjlodmmk', 'arivtgmjdm']; const file2 = ['s', 'qj', 'tu', 'ur', 'qerhjjhyvx', 't']; assertComputeEdits(file1, file2); }); test('generated4', () => { const file1 = ['ig', 'kh', 'hxegci', 'smvker', 'pkdmjjdqnv', 'vgkkqqx', '', 'jrzeb']; const file2 = ['yk', '']; assertComputeEdits(file1, file2); }); test('does insertions in the middle of the document', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 1', 'line 2', 'line 5', 'line 3' ]; assertComputeEdits(file1, file2); }); test('does insertions at the end of the document', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 1', 'line 2', 'line 3', 'line 4' ]; assertComputeEdits(file1, file2); }); test('does insertions at the beginning of the document', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 0', 'line 1', 'line 2', 'line 3' ]; assertComputeEdits(file1, file2); }); test('does replacements', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 1', 'line 7', 'line 3' ]; assertComputeEdits(file1, file2); }); test('does deletions', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 1', 'line 3' ]; assertComputeEdits(file1, file2); }); test('does insert, replace, and delete', () => { const file1 = [ 'line 1', 'line 2', 'line 3', 'line 4', 'line 5', ]; const file2 = [ 'line 0', // insert line 0 'line 1', 'replace line 2', // replace line 2 'line 3', // delete line 4 'line 5', ]; assertComputeEdits(file1, file2); }); }); function assertComputeEdits(lines1: string[], lines2: string[]): void { const model = TextModel.createFromString(lines1.join('\n')); const textBuffer = createTextBuffer(lines2.join('\n'), DefaultEndOfLine.LF); // compute required edits // let start = Date.now(); const edits = ModelServiceImpl._computeEdits(model, textBuffer); // console.log(`took ${Date.now() - start} ms.`); // apply edits model.pushEditOperations([], edits, null); assert.equal(model.getValue(), lines2.join('\n')); } function getRandomInt(min: number, max: number): number { return Math.floor(Math.random() * (max - min + 1)) + min; } function getRandomString(minLength: number, maxLength: number): string { let length = getRandomInt(minLength, maxLength); let t = createStringBuilder(length); for (let i = 0; i < length; i++) { t.appendASCII(getRandomInt(CharCode.a, CharCode.z)); } return t.build(); } function generateFile(small: boolean): string[] { let lineCount = getRandomInt(1, small ? 3 : 10000); let lines: string[] = []; for (let i = 0; i < lineCount; i++) { lines.push(getRandomString(0, small ? 3 : 10000)); } return lines; } if (GENERATE_TESTS) { let number = 1; while (true) { console.log('------TEST: ' + number++); const file1 = generateFile(true); const file2 = generateFile(true); console.log('------TEST GENERATED'); try { assertComputeEdits(file1, file2); } catch (err) { console.log(err); console.log(` const file1 = ${JSON.stringify(file1).replace(/"/g, '\'')}; const file2 = ${JSON.stringify(file2).replace(/"/g, '\'')}; assertComputeEdits(file1, file2); `); break; } } } export class TestTextResourcePropertiesService implements ITextResourcePropertiesService { _serviceBrand: undefined; constructor( @IConfigurationService private readonly configurationService: IConfigurationService, ) { } getEOL(resource: URI, language?: string): string { const eol = this.configurationService.getValue<string>('files.eol', { overrideIdentifier: language, resource }); if (eol && eol !== 'auto') { return eol; } return (platform.isLinux || platform.isMacintosh) ? '\n' : '\r\n'; } }
src/vs/editor/test/common/services/modelService.test.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017504316929262131, 0.00017307576490566134, 0.00016642329865135252, 0.00017354844021610916, 0.0000016512656202394282 ]
{ "id": 11, "code_window": [ "\t\t\tonDidAccept: this.onDidAcceptEmitter.event,\n", "\t\t\tonDidCustom: this.onDidCustomEmitter.event,\n", "\t\t\tonDidTriggerButton: this.onDidTriggerButtonEmitter.event,\n", "\t\t\tignoreFocusOut: false,\n", "\t\t\tkeyMods: this.keyMods,\n", "\t\t\tkeyDownSeenSinceShown: false,\n", "\t\t\tisScreenReaderOptimized: () => this.isScreenReaderOptimized(),\n", "\t\t\tshow: controller => this.show(controller),\n", "\t\t\thide: () => this.hide(),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 1178 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/
extensions/html-language-features/server/src/test/pathCompletionFixtures/about/media/icon.pic
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017469434533268213, 0.00017469434533268213, 0.00017469434533268213, 0.00017469434533268213, 0 ]
{ "id": 11, "code_window": [ "\t\t\tonDidAccept: this.onDidAcceptEmitter.event,\n", "\t\t\tonDidCustom: this.onDidCustomEmitter.event,\n", "\t\t\tonDidTriggerButton: this.onDidTriggerButtonEmitter.event,\n", "\t\t\tignoreFocusOut: false,\n", "\t\t\tkeyMods: this.keyMods,\n", "\t\t\tkeyDownSeenSinceShown: false,\n", "\t\t\tisScreenReaderOptimized: () => this.isScreenReaderOptimized(),\n", "\t\t\tshow: controller => this.show(controller),\n", "\t\t\thide: () => this.hide(),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "replace", "edit_start_line_idx": 1178 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { TimeoutTimer } from 'vs/base/common/async'; import { IDisposable } from 'vs/base/common/lifecycle'; import * as strings from 'vs/base/common/strings'; import { IViewLineTokens, LineTokens } from 'vs/editor/common/core/lineTokens'; import { ITextModel } from 'vs/editor/common/model'; import { ColorId, FontStyle, ITokenizationSupport, MetadataConsts, TokenizationRegistry } from 'vs/editor/common/modes'; import { IModeService } from 'vs/editor/common/services/modeService'; import { RenderLineInput, renderViewLine2 as renderViewLine } from 'vs/editor/common/viewLayout/viewLineRenderer'; import { ViewLineRenderingData } from 'vs/editor/common/viewModel/viewModel'; import { IStandaloneThemeService } from 'vs/editor/standalone/common/standaloneThemeService'; import { MonarchTokenizer } from 'vs/editor/standalone/common/monarch/monarchLexer'; export interface IColorizerOptions { tabSize?: number; } export interface IColorizerElementOptions extends IColorizerOptions { theme?: string; mimeType?: string; } export class Colorizer { public static colorizeElement(themeService: IStandaloneThemeService, modeService: IModeService, domNode: HTMLElement, options: IColorizerElementOptions): Promise<void> { options = options || {}; let theme = options.theme || 'vs'; let mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang'); if (!mimeType) { console.error('Mode not detected'); return Promise.resolve(); } themeService.setTheme(theme); let text = domNode.firstChild ? domNode.firstChild.nodeValue : ''; domNode.className += ' ' + theme; let render = (str: string) => { domNode.innerHTML = str; }; return this.colorize(modeService, text || '', mimeType, options).then(render, (err) => console.error(err)); } public static colorize(modeService: IModeService, text: string, mimeType: string, options: IColorizerOptions | null | undefined): Promise<string> { let tabSize = 4; if (options && typeof options.tabSize === 'number') { tabSize = options.tabSize; } if (strings.startsWithUTF8BOM(text)) { text = text.substr(1); } let lines = text.split(/\r\n|\r|\n/); let language = modeService.getModeId(mimeType); if (!language) { return Promise.resolve(_fakeColorize(lines, tabSize)); } // Send out the event to create the mode modeService.triggerMode(language); const tokenizationSupport = TokenizationRegistry.get(language); if (tokenizationSupport) { return _colorize(lines, tabSize, tokenizationSupport); } const tokenizationSupportPromise = TokenizationRegistry.getPromise(language); if (tokenizationSupportPromise) { // A tokenizer will be registered soon return new Promise<string>((resolve, reject) => { tokenizationSupportPromise.then(tokenizationSupport => { _colorize(lines, tabSize, tokenizationSupport).then(resolve, reject); }, reject); }); } return new Promise<string>((resolve, reject) => { let listener: IDisposable | null = null; let timeout: TimeoutTimer | null = null; const execute = () => { if (listener) { listener.dispose(); listener = null; } if (timeout) { timeout.dispose(); timeout = null; } const tokenizationSupport = TokenizationRegistry.get(language!); if (tokenizationSupport) { _colorize(lines, tabSize, tokenizationSupport).then(resolve, reject); return; } resolve(_fakeColorize(lines, tabSize)); }; // wait 500ms for mode to load, then give up timeout = new TimeoutTimer(); timeout.cancelAndSet(execute, 500); listener = TokenizationRegistry.onDidChange((e) => { if (e.changedLanguages.indexOf(language!) >= 0) { execute(); } }); }); } public static colorizeLine(line: string, mightContainNonBasicASCII: boolean, mightContainRTL: boolean, tokens: IViewLineTokens, tabSize: number = 4): string { const isBasicASCII = ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII); const containsRTL = ViewLineRenderingData.containsRTL(line, isBasicASCII, mightContainRTL); let renderResult = renderViewLine(new RenderLineInput( false, true, line, false, isBasicASCII, containsRTL, 0, tokens, [], tabSize, 0, -1, 'none', false, false, null )); return renderResult.html; } public static colorizeModelLine(model: ITextModel, lineNumber: number, tabSize: number = 4): string { let content = model.getLineContent(lineNumber); model.forceTokenization(lineNumber); let tokens = model.getLineTokens(lineNumber); let inflatedTokens = tokens.inflate(); return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize); } } function _colorize(lines: string[], tabSize: number, tokenizationSupport: ITokenizationSupport): Promise<string> { return new Promise<string>((c, e) => { const execute = () => { const result = _actualColorize(lines, tabSize, tokenizationSupport); if (tokenizationSupport instanceof MonarchTokenizer) { const status = tokenizationSupport.getLoadStatus(); if (status.loaded === false) { status.promise.then(execute, e); return; } } c(result); }; execute(); }); } function _fakeColorize(lines: string[], tabSize: number): string { let html: string[] = []; const defaultMetadata = ( (FontStyle.None << MetadataConsts.FONT_STYLE_OFFSET) | (ColorId.DefaultForeground << MetadataConsts.FOREGROUND_OFFSET) | (ColorId.DefaultBackground << MetadataConsts.BACKGROUND_OFFSET) ) >>> 0; const tokens = new Uint32Array(2); tokens[0] = 0; tokens[1] = defaultMetadata; for (let i = 0, length = lines.length; i < length; i++) { let line = lines[i]; tokens[0] = line.length; const lineTokens = new LineTokens(tokens, line); const isBasicASCII = ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */true); const containsRTL = ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */true); let renderResult = renderViewLine(new RenderLineInput( false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, -1, 'none', false, false, null )); html = html.concat(renderResult.html); html.push('<br/>'); } return html.join(''); } function _actualColorize(lines: string[], tabSize: number, tokenizationSupport: ITokenizationSupport): string { let html: string[] = []; let state = tokenizationSupport.getInitialState(); for (let i = 0, length = lines.length; i < length; i++) { let line = lines[i]; let tokenizeResult = tokenizationSupport.tokenize2(line, state, 0); LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length); let lineTokens = new LineTokens(tokenizeResult.tokens, line); const isBasicASCII = ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */true); const containsRTL = ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */true); let renderResult = renderViewLine(new RenderLineInput( false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens.inflate(), [], tabSize, 0, -1, 'none', false, false, null )); html = html.concat(renderResult.html); html.push('<br/>'); state = tokenizeResult.endState; } return html.join(''); }
src/vs/editor/standalone/browser/colorizer.ts
0
https://github.com/microsoft/vscode/commit/6b8c4b04f3b35f1e80d65fbd04ab7405ddd89e5c
[ 0.00017485767602920532, 0.00017120382108259946, 0.0001633529900573194, 0.00017178173584397882, 0.000002402500513198902 ]
{ "id": 1, "code_window": [ "import {BrowserModule} from '@angular/platform-browser';\n", "import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';\n", "import * as angular from '@angular/upgrade/src/common/angular1';\n", "import {UpgradeAdapter, UpgradeAdapterRef} from '@angular/upgrade/src/dynamic/upgrade_adapter';\n", "\n", "import {$apply, $digest, html, multiTrim, withEachNg1Version} from './test_helpers';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER} from '@angular/upgrade/src/common/constants';\n" ], "file_path": "packages/upgrade/test/dynamic/upgrade_spec.ts", "type": "add", "edit_start_line_idx": 13 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ChangeDetectionStrategy, ChangeDetectorRef, Compiler, Component, ComponentFactoryResolver, Directive, ElementRef, EventEmitter, Injector, Input, NgModule, NgModuleRef, OnChanges, OnDestroy, Output, SimpleChanges, destroyPlatform} from '@angular/core'; import {async, fakeAsync, tick} from '@angular/core/testing'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {UpgradeComponent, UpgradeModule, downgradeComponent} from '@angular/upgrade/static'; import * as angular from '@angular/upgrade/static/src/common/angular1'; import {$apply, bootstrap, html, multiTrim, withEachNg1Version} from '../test_helpers'; withEachNg1Version(() => { describe('downgrade ng2 component', () => { beforeEach(() => destroyPlatform()); afterEach(() => destroyPlatform()); it('should bind properties, events', async(() => { const ng1Module = angular.module('ng1', []).value('$exceptionHandler', (err: any) => { throw err; }).run(($rootScope: angular.IScope) => { $rootScope['name'] = 'world'; $rootScope['dataA'] = 'A'; $rootScope['dataB'] = 'B'; $rootScope['modelA'] = 'initModelA'; $rootScope['modelB'] = 'initModelB'; $rootScope['eventA'] = '?'; $rootScope['eventB'] = '?'; }); @Component({ selector: 'ng2', inputs: ['literal', 'interpolate', 'oneWayA', 'oneWayB', 'twoWayA', 'twoWayB'], outputs: [ 'eventA', 'eventB', 'twoWayAEmitter: twoWayAChange', 'twoWayBEmitter: twoWayBChange' ], template: 'ignore: {{ignore}}; ' + 'literal: {{literal}}; interpolate: {{interpolate}}; ' + 'oneWayA: {{oneWayA}}; oneWayB: {{oneWayB}}; ' + 'twoWayA: {{twoWayA}}; twoWayB: {{twoWayB}}; ({{ngOnChangesCount}})' }) class Ng2Component implements OnChanges { ngOnChangesCount = 0; ignore = '-'; literal = '?'; interpolate = '?'; oneWayA = '?'; oneWayB = '?'; twoWayA = '?'; twoWayB = '?'; eventA = new EventEmitter(); eventB = new EventEmitter(); twoWayAEmitter = new EventEmitter(); twoWayBEmitter = new EventEmitter(); ngOnChanges(changes: SimpleChanges) { const assert = (prop: string, value: any) => { const propVal = (this as any)[prop]; if (propVal != value) { throw new Error(`Expected: '${prop}' to be '${value}' but was '${propVal}'`); } }; const assertChange = (prop: string, value: any) => { assert(prop, value); if (!changes[prop]) { throw new Error(`Changes record for '${prop}' not found.`); } const actualValue = changes[prop].currentValue; if (actualValue != value) { throw new Error( `Expected changes record for'${prop}' to be '${value}' but was '${actualValue}'`); } }; switch (this.ngOnChangesCount++) { case 0: assert('ignore', '-'); assertChange('literal', 'Text'); assertChange('interpolate', 'Hello world'); assertChange('oneWayA', 'A'); assertChange('oneWayB', 'B'); assertChange('twoWayA', 'initModelA'); assertChange('twoWayB', 'initModelB'); this.twoWayAEmitter.emit('newA'); this.twoWayBEmitter.emit('newB'); this.eventA.emit('aFired'); this.eventB.emit('bFired'); break; case 1: assertChange('twoWayA', 'newA'); assertChange('twoWayB', 'newB'); break; case 2: assertChange('interpolate', 'Hello everyone'); break; default: throw new Error('Called too many times! ' + JSON.stringify(changes)); } } } ng1Module.directive('ng2', downgradeComponent({ component: Ng2Component, })); @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const element = html(` <div> <ng2 literal="Text" interpolate="Hello {{name}}" bind-one-way-a="dataA" [one-way-b]="dataB" bindon-two-way-a="modelA" [(two-way-b)]="modelB" on-event-a='eventA=$event' (event-b)="eventB=$event"></ng2> | modelA: {{modelA}}; modelB: {{modelB}}; eventA: {{eventA}}; eventB: {{eventB}}; </div>`); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(document.body.textContent)) .toEqual( 'ignore: -; ' + 'literal: Text; interpolate: Hello world; ' + 'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (2) | ' + 'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;'); $apply(upgrade, 'name = "everyone"'); expect(multiTrim(document.body.textContent)) .toEqual( 'ignore: -; ' + 'literal: Text; interpolate: Hello everyone; ' + 'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (3) | ' + 'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;'); }); })); it('should bind properties to onpush components', async(() => { const ng1Module = angular.module('ng1', []).value('$exceptionHandler', (err: any) => { throw err; }).run(($rootScope: angular.IScope) => { $rootScope['dataB'] = 'B'; }); @Component({ selector: 'ng2', inputs: ['oneWayB'], template: 'oneWayB: {{oneWayB}}', changeDetection: ChangeDetectionStrategy.OnPush }) class Ng2Component { ngOnChangesCount = 0; oneWayB = '?'; } ng1Module.directive('ng2', downgradeComponent({ component: Ng2Component, })); @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const element = html(` <div> <ng2 [one-way-b]="dataB"></ng2> </div>`); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(document.body.textContent)).toEqual('oneWayB: B'); $apply(upgrade, 'dataB= "everyone"'); expect(multiTrim(document.body.textContent)).toEqual('oneWayB: everyone'); }); })); it('should support two-way binding and event listener', async(() => { const listenerSpy = jasmine.createSpy('$rootScope.listener'); const ng1Module = angular.module('ng1', []).run(($rootScope: angular.IScope) => { $rootScope['value'] = 'world'; $rootScope['listener'] = listenerSpy; }); @Component({selector: 'ng2', template: `model: {{model}};`}) class Ng2Component implements OnChanges { ngOnChangesCount = 0; @Input() model = '?'; @Output() modelChange = new EventEmitter(); ngOnChanges(changes: SimpleChanges) { switch (this.ngOnChangesCount++) { case 0: expect(changes.model.currentValue).toBe('world'); this.modelChange.emit('newC'); break; case 1: expect(changes.model.currentValue).toBe('newC'); break; default: throw new Error('Called too many times! ' + JSON.stringify(changes)); } } } ng1Module.directive('ng2', downgradeComponent({component: Ng2Component})); @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const element = html(` <div> <ng2 [(model)]="value" (model-change)="listener($event)"></ng2> | value: {{value}} </div> `); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(element.textContent)).toEqual('model: newC; | value: newC'); expect(listenerSpy).toHaveBeenCalledWith('newC'); }); })); it('should run change-detection on every digest (by default)', async(() => { let ng2Component: Ng2Component; @Component({selector: 'ng2', template: '{{ value1 }} | {{ value2 }}'}) class Ng2Component { @Input() value1 = -1; @Input() value2 = -1; constructor() { ng2Component = this; } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng2Component], entryComponents: [Ng2Component] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive('ng2', downgradeComponent({component: Ng2Component})) .run(($rootScope: angular.IRootScopeService) => { $rootScope.value1 = 0; $rootScope.value2 = 0; }); const element = html('<ng2 [value1]="value1" value2="{{ value2 }}"></ng2>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService; expect(element.textContent).toBe('0 | 0'); // Digest should invoke CD $rootScope.$digest(); $rootScope.$digest(); expect(element.textContent).toBe('0 | 0'); // Internal changes should be detected on digest ng2Component.value1 = 1; ng2Component.value2 = 2; $rootScope.$digest(); expect(element.textContent).toBe('1 | 2'); // Digest should propagate change in prop-bound input $rootScope.$apply('value1 = 3'); expect(element.textContent).toBe('3 | 2'); // Digest should propagate change in attr-bound input ng2Component.value1 = 4; $rootScope.$apply('value2 = 5'); expect(element.textContent).toBe('4 | 5'); // Digest should propagate changes that happened before the digest $rootScope.value1 = 6; expect(element.textContent).toBe('4 | 5'); $rootScope.$digest(); expect(element.textContent).toBe('6 | 5'); }); })); it('should not run change-detection on every digest when opted out', async(() => { let ng2Component: Ng2Component; @Component({selector: 'ng2', template: '{{ value1 }} | {{ value2 }}'}) class Ng2Component { @Input() value1 = -1; @Input() value2 = -1; constructor() { ng2Component = this; } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng2Component], entryComponents: [Ng2Component] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive( 'ng2', downgradeComponent({component: Ng2Component, propagateDigest: false})) .run(($rootScope: angular.IRootScopeService) => { $rootScope.value1 = 0; $rootScope.value2 = 0; }); const element = html('<ng2 [value1]="value1" value2="{{ value2 }}"></ng2>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService; expect(element.textContent).toBe('0 | 0'); // Digest should not invoke CD $rootScope.$digest(); $rootScope.$digest(); expect(element.textContent).toBe('0 | 0'); // Digest should not invoke CD, even if component values have changed (internally) ng2Component.value1 = 1; ng2Component.value2 = 2; $rootScope.$digest(); expect(element.textContent).toBe('0 | 0'); // Digest should invoke CD, if prop-bound input has changed $rootScope.$apply('value1 = 3'); expect(element.textContent).toBe('3 | 2'); // Digest should invoke CD, if attr-bound input has changed ng2Component.value1 = 4; $rootScope.$apply('value2 = 5'); expect(element.textContent).toBe('4 | 5'); // Digest should invoke CD, if input has changed before the digest $rootScope.value1 = 6; $rootScope.$digest(); expect(element.textContent).toBe('6 | 5'); }); })); it('should still run normal Angular change-detection regardless of `propagateDigest`', fakeAsync(() => { let ng2Component: Ng2Component; @Component({selector: 'ng2', template: '{{ value }}'}) class Ng2Component { value = 'foo'; constructor() { setTimeout(() => this.value = 'bar', 1000); } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng2Component], entryComponents: [Ng2Component] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive( 'ng2A', downgradeComponent({component: Ng2Component, propagateDigest: true})) .directive( 'ng2B', downgradeComponent({component: Ng2Component, propagateDigest: false})); const element = html('<ng2-a></ng2-a> | <ng2-b></ng2-b>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { expect(element.textContent).toBe('foo | foo'); tick(1000); expect(element.textContent).toBe('bar | bar'); }); })); it('should initialize inputs in time for `ngOnChanges`', async(() => { @Component({ selector: 'ng2', template: ` ngOnChangesCount: {{ ngOnChangesCount }} | firstChangesCount: {{ firstChangesCount }} | initialValue: {{ initialValue }}` }) class Ng2Component implements OnChanges { ngOnChangesCount = 0; firstChangesCount = 0; // TODO(issue/24571): remove '!'. initialValue !: string; // TODO(issue/24571): remove '!'. @Input() foo !: string; ngOnChanges(changes: SimpleChanges) { this.ngOnChangesCount++; if (this.ngOnChangesCount === 1) { this.initialValue = this.foo; } if (changes['foo'] && changes['foo'].isFirstChange()) { this.firstChangesCount++; } } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng2Component], entryComponents: [Ng2Component] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []).directive( 'ng2', downgradeComponent({component: Ng2Component})); const element = html(` <ng2 [foo]="'foo'"></ng2> <ng2 foo="bar"></ng2> <ng2 [foo]="'baz'" ng-if="true"></ng2> <ng2 foo="qux" ng-if="true"></ng2> `); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { const nodes = element.querySelectorAll('ng2'); const expectedTextWith = (value: string) => `ngOnChangesCount: 1 | firstChangesCount: 1 | initialValue: ${value}`; expect(multiTrim(nodes[0].textContent)).toBe(expectedTextWith('foo')); expect(multiTrim(nodes[1].textContent)).toBe(expectedTextWith('bar')); expect(multiTrim(nodes[2].textContent)).toBe(expectedTextWith('baz')); expect(multiTrim(nodes[3].textContent)).toBe(expectedTextWith('qux')); }); })); it('should bind to ng-model', async(() => { const ng1Module = angular.module('ng1', []).run( ($rootScope: angular.IScope) => { $rootScope['modelA'] = 'A'; }); let ng2Instance: Ng2; @Component({selector: 'ng2', template: '<span>{{_value}}</span>'}) class Ng2 { private _value: any = ''; private _onChangeCallback: (_: any) => void = () => {}; private _onTouchedCallback: () => void = () => {}; constructor() { ng2Instance = this; } writeValue(value: any) { this._value = value; } registerOnChange(fn: any) { this._onChangeCallback = fn; } registerOnTouched(fn: any) { this._onTouchedCallback = fn; } doTouch() { this._onTouchedCallback(); } doChange(newValue: string) { this._value = newValue; this._onChangeCallback(newValue); } } ng1Module.directive('ng2', downgradeComponent({component: Ng2})); const element = html(`<div><ng2 ng-model="modelA"></ng2> | {{modelA}}</div>`); @NgModule( {declarations: [Ng2], entryComponents: [Ng2], imports: [BrowserModule, UpgradeModule]}) class Ng2Module { ngDoBootstrap() {} } platformBrowserDynamic().bootstrapModule(Ng2Module).then((ref) => { const adapter = ref.injector.get(UpgradeModule) as UpgradeModule; adapter.bootstrap(element, [ng1Module.name]); const $rootScope = adapter.$injector.get('$rootScope'); expect(multiTrim(document.body.textContent)).toEqual('A | A'); $rootScope.modelA = 'B'; $rootScope.$apply(); expect(multiTrim(document.body.textContent)).toEqual('B | B'); ng2Instance.doChange('C'); expect($rootScope.modelA).toBe('C'); expect(multiTrim(document.body.textContent)).toEqual('C | C'); const downgradedElement = <Element>document.body.querySelector('ng2'); expect(downgradedElement.classList.contains('ng-touched')).toBe(false); ng2Instance.doTouch(); $rootScope.$apply(); expect(downgradedElement.classList.contains('ng-touched')).toBe(true); }); })); it('should properly run cleanup when ng1 directive is destroyed', async(() => { let destroyed = false; @Component({selector: 'ng2', template: 'test'}) class Ng2Component implements OnDestroy { ngOnDestroy() { destroyed = true; } } @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive( 'ng1', () => { return {template: '<div ng-if="!destroyIt"><ng2></ng2></div>'}; }) .directive('ng2', downgradeComponent({component: Ng2Component})); const element = html('<ng1></ng1>'); platformBrowserDynamic().bootstrapModule(Ng2Module).then((ref) => { const adapter = ref.injector.get(UpgradeModule) as UpgradeModule; adapter.bootstrap(element, [ng1Module.name]); expect(element.textContent).toContain('test'); expect(destroyed).toBe(false); const $rootScope = adapter.$injector.get('$rootScope'); $rootScope.$apply('destroyIt = true'); expect(element.textContent).not.toContain('test'); expect(destroyed).toBe(true); }); })); it('should properly run cleanup with multiple levels of nesting', async(() => { let destroyed = false; @Component({ selector: 'ng2-outer', template: '<div *ngIf="!destroyIt"><ng1></ng1></div>', }) class Ng2OuterComponent { @Input() destroyIt = false; } @Component({selector: 'ng2-inner', template: 'test'}) class Ng2InnerComponent implements OnDestroy { ngOnDestroy() { destroyed = true; } } @Directive({selector: 'ng1'}) class Ng1ComponentFacade extends UpgradeComponent { constructor(elementRef: ElementRef, injector: Injector) { super('ng1', elementRef, injector); } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng1ComponentFacade, Ng2InnerComponent, Ng2OuterComponent], entryComponents: [Ng2InnerComponent, Ng2OuterComponent], }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive('ng1', () => ({template: '<ng2-inner></ng2-inner>'})) .directive('ng2Inner', downgradeComponent({component: Ng2InnerComponent})) .directive('ng2Outer', downgradeComponent({component: Ng2OuterComponent})); const element = html('<ng2-outer [destroy-it]="destroyIt"></ng2-outer>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { expect(element.textContent).toBe('test'); expect(destroyed).toBe(false); $apply(upgrade, 'destroyIt = true'); expect(element.textContent).toBe(''); expect(destroyed).toBe(true); }); })); it('should work when compiled outside the dom (by fallback to the root ng2.injector)', async(() => { @Component({selector: 'ng2', template: 'test'}) class Ng2Component { } @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive( 'ng1', [ '$compile', ($compile: angular.ICompileService) => { return { link: function( $scope: angular.IScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes) { // here we compile some HTML that contains a downgraded component // since it is not currently in the DOM it is not able to "require" // an ng2 injector so it should use the `moduleInjector` instead. const compiled = $compile('<ng2></ng2>'); const template = compiled($scope); $element.append !(template); } }; } ]) .directive('ng2', downgradeComponent({component: Ng2Component})); const element = html('<ng1></ng1>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { // the fact that the body contains the correct text means that the // downgraded component was able to access the moduleInjector // (since there is no other injector in this system) expect(multiTrim(document.body.textContent)).toEqual('test'); }); })); it('should allow attribute selectors for downgraded components', async(() => { @Component({selector: '[itWorks]', template: 'It works'}) class WorksComponent { } @NgModule({ declarations: [WorksComponent], entryComponents: [WorksComponent], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []).directive( 'worksComponent', downgradeComponent({component: WorksComponent})); const element = html('<works-component></works-component>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(document.body.textContent)).toBe('It works'); }); })); it('should allow attribute selectors for components in ng2', async(() => { @Component({selector: '[itWorks]', template: 'It works'}) class WorksComponent { } @Component({selector: 'root-component', template: '<span itWorks></span>!'}) class RootComponent { } @NgModule({ declarations: [RootComponent, WorksComponent], entryComponents: [RootComponent], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []).directive( 'rootComponent', downgradeComponent({component: RootComponent})); const element = html('<root-component></root-component>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(document.body.textContent)).toBe('It works!'); }); })); it('should respect hierarchical dependency injection for ng2', async(() => { @Component({selector: 'parent', template: 'parent(<ng-content></ng-content>)'}) class ParentComponent { } @Component({selector: 'child', template: 'child'}) class ChildComponent { constructor(parent: ParentComponent) {} } @NgModule({ declarations: [ParentComponent, ChildComponent], entryComponents: [ParentComponent, ChildComponent], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive('parent', downgradeComponent({component: ParentComponent})) .directive('child', downgradeComponent({component: ChildComponent})); const element = html('<parent><child></child></parent>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { expect(multiTrim(document.body.textContent)).toBe('parent(child)'); }); })); it('should work with ng2 lazy loaded components', async(() => { let componentInjector: Injector; @Component({selector: 'ng2', template: ''}) class Ng2Component { constructor(injector: Injector) { componentInjector = injector; } } @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule], }) class Ng2Module { ngDoBootstrap() {} } @Component({template: ''}) class LazyLoadedComponent { constructor(public module: NgModuleRef<any>) {} } @NgModule({ declarations: [LazyLoadedComponent], entryComponents: [LazyLoadedComponent], }) class LazyLoadedModule { } const ng1Module = angular.module('ng1', []).directive( 'ng2', downgradeComponent({component: Ng2Component})); const element = html('<ng2></ng2>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { const modInjector = upgrade.injector; // Emulate the router lazy loading a module and creating a component const compiler = modInjector.get(Compiler); const modFactory = compiler.compileModuleSync(LazyLoadedModule); const childMod = modFactory.create(modInjector); const cmpFactory = childMod.componentFactoryResolver.resolveComponentFactory(LazyLoadedComponent) !; const lazyCmp = cmpFactory.create(componentInjector); expect(lazyCmp.instance.module.injector).toBe(childMod.injector); }); })); }); });
packages/upgrade/test/static/integration/downgrade_component_spec.ts
1
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.0200249832123518, 0.0007917266339063644, 0.00016493487055413425, 0.00017605489119887352, 0.0026614232920110226 ]
{ "id": 1, "code_window": [ "import {BrowserModule} from '@angular/platform-browser';\n", "import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';\n", "import * as angular from '@angular/upgrade/src/common/angular1';\n", "import {UpgradeAdapter, UpgradeAdapterRef} from '@angular/upgrade/src/dynamic/upgrade_adapter';\n", "\n", "import {$apply, $digest, html, multiTrim, withEachNg1Version} from './test_helpers';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER} from '@angular/upgrade/src/common/constants';\n" ], "file_path": "packages/upgrade/test/dynamic/upgrade_spec.ts", "type": "add", "edit_start_line_idx": 13 }
// #docregion import { Component } from '@angular/core'; @Component({ selector: 'app-hero-list', template: ` <h2>Heroes from JSON File</h2> <div *ngFor="let hero of ('assets/heroes.json' | fetch) "> {{hero.name}} </div> <p>Heroes as JSON: {{'assets/heroes.json' | fetch | json}} </p>` }) export class HeroListComponent { }
aio/content/examples/pipes/src/app/hero-list.component.ts
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.0001723357563605532, 0.00017227858188562095, 0.00017222142196260393, 0.00017227858188562095, 5.716719897463918e-8 ]
{ "id": 1, "code_window": [ "import {BrowserModule} from '@angular/platform-browser';\n", "import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';\n", "import * as angular from '@angular/upgrade/src/common/angular1';\n", "import {UpgradeAdapter, UpgradeAdapterRef} from '@angular/upgrade/src/dynamic/upgrade_adapter';\n", "\n", "import {$apply, $digest, html, multiTrim, withEachNg1Version} from './test_helpers';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER} from '@angular/upgrade/src/common/constants';\n" ], "file_path": "packages/upgrade/test/dynamic/upgrade_spec.ts", "type": "add", "edit_start_line_idx": 13 }
module.exports = function() { return {name: 'publicApi'}; };
aio/tools/transforms/angular-api-package/tag-defs/publicApi.js
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.00016929399862419814, 0.00016929399862419814, 0.00016929399862419814, 0.00016929399862419814, 0 ]
{ "id": 1, "code_window": [ "import {BrowserModule} from '@angular/platform-browser';\n", "import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';\n", "import * as angular from '@angular/upgrade/src/common/angular1';\n", "import {UpgradeAdapter, UpgradeAdapterRef} from '@angular/upgrade/src/dynamic/upgrade_adapter';\n", "\n", "import {$apply, $digest, html, multiTrim, withEachNg1Version} from './test_helpers';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER} from '@angular/upgrade/src/common/constants';\n" ], "file_path": "packages/upgrade/test/dynamic/upgrade_spec.ts", "type": "add", "edit_start_line_idx": 13 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ];
packages/common/locales/extra/en-DG.ts
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.00017297286831308156, 0.0001722297165542841, 0.00017103513528127223, 0.00017268117517232895, 8.53056064897828e-7 ]
{ "id": 6, "code_window": [ "import {async, fakeAsync, tick} from '@angular/core/testing';\n", "import {BrowserModule} from '@angular/platform-browser';\n", "import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';\n", "import {UpgradeComponent, UpgradeModule, downgradeComponent} from '@angular/upgrade/static';\n", "import * as angular from '@angular/upgrade/static/src/common/angular1';\n", "import {$SCOPE} from '@angular/upgrade/static/src/common/constants';\n", "\n", "import {$digest, bootstrap, html, multiTrim, withEachNg1Version} from '../test_helpers';\n", "\n", "withEachNg1Version(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER, $SCOPE} from '@angular/upgrade/static/src/common/constants';\n" ], "file_path": "packages/upgrade/test/static/integration/upgrade_component_spec.ts", "type": "replace", "edit_start_line_idx": 14 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {NgZone, PlatformRef, Type} from '@angular/core'; import {UpgradeModule} from '@angular/upgrade/static'; import * as angular from '@angular/upgrade/static/src/common/angular1'; import {$ROOT_SCOPE} from '@angular/upgrade/static/src/common/constants'; import {createWithEachNg1VersionFn} from '../common/test_helpers'; export * from '../common/test_helpers'; export function bootstrap( platform: PlatformRef, Ng2Module: Type<{}>, element: Element, ng1Module: angular.IModule) { // We bootstrap the Angular module first; then when it is ready (async) we bootstrap the AngularJS // module on the bootstrap element (also ensuring that AngularJS errors will fail the test). return platform.bootstrapModule(Ng2Module).then(ref => { const ngZone = ref.injector.get<NgZone>(NgZone); const upgrade = ref.injector.get(UpgradeModule); const failHardModule: any = ($provide: angular.IProvideService) => { $provide.value('$exceptionHandler', (err: any) => { throw err; }); }; // The `bootstrap()` helper is used for convenience in tests, so that we don't have to inject // and call `upgrade.bootstrap()` on every Angular module. // In order to closer emulate what happens in real application, ensure AngularJS is bootstrapped // inside the Angular zone. // ngZone.run(() => upgrade.bootstrap(element, [failHardModule, ng1Module.name])); return upgrade; }); } export const withEachNg1Version = createWithEachNg1VersionFn(angular.setAngularJSGlobal); export function $apply(adapter: UpgradeModule, exp: angular.Ng1Expression) { const $rootScope = adapter.$injector.get($ROOT_SCOPE) as angular.IRootScopeService; $rootScope.$apply(exp); } export function $digest(adapter: UpgradeModule) { const $rootScope = adapter.$injector.get($ROOT_SCOPE) as angular.IRootScopeService; $rootScope.$digest(); }
packages/upgrade/test/static/test_helpers.ts
1
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.0061657242476940155, 0.0025991718284785748, 0.00016810398665256798, 0.0018698927015066147, 0.002288324059918523 ]
{ "id": 6, "code_window": [ "import {async, fakeAsync, tick} from '@angular/core/testing';\n", "import {BrowserModule} from '@angular/platform-browser';\n", "import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';\n", "import {UpgradeComponent, UpgradeModule, downgradeComponent} from '@angular/upgrade/static';\n", "import * as angular from '@angular/upgrade/static/src/common/angular1';\n", "import {$SCOPE} from '@angular/upgrade/static/src/common/constants';\n", "\n", "import {$digest, bootstrap, html, multiTrim, withEachNg1Version} from '../test_helpers';\n", "\n", "withEachNg1Version(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER, $SCOPE} from '@angular/upgrade/static/src/common/constants';\n" ], "file_path": "packages/upgrade/test/static/integration/upgrade_component_spec.ts", "type": "replace", "edit_start_line_idx": 14 }
import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http'; // #docregion excerpt import { finalize, tap } from 'rxjs/operators'; import { MessageService } from '../message.service'; @Injectable() export class LoggingInterceptor implements HttpInterceptor { constructor(private messenger: MessageService) {} intercept(req: HttpRequest<any>, next: HttpHandler) { const started = Date.now(); let ok: string; // extend server response observable with logging return next.handle(req) .pipe( tap( // Succeeds when there is a response; ignore other events event => ok = event instanceof HttpResponse ? 'succeeded' : '', // Operation failed; error is an HttpErrorResponse error => ok = 'failed' ), // Log when response observable either completes or errors finalize(() => { const elapsed = Date.now() - started; const msg = `${req.method} "${req.urlWithParams}" ${ok} in ${elapsed} ms.`; this.messenger.add(msg); }) ); } } // #enddocregion excerpt
aio/content/examples/http/src/app/http-interceptors/logging-interceptor.ts
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.00017339295300189406, 0.0001707629708107561, 0.00016758113633841276, 0.00017103890422731638, 0.0000022822293885838008 ]
{ "id": 6, "code_window": [ "import {async, fakeAsync, tick} from '@angular/core/testing';\n", "import {BrowserModule} from '@angular/platform-browser';\n", "import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';\n", "import {UpgradeComponent, UpgradeModule, downgradeComponent} from '@angular/upgrade/static';\n", "import * as angular from '@angular/upgrade/static/src/common/angular1';\n", "import {$SCOPE} from '@angular/upgrade/static/src/common/constants';\n", "\n", "import {$digest, bootstrap, html, multiTrim, withEachNg1Version} from '../test_helpers';\n", "\n", "withEachNg1Version(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER, $SCOPE} from '@angular/upgrade/static/src/common/constants';\n" ], "file_path": "packages/upgrade/test/static/integration/upgrade_component_spec.ts", "type": "replace", "edit_start_line_idx": 14 }
import { browser, element, by } from 'protractor'; describe('Hello world E2E Tests', function () { it('should display: Hello world!', function () { browser.get(''); expect(element(by.css('div')).getText()).toEqual('Hello world!'); }); });
integration/hello_world__systemjs_umd/e2e/app.e2e-spec.ts
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.0001743295870255679, 0.0001743295870255679, 0.0001743295870255679, 0.0001743295870255679, 0 ]
{ "id": 6, "code_window": [ "import {async, fakeAsync, tick} from '@angular/core/testing';\n", "import {BrowserModule} from '@angular/platform-browser';\n", "import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';\n", "import {UpgradeComponent, UpgradeModule, downgradeComponent} from '@angular/upgrade/static';\n", "import * as angular from '@angular/upgrade/static/src/common/angular1';\n", "import {$SCOPE} from '@angular/upgrade/static/src/common/constants';\n", "\n", "import {$digest, bootstrap, html, multiTrim, withEachNg1Version} from '../test_helpers';\n", "\n", "withEachNg1Version(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER, $SCOPE} from '@angular/upgrade/static/src/common/constants';\n" ], "file_path": "packages/upgrade/test/static/integration/upgrade_component_spec.ts", "type": "replace", "edit_start_line_idx": 14 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {FormErrorExamples as Examples} from './error_examples'; export class TemplateDrivenErrors { static modelParentException(): void { throw new Error(` ngModel cannot be used to register form controls with a parent formGroup directive. Try using formGroup's partner directive "formControlName" instead. Example: ${Examples.formControlName} Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions: Example: ${Examples.ngModelWithFormGroup}`); } static formGroupNameException(): void { throw new Error(` ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive. Option 1: Use formControlName instead of ngModel (reactive strategy): ${Examples.formGroupName} Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy): ${Examples.ngModelGroup}`); } static missingNameException() { throw new Error( `If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions. Example 1: <input [(ngModel)]="person.firstName" name="first"> Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">`); } static modelGroupParentException() { throw new Error(` ngModelGroup cannot be used with a parent formGroup directive. Option 1: Use formGroupName instead of ngModelGroup (reactive strategy): ${Examples.formGroupName} Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy): ${Examples.ngModelGroup}`); } static ngFormWarning() { console.warn(` It looks like you're using 'ngForm'. Support for using the 'ngForm' element selector has been deprecated in Angular v6 and will be removed in Angular v9. Use 'ng-form' instead. Before: <ngForm #myForm="ngForm"> After: <ng-form #myForm="ngForm"> `); } }
packages/forms/src/directives/template_driven_errors.ts
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.00017616685363464057, 0.0001740350853651762, 0.00017194544489029795, 0.00017407521954737604, 0.0000014818153886153596 ]
{ "id": 8, "code_window": [ " .component('ng1C', ng1ComponentC)\n", " .directive('ng2A', downgradeComponent({component: Ng2ComponentA}))\n", " .directive('ng2B', downgradeComponent({component: Ng2ComponentB}))\n", " .directive('ng2C', downgradeComponent({component: Ng2ComponentC}))\n", " .value('$exceptionHandler', mockExceptionHandler);\n", "\n", " // Define `Ng2Module`\n", " @NgModule({\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " .value($EXCEPTION_HANDLER, mockExceptionHandler);\n" ], "file_path": "packages/upgrade/test/static/integration/upgrade_component_spec.ts", "type": "replace", "edit_start_line_idx": 1788 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ChangeDetectionStrategy, ChangeDetectorRef, Compiler, Component, ComponentFactoryResolver, Directive, ElementRef, EventEmitter, Injector, Input, NgModule, NgModuleRef, OnChanges, OnDestroy, Output, SimpleChanges, destroyPlatform} from '@angular/core'; import {async, fakeAsync, tick} from '@angular/core/testing'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {UpgradeComponent, UpgradeModule, downgradeComponent} from '@angular/upgrade/static'; import * as angular from '@angular/upgrade/static/src/common/angular1'; import {$apply, bootstrap, html, multiTrim, withEachNg1Version} from '../test_helpers'; withEachNg1Version(() => { describe('downgrade ng2 component', () => { beforeEach(() => destroyPlatform()); afterEach(() => destroyPlatform()); it('should bind properties, events', async(() => { const ng1Module = angular.module('ng1', []).value('$exceptionHandler', (err: any) => { throw err; }).run(($rootScope: angular.IScope) => { $rootScope['name'] = 'world'; $rootScope['dataA'] = 'A'; $rootScope['dataB'] = 'B'; $rootScope['modelA'] = 'initModelA'; $rootScope['modelB'] = 'initModelB'; $rootScope['eventA'] = '?'; $rootScope['eventB'] = '?'; }); @Component({ selector: 'ng2', inputs: ['literal', 'interpolate', 'oneWayA', 'oneWayB', 'twoWayA', 'twoWayB'], outputs: [ 'eventA', 'eventB', 'twoWayAEmitter: twoWayAChange', 'twoWayBEmitter: twoWayBChange' ], template: 'ignore: {{ignore}}; ' + 'literal: {{literal}}; interpolate: {{interpolate}}; ' + 'oneWayA: {{oneWayA}}; oneWayB: {{oneWayB}}; ' + 'twoWayA: {{twoWayA}}; twoWayB: {{twoWayB}}; ({{ngOnChangesCount}})' }) class Ng2Component implements OnChanges { ngOnChangesCount = 0; ignore = '-'; literal = '?'; interpolate = '?'; oneWayA = '?'; oneWayB = '?'; twoWayA = '?'; twoWayB = '?'; eventA = new EventEmitter(); eventB = new EventEmitter(); twoWayAEmitter = new EventEmitter(); twoWayBEmitter = new EventEmitter(); ngOnChanges(changes: SimpleChanges) { const assert = (prop: string, value: any) => { const propVal = (this as any)[prop]; if (propVal != value) { throw new Error(`Expected: '${prop}' to be '${value}' but was '${propVal}'`); } }; const assertChange = (prop: string, value: any) => { assert(prop, value); if (!changes[prop]) { throw new Error(`Changes record for '${prop}' not found.`); } const actualValue = changes[prop].currentValue; if (actualValue != value) { throw new Error( `Expected changes record for'${prop}' to be '${value}' but was '${actualValue}'`); } }; switch (this.ngOnChangesCount++) { case 0: assert('ignore', '-'); assertChange('literal', 'Text'); assertChange('interpolate', 'Hello world'); assertChange('oneWayA', 'A'); assertChange('oneWayB', 'B'); assertChange('twoWayA', 'initModelA'); assertChange('twoWayB', 'initModelB'); this.twoWayAEmitter.emit('newA'); this.twoWayBEmitter.emit('newB'); this.eventA.emit('aFired'); this.eventB.emit('bFired'); break; case 1: assertChange('twoWayA', 'newA'); assertChange('twoWayB', 'newB'); break; case 2: assertChange('interpolate', 'Hello everyone'); break; default: throw new Error('Called too many times! ' + JSON.stringify(changes)); } } } ng1Module.directive('ng2', downgradeComponent({ component: Ng2Component, })); @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const element = html(` <div> <ng2 literal="Text" interpolate="Hello {{name}}" bind-one-way-a="dataA" [one-way-b]="dataB" bindon-two-way-a="modelA" [(two-way-b)]="modelB" on-event-a='eventA=$event' (event-b)="eventB=$event"></ng2> | modelA: {{modelA}}; modelB: {{modelB}}; eventA: {{eventA}}; eventB: {{eventB}}; </div>`); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(document.body.textContent)) .toEqual( 'ignore: -; ' + 'literal: Text; interpolate: Hello world; ' + 'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (2) | ' + 'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;'); $apply(upgrade, 'name = "everyone"'); expect(multiTrim(document.body.textContent)) .toEqual( 'ignore: -; ' + 'literal: Text; interpolate: Hello everyone; ' + 'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (3) | ' + 'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;'); }); })); it('should bind properties to onpush components', async(() => { const ng1Module = angular.module('ng1', []).value('$exceptionHandler', (err: any) => { throw err; }).run(($rootScope: angular.IScope) => { $rootScope['dataB'] = 'B'; }); @Component({ selector: 'ng2', inputs: ['oneWayB'], template: 'oneWayB: {{oneWayB}}', changeDetection: ChangeDetectionStrategy.OnPush }) class Ng2Component { ngOnChangesCount = 0; oneWayB = '?'; } ng1Module.directive('ng2', downgradeComponent({ component: Ng2Component, })); @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const element = html(` <div> <ng2 [one-way-b]="dataB"></ng2> </div>`); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(document.body.textContent)).toEqual('oneWayB: B'); $apply(upgrade, 'dataB= "everyone"'); expect(multiTrim(document.body.textContent)).toEqual('oneWayB: everyone'); }); })); it('should support two-way binding and event listener', async(() => { const listenerSpy = jasmine.createSpy('$rootScope.listener'); const ng1Module = angular.module('ng1', []).run(($rootScope: angular.IScope) => { $rootScope['value'] = 'world'; $rootScope['listener'] = listenerSpy; }); @Component({selector: 'ng2', template: `model: {{model}};`}) class Ng2Component implements OnChanges { ngOnChangesCount = 0; @Input() model = '?'; @Output() modelChange = new EventEmitter(); ngOnChanges(changes: SimpleChanges) { switch (this.ngOnChangesCount++) { case 0: expect(changes.model.currentValue).toBe('world'); this.modelChange.emit('newC'); break; case 1: expect(changes.model.currentValue).toBe('newC'); break; default: throw new Error('Called too many times! ' + JSON.stringify(changes)); } } } ng1Module.directive('ng2', downgradeComponent({component: Ng2Component})); @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const element = html(` <div> <ng2 [(model)]="value" (model-change)="listener($event)"></ng2> | value: {{value}} </div> `); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(element.textContent)).toEqual('model: newC; | value: newC'); expect(listenerSpy).toHaveBeenCalledWith('newC'); }); })); it('should run change-detection on every digest (by default)', async(() => { let ng2Component: Ng2Component; @Component({selector: 'ng2', template: '{{ value1 }} | {{ value2 }}'}) class Ng2Component { @Input() value1 = -1; @Input() value2 = -1; constructor() { ng2Component = this; } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng2Component], entryComponents: [Ng2Component] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive('ng2', downgradeComponent({component: Ng2Component})) .run(($rootScope: angular.IRootScopeService) => { $rootScope.value1 = 0; $rootScope.value2 = 0; }); const element = html('<ng2 [value1]="value1" value2="{{ value2 }}"></ng2>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService; expect(element.textContent).toBe('0 | 0'); // Digest should invoke CD $rootScope.$digest(); $rootScope.$digest(); expect(element.textContent).toBe('0 | 0'); // Internal changes should be detected on digest ng2Component.value1 = 1; ng2Component.value2 = 2; $rootScope.$digest(); expect(element.textContent).toBe('1 | 2'); // Digest should propagate change in prop-bound input $rootScope.$apply('value1 = 3'); expect(element.textContent).toBe('3 | 2'); // Digest should propagate change in attr-bound input ng2Component.value1 = 4; $rootScope.$apply('value2 = 5'); expect(element.textContent).toBe('4 | 5'); // Digest should propagate changes that happened before the digest $rootScope.value1 = 6; expect(element.textContent).toBe('4 | 5'); $rootScope.$digest(); expect(element.textContent).toBe('6 | 5'); }); })); it('should not run change-detection on every digest when opted out', async(() => { let ng2Component: Ng2Component; @Component({selector: 'ng2', template: '{{ value1 }} | {{ value2 }}'}) class Ng2Component { @Input() value1 = -1; @Input() value2 = -1; constructor() { ng2Component = this; } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng2Component], entryComponents: [Ng2Component] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive( 'ng2', downgradeComponent({component: Ng2Component, propagateDigest: false})) .run(($rootScope: angular.IRootScopeService) => { $rootScope.value1 = 0; $rootScope.value2 = 0; }); const element = html('<ng2 [value1]="value1" value2="{{ value2 }}"></ng2>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService; expect(element.textContent).toBe('0 | 0'); // Digest should not invoke CD $rootScope.$digest(); $rootScope.$digest(); expect(element.textContent).toBe('0 | 0'); // Digest should not invoke CD, even if component values have changed (internally) ng2Component.value1 = 1; ng2Component.value2 = 2; $rootScope.$digest(); expect(element.textContent).toBe('0 | 0'); // Digest should invoke CD, if prop-bound input has changed $rootScope.$apply('value1 = 3'); expect(element.textContent).toBe('3 | 2'); // Digest should invoke CD, if attr-bound input has changed ng2Component.value1 = 4; $rootScope.$apply('value2 = 5'); expect(element.textContent).toBe('4 | 5'); // Digest should invoke CD, if input has changed before the digest $rootScope.value1 = 6; $rootScope.$digest(); expect(element.textContent).toBe('6 | 5'); }); })); it('should still run normal Angular change-detection regardless of `propagateDigest`', fakeAsync(() => { let ng2Component: Ng2Component; @Component({selector: 'ng2', template: '{{ value }}'}) class Ng2Component { value = 'foo'; constructor() { setTimeout(() => this.value = 'bar', 1000); } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng2Component], entryComponents: [Ng2Component] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive( 'ng2A', downgradeComponent({component: Ng2Component, propagateDigest: true})) .directive( 'ng2B', downgradeComponent({component: Ng2Component, propagateDigest: false})); const element = html('<ng2-a></ng2-a> | <ng2-b></ng2-b>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { expect(element.textContent).toBe('foo | foo'); tick(1000); expect(element.textContent).toBe('bar | bar'); }); })); it('should initialize inputs in time for `ngOnChanges`', async(() => { @Component({ selector: 'ng2', template: ` ngOnChangesCount: {{ ngOnChangesCount }} | firstChangesCount: {{ firstChangesCount }} | initialValue: {{ initialValue }}` }) class Ng2Component implements OnChanges { ngOnChangesCount = 0; firstChangesCount = 0; // TODO(issue/24571): remove '!'. initialValue !: string; // TODO(issue/24571): remove '!'. @Input() foo !: string; ngOnChanges(changes: SimpleChanges) { this.ngOnChangesCount++; if (this.ngOnChangesCount === 1) { this.initialValue = this.foo; } if (changes['foo'] && changes['foo'].isFirstChange()) { this.firstChangesCount++; } } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng2Component], entryComponents: [Ng2Component] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []).directive( 'ng2', downgradeComponent({component: Ng2Component})); const element = html(` <ng2 [foo]="'foo'"></ng2> <ng2 foo="bar"></ng2> <ng2 [foo]="'baz'" ng-if="true"></ng2> <ng2 foo="qux" ng-if="true"></ng2> `); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { const nodes = element.querySelectorAll('ng2'); const expectedTextWith = (value: string) => `ngOnChangesCount: 1 | firstChangesCount: 1 | initialValue: ${value}`; expect(multiTrim(nodes[0].textContent)).toBe(expectedTextWith('foo')); expect(multiTrim(nodes[1].textContent)).toBe(expectedTextWith('bar')); expect(multiTrim(nodes[2].textContent)).toBe(expectedTextWith('baz')); expect(multiTrim(nodes[3].textContent)).toBe(expectedTextWith('qux')); }); })); it('should bind to ng-model', async(() => { const ng1Module = angular.module('ng1', []).run( ($rootScope: angular.IScope) => { $rootScope['modelA'] = 'A'; }); let ng2Instance: Ng2; @Component({selector: 'ng2', template: '<span>{{_value}}</span>'}) class Ng2 { private _value: any = ''; private _onChangeCallback: (_: any) => void = () => {}; private _onTouchedCallback: () => void = () => {}; constructor() { ng2Instance = this; } writeValue(value: any) { this._value = value; } registerOnChange(fn: any) { this._onChangeCallback = fn; } registerOnTouched(fn: any) { this._onTouchedCallback = fn; } doTouch() { this._onTouchedCallback(); } doChange(newValue: string) { this._value = newValue; this._onChangeCallback(newValue); } } ng1Module.directive('ng2', downgradeComponent({component: Ng2})); const element = html(`<div><ng2 ng-model="modelA"></ng2> | {{modelA}}</div>`); @NgModule( {declarations: [Ng2], entryComponents: [Ng2], imports: [BrowserModule, UpgradeModule]}) class Ng2Module { ngDoBootstrap() {} } platformBrowserDynamic().bootstrapModule(Ng2Module).then((ref) => { const adapter = ref.injector.get(UpgradeModule) as UpgradeModule; adapter.bootstrap(element, [ng1Module.name]); const $rootScope = adapter.$injector.get('$rootScope'); expect(multiTrim(document.body.textContent)).toEqual('A | A'); $rootScope.modelA = 'B'; $rootScope.$apply(); expect(multiTrim(document.body.textContent)).toEqual('B | B'); ng2Instance.doChange('C'); expect($rootScope.modelA).toBe('C'); expect(multiTrim(document.body.textContent)).toEqual('C | C'); const downgradedElement = <Element>document.body.querySelector('ng2'); expect(downgradedElement.classList.contains('ng-touched')).toBe(false); ng2Instance.doTouch(); $rootScope.$apply(); expect(downgradedElement.classList.contains('ng-touched')).toBe(true); }); })); it('should properly run cleanup when ng1 directive is destroyed', async(() => { let destroyed = false; @Component({selector: 'ng2', template: 'test'}) class Ng2Component implements OnDestroy { ngOnDestroy() { destroyed = true; } } @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive( 'ng1', () => { return {template: '<div ng-if="!destroyIt"><ng2></ng2></div>'}; }) .directive('ng2', downgradeComponent({component: Ng2Component})); const element = html('<ng1></ng1>'); platformBrowserDynamic().bootstrapModule(Ng2Module).then((ref) => { const adapter = ref.injector.get(UpgradeModule) as UpgradeModule; adapter.bootstrap(element, [ng1Module.name]); expect(element.textContent).toContain('test'); expect(destroyed).toBe(false); const $rootScope = adapter.$injector.get('$rootScope'); $rootScope.$apply('destroyIt = true'); expect(element.textContent).not.toContain('test'); expect(destroyed).toBe(true); }); })); it('should properly run cleanup with multiple levels of nesting', async(() => { let destroyed = false; @Component({ selector: 'ng2-outer', template: '<div *ngIf="!destroyIt"><ng1></ng1></div>', }) class Ng2OuterComponent { @Input() destroyIt = false; } @Component({selector: 'ng2-inner', template: 'test'}) class Ng2InnerComponent implements OnDestroy { ngOnDestroy() { destroyed = true; } } @Directive({selector: 'ng1'}) class Ng1ComponentFacade extends UpgradeComponent { constructor(elementRef: ElementRef, injector: Injector) { super('ng1', elementRef, injector); } } @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [Ng1ComponentFacade, Ng2InnerComponent, Ng2OuterComponent], entryComponents: [Ng2InnerComponent, Ng2OuterComponent], }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive('ng1', () => ({template: '<ng2-inner></ng2-inner>'})) .directive('ng2Inner', downgradeComponent({component: Ng2InnerComponent})) .directive('ng2Outer', downgradeComponent({component: Ng2OuterComponent})); const element = html('<ng2-outer [destroy-it]="destroyIt"></ng2-outer>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { expect(element.textContent).toBe('test'); expect(destroyed).toBe(false); $apply(upgrade, 'destroyIt = true'); expect(element.textContent).toBe(''); expect(destroyed).toBe(true); }); })); it('should work when compiled outside the dom (by fallback to the root ng2.injector)', async(() => { @Component({selector: 'ng2', template: 'test'}) class Ng2Component { } @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive( 'ng1', [ '$compile', ($compile: angular.ICompileService) => { return { link: function( $scope: angular.IScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes) { // here we compile some HTML that contains a downgraded component // since it is not currently in the DOM it is not able to "require" // an ng2 injector so it should use the `moduleInjector` instead. const compiled = $compile('<ng2></ng2>'); const template = compiled($scope); $element.append !(template); } }; } ]) .directive('ng2', downgradeComponent({component: Ng2Component})); const element = html('<ng1></ng1>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { // the fact that the body contains the correct text means that the // downgraded component was able to access the moduleInjector // (since there is no other injector in this system) expect(multiTrim(document.body.textContent)).toEqual('test'); }); })); it('should allow attribute selectors for downgraded components', async(() => { @Component({selector: '[itWorks]', template: 'It works'}) class WorksComponent { } @NgModule({ declarations: [WorksComponent], entryComponents: [WorksComponent], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []).directive( 'worksComponent', downgradeComponent({component: WorksComponent})); const element = html('<works-component></works-component>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(document.body.textContent)).toBe('It works'); }); })); it('should allow attribute selectors for components in ng2', async(() => { @Component({selector: '[itWorks]', template: 'It works'}) class WorksComponent { } @Component({selector: 'root-component', template: '<span itWorks></span>!'}) class RootComponent { } @NgModule({ declarations: [RootComponent, WorksComponent], entryComponents: [RootComponent], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []).directive( 'rootComponent', downgradeComponent({component: RootComponent})); const element = html('<root-component></root-component>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { expect(multiTrim(document.body.textContent)).toBe('It works!'); }); })); it('should respect hierarchical dependency injection for ng2', async(() => { @Component({selector: 'parent', template: 'parent(<ng-content></ng-content>)'}) class ParentComponent { } @Component({selector: 'child', template: 'child'}) class ChildComponent { constructor(parent: ParentComponent) {} } @NgModule({ declarations: [ParentComponent, ChildComponent], entryComponents: [ParentComponent, ChildComponent], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1', []) .directive('parent', downgradeComponent({component: ParentComponent})) .directive('child', downgradeComponent({component: ChildComponent})); const element = html('<parent><child></child></parent>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { expect(multiTrim(document.body.textContent)).toBe('parent(child)'); }); })); it('should work with ng2 lazy loaded components', async(() => { let componentInjector: Injector; @Component({selector: 'ng2', template: ''}) class Ng2Component { constructor(injector: Injector) { componentInjector = injector; } } @NgModule({ declarations: [Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule], }) class Ng2Module { ngDoBootstrap() {} } @Component({template: ''}) class LazyLoadedComponent { constructor(public module: NgModuleRef<any>) {} } @NgModule({ declarations: [LazyLoadedComponent], entryComponents: [LazyLoadedComponent], }) class LazyLoadedModule { } const ng1Module = angular.module('ng1', []).directive( 'ng2', downgradeComponent({component: Ng2Component})); const element = html('<ng2></ng2>'); bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { const modInjector = upgrade.injector; // Emulate the router lazy loading a module and creating a component const compiler = modInjector.get(Compiler); const modFactory = compiler.compileModuleSync(LazyLoadedModule); const childMod = modFactory.create(modInjector); const cmpFactory = childMod.componentFactoryResolver.resolveComponentFactory(LazyLoadedComponent) !; const lazyCmp = cmpFactory.create(componentInjector); expect(lazyCmp.instance.module.injector).toBe(childMod.injector); }); })); }); });
packages/upgrade/test/static/integration/downgrade_component_spec.ts
1
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.032587144523859024, 0.003008487168699503, 0.00016295240493491292, 0.000631441012956202, 0.005215105134993792 ]
{ "id": 8, "code_window": [ " .component('ng1C', ng1ComponentC)\n", " .directive('ng2A', downgradeComponent({component: Ng2ComponentA}))\n", " .directive('ng2B', downgradeComponent({component: Ng2ComponentB}))\n", " .directive('ng2C', downgradeComponent({component: Ng2ComponentC}))\n", " .value('$exceptionHandler', mockExceptionHandler);\n", "\n", " // Define `Ng2Module`\n", " @NgModule({\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " .value($EXCEPTION_HANDLER, mockExceptionHandler);\n" ], "file_path": "packages/upgrade/test/static/integration/upgrade_component_spec.ts", "type": "replace", "edit_start_line_idx": 1788 }
// #docregion // /*global jasmine, __karma__, window*/ Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing. // Uncomment to get full stacktrace output. Sometimes helpful, usually not. // Error.stackTraceLimit = Infinity; // jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; // builtPaths: root paths for output ("built") files // get from karma.config.js, then prefix with '/src/' (default is 'app/') var builtPaths = (__karma__.config.builtPaths || ['src/']) .map(function(p) { return '/base/'+p;}); __karma__.loaded = function () { }; function isJsFile(path) { return path.slice(-3) == '.js'; } function isSpecFile(path) { return /\.spec\.(.*\.)?js$/.test(path); } // Is a "built" file if is JavaScript file in one of the "built" folders function isBuiltFile(path) { return isJsFile(path) && builtPaths.reduce(function(keep, bp) { return keep || (path.substr(0, bp.length) === bp); }, false); } var allSpecFiles = Object.keys(window.__karma__.files) .filter(isSpecFile) .filter(isBuiltFile); System.config({ baseURL: 'base/src', // Extend usual application package list with testing folder packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } }, // Assume npm: is set in `paths` in systemjs.config // Map the angular testing umd bundles map: { '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js', '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js', '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js', '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js', '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js', '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js', '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js', '@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js', }, }); System.import('systemjs.config.js') .then(importSystemJsExtras) .then(initTestBed) .then(initTesting); /** Optional SystemJS configuration extras. Keep going w/o it */ function importSystemJsExtras(){ return System.import('systemjs.config.extras.js') .catch(function(reason) { console.log( 'Warning: System.import could not load the optional "systemjs.config.extras.js". Did you omit it by accident? Continuing without it.' ); console.log(reason); }); } function initTestBed(){ return Promise.all([ System.import('@angular/core/testing'), System.import('@angular/platform-browser-dynamic/testing') ]) .then(function (providers) { var coreTesting = providers[0]; var browserTesting = providers[1]; coreTesting.TestBed.initTestEnvironment( browserTesting.BrowserDynamicTestingModule, browserTesting.platformBrowserDynamicTesting()); }) } // Import all spec files and start karma function initTesting () { return Promise.all( allSpecFiles.map(function (moduleName) { return System.import(moduleName); }) ) .then(__karma__.start, __karma__.error); }
aio/content/examples/upgrade-phonecat-3-final/karma-test-shim.js
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.00017617727280594409, 0.00017313359421677887, 0.00017004336405079812, 0.0001727860071696341, 0.0000018858173689295654 ]
{ "id": 8, "code_window": [ " .component('ng1C', ng1ComponentC)\n", " .directive('ng2A', downgradeComponent({component: Ng2ComponentA}))\n", " .directive('ng2B', downgradeComponent({component: Ng2ComponentB}))\n", " .directive('ng2C', downgradeComponent({component: Ng2ComponentC}))\n", " .value('$exceptionHandler', mockExceptionHandler);\n", "\n", " // Define `Ng2Module`\n", " @NgModule({\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " .value($EXCEPTION_HANDLER, mockExceptionHandler);\n" ], "file_path": "packages/upgrade/test/static/integration/upgrade_component_spec.ts", "type": "replace", "edit_start_line_idx": 1788 }
module.exports = function() { // var MIXIN_PATTERN = /\S*\+\S*\(.*/; return { name: 'indentForMarkdown', process: function(str, width) { if (str == null || str.length === 0) { return ''; } width = width || 4; var lines = str.split('\n'); var newLines = []; var sp = spaces(width); var spMixin = spaces(width - 2); var isAfterMarkdownTag = true; lines.forEach(function(line) { // indent lines that match mixin pattern by 2 less than specified width if (line.indexOf('{@example') >= 0) { if (isAfterMarkdownTag) { // happens if example follows example if (newLines.length > 0) { newLines.pop(); } else { // weird case - first expression in str is an @example // in this case the :marked appear above the str passed in, // so we need to put 'something' into the markdown tag. newLines.push(sp + '.'); // '.' is a dummy char } } newLines.push(spMixin + line); // after a mixin line we need to reenter markdown. newLines.push(spMixin + ':marked'); isAfterMarkdownTag = true; } else { if ((!isAfterMarkdownTag) || (line.trim().length > 0)) { newLines.push(sp + line); isAfterMarkdownTag = false; } } }); if (isAfterMarkdownTag) { if (newLines.length > 0) { // if last line is a markdown tag remove it. newLines.pop(); } } // force character to be a newLine. if (newLines.length > 0) newLines.push(''); var res = newLines.join('\n'); return res; } }; function spaces(n) { var str = ''; for (var i = 0; i < n; i++) { str += ' '; } return str; } };
aio/tools/transforms/angular-base-package/rendering/indentForMarkdown.js
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.00017077552911359817, 0.00016735818644519895, 0.00016397470608353615, 0.00016674830112606287, 0.0000022365647964761592 ]
{ "id": 8, "code_window": [ " .component('ng1C', ng1ComponentC)\n", " .directive('ng2A', downgradeComponent({component: Ng2ComponentA}))\n", " .directive('ng2B', downgradeComponent({component: Ng2ComponentB}))\n", " .directive('ng2C', downgradeComponent({component: Ng2ComponentC}))\n", " .value('$exceptionHandler', mockExceptionHandler);\n", "\n", " // Define `Ng2Module`\n", " @NgModule({\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " .value($EXCEPTION_HANDLER, mockExceptionHandler);\n" ], "file_path": "packages/upgrade/test/static/integration/upgrade_component_spec.ts", "type": "replace", "edit_start_line_idx": 1788 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // This file intentionally left blank. It is used to load nothing in some cases. // Such as parse5/index is redirected here instead of loading into browser. export let __empty__: any;
packages/empty.ts
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.00017528100579511374, 0.00016991252778097987, 0.00016454403521493077, 0.00016991252778097987, 0.000005368485290091485 ]
{ "id": 12, "code_window": [ " */\n", "\n", "import {NgZone, PlatformRef, Type} from '@angular/core';\n", "import {UpgradeModule} from '@angular/upgrade/static';\n", "import * as angular from '@angular/upgrade/static/src/common/angular1';\n", "import {$ROOT_SCOPE} from '@angular/upgrade/static/src/common/constants';\n", "\n", "import {createWithEachNg1VersionFn} from '../common/test_helpers';\n", "export * from '../common/test_helpers';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER, $ROOT_SCOPE} from '@angular/upgrade/static/src/common/constants';\n" ], "file_path": "packages/upgrade/test/static/test_helpers.ts", "type": "replace", "edit_start_line_idx": 11 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export const $COMPILE = '$compile'; export const $CONTROLLER = '$controller'; export const $DELEGATE = '$delegate'; export const $HTTP_BACKEND = '$httpBackend'; export const $INJECTOR = '$injector'; export const $INTERVAL = '$interval'; export const $PARSE = '$parse'; export const $PROVIDE = '$provide'; export const $ROOT_SCOPE = '$rootScope'; export const $SCOPE = '$scope'; export const $TEMPLATE_CACHE = '$templateCache'; export const $TEMPLATE_REQUEST = '$templateRequest'; export const $$TESTABILITY = '$$testability'; export const COMPILER_KEY = '$$angularCompiler'; export const GROUP_PROJECTABLE_NODES_KEY = '$$angularGroupProjectableNodes'; export const INJECTOR_KEY = '$$angularInjector'; export const LAZY_MODULE_REF = '$$angularLazyModuleRef'; export const NG_ZONE_KEY = '$$angularNgZone'; export const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY; export const REQUIRE_NG_MODEL = '?ngModel'; export const UPGRADE_MODULE_NAME = '$$UpgradeModule';
packages/upgrade/src/common/constants.ts
1
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.0036552397068589926, 0.0010992652969434857, 0.0001683877781033516, 0.00028671688050962985, 0.0014764830702915788 ]
{ "id": 12, "code_window": [ " */\n", "\n", "import {NgZone, PlatformRef, Type} from '@angular/core';\n", "import {UpgradeModule} from '@angular/upgrade/static';\n", "import * as angular from '@angular/upgrade/static/src/common/angular1';\n", "import {$ROOT_SCOPE} from '@angular/upgrade/static/src/common/constants';\n", "\n", "import {createWithEachNg1VersionFn} from '../common/test_helpers';\n", "export * from '../common/test_helpers';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER, $ROOT_SCOPE} from '@angular/upgrade/static/src/common/constants';\n" ], "file_path": "packages/upgrade/test/static/test_helpers.ts", "type": "replace", "edit_start_line_idx": 11 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {IterableChangeRecord, IterableChanges} from '@angular/core/src/change_detection/differs/iterable_differs'; import {KeyValueChangeRecord, KeyValueChanges} from '@angular/core/src/change_detection/differs/keyvalue_differs'; import {looseIdentical, stringify} from '../../src/util'; export function iterableDifferToString<V>(iterableChanges: IterableChanges<V>) { const collection: string[] = []; iterableChanges.forEachItem( (record: IterableChangeRecord<V>) => collection.push(icrAsString(record))); const previous: string[] = []; iterableChanges.forEachPreviousItem( (record: IterableChangeRecord<V>) => previous.push(icrAsString(record))); const additions: string[] = []; iterableChanges.forEachAddedItem( (record: IterableChangeRecord<V>) => additions.push(icrAsString(record))); const moves: string[] = []; iterableChanges.forEachMovedItem( (record: IterableChangeRecord<V>) => moves.push(icrAsString(record))); const removals: string[] = []; iterableChanges.forEachRemovedItem( (record: IterableChangeRecord<V>) => removals.push(icrAsString(record))); const identityChanges: string[] = []; iterableChanges.forEachIdentityChange( (record: IterableChangeRecord<V>) => identityChanges.push(icrAsString(record))); return iterableChangesAsString( {collection, previous, additions, moves, removals, identityChanges}); } function icrAsString<V>(icr: IterableChangeRecord<V>): string { return icr.previousIndex === icr.currentIndex ? stringify(icr.item) : stringify(icr.item) + '[' + stringify(icr.previousIndex) + '->' + stringify(icr.currentIndex) + ']'; } export function iterableChangesAsString( {collection = [] as any, previous = [] as any, additions = [] as any, moves = [] as any, removals = [] as any, identityChanges = [] as any}): string { return 'collection: ' + collection.join(', ') + '\n' + 'previous: ' + previous.join(', ') + '\n' + 'additions: ' + additions.join(', ') + '\n' + 'moves: ' + moves.join(', ') + '\n' + 'removals: ' + removals.join(', ') + '\n' + 'identityChanges: ' + identityChanges.join(', ') + '\n'; } function kvcrAsString(kvcr: KeyValueChangeRecord<string, any>) { return looseIdentical(kvcr.previousValue, kvcr.currentValue) ? stringify(kvcr.key) : (stringify(kvcr.key) + '[' + stringify(kvcr.previousValue) + '->' + stringify(kvcr.currentValue) + ']'); } export function kvChangesAsString(kvChanges: KeyValueChanges<string, any>) { const map: string[] = []; const previous: string[] = []; const changes: string[] = []; const additions: string[] = []; const removals: string[] = []; kvChanges.forEachItem(r => map.push(kvcrAsString(r))); kvChanges.forEachPreviousItem(r => previous.push(kvcrAsString(r))); kvChanges.forEachChangedItem(r => changes.push(kvcrAsString(r))); kvChanges.forEachAddedItem(r => additions.push(kvcrAsString(r))); kvChanges.forEachRemovedItem(r => removals.push(kvcrAsString(r))); return testChangesAsString({map, previous, additions, changes, removals}); } export function testChangesAsString( {map, previous, additions, changes, removals}: {map?: any[], previous?: any[], additions?: any[], changes?: any[], removals?: any[]}): string { if (!map) map = []; if (!previous) previous = []; if (!additions) additions = []; if (!changes) changes = []; if (!removals) removals = []; return 'map: ' + map.join(', ') + '\n' + 'previous: ' + previous.join(', ') + '\n' + 'additions: ' + additions.join(', ') + '\n' + 'changes: ' + changes.join(', ') + '\n' + 'removals: ' + removals.join(', ') + '\n'; }
packages/core/test/change_detection/util.ts
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.00017779496556613594, 0.0001731879310682416, 0.0001668324402999133, 0.00017355398449581116, 0.000003993330210505519 ]
{ "id": 12, "code_window": [ " */\n", "\n", "import {NgZone, PlatformRef, Type} from '@angular/core';\n", "import {UpgradeModule} from '@angular/upgrade/static';\n", "import * as angular from '@angular/upgrade/static/src/common/angular1';\n", "import {$ROOT_SCOPE} from '@angular/upgrade/static/src/common/constants';\n", "\n", "import {createWithEachNg1VersionFn} from '../common/test_helpers';\n", "export * from '../common/test_helpers';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER, $ROOT_SCOPE} from '@angular/upgrade/static/src/common/constants';\n" ], "file_path": "packages/upgrade/test/static/test_helpers.ts", "type": "replace", "edit_start_line_idx": 11 }
# Building Angular with Bazel Note: this doc is for developing Angular, it is _not_ public documentation for building an Angular application with Bazel. The Bazel build tool (http://bazel.build) provides fast, reliable incremental builds. We plan to migrate Angular's build scripts to Bazel. ## Installation In order to ensure that everyone builds Angular in a _consistent_ way, Bazel will be installed through NPM and therefore it's not necessary to install Bazel manually. The binaries for Bazel will be provided by the [`@bazel/bazel`](https://github.com/bazelbuild/rules_nodejs/tree/master/packages) NPM package and its platform-specific dependencies. You can access Bazel with the `yarn bazel` command ## Configuration The `WORKSPACE` file indicates that our root directory is a Bazel project. It contains the version of the Bazel rules we use to execute build steps, from `build_bazel_rules_typescript`. The sources on [GitHub] are published from Google's internal repository (google3). Bazel accepts a lot of options. We check in some options in the `.bazelrc` file. See the [bazelrc doc]. For example, if you don't want Bazel to create several symlinks in your project directory (`bazel-*`) you can add the line `build --symlink_prefix=/` to your `.bazelrc` file. [GitHub]: https://github.com/bazelbuild/rules_typescript [bazelrc doc]: https://bazel.build/versions/master/docs/bazel-user-manual.html#bazelrc ## Building Angular - Build a package: `yarn bazel build packages/core` - Build all packages: `yarn bazel build packages/...` You can use [ibazel] to get a "watch mode" that continuously keeps the outputs up-to-date as you save sources. Note this is new as of May 2017 and not very stable yet. [ibazel]: https://github.com/bazelbuild/bazel-watcher ## Testing Angular - Test package in node: `yarn bazel test packages/core/test:test` - Test package in karma: `yarn bazel test packages/core/test:test_web` - Test all packages: `yarn bazel test packages/...` You can use [ibazel] to get a "watch mode" that continuously keeps the outputs up-to-date as you save sources. ### Various Flags Used For Tests If you're experiencing problems with seemingly unrelated tests failing, it may be because you're not using the proper flags with your Bazel test runs in Angular. See also: [`//.bazelrc`](https://github.com/angular/angular/blob/master/.bazelrc) where `--define=compile=legacy` is defined as default. - `--config=debug`: build and launch in debug mode (see [debugging](#debugging) instructions below) - `--test_arg=--node_options=--inspect=9228`: change the inspector port. - `--define=compile=<option>` Controls if ivy or legacy mode is enabled. This switches which compiler is used (ngc, ngtsc, or a tsc pass-through mode). - `legacy`: (default behavior) compile against View Engine, e.g. `--define=compile=legacy` - `jit`: Compile in ivy JIT mode, e.g. `--define=compile=jit` - `aot`: Compile in ivy AOT move, e.g. `--define=compile=aot` - `--test_tag_filters=<tag>`: filter tests down to tags defined in the `tag` config of your rules in any given `BUILD.bazel`. - `no-ivy-aot`: Useful for excluding build and test targets that are not meant to be executed in Ivy AOT mode (`--define=compile=aot`). - `no-ivy-jit`: Useful for excluding build and test targets that are not meant to be executed in Ivy JIT mode (`--define=compile=jit`). - `ivy-only`: Useful for excluding all Ivy build and tests targets with `--define=compile=legacy`. - `fixme-ivy-aot`: Useful for including/excluding build and test targets that are currently broken in Ivy AOT mode (`--define=compile=aot`). - `fixme-ivy-jit`: Useful for including/excluding build and test targets that are currently broken in Ivy JIT mode (`--define=compile=jit`). ### Debugging a Node Test <a id="debugging"></a> - Open chrome at: [chrome://inspect](chrome://inspect) - Click on `Open dedicated DevTools for Node` to launch a debugger. - Run test: `yarn bazel test packages/core/test:test --config=debug` The process should automatically connect to the debugger. For additional info and testing options, see the [nodejs_test documentation](https://bazelbuild.github.io/rules_nodejs/node/node.html#nodejs_test). ### Debugging a Node Test in VSCode First time setup: - Go to Debug > Add configuration (in the menu bar) to open `launch.json` - Add the following to the `configurations` array: ```json { "name": "Attach (inspect)", "type": "node", "request": "attach", "port": 9229, "address": "localhost", "restart": false, "sourceMaps": true, "localRoot": "${workspaceRoot}", "remoteRoot": null }, { "name": "Attach (no-sm,inspect)", "type": "node", "request": "attach", "port": 9229, "address": "localhost", "restart": false, "sourceMaps": false, "localRoot": "${workspaceRoot}", "remoteRoot": null }, ``` **Setting breakpoints directly in your code files may not work in VSCode**. This is because the files you're actually debugging are built files that exist in a `./private/...` folder. The easiest way to debug a test for now is to add a `debugger` statement in the code and launch the bazel corresponding test (`yarn bazel test <target> --config=debug`). Bazel will wait on a connection. Go to the debug view (by clicking on the sidebar or Apple+Shift+D on Mac) and click on the green play icon next to the configuration name (ie `Attach (inspect)`). ### Debugging a Karma Test - Run test: `yarn bazel run packages/core/test:test_web` - Open chrome at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html) - Open chrome inspector ### Debugging Bazel rules Open `external` directory which contains everything that bazel downloaded while executing the workspace file: ```sh open $(bazel info output_base)/external ``` See subcommands that bazel executes (helpful for debugging): ```sh yarn bazel build //packages/core:package -s ``` To debug nodejs_binary executable paths uncomment `find . -name rollup 1>&2` (~ line 96) in ```sh open $(bazel info output_base)/external/build_bazel_rules_nodejs/internal/node_launcher.sh ``` ## Stamping Bazel supports the ability to include non-hermetic information from the version control system in built artifacts. This is called stamping. You can see an overview at https://www.kchodorow.com/blog/2017/03/27/stamping-your-builds/ In our repo, here is how it's configured: 1) In `tools/bazel_stamp_vars.sh` we run the `git` commands to generate our versioning info. 1) In `.bazelrc` we register this script as the value for the `workspace_status_command` flag. Bazel will run the script when it needs to stamp a binary. Note that Bazel has a `--stamp` argument to `yarn bazel build`, but this has no effect since our stamping takes place in Skylark rules. See https://github.com/bazelbuild/bazel/issues/1054 ## Remote cache Bazel supports fetching action results from a cache, allowing a clean build to pick up artifacts from prior builds. This makes builds incremental, even on CI. It works because Bazel assigns a content-based hash to all action inputs, which is used as the cache key for the action outputs. Thanks to the hermeticity property, we can skip executing an action if the inputs hash is already present in the cache. Of course, non-hermeticity in an action can cause problems. At worst, you can fetch a broken artifact from the cache, making your build non-reproducible. For this reason, we are careful to implement our Bazel rules to depend only on their inputs. Currently we only use remote caching on CircleCI. We could enable it for developer builds as well, which would make initial builds much faster for developers by fetching already-built artifacts from the cache. This feature is experimental, and developed by the CircleCI team with guidance from Angular. Contact Alex Eagle with questions. *How it's configured*: 1. In `.circleci/config.yml`, each CircleCI job downloads a proxy binary, which is built from https://github.com/notnoopci/bazel-remote-proxy. The download is done by running `.circleci/setup_cache.sh`. When the feature graduates from experimental, this proxy will be installed by default on every CircleCI worker, and this step will not be needed. 1. Next, each job runs the `setup-bazel-remote-cache` anchor. This starts up the proxy running in the background. In the CircleCI UI, you'll see this step continues running while later steps run, and you can see logging from the proxy process. 1. Bazel must be configured to connect to the proxy on a local port. This configuration lives in `.circleci/bazel.rc` and is enabled because we overwrite the system Bazel settings in /etc/bazel.bazelrc with this file. 1. Each `bazel` command in `.circleci/config.yml` picks up and uses the caching flags. ## Known issues ### Webstorm The autocompletion in WebStorm can be added via a Bazel plugin intended for IntelliJ IDEA, but the plugin needs to be installed in a special way. See [bazelbuild/intellij#246](https://github.com/bazelbuild/intellij/issues/246) for more info. ### Xcode If you see the following error: ``` $ yarn bazel build packages/... ERROR: /private/var/tmp/[...]/external/local_config_cc/BUILD:50:5: in apple_cc_toolchain rule @local_config_cc//:cc-compiler-darwin_x86_64: Xcode version must be specified to use an Apple CROSSTOOL ERROR: Analysis of target '//packages/core/test/render3:render3' failed; build aborted: Analysis of target '@local_config_cc//:cc-compiler-darwin_x86_64' failed; build aborted ``` It might be linked to an interaction with VSCode. If closing VSCode fixes the issue, you can add the following line to your VSCode configuration: ``` "files.exclude": {"bazel-*": true} ``` source: https://github.com/bazelbuild/bazel/issues/4603 If VSCode is not the root cause, you might try: - Quit VSCode (make sure no VSCode is running). ``` bazel clean --expunge sudo xcode-select -s /Applications/Xcode.app/Contents/Developer sudo xcodebuild -license yarn bazel build //packages/core # Run a build outside VSCode to pre-build the xcode; then safe to run VSCode ``` Source: https://stackoverflow.com/questions/45276830/xcode-version-must-be-specified-to-use-an-apple-crosstool
docs/BAZEL.md
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.00017313785792794079, 0.00016885882359929383, 0.00016234104987233877, 0.00016953566228039563, 0.0000034785525713232346 ]
{ "id": 12, "code_window": [ " */\n", "\n", "import {NgZone, PlatformRef, Type} from '@angular/core';\n", "import {UpgradeModule} from '@angular/upgrade/static';\n", "import * as angular from '@angular/upgrade/static/src/common/angular1';\n", "import {$ROOT_SCOPE} from '@angular/upgrade/static/src/common/constants';\n", "\n", "import {createWithEachNg1VersionFn} from '../common/test_helpers';\n", "export * from '../common/test_helpers';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {$EXCEPTION_HANDLER, $ROOT_SCOPE} from '@angular/upgrade/static/src/common/constants';\n" ], "file_path": "packages/upgrade/test/static/test_helpers.ts", "type": "replace", "edit_start_line_idx": 11 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {describe, expect, it} from '@angular/core/testing/src/testing_internal'; import {URLSearchParams} from '@angular/http/src/url_search_params'; { describe('URLSearchParams', () => { it('should conform to spec', () => { const paramsString = 'q=URLUtils.searchParams&topic=api'; const searchParams = new URLSearchParams(paramsString); // Tests borrowed from example at // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams // Compliant with spec described at https://url.spec.whatwg.org/#urlsearchparams expect(searchParams.has('topic')).toBe(true); expect(searchParams.has('foo')).toBe(false); expect(searchParams.get('topic')).toEqual('api'); expect(searchParams.getAll('topic')).toEqual(['api']); expect(searchParams.get('foo')).toBe(null); searchParams.append('topic', 'webdev'); expect(searchParams.getAll('topic')).toEqual(['api', 'webdev']); expect(searchParams.toString()).toEqual('q=URLUtils.searchParams&topic=api&topic=webdev'); searchParams.delete('topic'); expect(searchParams.toString()).toEqual('q=URLUtils.searchParams'); // Test default constructor expect(new URLSearchParams().toString()).toBe(''); }); it('should optionally accept a custom parser', () => { const fooEveryThingParser = { encodeKey() { return 'I AM KEY'; }, encodeValue() { return 'I AM VALUE'; } }; const params = new URLSearchParams('', fooEveryThingParser); params.set('myKey', 'myValue'); expect(params.toString()).toBe('I AM KEY=I AM VALUE'); }); it('should encode special characters in params', () => { const searchParams = new URLSearchParams(); searchParams.append('a', '1+1'); searchParams.append('b c', '2'); searchParams.append('d%', '3$'); expect(searchParams.toString()).toEqual('a=1+1&b%20c=2&d%25=3$'); }); it('should not encode allowed characters', () => { /* * https://tools.ietf.org/html/rfc3986#section-3.4 * Allowed: ( pchar / "/" / "?" ) * pchar: unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved: ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded: "%" HEXDIG HEXDIG * sub-delims: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" * * & and = are excluded and should be encoded inside keys and values * because URLSearchParams is responsible for inserting this. **/ let params = new URLSearchParams(); '! $ \' ( ) * + , ; A 9 - . _ ~ ? / ='.split(' ').forEach( (char, idx) => { params.set(`a${idx}`, char); }); expect(params.toString()) .toBe( `a0=!&a1=$&a2=\'&a3=(&a4=)&a5=*&a6=+&a7=,&a8=;&a9=A&a10=9&a11=-&a12=.&a13=_&a14=~&a15=?&a16=/&a17==` .replace(/\s/g, '')); // Original example from https://github.com/angular/angular/issues/9348 for posterity params = new URLSearchParams(); params.set('q', 'repo:janbaer/howcani+type:issue'); params.set('sort', 'created'); params.set('order', 'desc'); params.set('page', '1'); expect(params.toString()) .toBe('q=repo:janbaer/howcani+type:issue&sort=created&order=desc&page=1'); }); it('should support map-like merging operation via setAll()', () => { const mapA = new URLSearchParams('a=1&a=2&a=3&c=8'); const mapB = new URLSearchParams('a=4&a=5&a=6&b=7'); mapA.setAll(mapB); expect(mapA.has('a')).toBe(true); expect(mapA.has('b')).toBe(true); expect(mapA.has('c')).toBe(true); expect(mapA.getAll('a')).toEqual(['4']); expect(mapA.getAll('b')).toEqual(['7']); expect(mapA.getAll('c')).toEqual(['8']); expect(mapA.toString()).toEqual('a=4&c=8&b=7'); }); it('should support multimap-like merging operation via appendAll()', () => { const mapA = new URLSearchParams('a=1&a=2&a=3&c=8'); const mapB = new URLSearchParams('a=4&a=5&a=6&b=7'); mapA.appendAll(mapB); expect(mapA.has('a')).toBe(true); expect(mapA.has('b')).toBe(true); expect(mapA.has('c')).toBe(true); expect(mapA.getAll('a')).toEqual(['1', '2', '3', '4', '5', '6']); expect(mapA.getAll('b')).toEqual(['7']); expect(mapA.getAll('c')).toEqual(['8']); expect(mapA.toString()).toEqual('a=1&a=2&a=3&a=4&a=5&a=6&c=8&b=7'); }); it('should support multimap-like merging operation via replaceAll()', () => { const mapA = new URLSearchParams('a=1&a=2&a=3&c=8'); const mapB = new URLSearchParams('a=4&a=5&a=6&b=7'); mapA.replaceAll(mapB); expect(mapA.has('a')).toBe(true); expect(mapA.has('b')).toBe(true); expect(mapA.has('c')).toBe(true); expect(mapA.getAll('a')).toEqual(['4', '5', '6']); expect(mapA.getAll('b')).toEqual(['7']); expect(mapA.getAll('c')).toEqual(['8']); expect(mapA.toString()).toEqual('a=4&a=5&a=6&c=8&b=7'); }); it('should support a clone operation via clone()', () => { const fooQueryEncoder = { encodeKey(k: string) { return encodeURIComponent(k); }, encodeValue(v: string) { return encodeURIComponent(v); } }; const paramsA = new URLSearchParams('', fooQueryEncoder); paramsA.set('a', '2'); paramsA.set('q', '4+'); paramsA.set('c', '8'); const paramsB = new URLSearchParams(); paramsB.set('a', '2'); paramsB.set('q', '4+'); paramsB.set('c', '8'); expect(paramsB.toString()).toEqual('a=2&q=4+&c=8'); const paramsC = paramsA.clone(); expect(paramsC.has('a')).toBe(true); expect(paramsC.has('b')).toBe(false); expect(paramsC.has('c')).toBe(true); expect(paramsC.toString()).toEqual('a=2&q=4%2B&c=8'); }); it('should remove the parameter when set to undefined or null', () => { const params = new URLSearchParams('q=Q'); params.set('q', undefined !); expect(params.has('q')).toBe(false); expect(params.toString()).toEqual(''); params.set('q', null !); expect(params.has('q')).toBe(false); expect(params.toString()).toEqual(''); }); it('should ignore the value when append undefined or null', () => { const params = new URLSearchParams('q=Q'); params.append('q', undefined !); expect(params.toString()).toEqual('q=Q'); params.append('q', null !); expect(params.toString()).toEqual('q=Q'); }); }); }
packages/http/test/url_search_params_spec.ts
0
https://github.com/angular/angular/commit/6c5c97b2f92a0ea4f0aab2afc0dc8c958db47487
[ 0.0001787202781997621, 0.00017478580411989242, 0.00016889447579160333, 0.00017528634634800255, 0.0000030840760700812098 ]
{ "id": 0, "code_window": [ "\n", "\t/**\n", "\t * Returns the element's parent in a promise.\n", "\t */\n", "\tgetParent(tree: ITree, element: any): WinJS.Promise;\n", "}\n", "\n", "export interface IRenderer {\n", "\n", "\t/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t/**\n", "\t * Returns whether an element should be expanded when first added to the tree.\n", "\t */\n", "\tshouldAutoexpand?(tree: ITree, element: any): boolean;\n" ], "file_path": "src/vs/base/parts/tree/browser/tree.ts", "type": "add", "edit_start_line_idx": 366 }
/*--------------------------------------------------------------------------------------------- * 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/searchviewlet'; import nls = require('vs/nls'); import { TPromise } from 'vs/base/common/winjs.base'; import { Emitter, debounceEvent } from 'vs/base/common/event'; import { EditorType, ICommonCodeEditor } from 'vs/editor/common/editorCommon'; import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import aria = require('vs/base/browser/ui/aria/aria'); import { IExpression } from 'vs/base/common/glob'; import env = require('vs/base/common/platform'); import { isFunction } from 'vs/base/common/types'; import { Delayer } from 'vs/base/common/async'; import URI from 'vs/base/common/uri'; import strings = require('vs/base/common/strings'); import dom = require('vs/base/browser/dom'); import { IAction, Action } from 'vs/base/common/actions'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import { FindInput } from 'vs/base/browser/ui/findinput/findInput'; import { ITree } from 'vs/base/parts/tree/browser/tree'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { Scope } from 'vs/workbench/common/memento'; import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { getOutOfWorkspaceEditorResources } from 'vs/workbench/common/editor'; import { FileChangeType, FileChangesEvent, IFileService, isEqual } from 'vs/platform/files/common/files'; import { Viewlet } from 'vs/workbench/browser/viewlet'; import { Match, FileMatch, SearchModel, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService } from 'vs/workbench/parts/search/common/searchModel'; import { QueryBuilder } from 'vs/workbench/parts/search/common/searchQuery'; import { MessageType, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { getExcludes, ISearchProgressItem, ISearchComplete, ISearchQuery, IQueryOptions, ISearchConfiguration } from 'vs/platform/search/common/search'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IMessageService } from 'vs/platform/message/common/message'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { KeyCode } from 'vs/base/common/keyCodes'; import { PatternInputWidget } from 'vs/workbench/parts/search/browser/patternInputWidget'; import { SearchRenderer, SearchDataSource, SearchSorter, SearchController, SearchAccessibilityProvider, SearchFilter } from 'vs/workbench/parts/search/browser/searchResultsView'; import { SearchWidget } from 'vs/workbench/parts/search/browser/searchWidget'; import { RefreshAction, CollapseAllAction, ClearSearchResultsAction, ConfigureGlobalExclusionsAction } from 'vs/workbench/parts/search/browser/searchActions'; import { IReplaceService } from 'vs/workbench/parts/search/common/replace'; import Severity from 'vs/base/common/severity'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { OpenFolderAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/fileActions'; import * as Constants from 'vs/workbench/parts/search/common/constants'; import { IListService } from 'vs/platform/list/browser/listService'; import { IThemeService, ITheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { editorFindMatchHighlight } from 'vs/platform/theme/common/colorRegistry'; export class SearchViewlet extends Viewlet { private static MAX_TEXT_RESULTS = 2048; private static SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace'; private isDisposed: boolean; private toDispose: lifecycle.IDisposable[]; private loading: boolean; private queryBuilder: QueryBuilder; private viewModel: SearchModel; private callOnModelChange: lifecycle.IDisposable[]; private viewletVisible: IContextKey<boolean>; private inputBoxFocussed: IContextKey<boolean>; private actionRegistry: { [key: string]: Action; }; private tree: ITree; private viewletSettings: any; private domNode: Builder; private messages: Builder; private searchWidgetsContainer: Builder; private searchWidget: SearchWidget; private size: Dimension; private queryDetails: HTMLElement; private inputPatternExclusions: PatternInputWidget; private inputPatternGlobalExclusions: InputBox; private inputPatternGlobalExclusionsContainer: Builder; private inputPatternIncludes: PatternInputWidget; private results: Builder; private currentSelectedFileMatch: FileMatch; private selectCurrentMatchEmitter: Emitter<string>; private delayedRefresh: Delayer<void>; constructor( @ITelemetryService telemetryService: ITelemetryService, @IFileService private fileService: IFileService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IProgressService private progressService: IProgressService, @IMessageService private messageService: IMessageService, @IStorageService private storageService: IStorageService, @IContextViewService private contextViewService: IContextViewService, @IInstantiationService private instantiationService: IInstantiationService, @IConfigurationService private configurationService: IConfigurationService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService, @IContextKeyService private contextKeyService: IContextKeyService, @IKeybindingService private keybindingService: IKeybindingService, @IReplaceService private replaceService: IReplaceService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IPreferencesService private preferencesService: IPreferencesService, @IListService private listService: IListService, @IThemeService protected themeService: IThemeService ) { super(Constants.VIEWLET_ID, telemetryService, themeService); this.toDispose = []; this.viewletVisible = Constants.SearchViewletVisibleKey.bindTo(contextKeyService); this.inputBoxFocussed = Constants.InputBoxFocussedKey.bindTo(this.contextKeyService); this.callOnModelChange = []; this.queryBuilder = this.instantiationService.createInstance(QueryBuilder); this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE); this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e))); this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); this.selectCurrentMatchEmitter = new Emitter<string>(); debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true) (() => this.selectCurrentMatch()); this.delayedRefresh = new Delayer<void>(250); } private onConfigurationUpdated(configuration: any): void { this.updateGlobalPatternExclusions(configuration); } public create(parent: Builder): TPromise<void> { super.create(parent); this.viewModel = this.searchWorkbenchService.searchModel; let builder: Builder; this.domNode = parent.div({ 'class': 'search-viewlet' }, (div) => { builder = div; }); builder.div({ 'class': ['search-widgets-container'] }, (div) => { this.searchWidgetsContainer = div; }); this.createSearchWidget(this.searchWidgetsContainer); let filePatterns = this.viewletSettings['query.filePatterns'] || ''; let patternExclusions = this.viewletSettings['query.folderExclusions'] || ''; let exclusionsUsePattern = this.viewletSettings['query.exclusionsUsePattern']; let includesUsePattern = this.viewletSettings['query.includesUsePattern']; let patternIncludes = this.viewletSettings['query.folderIncludes'] || ''; let useIgnoreFiles = this.viewletSettings['query.useIgnoreFiles']; this.queryDetails = this.searchWidgetsContainer.div({ 'class': ['query-details'] }, (builder) => { builder.div({ 'class': 'more', 'tabindex': 0, 'role': 'button', 'title': nls.localize('moreSearch', "Toggle Search Details") }) .on(dom.EventType.CLICK, (e) => { dom.EventHelper.stop(e); this.toggleFileTypes(true); }).on(dom.EventType.KEY_UP, (e: KeyboardEvent) => { let event = new StandardKeyboardEvent(e); if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { dom.EventHelper.stop(e); this.toggleFileTypes(); } }); //folder includes list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.includes', "files to include"); builder.element('h4', { text: title }); this.inputPatternIncludes = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.includes', 'Search Include Patterns') }); this.inputPatternIncludes.setIsGlobPattern(includesUsePattern); this.inputPatternIncludes.setValue(patternIncludes); this.inputPatternIncludes .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternIncludes.inputFocusTracker); }); //pattern exclusion list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.excludes', "files to exclude"); builder.element('h4', { text: title }); const configuration = this.configurationService.getConfiguration<ISearchConfiguration>(); this.inputPatternExclusions = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns') }, configuration.search.useRipgrep); this.inputPatternExclusions.setIsGlobPattern(exclusionsUsePattern); this.inputPatternExclusions.setValue(patternExclusions); this.inputPatternExclusions.setUseIgnoreFiles(useIgnoreFiles); this.inputPatternExclusions .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternExclusions.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternExclusions.inputFocusTracker); }); // add hint if we have global exclusion this.inputPatternGlobalExclusionsContainer = builder.div({ 'class': 'file-types global-exclude disabled' }, (builder) => { let title = nls.localize('global.searchScope.folders', "files excluded through settings"); builder.element('h4', { text: title }); this.inputPatternGlobalExclusions = new InputBox(builder.getContainer(), this.contextViewService, { actions: [this.instantiationService.createInstance(ConfigureGlobalExclusionsAction)], ariaLabel: nls.localize('label.global.excludes', 'Configured Search Exclude Patterns') }); this.inputPatternGlobalExclusions.inputElement.readOnly = true; $(this.inputPatternGlobalExclusions.inputElement).attr('aria-readonly', 'true'); $(this.inputPatternGlobalExclusions.inputElement).addClass('disabled'); }).hide(); }).getHTMLElement(); this.messages = builder.div({ 'class': 'messages' }).hide().clone(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.createSearchResultsView(builder); this.actionRegistry = <any>{}; let actions: Action[] = [new CollapseAllAction(this), new RefreshAction(this), new ClearSearchResultsAction(this)]; actions.forEach((action) => { this.actionRegistry[action.id] = action; }); if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '') { this.toggleFileTypes(true, true, true); } this.updateGlobalPatternExclusions(this.configurationService.getConfiguration<ISearchConfiguration>()); this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event))); return TPromise.as(null); } public get searchAndReplaceWidget(): SearchWidget { return this.searchWidget; } private createSearchWidget(builder: Builder): void { let contentPattern = this.viewletSettings['query.contentPattern'] || ''; let isRegex = this.viewletSettings['query.regex'] === true; let isWholeWords = this.viewletSettings['query.wholeWords'] === true; let isCaseSensitive = this.viewletSettings['query.caseSensitive'] === true; this.searchWidget = new SearchWidget(builder, this.contextViewService, { value: contentPattern, isRegex: isRegex, isCaseSensitive: isCaseSensitive, isWholeWords: isWholeWords }, this.contextKeyService, this.keybindingService, this.instantiationService); if (this.storageService.getBoolean(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) { this.searchWidget.toggleReplace(true); } this.toUnbind.push(this.searchWidget); this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh))); this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch())); this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard))); this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled())); this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => { this.viewModel.replaceActive = state; this.tree.refresh(); })); this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => { this.viewModel.replaceString = this.searchWidget.getReplaceValue(); this.delayedRefresh.trigger(() => this.tree.refresh()); })); this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll())); this.trackInputBox(this.searchWidget.searchInputFocusTracker); this.trackInputBox(this.searchWidget.replaceInputFocusTracker); } private trackInputBox(inputFocusTracker: dom.IFocusTracker): void { this.toUnbind.push(inputFocusTracker.addFocusListener(() => { this.inputBoxFocussed.set(true); })); this.toUnbind.push(inputFocusTracker.addBlurListener(() => { this.inputBoxFocussed.set(this.searchWidget.searchInputHasFocus() || this.searchWidget.replaceInputHasFocus() || this.inputPatternIncludes.inputHasFocus() || this.inputPatternExclusions.inputHasFocus()); })); } private onReplaceToggled(): void { this.layout(this.size); this.storageService.store(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, this.searchAndReplaceWidget.isReplaceShown(), StorageScope.WORKSPACE); } private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> { return this.refreshTree(event).then(() => { this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty()); this.updateSearchResultCount(); }); } private refreshTree(event?: IChangeEvent): TPromise<any> { if (!event) { return this.tree.refresh(this.viewModel.searchResult); } if (event.added || event.removed) { return this.tree.refresh(this.viewModel.searchResult).then(() => { if (event.added) { event.elements.forEach(element => { this.autoExpandFileMatch(element, true); }); } }); } else { if (event.elements.length === 1) { return this.tree.refresh(event.elements[0]); } else { return this.tree.refresh(event.elements); } } } private replaceAll(): void { if (this.viewModel.searchResult.count() === 0) { return; } let progressRunner = this.progressService.show(100); let occurrences = this.viewModel.searchResult.count(); let fileCount = this.viewModel.searchResult.fileCount(); let replaceValue = this.searchWidget.getReplaceValue() || ''; let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue); let confirmation = { title: nls.localize('replaceAll.confirmation.title', "Replace All"), message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue), primaryButton: nls.localize('replaceAll.confirm.button', "Replace") }; if (this.messageService.confirm(confirmation)) { this.searchWidget.setReplaceAllActionState(false); this.viewModel.searchResult.replaceAll(progressRunner).then(() => { progressRunner.done(); this.clearMessage() .p({ text: afterReplaceAllMessage }); }, (error) => { progressRunner.done(); errors.isPromiseCanceledError(error); this.messageService.show(Severity.Error, error); }); } } private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount); } private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount); } private clearMessage(): Builder { return this.messages.empty().show() .asContainer().div({ 'class': 'message' }) .asContainer(); } private createSearchResultsView(builder: Builder): void { builder.div({ 'class': 'results' }, (div) => { this.results = div; this.results.addClass('show-file-icons'); let dataSource = new SearchDataSource(); let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this); this.tree = new Tree(div.getHTMLElement(), { dataSource: dataSource, renderer: renderer, sorter: new SearchSorter(), filter: new SearchFilter(), controller: new SearchController(this, this.instantiationService), accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider) }, { ariaLabel: nls.localize('treeAriaLabel', "Search Results"), keyboardSupport: false }); this.tree.setInput(this.viewModel.searchResult); this.toUnbind.push(renderer); this.toUnbind.push(this.listService.register(this.tree)); let focusToSelectionDelayHandle: number; let lastFocusToSelection: number; const focusToSelection = (originalEvent: KeyboardEvent | MouseEvent) => { lastFocusToSelection = Date.now(); const focus = this.tree.getFocus(); let payload: any; if (focus instanceof Match) { payload = { origin: 'keyboard', originalEvent, preserveFocus: true }; } this.tree.setSelection([focus], payload); focusToSelectionDelayHandle = void 0; }; this.toUnbind.push(this.tree.addListener2('focus', (event: any) => { let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; // debounce setting selection so that we are not too quickly opening // when the user is pressing and holding the key to move focus if (focusToSelectionDelayHandle || (Date.now() - lastFocusToSelection <= 75)) { window.clearTimeout(focusToSelectionDelayHandle); focusToSelectionDelayHandle = window.setTimeout(() => focusToSelection(originalEvent), 300); } else { focusToSelection(originalEvent); } } })); this.toUnbind.push(this.tree.addListener2('selection', (event: any) => { let element: any; let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { element = this.tree.getFocus(); } else { element = event.selection[0]; } let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; let doubleClick = (event.payload && event.payload.origin === 'mouse' && originalEvent && originalEvent.detail === 2); if (doubleClick && originalEvent) { originalEvent.preventDefault(); // focus moves to editor, we need to prevent default } let sideBySide = (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey)); let focusEditor = (keyboard && (!event.payload || !event.payload.preserveFocus)) || doubleClick; if (element instanceof Match) { let selectedMatch: Match = element; if (this.currentSelectedFileMatch) { this.currentSelectedFileMatch.setSelectedMatch(null); } this.currentSelectedFileMatch = selectedMatch.parent(); this.currentSelectedFileMatch.setSelectedMatch(selectedMatch); if (!event.payload.preventEditorOpen) { this.onFocus(selectedMatch, !focusEditor, sideBySide, doubleClick); } } })); }); } private updateGlobalPatternExclusions(configuration: ISearchConfiguration): void { if (this.inputPatternGlobalExclusionsContainer) { let excludes = getExcludes(configuration); if (excludes) { let exclusions = Object.getOwnPropertyNames(excludes).filter(exclude => excludes[exclude] === true || typeof excludes[exclude].when === 'string').map(exclude => { if (excludes[exclude] === true) { return exclude; } return nls.localize('globLabel', "{0} when {1}", exclude, excludes[exclude].when); }); if (exclusions.length) { const values = exclusions.join(', '); this.inputPatternGlobalExclusions.value = values; this.inputPatternGlobalExclusions.inputElement.title = values; this.inputPatternGlobalExclusionsContainer.show(); } else { this.inputPatternGlobalExclusionsContainer.hide(); } } } } public selectCurrentMatch(): void { const focused = this.tree.getFocus(); const eventPayload = { focusEditor: true }; this.tree.setSelection([focused], eventPayload); } public selectNextMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); // Expand the initial selected node, if needed if (selected instanceof FileMatch) { if (!this.tree.isExpanded(selected)) { this.tree.expand(selected); } } let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let next = navigator.next(); if (!next) { // Reached the end - get a new navigator from the root. // .first and .last only work when subTreeOnly = true. Maybe there's a simpler way. navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); next = navigator.first(); } // Expand and go past FileMatch nodes if (!(next instanceof Match)) { if (!this.tree.isExpanded(next)) { this.tree.expand(next); } // Select the FileMatch's first child next = navigator.next(); } // Reveal the newly selected element const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(next, eventPayload); this.tree.setSelection([next], eventPayload); this.tree.reveal(next); this.selectCurrentMatchEmitter.fire(); } public selectPreviousMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let prev = navigator.previous(); // Expand and go past FileMatch nodes if (!(prev instanceof Match)) { prev = navigator.previous(); if (!prev) { // Wrap around. Get a new tree starting from the root navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); prev = navigator.last(); // This is complicated because .last will set the navigator to the last FileMatch, // so expand it and FF to its last child this.tree.expand(prev); let tmp; while (tmp = navigator.next()) { prev = tmp; } } if (!(prev instanceof Match)) { // There is a second non-Match result, which must be a collapsed FileMatch. // Expand it then select its last child. navigator.next(); this.tree.expand(prev); prev = navigator.previous(); } } // Reveal the newly selected element if (prev) { const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(prev, eventPayload); this.tree.setSelection([prev], eventPayload); this.tree.reveal(prev); this.selectCurrentMatchEmitter.fire(); } } public setVisible(visible: boolean): TPromise<void> { let promise: TPromise<void>; this.viewletVisible.set(visible); if (visible) { promise = super.setVisible(visible); this.tree.onVisible(); } else { this.tree.onHidden(); promise = super.setVisible(visible); } // Enable highlights if there are searchresults if (this.viewModel) { this.viewModel.searchResult.toggleHighlights(visible); } // Open focused element from results in case the editor area is otherwise empty if (visible && !this.editorService.getActiveEditor()) { let focus = this.tree.getFocus(); if (focus) { this.onFocus(focus, true); } } return promise; } public focus(): void { super.focus(); let selectedText = this.getSearchTextFromEditor(); if (selectedText) { this.searchWidget.searchInput.setValue(selectedText); } this.searchWidget.focus(); } public focusNextInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { if (this.searchWidget.isReplaceShown()) { this.searchWidget.focus(true, true); } else { this.moveFocusFromSearchOrReplace(); } return; } if (this.searchWidget.replaceInputHasFocus()) { this.moveFocusFromSearchOrReplace(); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.selectTreeIfNotSelected(); return; } } private moveFocusFromSearchOrReplace() { if (this.showsFileTypes()) { this.toggleFileTypes(true, this.showsFileTypes()); } else { this.selectTreeIfNotSelected(); } } public focusPreviousInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { return; } if (this.searchWidget.replaceInputHasFocus()) { this.searchWidget.focus(true); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.searchWidget.focus(true, true); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); return; } } public moveFocusFromResults(): void { if (this.showsFileTypes()) { this.toggleFileTypes(true, true, false, true); } else { this.searchWidget.focus(true, true); } } private reLayout(): void { if (this.isDisposed) { return; } this.searchWidget.setWidth(this.size.width - 25 /* container margin */); this.inputPatternExclusions.setWidth(this.size.width - 28 /* container margin */); this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */); this.inputPatternGlobalExclusions.width = this.size.width - 28 /* container margin */ - 24 /* actions */; const messagesSize = this.messages.isHidden() ? 0 : dom.getTotalHeight(this.messages.getHTMLElement()); const searchResultContainerSize = this.size.height - messagesSize - dom.getTotalHeight(this.searchWidgetsContainer.getContainer()); this.results.style({ height: searchResultContainerSize + 'px' }); this.tree.layout(searchResultContainerSize); } public layout(dimension: Dimension): void { this.size = dimension; this.reLayout(); } public getControl(): ITree { return this.tree; } public clearSearchResults(): void { this.viewModel.searchResult.clear(); this.showEmptyStage(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.searchWidget.clear(); this.viewModel.cancelSearch(); } public cancelSearch(): boolean { if (this.viewModel.cancelSearch()) { this.searchWidget.focus(); return true; } return false; } private selectTreeIfNotSelected(): void { if (this.tree.getInput()) { this.tree.DOMFocus(); let selection = this.tree.getSelection(); if (selection.length === 0) { this.tree.focusNext(); } } } private getSearchTextFromEditor(): string { if (!this.editorService.getActiveEditor()) { return null; } let editorControl: any = this.editorService.getActiveEditor().getControl(); if (!editorControl || !isFunction(editorControl.getEditorType) || editorControl.getEditorType() !== EditorType.ICodeEditor) { // Substitute for (editor instanceof ICodeEditor) return null; } let range = editorControl.getSelection(); if (range && !range.isEmpty() && range.startLineNumber === range.endLineNumber) { let searchText = editorControl.getModel().getLineContent(range.startLineNumber); searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1); return searchText; } return null; } private showsFileTypes(): boolean { return dom.hasClass(this.queryDetails, 'more'); } public toggleCaseSensitive(): void { this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive()); this.onQueryChanged(true, true); } public toggleWholeWords(): void { this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords()); this.onQueryChanged(true, true); } public toggleRegex(): void { this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex()); this.onQueryChanged(true, true); } public toggleFileTypes(moveFocus?: boolean, show?: boolean, skipLayout?: boolean, reverse?: boolean): void { let cls = 'more'; show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show); skipLayout = Boolean(skipLayout); if (show) { dom.addClass(this.queryDetails, cls); if (moveFocus) { if (reverse) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); } else { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); } } } else { dom.removeClass(this.queryDetails, cls); if (moveFocus) { this.searchWidget.focus(); } } if (!skipLayout && this.size) { this.layout(this.size); } } public searchInFolder(resource: URI): void { const workspace = this.contextService.getWorkspace(); if (!workspace) { return; } if (isEqual(workspace.resource.fsPath, resource.fsPath)) { this.inputPatternIncludes.setValue(''); this.searchWidget.focus(); return; } if (!this.showsFileTypes()) { this.toggleFileTypes(true, true); } const workspaceRelativePath = this.contextService.toWorkspaceRelativePath(resource); if (workspaceRelativePath) { this.inputPatternIncludes.setIsGlobPattern(false); this.inputPatternIncludes.setValue(workspaceRelativePath); this.searchWidget.focus(false); } } public onQueryChanged(rerunQuery: boolean, preserveFocus?: boolean): void { const isRegex = this.searchWidget.searchInput.getRegex(); const isWholeWords = this.searchWidget.searchInput.getWholeWords(); const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive(); const contentPattern = this.searchWidget.searchInput.getValue(); const patternExcludes = this.inputPatternExclusions.getValue().trim(); const exclusionsUsePattern = this.inputPatternExclusions.isGlobPattern(); const patternIncludes = this.inputPatternIncludes.getValue().trim(); const includesUsePattern = this.inputPatternIncludes.isGlobPattern(); const useIgnoreFiles = this.inputPatternExclusions.useIgnoreFiles(); // store memento this.viewletSettings['query.contentPattern'] = contentPattern; this.viewletSettings['query.regex'] = isRegex; this.viewletSettings['query.wholeWords'] = isWholeWords; this.viewletSettings['query.caseSensitive'] = isCaseSensitive; this.viewletSettings['query.folderExclusions'] = patternExcludes; this.viewletSettings['query.exclusionsUsePattern'] = exclusionsUsePattern; this.viewletSettings['query.folderIncludes'] = patternIncludes; this.viewletSettings['query.includesUsePattern'] = includesUsePattern; this.viewletSettings['query.useIgnoreFiles'] = useIgnoreFiles; if (!rerunQuery) { return; } if (contentPattern.length === 0) { return; } // Validate regex is OK if (isRegex) { let regExp: RegExp; try { regExp = new RegExp(contentPattern); } catch (e) { return; // malformed regex } if (strings.regExpLeadsToEndlessLoop(regExp)) { return; // endless regex } } let content = { pattern: contentPattern, isRegExp: isRegex, isCaseSensitive: isCaseSensitive, isWordMatch: isWholeWords }; let excludes: IExpression = this.inputPatternExclusions.getGlob(); let includes: IExpression = this.inputPatternIncludes.getGlob(); let options: IQueryOptions = { folderResources: this.contextService.hasWorkspace() ? [this.contextService.getWorkspace().resource] : [], extraFileResources: getOutOfWorkspaceEditorResources(this.editorGroupService, this.contextService), excludePattern: excludes, maxResults: SearchViewlet.MAX_TEXT_RESULTS, includePattern: includes, useIgnoreFiles }; this.onQueryTriggered(this.queryBuilder.text(content, options), patternExcludes, patternIncludes); if (!preserveFocus) { this.searchWidget.focus(false); // focus back to input field } } private autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void { let length = fileMatch.matches().length; if (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) { this.tree.expand(fileMatch).done(null, errors.onUnexpectedError); } else { this.tree.collapse(fileMatch).done(null, errors.onUnexpectedError); } } private onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void { this.viewModel.cancelSearch(); // Progress total is 100.0% for more progress bar granularity let progressTotal = 1000; let progressWorked = 0; let progressRunner = query.useRipgrep ? this.progressService.show(/*infinite=*/true) : this.progressService.show(progressTotal); this.loading = true; this.searchWidget.searchInput.clearMessage(); this.showEmptyStage(); let handledMatches: { [id: string]: boolean } = Object.create(null); let autoExpand = (alwaysExpandIfOneResult: boolean) => { // Auto-expand / collapse based on number of matches: // - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file // - expand file results if we have more than one file result and less than 10 matches on a file let matches = this.viewModel.searchResult.matches(); matches.forEach((match) => { if (handledMatches[match.id()]) { return; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile) } handledMatches[match.id()] = true; this.autoExpandFileMatch(match, alwaysExpandIfOneResult); }); }; let isDone = false; let onComplete = (completed?: ISearchComplete) => { isDone = true; // Complete up to 100% as needed if (completed && !query.useRipgrep) { progressRunner.worked(progressTotal - progressWorked); setTimeout(() => progressRunner.done(), 200); } else { progressRunner.done(); } this.onSearchResultsChanged().then(() => autoExpand(true)); this.viewModel.replaceString = this.searchWidget.getReplaceValue(); let hasResults = !this.viewModel.searchResult.isEmpty(); this.loading = false; this.actionRegistry['refresh'].enabled = true; this.actionRegistry['vs.tree.collapse'].enabled = hasResults; this.actionRegistry['clearSearchResults'].enabled = hasResults; if (completed && completed.limitHit) { this.searchWidget.searchInput.showMessage({ content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."), type: MessageType.WARNING }); } if (!hasResults) { let hasExcludes = !!excludePattern; let hasIncludes = !!includePattern; let message: string; if (!completed) { message = nls.localize('searchCanceled', "Search was canceled before any results could be found - "); } else if (hasIncludes && hasExcludes) { message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePattern, excludePattern); } else if (hasIncludes) { message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePattern); } else if (hasExcludes) { message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePattern); } else { message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions - "); } // Indicate as status to ARIA aria.status(message); this.tree.onHidden(); this.results.hide(); const div = this.clearMessage(); const p = $(div).p({ text: message }); if (!completed) { $(p).a({ 'class': ['pointer', 'prominent'], text: nls.localize('rerunSearch.message', "Search again") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.onQueryChanged(true); }); } else if (hasIncludes || hasExcludes) { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('rerunSearchInAll.message', "Search again in all files") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.inputPatternExclusions.setValue(''); this.inputPatternIncludes.setValue(''); this.onQueryChanged(true); }); } else { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openSettings.message', "Open Settings") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); if (this.contextService.hasWorkspace()) { this.preferencesService.openWorkspaceSettings().done(() => null, errors.onUnexpectedError); } else { this.preferencesService.openGlobalSettings().done(() => null, errors.onUnexpectedError); } }); } if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(div); } } else { this.viewModel.searchResult.toggleHighlights(true); // show highlights // Indicate final search result count for ARIA aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount())); } }; let onError = (e: any) => { if (errors.isPromiseCanceledError(e)) { onComplete(null); } else { this.loading = false; isDone = true; progressRunner.done(); this.messageService.show(2 /* ERROR */, e); } }; let total: number = 0; let worked: number = 0; let visibleMatches = 0; let onProgress = (p: ISearchProgressItem) => { // Progress if (p.total) { total = p.total; } if (p.worked) { worked = p.worked; } }; // Handle UI updates in an interval to show frequent progress and results let uiRefreshHandle = setInterval(() => { if (isDone) { window.clearInterval(uiRefreshHandle); return; } if (!query.useRipgrep) { // Progress bar update let fakeProgress = true; if (total > 0 && worked > 0) { let ratio = Math.round((worked / total) * progressTotal); if (ratio > progressWorked) { // never show less progress than what we have already progressRunner.worked(ratio - progressWorked); progressWorked = ratio; fakeProgress = false; } } // Fake progress up to 90%, or when actual progress beats it const fakeMax = 900; const fakeMultiplier = 12; if (fakeProgress && progressWorked < fakeMax) { // Linearly decrease the rate of fake progress. // 1 is the smallest allowed amount of progress. const fakeAmt = Math.round((fakeMax - progressWorked) / fakeMax * fakeMultiplier) || 1; progressWorked += fakeAmt; progressRunner.worked(fakeAmt); } } // Search result tree update const fileCount = this.viewModel.searchResult.fileCount(); if (visibleMatches !== fileCount) { visibleMatches = fileCount; this.tree.refresh().then(() => { autoExpand(false); }).done(null, errors.onUnexpectedError); this.updateSearchResultCount(); } if (fileCount > 0) { // since we have results now, enable some actions if (!this.actionRegistry['vs.tree.collapse'].enabled) { this.actionRegistry['vs.tree.collapse'].enabled = true; } } }, 100); this.searchWidget.setReplaceAllActionState(false); // this.replaceService.disposeAllReplacePreviews(); this.viewModel.search(query).done(onComplete, onError, query.useRipgrep ? undefined : onProgress); } private updateSearchResultCount(): void { const fileCount = this.viewModel.searchResult.fileCount(); const msgWasHidden = this.messages.isHidden(); if (fileCount > 0) { const div = this.clearMessage(); $(div).p({ text: this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount) }); if (msgWasHidden) { this.reLayout(); } } else if (!msgWasHidden) { this.messages.hide(); } } private buildResultCountMessage(resultCount: number, fileCount: number): string { if (resultCount === 1 && fileCount === 1) { return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount); } else if (resultCount === 1) { return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount); } else if (fileCount === 1) { return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount); } else { return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount); } } private searchWithoutFolderMessage(div: Builder): void { $(div).p({ text: nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ") }) .asContainer().a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openFolder', "Open Folder") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); const actionClass = env.isMacintosh ? OpenFileFolderAction : OpenFolderAction; const action = this.instantiationService.createInstance<string, string, IAction>(actionClass, actionClass.ID, actionClass.LABEL); this.actionRunner.run(action).done(() => { action.dispose(); }, err => { action.dispose(); errors.onUnexpectedError(err); }); }); } private showEmptyStage(): void { // disable 'result'-actions this.actionRegistry['refresh'].enabled = false; this.actionRegistry['vs.tree.collapse'].enabled = false; this.actionRegistry['clearSearchResults'].enabled = false; // clean up ui // this.replaceService.disposeAllReplacePreviews(); this.messages.hide(); this.results.show(); this.tree.onVisible(); this.currentSelectedFileMatch = null; } private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { if (!(lineMatch instanceof Match)) { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); return TPromise.as(true); } this.telemetryService.publicLog('searchResultChosen'); return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ? this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) : this.open(lineMatch, preserveFocus, sideBySide, pinned); } public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { let selection = this.getSelectionFrom(element); let resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource(); return this.editorService.openEditor({ resource: resource, options: { preserveFocus, pinned, selection, revealIfVisible: !sideBySide } }, sideBySide).then(editor => { if (editor && element instanceof Match && preserveFocus) { this.viewModel.searchResult.rangeHighlightDecorations.highlightRange({ resource, range: element.range() }, <ICommonCodeEditor>editor.getControl()); } else { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); } }, errors.onUnexpectedError); } private getSelectionFrom(element: FileMatchOrMatch): any { let match: Match = null; if (element instanceof Match) { match = element; } if (element instanceof FileMatch && element.count() > 0) { match = element.matches()[element.matches().length - 1]; } if (match) { let range = match.range(); if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) { let replaceString = match.replaceString; return { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.startLineNumber, endColumn: range.startColumn + replaceString.length }; } return range; } return void 0; } private onUntitledDidChangeDirty(resource: URI): void { if (!this.viewModel) { return; } // remove search results from this resource as it got disposed if (!this.untitledEditorService.isDirty(resource)) { let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (resource.toString() === matches[i].resource().toString()) { this.viewModel.searchResult.remove(matches[i]); } } } } private onFilesChanged(e: FileChangesEvent): void { if (!this.viewModel) { return; } let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (e.contains(matches[i].resource(), FileChangeType.DELETED)) { this.viewModel.searchResult.remove(matches[i]); } } } public getActions(): IAction[] { return [ this.actionRegistry['refresh'], this.actionRegistry['vs.tree.collapse'], this.actionRegistry['clearSearchResults'] ]; } public dispose(): void { this.isDisposed = true; this.toDispose = lifecycle.dispose(this.toDispose); if (this.tree) { this.tree.dispose(); } this.searchWidget.dispose(); this.inputPatternIncludes.dispose(); this.inputPatternExclusions.dispose(); this.viewModel.dispose(); super.dispose(); } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { let matchHighlightColor = theme.getColor(editorFindMatchHighlight); if (matchHighlightColor) { collector.addRule(`.search-viewlet .findInFileMatch { background-color: ${matchHighlightColor}; }`); collector.addRule(`.search-viewlet .highlight { background-color: ${matchHighlightColor}; }`); } });
src/vs/workbench/parts/search/browser/searchViewlet.ts
1
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.9869791269302368, 0.0074246712028980255, 0.00016440085892099887, 0.00017120498523581773, 0.08339153975248337 ]
{ "id": 0, "code_window": [ "\n", "\t/**\n", "\t * Returns the element's parent in a promise.\n", "\t */\n", "\tgetParent(tree: ITree, element: any): WinJS.Promise;\n", "}\n", "\n", "export interface IRenderer {\n", "\n", "\t/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t/**\n", "\t * Returns whether an element should be expanded when first added to the tree.\n", "\t */\n", "\tshouldAutoexpand?(tree: ITree, element: any): boolean;\n" ], "file_path": "src/vs/base/parts/tree/browser/tree.ts", "type": "add", "edit_start_line_idx": 366 }
/*--------------------------------------------------------------------------------------------- * 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. { "activeVersion": "현재 활성", "channelName": "TypeScript", "later": "이상", "learnMore": "자세한 정보", "noBundledServerFound": "잘못 동작하는 바이러스 감지 도구와 같은 다른 응용 프로그램에서 VSCode의 tsserver가 삭제되었습니다. VS Code를 다시 설치하세요.", "noServerFound": "경로 {0}이(가) 올바른 tsserver 설치를 가리키지 않습니다. 포함된 TypeScript 버전을 대신 사용합니다.", "reloadBlurb": "창을 다시 로드하여 변경 내용 적용", "reloadTitle": "다시 로드", "selectTsVersion": "JavaScript 및 TypeScript 언어 기능에 사용되는 TypeScript 버전 선택", "serverCouldNotBeStarted": "TypeScript 언어 서버를 시작할 수 없습니다. 오류 메시지: {0}", "serverDied": "TypeScript 언어 서비스가 지난 5분 동안 예기치 않게 5번 종료되었습니다.", "serverDiedAfterStart": "TypeScript 언어 서비스가 시작된 직후 5번 종료되었습니다. 서비스가 다시 시작되지 않습니다.", "serverDiedReportIssue": "문제 보고", "useVSCodeVersionOption": "VSCode의 버전 사용", "useWorkspaceVersionOption": "작업 영역 버전 사용", "versionNumber.custom": "사용자 지정" }
i18n/kor/extensions/typescript/out/typescriptServiceClient.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0003059789596591145, 0.00021559568995144218, 0.00016769877402111888, 0.00017310932162217796, 0.0000639487843727693 ]
{ "id": 0, "code_window": [ "\n", "\t/**\n", "\t * Returns the element's parent in a promise.\n", "\t */\n", "\tgetParent(tree: ITree, element: any): WinJS.Promise;\n", "}\n", "\n", "export interface IRenderer {\n", "\n", "\t/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t/**\n", "\t * Returns whether an element should be expanded when first added to the tree.\n", "\t */\n", "\tshouldAutoexpand?(tree: ITree, element: any): boolean;\n" ], "file_path": "src/vs/base/parts/tree/browser/tree.ts", "type": "add", "edit_start_line_idx": 366 }
use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line"); println!("You guessed: {}", guess); }
extensions/rust/test/colorize-fixtures/test.rs
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00017789941921364516, 0.0001766397908795625, 0.0001753801479935646, 0.0001766397908795625, 0.0000012596356100402772 ]
{ "id": 0, "code_window": [ "\n", "\t/**\n", "\t * Returns the element's parent in a promise.\n", "\t */\n", "\tgetParent(tree: ITree, element: any): WinJS.Promise;\n", "}\n", "\n", "export interface IRenderer {\n", "\n", "\t/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t/**\n", "\t * Returns whether an element should be expanded when first added to the tree.\n", "\t */\n", "\tshouldAutoexpand?(tree: ITree, element: any): boolean;\n" ], "file_path": "src/vs/base/parts/tree/browser/tree.ts", "type": "add", "edit_start_line_idx": 366 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; export function not<A>(fn: (a: A) => boolean): (a: A) => boolean; export function not(fn: Function): Function { return (...args) => !fn(...args); } export function once<T extends Function>(fn: T): T { const _this = this; let didCall = false; let result: any; return function () { if (didCall) { return result; } didCall = true; result = fn.apply(_this, arguments); return result; } as any as T; }
src/vs/base/common/functional.ts
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0005226194625720382, 0.0002922053390648216, 0.0001686072355369106, 0.0001853893481893465, 0.00016307138139382005 ]
{ "id": 1, "code_window": [ "\n", "\t\tthis.userContent = null;\n", "\t\tthis.traits = {};\n", "\t\tthis.depth = 0;\n", "\t\tthis.expanded = false;\n", "\n", "\t\tthis.emit('item:create', { item: this });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.expanded = this.context.dataSource.shouldAutoexpand && this.context.dataSource.shouldAutoexpand(this.context.tree, element);\n" ], "file_path": "src/vs/base/parts/tree/browser/treeModel.ts", "type": "replace", "edit_start_line_idx": 243 }
/*--------------------------------------------------------------------------------------------- * 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/searchviewlet'; import nls = require('vs/nls'); import { TPromise } from 'vs/base/common/winjs.base'; import { Emitter, debounceEvent } from 'vs/base/common/event'; import { EditorType, ICommonCodeEditor } from 'vs/editor/common/editorCommon'; import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import aria = require('vs/base/browser/ui/aria/aria'); import { IExpression } from 'vs/base/common/glob'; import env = require('vs/base/common/platform'); import { isFunction } from 'vs/base/common/types'; import { Delayer } from 'vs/base/common/async'; import URI from 'vs/base/common/uri'; import strings = require('vs/base/common/strings'); import dom = require('vs/base/browser/dom'); import { IAction, Action } from 'vs/base/common/actions'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import { FindInput } from 'vs/base/browser/ui/findinput/findInput'; import { ITree } from 'vs/base/parts/tree/browser/tree'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { Scope } from 'vs/workbench/common/memento'; import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { getOutOfWorkspaceEditorResources } from 'vs/workbench/common/editor'; import { FileChangeType, FileChangesEvent, IFileService, isEqual } from 'vs/platform/files/common/files'; import { Viewlet } from 'vs/workbench/browser/viewlet'; import { Match, FileMatch, SearchModel, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService } from 'vs/workbench/parts/search/common/searchModel'; import { QueryBuilder } from 'vs/workbench/parts/search/common/searchQuery'; import { MessageType, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { getExcludes, ISearchProgressItem, ISearchComplete, ISearchQuery, IQueryOptions, ISearchConfiguration } from 'vs/platform/search/common/search'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IMessageService } from 'vs/platform/message/common/message'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { KeyCode } from 'vs/base/common/keyCodes'; import { PatternInputWidget } from 'vs/workbench/parts/search/browser/patternInputWidget'; import { SearchRenderer, SearchDataSource, SearchSorter, SearchController, SearchAccessibilityProvider, SearchFilter } from 'vs/workbench/parts/search/browser/searchResultsView'; import { SearchWidget } from 'vs/workbench/parts/search/browser/searchWidget'; import { RefreshAction, CollapseAllAction, ClearSearchResultsAction, ConfigureGlobalExclusionsAction } from 'vs/workbench/parts/search/browser/searchActions'; import { IReplaceService } from 'vs/workbench/parts/search/common/replace'; import Severity from 'vs/base/common/severity'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { OpenFolderAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/fileActions'; import * as Constants from 'vs/workbench/parts/search/common/constants'; import { IListService } from 'vs/platform/list/browser/listService'; import { IThemeService, ITheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { editorFindMatchHighlight } from 'vs/platform/theme/common/colorRegistry'; export class SearchViewlet extends Viewlet { private static MAX_TEXT_RESULTS = 2048; private static SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace'; private isDisposed: boolean; private toDispose: lifecycle.IDisposable[]; private loading: boolean; private queryBuilder: QueryBuilder; private viewModel: SearchModel; private callOnModelChange: lifecycle.IDisposable[]; private viewletVisible: IContextKey<boolean>; private inputBoxFocussed: IContextKey<boolean>; private actionRegistry: { [key: string]: Action; }; private tree: ITree; private viewletSettings: any; private domNode: Builder; private messages: Builder; private searchWidgetsContainer: Builder; private searchWidget: SearchWidget; private size: Dimension; private queryDetails: HTMLElement; private inputPatternExclusions: PatternInputWidget; private inputPatternGlobalExclusions: InputBox; private inputPatternGlobalExclusionsContainer: Builder; private inputPatternIncludes: PatternInputWidget; private results: Builder; private currentSelectedFileMatch: FileMatch; private selectCurrentMatchEmitter: Emitter<string>; private delayedRefresh: Delayer<void>; constructor( @ITelemetryService telemetryService: ITelemetryService, @IFileService private fileService: IFileService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IProgressService private progressService: IProgressService, @IMessageService private messageService: IMessageService, @IStorageService private storageService: IStorageService, @IContextViewService private contextViewService: IContextViewService, @IInstantiationService private instantiationService: IInstantiationService, @IConfigurationService private configurationService: IConfigurationService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService, @IContextKeyService private contextKeyService: IContextKeyService, @IKeybindingService private keybindingService: IKeybindingService, @IReplaceService private replaceService: IReplaceService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IPreferencesService private preferencesService: IPreferencesService, @IListService private listService: IListService, @IThemeService protected themeService: IThemeService ) { super(Constants.VIEWLET_ID, telemetryService, themeService); this.toDispose = []; this.viewletVisible = Constants.SearchViewletVisibleKey.bindTo(contextKeyService); this.inputBoxFocussed = Constants.InputBoxFocussedKey.bindTo(this.contextKeyService); this.callOnModelChange = []; this.queryBuilder = this.instantiationService.createInstance(QueryBuilder); this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE); this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e))); this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); this.selectCurrentMatchEmitter = new Emitter<string>(); debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true) (() => this.selectCurrentMatch()); this.delayedRefresh = new Delayer<void>(250); } private onConfigurationUpdated(configuration: any): void { this.updateGlobalPatternExclusions(configuration); } public create(parent: Builder): TPromise<void> { super.create(parent); this.viewModel = this.searchWorkbenchService.searchModel; let builder: Builder; this.domNode = parent.div({ 'class': 'search-viewlet' }, (div) => { builder = div; }); builder.div({ 'class': ['search-widgets-container'] }, (div) => { this.searchWidgetsContainer = div; }); this.createSearchWidget(this.searchWidgetsContainer); let filePatterns = this.viewletSettings['query.filePatterns'] || ''; let patternExclusions = this.viewletSettings['query.folderExclusions'] || ''; let exclusionsUsePattern = this.viewletSettings['query.exclusionsUsePattern']; let includesUsePattern = this.viewletSettings['query.includesUsePattern']; let patternIncludes = this.viewletSettings['query.folderIncludes'] || ''; let useIgnoreFiles = this.viewletSettings['query.useIgnoreFiles']; this.queryDetails = this.searchWidgetsContainer.div({ 'class': ['query-details'] }, (builder) => { builder.div({ 'class': 'more', 'tabindex': 0, 'role': 'button', 'title': nls.localize('moreSearch', "Toggle Search Details") }) .on(dom.EventType.CLICK, (e) => { dom.EventHelper.stop(e); this.toggleFileTypes(true); }).on(dom.EventType.KEY_UP, (e: KeyboardEvent) => { let event = new StandardKeyboardEvent(e); if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { dom.EventHelper.stop(e); this.toggleFileTypes(); } }); //folder includes list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.includes', "files to include"); builder.element('h4', { text: title }); this.inputPatternIncludes = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.includes', 'Search Include Patterns') }); this.inputPatternIncludes.setIsGlobPattern(includesUsePattern); this.inputPatternIncludes.setValue(patternIncludes); this.inputPatternIncludes .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternIncludes.inputFocusTracker); }); //pattern exclusion list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.excludes', "files to exclude"); builder.element('h4', { text: title }); const configuration = this.configurationService.getConfiguration<ISearchConfiguration>(); this.inputPatternExclusions = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns') }, configuration.search.useRipgrep); this.inputPatternExclusions.setIsGlobPattern(exclusionsUsePattern); this.inputPatternExclusions.setValue(patternExclusions); this.inputPatternExclusions.setUseIgnoreFiles(useIgnoreFiles); this.inputPatternExclusions .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternExclusions.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternExclusions.inputFocusTracker); }); // add hint if we have global exclusion this.inputPatternGlobalExclusionsContainer = builder.div({ 'class': 'file-types global-exclude disabled' }, (builder) => { let title = nls.localize('global.searchScope.folders', "files excluded through settings"); builder.element('h4', { text: title }); this.inputPatternGlobalExclusions = new InputBox(builder.getContainer(), this.contextViewService, { actions: [this.instantiationService.createInstance(ConfigureGlobalExclusionsAction)], ariaLabel: nls.localize('label.global.excludes', 'Configured Search Exclude Patterns') }); this.inputPatternGlobalExclusions.inputElement.readOnly = true; $(this.inputPatternGlobalExclusions.inputElement).attr('aria-readonly', 'true'); $(this.inputPatternGlobalExclusions.inputElement).addClass('disabled'); }).hide(); }).getHTMLElement(); this.messages = builder.div({ 'class': 'messages' }).hide().clone(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.createSearchResultsView(builder); this.actionRegistry = <any>{}; let actions: Action[] = [new CollapseAllAction(this), new RefreshAction(this), new ClearSearchResultsAction(this)]; actions.forEach((action) => { this.actionRegistry[action.id] = action; }); if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '') { this.toggleFileTypes(true, true, true); } this.updateGlobalPatternExclusions(this.configurationService.getConfiguration<ISearchConfiguration>()); this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event))); return TPromise.as(null); } public get searchAndReplaceWidget(): SearchWidget { return this.searchWidget; } private createSearchWidget(builder: Builder): void { let contentPattern = this.viewletSettings['query.contentPattern'] || ''; let isRegex = this.viewletSettings['query.regex'] === true; let isWholeWords = this.viewletSettings['query.wholeWords'] === true; let isCaseSensitive = this.viewletSettings['query.caseSensitive'] === true; this.searchWidget = new SearchWidget(builder, this.contextViewService, { value: contentPattern, isRegex: isRegex, isCaseSensitive: isCaseSensitive, isWholeWords: isWholeWords }, this.contextKeyService, this.keybindingService, this.instantiationService); if (this.storageService.getBoolean(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) { this.searchWidget.toggleReplace(true); } this.toUnbind.push(this.searchWidget); this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh))); this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch())); this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard))); this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled())); this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => { this.viewModel.replaceActive = state; this.tree.refresh(); })); this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => { this.viewModel.replaceString = this.searchWidget.getReplaceValue(); this.delayedRefresh.trigger(() => this.tree.refresh()); })); this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll())); this.trackInputBox(this.searchWidget.searchInputFocusTracker); this.trackInputBox(this.searchWidget.replaceInputFocusTracker); } private trackInputBox(inputFocusTracker: dom.IFocusTracker): void { this.toUnbind.push(inputFocusTracker.addFocusListener(() => { this.inputBoxFocussed.set(true); })); this.toUnbind.push(inputFocusTracker.addBlurListener(() => { this.inputBoxFocussed.set(this.searchWidget.searchInputHasFocus() || this.searchWidget.replaceInputHasFocus() || this.inputPatternIncludes.inputHasFocus() || this.inputPatternExclusions.inputHasFocus()); })); } private onReplaceToggled(): void { this.layout(this.size); this.storageService.store(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, this.searchAndReplaceWidget.isReplaceShown(), StorageScope.WORKSPACE); } private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> { return this.refreshTree(event).then(() => { this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty()); this.updateSearchResultCount(); }); } private refreshTree(event?: IChangeEvent): TPromise<any> { if (!event) { return this.tree.refresh(this.viewModel.searchResult); } if (event.added || event.removed) { return this.tree.refresh(this.viewModel.searchResult).then(() => { if (event.added) { event.elements.forEach(element => { this.autoExpandFileMatch(element, true); }); } }); } else { if (event.elements.length === 1) { return this.tree.refresh(event.elements[0]); } else { return this.tree.refresh(event.elements); } } } private replaceAll(): void { if (this.viewModel.searchResult.count() === 0) { return; } let progressRunner = this.progressService.show(100); let occurrences = this.viewModel.searchResult.count(); let fileCount = this.viewModel.searchResult.fileCount(); let replaceValue = this.searchWidget.getReplaceValue() || ''; let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue); let confirmation = { title: nls.localize('replaceAll.confirmation.title', "Replace All"), message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue), primaryButton: nls.localize('replaceAll.confirm.button', "Replace") }; if (this.messageService.confirm(confirmation)) { this.searchWidget.setReplaceAllActionState(false); this.viewModel.searchResult.replaceAll(progressRunner).then(() => { progressRunner.done(); this.clearMessage() .p({ text: afterReplaceAllMessage }); }, (error) => { progressRunner.done(); errors.isPromiseCanceledError(error); this.messageService.show(Severity.Error, error); }); } } private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount); } private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount); } private clearMessage(): Builder { return this.messages.empty().show() .asContainer().div({ 'class': 'message' }) .asContainer(); } private createSearchResultsView(builder: Builder): void { builder.div({ 'class': 'results' }, (div) => { this.results = div; this.results.addClass('show-file-icons'); let dataSource = new SearchDataSource(); let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this); this.tree = new Tree(div.getHTMLElement(), { dataSource: dataSource, renderer: renderer, sorter: new SearchSorter(), filter: new SearchFilter(), controller: new SearchController(this, this.instantiationService), accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider) }, { ariaLabel: nls.localize('treeAriaLabel', "Search Results"), keyboardSupport: false }); this.tree.setInput(this.viewModel.searchResult); this.toUnbind.push(renderer); this.toUnbind.push(this.listService.register(this.tree)); let focusToSelectionDelayHandle: number; let lastFocusToSelection: number; const focusToSelection = (originalEvent: KeyboardEvent | MouseEvent) => { lastFocusToSelection = Date.now(); const focus = this.tree.getFocus(); let payload: any; if (focus instanceof Match) { payload = { origin: 'keyboard', originalEvent, preserveFocus: true }; } this.tree.setSelection([focus], payload); focusToSelectionDelayHandle = void 0; }; this.toUnbind.push(this.tree.addListener2('focus', (event: any) => { let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; // debounce setting selection so that we are not too quickly opening // when the user is pressing and holding the key to move focus if (focusToSelectionDelayHandle || (Date.now() - lastFocusToSelection <= 75)) { window.clearTimeout(focusToSelectionDelayHandle); focusToSelectionDelayHandle = window.setTimeout(() => focusToSelection(originalEvent), 300); } else { focusToSelection(originalEvent); } } })); this.toUnbind.push(this.tree.addListener2('selection', (event: any) => { let element: any; let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { element = this.tree.getFocus(); } else { element = event.selection[0]; } let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; let doubleClick = (event.payload && event.payload.origin === 'mouse' && originalEvent && originalEvent.detail === 2); if (doubleClick && originalEvent) { originalEvent.preventDefault(); // focus moves to editor, we need to prevent default } let sideBySide = (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey)); let focusEditor = (keyboard && (!event.payload || !event.payload.preserveFocus)) || doubleClick; if (element instanceof Match) { let selectedMatch: Match = element; if (this.currentSelectedFileMatch) { this.currentSelectedFileMatch.setSelectedMatch(null); } this.currentSelectedFileMatch = selectedMatch.parent(); this.currentSelectedFileMatch.setSelectedMatch(selectedMatch); if (!event.payload.preventEditorOpen) { this.onFocus(selectedMatch, !focusEditor, sideBySide, doubleClick); } } })); }); } private updateGlobalPatternExclusions(configuration: ISearchConfiguration): void { if (this.inputPatternGlobalExclusionsContainer) { let excludes = getExcludes(configuration); if (excludes) { let exclusions = Object.getOwnPropertyNames(excludes).filter(exclude => excludes[exclude] === true || typeof excludes[exclude].when === 'string').map(exclude => { if (excludes[exclude] === true) { return exclude; } return nls.localize('globLabel', "{0} when {1}", exclude, excludes[exclude].when); }); if (exclusions.length) { const values = exclusions.join(', '); this.inputPatternGlobalExclusions.value = values; this.inputPatternGlobalExclusions.inputElement.title = values; this.inputPatternGlobalExclusionsContainer.show(); } else { this.inputPatternGlobalExclusionsContainer.hide(); } } } } public selectCurrentMatch(): void { const focused = this.tree.getFocus(); const eventPayload = { focusEditor: true }; this.tree.setSelection([focused], eventPayload); } public selectNextMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); // Expand the initial selected node, if needed if (selected instanceof FileMatch) { if (!this.tree.isExpanded(selected)) { this.tree.expand(selected); } } let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let next = navigator.next(); if (!next) { // Reached the end - get a new navigator from the root. // .first and .last only work when subTreeOnly = true. Maybe there's a simpler way. navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); next = navigator.first(); } // Expand and go past FileMatch nodes if (!(next instanceof Match)) { if (!this.tree.isExpanded(next)) { this.tree.expand(next); } // Select the FileMatch's first child next = navigator.next(); } // Reveal the newly selected element const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(next, eventPayload); this.tree.setSelection([next], eventPayload); this.tree.reveal(next); this.selectCurrentMatchEmitter.fire(); } public selectPreviousMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let prev = navigator.previous(); // Expand and go past FileMatch nodes if (!(prev instanceof Match)) { prev = navigator.previous(); if (!prev) { // Wrap around. Get a new tree starting from the root navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); prev = navigator.last(); // This is complicated because .last will set the navigator to the last FileMatch, // so expand it and FF to its last child this.tree.expand(prev); let tmp; while (tmp = navigator.next()) { prev = tmp; } } if (!(prev instanceof Match)) { // There is a second non-Match result, which must be a collapsed FileMatch. // Expand it then select its last child. navigator.next(); this.tree.expand(prev); prev = navigator.previous(); } } // Reveal the newly selected element if (prev) { const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(prev, eventPayload); this.tree.setSelection([prev], eventPayload); this.tree.reveal(prev); this.selectCurrentMatchEmitter.fire(); } } public setVisible(visible: boolean): TPromise<void> { let promise: TPromise<void>; this.viewletVisible.set(visible); if (visible) { promise = super.setVisible(visible); this.tree.onVisible(); } else { this.tree.onHidden(); promise = super.setVisible(visible); } // Enable highlights if there are searchresults if (this.viewModel) { this.viewModel.searchResult.toggleHighlights(visible); } // Open focused element from results in case the editor area is otherwise empty if (visible && !this.editorService.getActiveEditor()) { let focus = this.tree.getFocus(); if (focus) { this.onFocus(focus, true); } } return promise; } public focus(): void { super.focus(); let selectedText = this.getSearchTextFromEditor(); if (selectedText) { this.searchWidget.searchInput.setValue(selectedText); } this.searchWidget.focus(); } public focusNextInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { if (this.searchWidget.isReplaceShown()) { this.searchWidget.focus(true, true); } else { this.moveFocusFromSearchOrReplace(); } return; } if (this.searchWidget.replaceInputHasFocus()) { this.moveFocusFromSearchOrReplace(); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.selectTreeIfNotSelected(); return; } } private moveFocusFromSearchOrReplace() { if (this.showsFileTypes()) { this.toggleFileTypes(true, this.showsFileTypes()); } else { this.selectTreeIfNotSelected(); } } public focusPreviousInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { return; } if (this.searchWidget.replaceInputHasFocus()) { this.searchWidget.focus(true); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.searchWidget.focus(true, true); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); return; } } public moveFocusFromResults(): void { if (this.showsFileTypes()) { this.toggleFileTypes(true, true, false, true); } else { this.searchWidget.focus(true, true); } } private reLayout(): void { if (this.isDisposed) { return; } this.searchWidget.setWidth(this.size.width - 25 /* container margin */); this.inputPatternExclusions.setWidth(this.size.width - 28 /* container margin */); this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */); this.inputPatternGlobalExclusions.width = this.size.width - 28 /* container margin */ - 24 /* actions */; const messagesSize = this.messages.isHidden() ? 0 : dom.getTotalHeight(this.messages.getHTMLElement()); const searchResultContainerSize = this.size.height - messagesSize - dom.getTotalHeight(this.searchWidgetsContainer.getContainer()); this.results.style({ height: searchResultContainerSize + 'px' }); this.tree.layout(searchResultContainerSize); } public layout(dimension: Dimension): void { this.size = dimension; this.reLayout(); } public getControl(): ITree { return this.tree; } public clearSearchResults(): void { this.viewModel.searchResult.clear(); this.showEmptyStage(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.searchWidget.clear(); this.viewModel.cancelSearch(); } public cancelSearch(): boolean { if (this.viewModel.cancelSearch()) { this.searchWidget.focus(); return true; } return false; } private selectTreeIfNotSelected(): void { if (this.tree.getInput()) { this.tree.DOMFocus(); let selection = this.tree.getSelection(); if (selection.length === 0) { this.tree.focusNext(); } } } private getSearchTextFromEditor(): string { if (!this.editorService.getActiveEditor()) { return null; } let editorControl: any = this.editorService.getActiveEditor().getControl(); if (!editorControl || !isFunction(editorControl.getEditorType) || editorControl.getEditorType() !== EditorType.ICodeEditor) { // Substitute for (editor instanceof ICodeEditor) return null; } let range = editorControl.getSelection(); if (range && !range.isEmpty() && range.startLineNumber === range.endLineNumber) { let searchText = editorControl.getModel().getLineContent(range.startLineNumber); searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1); return searchText; } return null; } private showsFileTypes(): boolean { return dom.hasClass(this.queryDetails, 'more'); } public toggleCaseSensitive(): void { this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive()); this.onQueryChanged(true, true); } public toggleWholeWords(): void { this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords()); this.onQueryChanged(true, true); } public toggleRegex(): void { this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex()); this.onQueryChanged(true, true); } public toggleFileTypes(moveFocus?: boolean, show?: boolean, skipLayout?: boolean, reverse?: boolean): void { let cls = 'more'; show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show); skipLayout = Boolean(skipLayout); if (show) { dom.addClass(this.queryDetails, cls); if (moveFocus) { if (reverse) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); } else { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); } } } else { dom.removeClass(this.queryDetails, cls); if (moveFocus) { this.searchWidget.focus(); } } if (!skipLayout && this.size) { this.layout(this.size); } } public searchInFolder(resource: URI): void { const workspace = this.contextService.getWorkspace(); if (!workspace) { return; } if (isEqual(workspace.resource.fsPath, resource.fsPath)) { this.inputPatternIncludes.setValue(''); this.searchWidget.focus(); return; } if (!this.showsFileTypes()) { this.toggleFileTypes(true, true); } const workspaceRelativePath = this.contextService.toWorkspaceRelativePath(resource); if (workspaceRelativePath) { this.inputPatternIncludes.setIsGlobPattern(false); this.inputPatternIncludes.setValue(workspaceRelativePath); this.searchWidget.focus(false); } } public onQueryChanged(rerunQuery: boolean, preserveFocus?: boolean): void { const isRegex = this.searchWidget.searchInput.getRegex(); const isWholeWords = this.searchWidget.searchInput.getWholeWords(); const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive(); const contentPattern = this.searchWidget.searchInput.getValue(); const patternExcludes = this.inputPatternExclusions.getValue().trim(); const exclusionsUsePattern = this.inputPatternExclusions.isGlobPattern(); const patternIncludes = this.inputPatternIncludes.getValue().trim(); const includesUsePattern = this.inputPatternIncludes.isGlobPattern(); const useIgnoreFiles = this.inputPatternExclusions.useIgnoreFiles(); // store memento this.viewletSettings['query.contentPattern'] = contentPattern; this.viewletSettings['query.regex'] = isRegex; this.viewletSettings['query.wholeWords'] = isWholeWords; this.viewletSettings['query.caseSensitive'] = isCaseSensitive; this.viewletSettings['query.folderExclusions'] = patternExcludes; this.viewletSettings['query.exclusionsUsePattern'] = exclusionsUsePattern; this.viewletSettings['query.folderIncludes'] = patternIncludes; this.viewletSettings['query.includesUsePattern'] = includesUsePattern; this.viewletSettings['query.useIgnoreFiles'] = useIgnoreFiles; if (!rerunQuery) { return; } if (contentPattern.length === 0) { return; } // Validate regex is OK if (isRegex) { let regExp: RegExp; try { regExp = new RegExp(contentPattern); } catch (e) { return; // malformed regex } if (strings.regExpLeadsToEndlessLoop(regExp)) { return; // endless regex } } let content = { pattern: contentPattern, isRegExp: isRegex, isCaseSensitive: isCaseSensitive, isWordMatch: isWholeWords }; let excludes: IExpression = this.inputPatternExclusions.getGlob(); let includes: IExpression = this.inputPatternIncludes.getGlob(); let options: IQueryOptions = { folderResources: this.contextService.hasWorkspace() ? [this.contextService.getWorkspace().resource] : [], extraFileResources: getOutOfWorkspaceEditorResources(this.editorGroupService, this.contextService), excludePattern: excludes, maxResults: SearchViewlet.MAX_TEXT_RESULTS, includePattern: includes, useIgnoreFiles }; this.onQueryTriggered(this.queryBuilder.text(content, options), patternExcludes, patternIncludes); if (!preserveFocus) { this.searchWidget.focus(false); // focus back to input field } } private autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void { let length = fileMatch.matches().length; if (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) { this.tree.expand(fileMatch).done(null, errors.onUnexpectedError); } else { this.tree.collapse(fileMatch).done(null, errors.onUnexpectedError); } } private onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void { this.viewModel.cancelSearch(); // Progress total is 100.0% for more progress bar granularity let progressTotal = 1000; let progressWorked = 0; let progressRunner = query.useRipgrep ? this.progressService.show(/*infinite=*/true) : this.progressService.show(progressTotal); this.loading = true; this.searchWidget.searchInput.clearMessage(); this.showEmptyStage(); let handledMatches: { [id: string]: boolean } = Object.create(null); let autoExpand = (alwaysExpandIfOneResult: boolean) => { // Auto-expand / collapse based on number of matches: // - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file // - expand file results if we have more than one file result and less than 10 matches on a file let matches = this.viewModel.searchResult.matches(); matches.forEach((match) => { if (handledMatches[match.id()]) { return; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile) } handledMatches[match.id()] = true; this.autoExpandFileMatch(match, alwaysExpandIfOneResult); }); }; let isDone = false; let onComplete = (completed?: ISearchComplete) => { isDone = true; // Complete up to 100% as needed if (completed && !query.useRipgrep) { progressRunner.worked(progressTotal - progressWorked); setTimeout(() => progressRunner.done(), 200); } else { progressRunner.done(); } this.onSearchResultsChanged().then(() => autoExpand(true)); this.viewModel.replaceString = this.searchWidget.getReplaceValue(); let hasResults = !this.viewModel.searchResult.isEmpty(); this.loading = false; this.actionRegistry['refresh'].enabled = true; this.actionRegistry['vs.tree.collapse'].enabled = hasResults; this.actionRegistry['clearSearchResults'].enabled = hasResults; if (completed && completed.limitHit) { this.searchWidget.searchInput.showMessage({ content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."), type: MessageType.WARNING }); } if (!hasResults) { let hasExcludes = !!excludePattern; let hasIncludes = !!includePattern; let message: string; if (!completed) { message = nls.localize('searchCanceled', "Search was canceled before any results could be found - "); } else if (hasIncludes && hasExcludes) { message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePattern, excludePattern); } else if (hasIncludes) { message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePattern); } else if (hasExcludes) { message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePattern); } else { message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions - "); } // Indicate as status to ARIA aria.status(message); this.tree.onHidden(); this.results.hide(); const div = this.clearMessage(); const p = $(div).p({ text: message }); if (!completed) { $(p).a({ 'class': ['pointer', 'prominent'], text: nls.localize('rerunSearch.message', "Search again") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.onQueryChanged(true); }); } else if (hasIncludes || hasExcludes) { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('rerunSearchInAll.message', "Search again in all files") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.inputPatternExclusions.setValue(''); this.inputPatternIncludes.setValue(''); this.onQueryChanged(true); }); } else { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openSettings.message', "Open Settings") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); if (this.contextService.hasWorkspace()) { this.preferencesService.openWorkspaceSettings().done(() => null, errors.onUnexpectedError); } else { this.preferencesService.openGlobalSettings().done(() => null, errors.onUnexpectedError); } }); } if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(div); } } else { this.viewModel.searchResult.toggleHighlights(true); // show highlights // Indicate final search result count for ARIA aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount())); } }; let onError = (e: any) => { if (errors.isPromiseCanceledError(e)) { onComplete(null); } else { this.loading = false; isDone = true; progressRunner.done(); this.messageService.show(2 /* ERROR */, e); } }; let total: number = 0; let worked: number = 0; let visibleMatches = 0; let onProgress = (p: ISearchProgressItem) => { // Progress if (p.total) { total = p.total; } if (p.worked) { worked = p.worked; } }; // Handle UI updates in an interval to show frequent progress and results let uiRefreshHandle = setInterval(() => { if (isDone) { window.clearInterval(uiRefreshHandle); return; } if (!query.useRipgrep) { // Progress bar update let fakeProgress = true; if (total > 0 && worked > 0) { let ratio = Math.round((worked / total) * progressTotal); if (ratio > progressWorked) { // never show less progress than what we have already progressRunner.worked(ratio - progressWorked); progressWorked = ratio; fakeProgress = false; } } // Fake progress up to 90%, or when actual progress beats it const fakeMax = 900; const fakeMultiplier = 12; if (fakeProgress && progressWorked < fakeMax) { // Linearly decrease the rate of fake progress. // 1 is the smallest allowed amount of progress. const fakeAmt = Math.round((fakeMax - progressWorked) / fakeMax * fakeMultiplier) || 1; progressWorked += fakeAmt; progressRunner.worked(fakeAmt); } } // Search result tree update const fileCount = this.viewModel.searchResult.fileCount(); if (visibleMatches !== fileCount) { visibleMatches = fileCount; this.tree.refresh().then(() => { autoExpand(false); }).done(null, errors.onUnexpectedError); this.updateSearchResultCount(); } if (fileCount > 0) { // since we have results now, enable some actions if (!this.actionRegistry['vs.tree.collapse'].enabled) { this.actionRegistry['vs.tree.collapse'].enabled = true; } } }, 100); this.searchWidget.setReplaceAllActionState(false); // this.replaceService.disposeAllReplacePreviews(); this.viewModel.search(query).done(onComplete, onError, query.useRipgrep ? undefined : onProgress); } private updateSearchResultCount(): void { const fileCount = this.viewModel.searchResult.fileCount(); const msgWasHidden = this.messages.isHidden(); if (fileCount > 0) { const div = this.clearMessage(); $(div).p({ text: this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount) }); if (msgWasHidden) { this.reLayout(); } } else if (!msgWasHidden) { this.messages.hide(); } } private buildResultCountMessage(resultCount: number, fileCount: number): string { if (resultCount === 1 && fileCount === 1) { return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount); } else if (resultCount === 1) { return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount); } else if (fileCount === 1) { return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount); } else { return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount); } } private searchWithoutFolderMessage(div: Builder): void { $(div).p({ text: nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ") }) .asContainer().a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openFolder', "Open Folder") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); const actionClass = env.isMacintosh ? OpenFileFolderAction : OpenFolderAction; const action = this.instantiationService.createInstance<string, string, IAction>(actionClass, actionClass.ID, actionClass.LABEL); this.actionRunner.run(action).done(() => { action.dispose(); }, err => { action.dispose(); errors.onUnexpectedError(err); }); }); } private showEmptyStage(): void { // disable 'result'-actions this.actionRegistry['refresh'].enabled = false; this.actionRegistry['vs.tree.collapse'].enabled = false; this.actionRegistry['clearSearchResults'].enabled = false; // clean up ui // this.replaceService.disposeAllReplacePreviews(); this.messages.hide(); this.results.show(); this.tree.onVisible(); this.currentSelectedFileMatch = null; } private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { if (!(lineMatch instanceof Match)) { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); return TPromise.as(true); } this.telemetryService.publicLog('searchResultChosen'); return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ? this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) : this.open(lineMatch, preserveFocus, sideBySide, pinned); } public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { let selection = this.getSelectionFrom(element); let resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource(); return this.editorService.openEditor({ resource: resource, options: { preserveFocus, pinned, selection, revealIfVisible: !sideBySide } }, sideBySide).then(editor => { if (editor && element instanceof Match && preserveFocus) { this.viewModel.searchResult.rangeHighlightDecorations.highlightRange({ resource, range: element.range() }, <ICommonCodeEditor>editor.getControl()); } else { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); } }, errors.onUnexpectedError); } private getSelectionFrom(element: FileMatchOrMatch): any { let match: Match = null; if (element instanceof Match) { match = element; } if (element instanceof FileMatch && element.count() > 0) { match = element.matches()[element.matches().length - 1]; } if (match) { let range = match.range(); if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) { let replaceString = match.replaceString; return { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.startLineNumber, endColumn: range.startColumn + replaceString.length }; } return range; } return void 0; } private onUntitledDidChangeDirty(resource: URI): void { if (!this.viewModel) { return; } // remove search results from this resource as it got disposed if (!this.untitledEditorService.isDirty(resource)) { let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (resource.toString() === matches[i].resource().toString()) { this.viewModel.searchResult.remove(matches[i]); } } } } private onFilesChanged(e: FileChangesEvent): void { if (!this.viewModel) { return; } let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (e.contains(matches[i].resource(), FileChangeType.DELETED)) { this.viewModel.searchResult.remove(matches[i]); } } } public getActions(): IAction[] { return [ this.actionRegistry['refresh'], this.actionRegistry['vs.tree.collapse'], this.actionRegistry['clearSearchResults'] ]; } public dispose(): void { this.isDisposed = true; this.toDispose = lifecycle.dispose(this.toDispose); if (this.tree) { this.tree.dispose(); } this.searchWidget.dispose(); this.inputPatternIncludes.dispose(); this.inputPatternExclusions.dispose(); this.viewModel.dispose(); super.dispose(); } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { let matchHighlightColor = theme.getColor(editorFindMatchHighlight); if (matchHighlightColor) { collector.addRule(`.search-viewlet .findInFileMatch { background-color: ${matchHighlightColor}; }`); collector.addRule(`.search-viewlet .highlight { background-color: ${matchHighlightColor}; }`); } });
src/vs/workbench/parts/search/browser/searchViewlet.ts
1
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0013611905742436647, 0.00017870029842015356, 0.0001639101537875831, 0.0001693585654720664, 0.00010078309423988685 ]
{ "id": 1, "code_window": [ "\n", "\t\tthis.userContent = null;\n", "\t\tthis.traits = {};\n", "\t\tthis.depth = 0;\n", "\t\tthis.expanded = false;\n", "\n", "\t\tthis.emit('item:create', { item: this });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.expanded = this.context.dataSource.shouldAutoexpand && this.context.dataSource.shouldAutoexpand(this.context.tree, element);\n" ], "file_path": "src/vs/base/parts/tree/browser/treeModel.ts", "type": "replace", "edit_start_line_idx": 243 }
/*--------------------------------------------------------------------------------------------- * 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. { "ariaCurrentSuggestion": "{0}、候補", "ariaCurrentSuggestionWithDetails": "{0}、候補、詳細あり", "goback": "戻る", "readMore": "詳細を表示...{0}", "suggestWidget.loading": "読み込んでいます...", "suggestWidget.noSuggestions": "候補はありません。", "suggestionAriaAccepted": "{0}、受け入れ済み", "suggestionAriaLabel": "{0}、候補", "suggestionWithDetailsAriaLabel": "{0}、候補、詳細あり" }
i18n/jpn/src/vs/editor/contrib/suggest/browser/suggestWidget.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0001746645284583792, 0.00017289118841290474, 0.00017111783381551504, 0.00017289118841290474, 0.0000017733473214320838 ]
{ "id": 1, "code_window": [ "\n", "\t\tthis.userContent = null;\n", "\t\tthis.traits = {};\n", "\t\tthis.depth = 0;\n", "\t\tthis.expanded = false;\n", "\n", "\t\tthis.emit('item:create', { item: this });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.expanded = this.context.dataSource.shouldAutoexpand && this.context.dataSource.shouldAutoexpand(this.context.tree, element);\n" ], "file_path": "src/vs/base/parts/tree/browser/treeModel.ts", "type": "replace", "edit_start_line_idx": 243 }
/*--------------------------------------------------------------------------------------------- * 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 { TokenizationRegistry, IState, LanguageIdentifier, ColorId, FontStyle, MetadataConsts } from 'vs/editor/common/modes'; import { tokenizeToString, tokenizeLineToHTML } from 'vs/editor/common/modes/textToHtmlTokenizer'; import { MockMode } from 'vs/editor/test/common/mocks/mockMode'; import { TokenizationResult2 } from 'vs/editor/common/core/token'; import { ViewLineToken } from 'vs/editor/common/core/viewLineToken'; suite('Editor Modes - textToHtmlTokenizer', () => { function toStr(pieces: { className: string; text: string }[]): string { let resultArr = pieces.map((t) => `<span class="${t.className}">${t.text}</span>`); return resultArr.join(''); } test('TextToHtmlTokenizer 1', () => { let mode = new Mode(); let actual = tokenizeToString('.abc..def...gh', mode.getId()); let expected = [ { className: 'mtk7', text: '.' }, { className: 'mtk9', text: 'abc' }, { className: 'mtk7', text: '..' }, { className: 'mtk9', text: 'def' }, { className: 'mtk7', text: '...' }, { className: 'mtk9', text: 'gh' }, ]; let expectedStr = `<div class="monaco-tokenized-source">${toStr(expected)}</div>`; assert.equal(actual, expectedStr); mode.dispose(); }); test('TextToHtmlTokenizer 2', () => { let mode = new Mode(); let actual = tokenizeToString('.abc..def...gh\n.abc..def...gh', mode.getId()); let expected1 = [ { className: 'mtk7', text: '.' }, { className: 'mtk9', text: 'abc' }, { className: 'mtk7', text: '..' }, { className: 'mtk9', text: 'def' }, { className: 'mtk7', text: '...' }, { className: 'mtk9', text: 'gh' }, ]; let expected2 = [ { className: 'mtk7', text: '.' }, { className: 'mtk9', text: 'abc' }, { className: 'mtk7', text: '..' }, { className: 'mtk9', text: 'def' }, { className: 'mtk7', text: '...' }, { className: 'mtk9', text: 'gh' }, ]; let expectedStr1 = toStr(expected1); let expectedStr2 = toStr(expected2); let expectedStr = `<div class="monaco-tokenized-source">${expectedStr1}<br/>${expectedStr2}</div>`; assert.equal(actual, expectedStr); mode.dispose(); }); test('tokenizeLineToHTML', () => { const text = 'Ciao hello world!'; const lineTokens = [ new ViewLineToken( 4, ( (3 << MetadataConsts.FOREGROUND_OFFSET) | ((FontStyle.Bold | FontStyle.Italic) << MetadataConsts.FONT_STYLE_OFFSET) ) >>> 0 ), new ViewLineToken( 5, ( (1 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 10, ( (4 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 11, ( (1 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 17, ( (5 << MetadataConsts.FOREGROUND_OFFSET) | ((FontStyle.Underline) << MetadataConsts.FONT_STYLE_OFFSET) ) >>> 0 ) ]; const colorMap = [null, '#000000', '#ffffff', '#ff0000', '#00ff00', '#0000ff']; assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 0, 17, 4), [ '<div>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">Ciao</span>', '<span style="color: #000000;"> </span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;"> </span>', '<span style="color: #0000ff;text-decoration: underline;">world!</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 0, 12, 4), [ '<div>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">Ciao</span>', '<span style="color: #000000;"> </span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;"> </span>', '<span style="color: #0000ff;text-decoration: underline;">w</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 0, 11, 4), [ '<div>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">Ciao</span>', '<span style="color: #000000;"> </span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;"> </span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 1, 11, 4), [ '<div>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">iao</span>', '<span style="color: #000000;"> </span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;"> </span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 4, 11, 4), [ '<div>', '<span style="color: #000000;"> </span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;"> </span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 5, 11, 4), [ '<div>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;"> </span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 5, 10, 4), [ '<div>', '<span style="color: #00ff00;">hello</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 6, 9, 4), [ '<div>', '<span style="color: #00ff00;">ell</span>', '</div>' ].join('') ); }); }); class Mode extends MockMode { private static _id = new LanguageIdentifier('textToHtmlTokenizerMode', 3); constructor() { super(Mode._id); this._register(TokenizationRegistry.register(this.getId(), { getInitialState: (): IState => null, tokenize: undefined, tokenize2: (line: string, state: IState): TokenizationResult2 => { let tokensArr: number[] = []; let prevColor: ColorId = -1; for (let i = 0; i < line.length; i++) { let colorId = line.charAt(i) === '.' ? 7 : 9; if (prevColor !== colorId) { tokensArr.push(i); tokensArr.push(( colorId << MetadataConsts.FOREGROUND_OFFSET ) >>> 0); } prevColor = colorId; } let tokens = new Uint32Array(tokensArr.length); for (let i = 0; i < tokens.length; i++) { tokens[i] = tokensArr[i]; } return new TokenizationResult2(tokens, null); } })); } }
src/vs/editor/test/common/modes/textToHtmlTokenizer.test.ts
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00017629809735808522, 0.00017340145132038742, 0.00016206373402383178, 0.0001736929698381573, 0.0000027262801722827135 ]
{ "id": 1, "code_window": [ "\n", "\t\tthis.userContent = null;\n", "\t\tthis.traits = {};\n", "\t\tthis.depth = 0;\n", "\t\tthis.expanded = false;\n", "\n", "\t\tthis.emit('item:create', { item: this });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.expanded = this.context.dataSource.shouldAutoexpand && this.context.dataSource.shouldAutoexpand(this.context.tree, element);\n" ], "file_path": "src/vs/base/parts/tree/browser/treeModel.ts", "type": "replace", "edit_start_line_idx": 243 }
/*--------------------------------------------------------------------------------------------- * 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. { "updateImageSize": "Emmet: Actualizar tamaño de la imagen" }
i18n/esn/src/vs/workbench/parts/emmet/node/actions/updateImageSize.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0001769241935107857, 0.0001769241935107857, 0.0001769241935107857, 0.0001769241935107857, 0 ]
{ "id": 2, "code_window": [ "\n", "export class SearchDataSource implements IDataSource {\n", "\n", "\tpublic getId(tree: ITree, element: any): string {\n", "\t\tif (element instanceof FileMatch) {\n", "\t\t\treturn element.id();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static AUTOEXPAND_CHILD_LIMIT = 10;\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "add", "edit_start_line_idx": 32 }
/*--------------------------------------------------------------------------------------------- * 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/searchviewlet'; import nls = require('vs/nls'); import { TPromise } from 'vs/base/common/winjs.base'; import { Emitter, debounceEvent } from 'vs/base/common/event'; import { EditorType, ICommonCodeEditor } from 'vs/editor/common/editorCommon'; import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import aria = require('vs/base/browser/ui/aria/aria'); import { IExpression } from 'vs/base/common/glob'; import env = require('vs/base/common/platform'); import { isFunction } from 'vs/base/common/types'; import { Delayer } from 'vs/base/common/async'; import URI from 'vs/base/common/uri'; import strings = require('vs/base/common/strings'); import dom = require('vs/base/browser/dom'); import { IAction, Action } from 'vs/base/common/actions'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import { FindInput } from 'vs/base/browser/ui/findinput/findInput'; import { ITree } from 'vs/base/parts/tree/browser/tree'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { Scope } from 'vs/workbench/common/memento'; import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { getOutOfWorkspaceEditorResources } from 'vs/workbench/common/editor'; import { FileChangeType, FileChangesEvent, IFileService, isEqual } from 'vs/platform/files/common/files'; import { Viewlet } from 'vs/workbench/browser/viewlet'; import { Match, FileMatch, SearchModel, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService } from 'vs/workbench/parts/search/common/searchModel'; import { QueryBuilder } from 'vs/workbench/parts/search/common/searchQuery'; import { MessageType, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { getExcludes, ISearchProgressItem, ISearchComplete, ISearchQuery, IQueryOptions, ISearchConfiguration } from 'vs/platform/search/common/search'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IMessageService } from 'vs/platform/message/common/message'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { KeyCode } from 'vs/base/common/keyCodes'; import { PatternInputWidget } from 'vs/workbench/parts/search/browser/patternInputWidget'; import { SearchRenderer, SearchDataSource, SearchSorter, SearchController, SearchAccessibilityProvider, SearchFilter } from 'vs/workbench/parts/search/browser/searchResultsView'; import { SearchWidget } from 'vs/workbench/parts/search/browser/searchWidget'; import { RefreshAction, CollapseAllAction, ClearSearchResultsAction, ConfigureGlobalExclusionsAction } from 'vs/workbench/parts/search/browser/searchActions'; import { IReplaceService } from 'vs/workbench/parts/search/common/replace'; import Severity from 'vs/base/common/severity'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { OpenFolderAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/fileActions'; import * as Constants from 'vs/workbench/parts/search/common/constants'; import { IListService } from 'vs/platform/list/browser/listService'; import { IThemeService, ITheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { editorFindMatchHighlight } from 'vs/platform/theme/common/colorRegistry'; export class SearchViewlet extends Viewlet { private static MAX_TEXT_RESULTS = 2048; private static SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace'; private isDisposed: boolean; private toDispose: lifecycle.IDisposable[]; private loading: boolean; private queryBuilder: QueryBuilder; private viewModel: SearchModel; private callOnModelChange: lifecycle.IDisposable[]; private viewletVisible: IContextKey<boolean>; private inputBoxFocussed: IContextKey<boolean>; private actionRegistry: { [key: string]: Action; }; private tree: ITree; private viewletSettings: any; private domNode: Builder; private messages: Builder; private searchWidgetsContainer: Builder; private searchWidget: SearchWidget; private size: Dimension; private queryDetails: HTMLElement; private inputPatternExclusions: PatternInputWidget; private inputPatternGlobalExclusions: InputBox; private inputPatternGlobalExclusionsContainer: Builder; private inputPatternIncludes: PatternInputWidget; private results: Builder; private currentSelectedFileMatch: FileMatch; private selectCurrentMatchEmitter: Emitter<string>; private delayedRefresh: Delayer<void>; constructor( @ITelemetryService telemetryService: ITelemetryService, @IFileService private fileService: IFileService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IProgressService private progressService: IProgressService, @IMessageService private messageService: IMessageService, @IStorageService private storageService: IStorageService, @IContextViewService private contextViewService: IContextViewService, @IInstantiationService private instantiationService: IInstantiationService, @IConfigurationService private configurationService: IConfigurationService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService, @IContextKeyService private contextKeyService: IContextKeyService, @IKeybindingService private keybindingService: IKeybindingService, @IReplaceService private replaceService: IReplaceService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IPreferencesService private preferencesService: IPreferencesService, @IListService private listService: IListService, @IThemeService protected themeService: IThemeService ) { super(Constants.VIEWLET_ID, telemetryService, themeService); this.toDispose = []; this.viewletVisible = Constants.SearchViewletVisibleKey.bindTo(contextKeyService); this.inputBoxFocussed = Constants.InputBoxFocussedKey.bindTo(this.contextKeyService); this.callOnModelChange = []; this.queryBuilder = this.instantiationService.createInstance(QueryBuilder); this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE); this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e))); this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); this.selectCurrentMatchEmitter = new Emitter<string>(); debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true) (() => this.selectCurrentMatch()); this.delayedRefresh = new Delayer<void>(250); } private onConfigurationUpdated(configuration: any): void { this.updateGlobalPatternExclusions(configuration); } public create(parent: Builder): TPromise<void> { super.create(parent); this.viewModel = this.searchWorkbenchService.searchModel; let builder: Builder; this.domNode = parent.div({ 'class': 'search-viewlet' }, (div) => { builder = div; }); builder.div({ 'class': ['search-widgets-container'] }, (div) => { this.searchWidgetsContainer = div; }); this.createSearchWidget(this.searchWidgetsContainer); let filePatterns = this.viewletSettings['query.filePatterns'] || ''; let patternExclusions = this.viewletSettings['query.folderExclusions'] || ''; let exclusionsUsePattern = this.viewletSettings['query.exclusionsUsePattern']; let includesUsePattern = this.viewletSettings['query.includesUsePattern']; let patternIncludes = this.viewletSettings['query.folderIncludes'] || ''; let useIgnoreFiles = this.viewletSettings['query.useIgnoreFiles']; this.queryDetails = this.searchWidgetsContainer.div({ 'class': ['query-details'] }, (builder) => { builder.div({ 'class': 'more', 'tabindex': 0, 'role': 'button', 'title': nls.localize('moreSearch', "Toggle Search Details") }) .on(dom.EventType.CLICK, (e) => { dom.EventHelper.stop(e); this.toggleFileTypes(true); }).on(dom.EventType.KEY_UP, (e: KeyboardEvent) => { let event = new StandardKeyboardEvent(e); if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { dom.EventHelper.stop(e); this.toggleFileTypes(); } }); //folder includes list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.includes', "files to include"); builder.element('h4', { text: title }); this.inputPatternIncludes = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.includes', 'Search Include Patterns') }); this.inputPatternIncludes.setIsGlobPattern(includesUsePattern); this.inputPatternIncludes.setValue(patternIncludes); this.inputPatternIncludes .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternIncludes.inputFocusTracker); }); //pattern exclusion list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.excludes', "files to exclude"); builder.element('h4', { text: title }); const configuration = this.configurationService.getConfiguration<ISearchConfiguration>(); this.inputPatternExclusions = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns') }, configuration.search.useRipgrep); this.inputPatternExclusions.setIsGlobPattern(exclusionsUsePattern); this.inputPatternExclusions.setValue(patternExclusions); this.inputPatternExclusions.setUseIgnoreFiles(useIgnoreFiles); this.inputPatternExclusions .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternExclusions.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternExclusions.inputFocusTracker); }); // add hint if we have global exclusion this.inputPatternGlobalExclusionsContainer = builder.div({ 'class': 'file-types global-exclude disabled' }, (builder) => { let title = nls.localize('global.searchScope.folders', "files excluded through settings"); builder.element('h4', { text: title }); this.inputPatternGlobalExclusions = new InputBox(builder.getContainer(), this.contextViewService, { actions: [this.instantiationService.createInstance(ConfigureGlobalExclusionsAction)], ariaLabel: nls.localize('label.global.excludes', 'Configured Search Exclude Patterns') }); this.inputPatternGlobalExclusions.inputElement.readOnly = true; $(this.inputPatternGlobalExclusions.inputElement).attr('aria-readonly', 'true'); $(this.inputPatternGlobalExclusions.inputElement).addClass('disabled'); }).hide(); }).getHTMLElement(); this.messages = builder.div({ 'class': 'messages' }).hide().clone(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.createSearchResultsView(builder); this.actionRegistry = <any>{}; let actions: Action[] = [new CollapseAllAction(this), new RefreshAction(this), new ClearSearchResultsAction(this)]; actions.forEach((action) => { this.actionRegistry[action.id] = action; }); if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '') { this.toggleFileTypes(true, true, true); } this.updateGlobalPatternExclusions(this.configurationService.getConfiguration<ISearchConfiguration>()); this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event))); return TPromise.as(null); } public get searchAndReplaceWidget(): SearchWidget { return this.searchWidget; } private createSearchWidget(builder: Builder): void { let contentPattern = this.viewletSettings['query.contentPattern'] || ''; let isRegex = this.viewletSettings['query.regex'] === true; let isWholeWords = this.viewletSettings['query.wholeWords'] === true; let isCaseSensitive = this.viewletSettings['query.caseSensitive'] === true; this.searchWidget = new SearchWidget(builder, this.contextViewService, { value: contentPattern, isRegex: isRegex, isCaseSensitive: isCaseSensitive, isWholeWords: isWholeWords }, this.contextKeyService, this.keybindingService, this.instantiationService); if (this.storageService.getBoolean(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) { this.searchWidget.toggleReplace(true); } this.toUnbind.push(this.searchWidget); this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh))); this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch())); this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard))); this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled())); this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => { this.viewModel.replaceActive = state; this.tree.refresh(); })); this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => { this.viewModel.replaceString = this.searchWidget.getReplaceValue(); this.delayedRefresh.trigger(() => this.tree.refresh()); })); this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll())); this.trackInputBox(this.searchWidget.searchInputFocusTracker); this.trackInputBox(this.searchWidget.replaceInputFocusTracker); } private trackInputBox(inputFocusTracker: dom.IFocusTracker): void { this.toUnbind.push(inputFocusTracker.addFocusListener(() => { this.inputBoxFocussed.set(true); })); this.toUnbind.push(inputFocusTracker.addBlurListener(() => { this.inputBoxFocussed.set(this.searchWidget.searchInputHasFocus() || this.searchWidget.replaceInputHasFocus() || this.inputPatternIncludes.inputHasFocus() || this.inputPatternExclusions.inputHasFocus()); })); } private onReplaceToggled(): void { this.layout(this.size); this.storageService.store(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, this.searchAndReplaceWidget.isReplaceShown(), StorageScope.WORKSPACE); } private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> { return this.refreshTree(event).then(() => { this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty()); this.updateSearchResultCount(); }); } private refreshTree(event?: IChangeEvent): TPromise<any> { if (!event) { return this.tree.refresh(this.viewModel.searchResult); } if (event.added || event.removed) { return this.tree.refresh(this.viewModel.searchResult).then(() => { if (event.added) { event.elements.forEach(element => { this.autoExpandFileMatch(element, true); }); } }); } else { if (event.elements.length === 1) { return this.tree.refresh(event.elements[0]); } else { return this.tree.refresh(event.elements); } } } private replaceAll(): void { if (this.viewModel.searchResult.count() === 0) { return; } let progressRunner = this.progressService.show(100); let occurrences = this.viewModel.searchResult.count(); let fileCount = this.viewModel.searchResult.fileCount(); let replaceValue = this.searchWidget.getReplaceValue() || ''; let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue); let confirmation = { title: nls.localize('replaceAll.confirmation.title', "Replace All"), message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue), primaryButton: nls.localize('replaceAll.confirm.button', "Replace") }; if (this.messageService.confirm(confirmation)) { this.searchWidget.setReplaceAllActionState(false); this.viewModel.searchResult.replaceAll(progressRunner).then(() => { progressRunner.done(); this.clearMessage() .p({ text: afterReplaceAllMessage }); }, (error) => { progressRunner.done(); errors.isPromiseCanceledError(error); this.messageService.show(Severity.Error, error); }); } } private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount); } private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount); } private clearMessage(): Builder { return this.messages.empty().show() .asContainer().div({ 'class': 'message' }) .asContainer(); } private createSearchResultsView(builder: Builder): void { builder.div({ 'class': 'results' }, (div) => { this.results = div; this.results.addClass('show-file-icons'); let dataSource = new SearchDataSource(); let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this); this.tree = new Tree(div.getHTMLElement(), { dataSource: dataSource, renderer: renderer, sorter: new SearchSorter(), filter: new SearchFilter(), controller: new SearchController(this, this.instantiationService), accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider) }, { ariaLabel: nls.localize('treeAriaLabel', "Search Results"), keyboardSupport: false }); this.tree.setInput(this.viewModel.searchResult); this.toUnbind.push(renderer); this.toUnbind.push(this.listService.register(this.tree)); let focusToSelectionDelayHandle: number; let lastFocusToSelection: number; const focusToSelection = (originalEvent: KeyboardEvent | MouseEvent) => { lastFocusToSelection = Date.now(); const focus = this.tree.getFocus(); let payload: any; if (focus instanceof Match) { payload = { origin: 'keyboard', originalEvent, preserveFocus: true }; } this.tree.setSelection([focus], payload); focusToSelectionDelayHandle = void 0; }; this.toUnbind.push(this.tree.addListener2('focus', (event: any) => { let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; // debounce setting selection so that we are not too quickly opening // when the user is pressing and holding the key to move focus if (focusToSelectionDelayHandle || (Date.now() - lastFocusToSelection <= 75)) { window.clearTimeout(focusToSelectionDelayHandle); focusToSelectionDelayHandle = window.setTimeout(() => focusToSelection(originalEvent), 300); } else { focusToSelection(originalEvent); } } })); this.toUnbind.push(this.tree.addListener2('selection', (event: any) => { let element: any; let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { element = this.tree.getFocus(); } else { element = event.selection[0]; } let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; let doubleClick = (event.payload && event.payload.origin === 'mouse' && originalEvent && originalEvent.detail === 2); if (doubleClick && originalEvent) { originalEvent.preventDefault(); // focus moves to editor, we need to prevent default } let sideBySide = (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey)); let focusEditor = (keyboard && (!event.payload || !event.payload.preserveFocus)) || doubleClick; if (element instanceof Match) { let selectedMatch: Match = element; if (this.currentSelectedFileMatch) { this.currentSelectedFileMatch.setSelectedMatch(null); } this.currentSelectedFileMatch = selectedMatch.parent(); this.currentSelectedFileMatch.setSelectedMatch(selectedMatch); if (!event.payload.preventEditorOpen) { this.onFocus(selectedMatch, !focusEditor, sideBySide, doubleClick); } } })); }); } private updateGlobalPatternExclusions(configuration: ISearchConfiguration): void { if (this.inputPatternGlobalExclusionsContainer) { let excludes = getExcludes(configuration); if (excludes) { let exclusions = Object.getOwnPropertyNames(excludes).filter(exclude => excludes[exclude] === true || typeof excludes[exclude].when === 'string').map(exclude => { if (excludes[exclude] === true) { return exclude; } return nls.localize('globLabel', "{0} when {1}", exclude, excludes[exclude].when); }); if (exclusions.length) { const values = exclusions.join(', '); this.inputPatternGlobalExclusions.value = values; this.inputPatternGlobalExclusions.inputElement.title = values; this.inputPatternGlobalExclusionsContainer.show(); } else { this.inputPatternGlobalExclusionsContainer.hide(); } } } } public selectCurrentMatch(): void { const focused = this.tree.getFocus(); const eventPayload = { focusEditor: true }; this.tree.setSelection([focused], eventPayload); } public selectNextMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); // Expand the initial selected node, if needed if (selected instanceof FileMatch) { if (!this.tree.isExpanded(selected)) { this.tree.expand(selected); } } let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let next = navigator.next(); if (!next) { // Reached the end - get a new navigator from the root. // .first and .last only work when subTreeOnly = true. Maybe there's a simpler way. navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); next = navigator.first(); } // Expand and go past FileMatch nodes if (!(next instanceof Match)) { if (!this.tree.isExpanded(next)) { this.tree.expand(next); } // Select the FileMatch's first child next = navigator.next(); } // Reveal the newly selected element const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(next, eventPayload); this.tree.setSelection([next], eventPayload); this.tree.reveal(next); this.selectCurrentMatchEmitter.fire(); } public selectPreviousMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let prev = navigator.previous(); // Expand and go past FileMatch nodes if (!(prev instanceof Match)) { prev = navigator.previous(); if (!prev) { // Wrap around. Get a new tree starting from the root navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); prev = navigator.last(); // This is complicated because .last will set the navigator to the last FileMatch, // so expand it and FF to its last child this.tree.expand(prev); let tmp; while (tmp = navigator.next()) { prev = tmp; } } if (!(prev instanceof Match)) { // There is a second non-Match result, which must be a collapsed FileMatch. // Expand it then select its last child. navigator.next(); this.tree.expand(prev); prev = navigator.previous(); } } // Reveal the newly selected element if (prev) { const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(prev, eventPayload); this.tree.setSelection([prev], eventPayload); this.tree.reveal(prev); this.selectCurrentMatchEmitter.fire(); } } public setVisible(visible: boolean): TPromise<void> { let promise: TPromise<void>; this.viewletVisible.set(visible); if (visible) { promise = super.setVisible(visible); this.tree.onVisible(); } else { this.tree.onHidden(); promise = super.setVisible(visible); } // Enable highlights if there are searchresults if (this.viewModel) { this.viewModel.searchResult.toggleHighlights(visible); } // Open focused element from results in case the editor area is otherwise empty if (visible && !this.editorService.getActiveEditor()) { let focus = this.tree.getFocus(); if (focus) { this.onFocus(focus, true); } } return promise; } public focus(): void { super.focus(); let selectedText = this.getSearchTextFromEditor(); if (selectedText) { this.searchWidget.searchInput.setValue(selectedText); } this.searchWidget.focus(); } public focusNextInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { if (this.searchWidget.isReplaceShown()) { this.searchWidget.focus(true, true); } else { this.moveFocusFromSearchOrReplace(); } return; } if (this.searchWidget.replaceInputHasFocus()) { this.moveFocusFromSearchOrReplace(); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.selectTreeIfNotSelected(); return; } } private moveFocusFromSearchOrReplace() { if (this.showsFileTypes()) { this.toggleFileTypes(true, this.showsFileTypes()); } else { this.selectTreeIfNotSelected(); } } public focusPreviousInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { return; } if (this.searchWidget.replaceInputHasFocus()) { this.searchWidget.focus(true); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.searchWidget.focus(true, true); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); return; } } public moveFocusFromResults(): void { if (this.showsFileTypes()) { this.toggleFileTypes(true, true, false, true); } else { this.searchWidget.focus(true, true); } } private reLayout(): void { if (this.isDisposed) { return; } this.searchWidget.setWidth(this.size.width - 25 /* container margin */); this.inputPatternExclusions.setWidth(this.size.width - 28 /* container margin */); this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */); this.inputPatternGlobalExclusions.width = this.size.width - 28 /* container margin */ - 24 /* actions */; const messagesSize = this.messages.isHidden() ? 0 : dom.getTotalHeight(this.messages.getHTMLElement()); const searchResultContainerSize = this.size.height - messagesSize - dom.getTotalHeight(this.searchWidgetsContainer.getContainer()); this.results.style({ height: searchResultContainerSize + 'px' }); this.tree.layout(searchResultContainerSize); } public layout(dimension: Dimension): void { this.size = dimension; this.reLayout(); } public getControl(): ITree { return this.tree; } public clearSearchResults(): void { this.viewModel.searchResult.clear(); this.showEmptyStage(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.searchWidget.clear(); this.viewModel.cancelSearch(); } public cancelSearch(): boolean { if (this.viewModel.cancelSearch()) { this.searchWidget.focus(); return true; } return false; } private selectTreeIfNotSelected(): void { if (this.tree.getInput()) { this.tree.DOMFocus(); let selection = this.tree.getSelection(); if (selection.length === 0) { this.tree.focusNext(); } } } private getSearchTextFromEditor(): string { if (!this.editorService.getActiveEditor()) { return null; } let editorControl: any = this.editorService.getActiveEditor().getControl(); if (!editorControl || !isFunction(editorControl.getEditorType) || editorControl.getEditorType() !== EditorType.ICodeEditor) { // Substitute for (editor instanceof ICodeEditor) return null; } let range = editorControl.getSelection(); if (range && !range.isEmpty() && range.startLineNumber === range.endLineNumber) { let searchText = editorControl.getModel().getLineContent(range.startLineNumber); searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1); return searchText; } return null; } private showsFileTypes(): boolean { return dom.hasClass(this.queryDetails, 'more'); } public toggleCaseSensitive(): void { this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive()); this.onQueryChanged(true, true); } public toggleWholeWords(): void { this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords()); this.onQueryChanged(true, true); } public toggleRegex(): void { this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex()); this.onQueryChanged(true, true); } public toggleFileTypes(moveFocus?: boolean, show?: boolean, skipLayout?: boolean, reverse?: boolean): void { let cls = 'more'; show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show); skipLayout = Boolean(skipLayout); if (show) { dom.addClass(this.queryDetails, cls); if (moveFocus) { if (reverse) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); } else { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); } } } else { dom.removeClass(this.queryDetails, cls); if (moveFocus) { this.searchWidget.focus(); } } if (!skipLayout && this.size) { this.layout(this.size); } } public searchInFolder(resource: URI): void { const workspace = this.contextService.getWorkspace(); if (!workspace) { return; } if (isEqual(workspace.resource.fsPath, resource.fsPath)) { this.inputPatternIncludes.setValue(''); this.searchWidget.focus(); return; } if (!this.showsFileTypes()) { this.toggleFileTypes(true, true); } const workspaceRelativePath = this.contextService.toWorkspaceRelativePath(resource); if (workspaceRelativePath) { this.inputPatternIncludes.setIsGlobPattern(false); this.inputPatternIncludes.setValue(workspaceRelativePath); this.searchWidget.focus(false); } } public onQueryChanged(rerunQuery: boolean, preserveFocus?: boolean): void { const isRegex = this.searchWidget.searchInput.getRegex(); const isWholeWords = this.searchWidget.searchInput.getWholeWords(); const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive(); const contentPattern = this.searchWidget.searchInput.getValue(); const patternExcludes = this.inputPatternExclusions.getValue().trim(); const exclusionsUsePattern = this.inputPatternExclusions.isGlobPattern(); const patternIncludes = this.inputPatternIncludes.getValue().trim(); const includesUsePattern = this.inputPatternIncludes.isGlobPattern(); const useIgnoreFiles = this.inputPatternExclusions.useIgnoreFiles(); // store memento this.viewletSettings['query.contentPattern'] = contentPattern; this.viewletSettings['query.regex'] = isRegex; this.viewletSettings['query.wholeWords'] = isWholeWords; this.viewletSettings['query.caseSensitive'] = isCaseSensitive; this.viewletSettings['query.folderExclusions'] = patternExcludes; this.viewletSettings['query.exclusionsUsePattern'] = exclusionsUsePattern; this.viewletSettings['query.folderIncludes'] = patternIncludes; this.viewletSettings['query.includesUsePattern'] = includesUsePattern; this.viewletSettings['query.useIgnoreFiles'] = useIgnoreFiles; if (!rerunQuery) { return; } if (contentPattern.length === 0) { return; } // Validate regex is OK if (isRegex) { let regExp: RegExp; try { regExp = new RegExp(contentPattern); } catch (e) { return; // malformed regex } if (strings.regExpLeadsToEndlessLoop(regExp)) { return; // endless regex } } let content = { pattern: contentPattern, isRegExp: isRegex, isCaseSensitive: isCaseSensitive, isWordMatch: isWholeWords }; let excludes: IExpression = this.inputPatternExclusions.getGlob(); let includes: IExpression = this.inputPatternIncludes.getGlob(); let options: IQueryOptions = { folderResources: this.contextService.hasWorkspace() ? [this.contextService.getWorkspace().resource] : [], extraFileResources: getOutOfWorkspaceEditorResources(this.editorGroupService, this.contextService), excludePattern: excludes, maxResults: SearchViewlet.MAX_TEXT_RESULTS, includePattern: includes, useIgnoreFiles }; this.onQueryTriggered(this.queryBuilder.text(content, options), patternExcludes, patternIncludes); if (!preserveFocus) { this.searchWidget.focus(false); // focus back to input field } } private autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void { let length = fileMatch.matches().length; if (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) { this.tree.expand(fileMatch).done(null, errors.onUnexpectedError); } else { this.tree.collapse(fileMatch).done(null, errors.onUnexpectedError); } } private onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void { this.viewModel.cancelSearch(); // Progress total is 100.0% for more progress bar granularity let progressTotal = 1000; let progressWorked = 0; let progressRunner = query.useRipgrep ? this.progressService.show(/*infinite=*/true) : this.progressService.show(progressTotal); this.loading = true; this.searchWidget.searchInput.clearMessage(); this.showEmptyStage(); let handledMatches: { [id: string]: boolean } = Object.create(null); let autoExpand = (alwaysExpandIfOneResult: boolean) => { // Auto-expand / collapse based on number of matches: // - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file // - expand file results if we have more than one file result and less than 10 matches on a file let matches = this.viewModel.searchResult.matches(); matches.forEach((match) => { if (handledMatches[match.id()]) { return; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile) } handledMatches[match.id()] = true; this.autoExpandFileMatch(match, alwaysExpandIfOneResult); }); }; let isDone = false; let onComplete = (completed?: ISearchComplete) => { isDone = true; // Complete up to 100% as needed if (completed && !query.useRipgrep) { progressRunner.worked(progressTotal - progressWorked); setTimeout(() => progressRunner.done(), 200); } else { progressRunner.done(); } this.onSearchResultsChanged().then(() => autoExpand(true)); this.viewModel.replaceString = this.searchWidget.getReplaceValue(); let hasResults = !this.viewModel.searchResult.isEmpty(); this.loading = false; this.actionRegistry['refresh'].enabled = true; this.actionRegistry['vs.tree.collapse'].enabled = hasResults; this.actionRegistry['clearSearchResults'].enabled = hasResults; if (completed && completed.limitHit) { this.searchWidget.searchInput.showMessage({ content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."), type: MessageType.WARNING }); } if (!hasResults) { let hasExcludes = !!excludePattern; let hasIncludes = !!includePattern; let message: string; if (!completed) { message = nls.localize('searchCanceled', "Search was canceled before any results could be found - "); } else if (hasIncludes && hasExcludes) { message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePattern, excludePattern); } else if (hasIncludes) { message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePattern); } else if (hasExcludes) { message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePattern); } else { message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions - "); } // Indicate as status to ARIA aria.status(message); this.tree.onHidden(); this.results.hide(); const div = this.clearMessage(); const p = $(div).p({ text: message }); if (!completed) { $(p).a({ 'class': ['pointer', 'prominent'], text: nls.localize('rerunSearch.message', "Search again") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.onQueryChanged(true); }); } else if (hasIncludes || hasExcludes) { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('rerunSearchInAll.message', "Search again in all files") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.inputPatternExclusions.setValue(''); this.inputPatternIncludes.setValue(''); this.onQueryChanged(true); }); } else { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openSettings.message', "Open Settings") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); if (this.contextService.hasWorkspace()) { this.preferencesService.openWorkspaceSettings().done(() => null, errors.onUnexpectedError); } else { this.preferencesService.openGlobalSettings().done(() => null, errors.onUnexpectedError); } }); } if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(div); } } else { this.viewModel.searchResult.toggleHighlights(true); // show highlights // Indicate final search result count for ARIA aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount())); } }; let onError = (e: any) => { if (errors.isPromiseCanceledError(e)) { onComplete(null); } else { this.loading = false; isDone = true; progressRunner.done(); this.messageService.show(2 /* ERROR */, e); } }; let total: number = 0; let worked: number = 0; let visibleMatches = 0; let onProgress = (p: ISearchProgressItem) => { // Progress if (p.total) { total = p.total; } if (p.worked) { worked = p.worked; } }; // Handle UI updates in an interval to show frequent progress and results let uiRefreshHandle = setInterval(() => { if (isDone) { window.clearInterval(uiRefreshHandle); return; } if (!query.useRipgrep) { // Progress bar update let fakeProgress = true; if (total > 0 && worked > 0) { let ratio = Math.round((worked / total) * progressTotal); if (ratio > progressWorked) { // never show less progress than what we have already progressRunner.worked(ratio - progressWorked); progressWorked = ratio; fakeProgress = false; } } // Fake progress up to 90%, or when actual progress beats it const fakeMax = 900; const fakeMultiplier = 12; if (fakeProgress && progressWorked < fakeMax) { // Linearly decrease the rate of fake progress. // 1 is the smallest allowed amount of progress. const fakeAmt = Math.round((fakeMax - progressWorked) / fakeMax * fakeMultiplier) || 1; progressWorked += fakeAmt; progressRunner.worked(fakeAmt); } } // Search result tree update const fileCount = this.viewModel.searchResult.fileCount(); if (visibleMatches !== fileCount) { visibleMatches = fileCount; this.tree.refresh().then(() => { autoExpand(false); }).done(null, errors.onUnexpectedError); this.updateSearchResultCount(); } if (fileCount > 0) { // since we have results now, enable some actions if (!this.actionRegistry['vs.tree.collapse'].enabled) { this.actionRegistry['vs.tree.collapse'].enabled = true; } } }, 100); this.searchWidget.setReplaceAllActionState(false); // this.replaceService.disposeAllReplacePreviews(); this.viewModel.search(query).done(onComplete, onError, query.useRipgrep ? undefined : onProgress); } private updateSearchResultCount(): void { const fileCount = this.viewModel.searchResult.fileCount(); const msgWasHidden = this.messages.isHidden(); if (fileCount > 0) { const div = this.clearMessage(); $(div).p({ text: this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount) }); if (msgWasHidden) { this.reLayout(); } } else if (!msgWasHidden) { this.messages.hide(); } } private buildResultCountMessage(resultCount: number, fileCount: number): string { if (resultCount === 1 && fileCount === 1) { return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount); } else if (resultCount === 1) { return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount); } else if (fileCount === 1) { return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount); } else { return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount); } } private searchWithoutFolderMessage(div: Builder): void { $(div).p({ text: nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ") }) .asContainer().a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openFolder', "Open Folder") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); const actionClass = env.isMacintosh ? OpenFileFolderAction : OpenFolderAction; const action = this.instantiationService.createInstance<string, string, IAction>(actionClass, actionClass.ID, actionClass.LABEL); this.actionRunner.run(action).done(() => { action.dispose(); }, err => { action.dispose(); errors.onUnexpectedError(err); }); }); } private showEmptyStage(): void { // disable 'result'-actions this.actionRegistry['refresh'].enabled = false; this.actionRegistry['vs.tree.collapse'].enabled = false; this.actionRegistry['clearSearchResults'].enabled = false; // clean up ui // this.replaceService.disposeAllReplacePreviews(); this.messages.hide(); this.results.show(); this.tree.onVisible(); this.currentSelectedFileMatch = null; } private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { if (!(lineMatch instanceof Match)) { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); return TPromise.as(true); } this.telemetryService.publicLog('searchResultChosen'); return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ? this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) : this.open(lineMatch, preserveFocus, sideBySide, pinned); } public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { let selection = this.getSelectionFrom(element); let resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource(); return this.editorService.openEditor({ resource: resource, options: { preserveFocus, pinned, selection, revealIfVisible: !sideBySide } }, sideBySide).then(editor => { if (editor && element instanceof Match && preserveFocus) { this.viewModel.searchResult.rangeHighlightDecorations.highlightRange({ resource, range: element.range() }, <ICommonCodeEditor>editor.getControl()); } else { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); } }, errors.onUnexpectedError); } private getSelectionFrom(element: FileMatchOrMatch): any { let match: Match = null; if (element instanceof Match) { match = element; } if (element instanceof FileMatch && element.count() > 0) { match = element.matches()[element.matches().length - 1]; } if (match) { let range = match.range(); if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) { let replaceString = match.replaceString; return { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.startLineNumber, endColumn: range.startColumn + replaceString.length }; } return range; } return void 0; } private onUntitledDidChangeDirty(resource: URI): void { if (!this.viewModel) { return; } // remove search results from this resource as it got disposed if (!this.untitledEditorService.isDirty(resource)) { let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (resource.toString() === matches[i].resource().toString()) { this.viewModel.searchResult.remove(matches[i]); } } } } private onFilesChanged(e: FileChangesEvent): void { if (!this.viewModel) { return; } let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (e.contains(matches[i].resource(), FileChangeType.DELETED)) { this.viewModel.searchResult.remove(matches[i]); } } } public getActions(): IAction[] { return [ this.actionRegistry['refresh'], this.actionRegistry['vs.tree.collapse'], this.actionRegistry['clearSearchResults'] ]; } public dispose(): void { this.isDisposed = true; this.toDispose = lifecycle.dispose(this.toDispose); if (this.tree) { this.tree.dispose(); } this.searchWidget.dispose(); this.inputPatternIncludes.dispose(); this.inputPatternExclusions.dispose(); this.viewModel.dispose(); super.dispose(); } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { let matchHighlightColor = theme.getColor(editorFindMatchHighlight); if (matchHighlightColor) { collector.addRule(`.search-viewlet .findInFileMatch { background-color: ${matchHighlightColor}; }`); collector.addRule(`.search-viewlet .highlight { background-color: ${matchHighlightColor}; }`); } });
src/vs/workbench/parts/search/browser/searchViewlet.ts
1
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.998738706111908, 0.02433435246348381, 0.00015933172835502774, 0.00017313440912403166, 0.14699076116085052 ]
{ "id": 2, "code_window": [ "\n", "export class SearchDataSource implements IDataSource {\n", "\n", "\tpublic getId(tree: ITree, element: any): string {\n", "\t\tif (element instanceof FileMatch) {\n", "\t\t\treturn element.id();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static AUTOEXPAND_CHILD_LIMIT = 10;\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "add", "edit_start_line_idx": 32 }
/*--------------------------------------------------------------------------------------------- * 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. { "ShowAccessibilityHelpAction": "Afficher l'aide sur l'accessibilité", "introMsg": "Nous vous remercions de tester les options d'accessibilité de VS Code.", "outroMsg": "Vous pouvez masquer cette info-bulle et revenir à l'éditeur en appuyant sur Échap.", "status": "État :", "tabFocusModeOffMsg": "Appuyez sur Tab dans l'éditeur pour insérer le caractère de tabulation. Activez ou désactivez ce comportement en appuyant sur {0}.", "tabFocusModeOffMsgNoKb": "Appuyez sur Tab dans l'éditeur pour insérer le caractère de tabulation. La commande {0} ne peut pas être déclenchée par une combinaison de touches.", "tabFocusModeOnMsg": "Appuyez sur Tab dans l'éditeur pour déplacer le focus vers le prochain élément pouvant être désigné comme élément actif. Activez ou désactivez ce comportement en appuyant sur {0}.", "tabFocusModeOnMsgNoKb": "Appuyez sur Tab dans l'éditeur pour déplacer le focus vers le prochain élément pouvant être désigné comme élément actif. La commande {0} ne peut pas être déclenchée par une combinaison de touches." }
i18n/fra/src/vs/editor/contrib/accessibility/browser/accessibility.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00017426861450076103, 0.00017214147374033928, 0.00017001433297991753, 0.00017214147374033928, 0.000002127140760421753 ]
{ "id": 2, "code_window": [ "\n", "export class SearchDataSource implements IDataSource {\n", "\n", "\tpublic getId(tree: ITree, element: any): string {\n", "\t\tif (element instanceof FileMatch) {\n", "\t\t\treturn element.id();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static AUTOEXPAND_CHILD_LIMIT = 10;\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "add", "edit_start_line_idx": 32 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "toggle.wordwrap": "Visualizza: Attiva/Disattiva ritorno a capo automatico" }
i18n/ita/src/vs/editor/contrib/toggleWordWrap/common/toggleWordWrap.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0001764767075655982, 0.0001764767075655982, 0.0001764767075655982, 0.0001764767075655982, 0 ]
{ "id": 2, "code_window": [ "\n", "export class SearchDataSource implements IDataSource {\n", "\n", "\tpublic getId(tree: ITree, element: any): string {\n", "\t\tif (element instanceof FileMatch) {\n", "\t\t\treturn element.id();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static AUTOEXPAND_CHILD_LIMIT = 10;\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "add", "edit_start_line_idx": 32 }
/*--------------------------------------------------------------------------------------------- * 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 { IGitOperation, IRawStatus } from 'vs/workbench/parts/git/common/git'; import { TPromise } from 'vs/base/common/winjs.base'; export class GitOperation implements IGitOperation { id: string; constructor(id: string, private fn: () => TPromise<IRawStatus>) { this.id = id; } run(): TPromise<IRawStatus> { return this.fn(); } dispose(): void { // noop } }
src/vs/workbench/parts/git/browser/gitOperations.ts
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00017411696899216622, 0.00017180381109938025, 0.00016773988318163902, 0.0001735545665724203, 0.0000028827853384427726 ]
{ "id": 3, "code_window": [ "\n", "\t\treturn 'root';\n", "\t}\n", "\n", "\tpublic getChildren(tree: ITree, element: any): TPromise<any[]> {\n", "\t\tlet value: any[] = [];\n", "\n", "\t\tif (element instanceof FileMatch) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tprivate _getChildren(element: any): any[] {\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 44 }
/*--------------------------------------------------------------------------------------------- * 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/searchviewlet'; import nls = require('vs/nls'); import { TPromise } from 'vs/base/common/winjs.base'; import { Emitter, debounceEvent } from 'vs/base/common/event'; import { EditorType, ICommonCodeEditor } from 'vs/editor/common/editorCommon'; import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import aria = require('vs/base/browser/ui/aria/aria'); import { IExpression } from 'vs/base/common/glob'; import env = require('vs/base/common/platform'); import { isFunction } from 'vs/base/common/types'; import { Delayer } from 'vs/base/common/async'; import URI from 'vs/base/common/uri'; import strings = require('vs/base/common/strings'); import dom = require('vs/base/browser/dom'); import { IAction, Action } from 'vs/base/common/actions'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import { FindInput } from 'vs/base/browser/ui/findinput/findInput'; import { ITree } from 'vs/base/parts/tree/browser/tree'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { Scope } from 'vs/workbench/common/memento'; import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { getOutOfWorkspaceEditorResources } from 'vs/workbench/common/editor'; import { FileChangeType, FileChangesEvent, IFileService, isEqual } from 'vs/platform/files/common/files'; import { Viewlet } from 'vs/workbench/browser/viewlet'; import { Match, FileMatch, SearchModel, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService } from 'vs/workbench/parts/search/common/searchModel'; import { QueryBuilder } from 'vs/workbench/parts/search/common/searchQuery'; import { MessageType, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { getExcludes, ISearchProgressItem, ISearchComplete, ISearchQuery, IQueryOptions, ISearchConfiguration } from 'vs/platform/search/common/search'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IMessageService } from 'vs/platform/message/common/message'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { KeyCode } from 'vs/base/common/keyCodes'; import { PatternInputWidget } from 'vs/workbench/parts/search/browser/patternInputWidget'; import { SearchRenderer, SearchDataSource, SearchSorter, SearchController, SearchAccessibilityProvider, SearchFilter } from 'vs/workbench/parts/search/browser/searchResultsView'; import { SearchWidget } from 'vs/workbench/parts/search/browser/searchWidget'; import { RefreshAction, CollapseAllAction, ClearSearchResultsAction, ConfigureGlobalExclusionsAction } from 'vs/workbench/parts/search/browser/searchActions'; import { IReplaceService } from 'vs/workbench/parts/search/common/replace'; import Severity from 'vs/base/common/severity'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { OpenFolderAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/fileActions'; import * as Constants from 'vs/workbench/parts/search/common/constants'; import { IListService } from 'vs/platform/list/browser/listService'; import { IThemeService, ITheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { editorFindMatchHighlight } from 'vs/platform/theme/common/colorRegistry'; export class SearchViewlet extends Viewlet { private static MAX_TEXT_RESULTS = 2048; private static SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace'; private isDisposed: boolean; private toDispose: lifecycle.IDisposable[]; private loading: boolean; private queryBuilder: QueryBuilder; private viewModel: SearchModel; private callOnModelChange: lifecycle.IDisposable[]; private viewletVisible: IContextKey<boolean>; private inputBoxFocussed: IContextKey<boolean>; private actionRegistry: { [key: string]: Action; }; private tree: ITree; private viewletSettings: any; private domNode: Builder; private messages: Builder; private searchWidgetsContainer: Builder; private searchWidget: SearchWidget; private size: Dimension; private queryDetails: HTMLElement; private inputPatternExclusions: PatternInputWidget; private inputPatternGlobalExclusions: InputBox; private inputPatternGlobalExclusionsContainer: Builder; private inputPatternIncludes: PatternInputWidget; private results: Builder; private currentSelectedFileMatch: FileMatch; private selectCurrentMatchEmitter: Emitter<string>; private delayedRefresh: Delayer<void>; constructor( @ITelemetryService telemetryService: ITelemetryService, @IFileService private fileService: IFileService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IProgressService private progressService: IProgressService, @IMessageService private messageService: IMessageService, @IStorageService private storageService: IStorageService, @IContextViewService private contextViewService: IContextViewService, @IInstantiationService private instantiationService: IInstantiationService, @IConfigurationService private configurationService: IConfigurationService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService, @IContextKeyService private contextKeyService: IContextKeyService, @IKeybindingService private keybindingService: IKeybindingService, @IReplaceService private replaceService: IReplaceService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IPreferencesService private preferencesService: IPreferencesService, @IListService private listService: IListService, @IThemeService protected themeService: IThemeService ) { super(Constants.VIEWLET_ID, telemetryService, themeService); this.toDispose = []; this.viewletVisible = Constants.SearchViewletVisibleKey.bindTo(contextKeyService); this.inputBoxFocussed = Constants.InputBoxFocussedKey.bindTo(this.contextKeyService); this.callOnModelChange = []; this.queryBuilder = this.instantiationService.createInstance(QueryBuilder); this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE); this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e))); this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); this.selectCurrentMatchEmitter = new Emitter<string>(); debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true) (() => this.selectCurrentMatch()); this.delayedRefresh = new Delayer<void>(250); } private onConfigurationUpdated(configuration: any): void { this.updateGlobalPatternExclusions(configuration); } public create(parent: Builder): TPromise<void> { super.create(parent); this.viewModel = this.searchWorkbenchService.searchModel; let builder: Builder; this.domNode = parent.div({ 'class': 'search-viewlet' }, (div) => { builder = div; }); builder.div({ 'class': ['search-widgets-container'] }, (div) => { this.searchWidgetsContainer = div; }); this.createSearchWidget(this.searchWidgetsContainer); let filePatterns = this.viewletSettings['query.filePatterns'] || ''; let patternExclusions = this.viewletSettings['query.folderExclusions'] || ''; let exclusionsUsePattern = this.viewletSettings['query.exclusionsUsePattern']; let includesUsePattern = this.viewletSettings['query.includesUsePattern']; let patternIncludes = this.viewletSettings['query.folderIncludes'] || ''; let useIgnoreFiles = this.viewletSettings['query.useIgnoreFiles']; this.queryDetails = this.searchWidgetsContainer.div({ 'class': ['query-details'] }, (builder) => { builder.div({ 'class': 'more', 'tabindex': 0, 'role': 'button', 'title': nls.localize('moreSearch', "Toggle Search Details") }) .on(dom.EventType.CLICK, (e) => { dom.EventHelper.stop(e); this.toggleFileTypes(true); }).on(dom.EventType.KEY_UP, (e: KeyboardEvent) => { let event = new StandardKeyboardEvent(e); if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { dom.EventHelper.stop(e); this.toggleFileTypes(); } }); //folder includes list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.includes', "files to include"); builder.element('h4', { text: title }); this.inputPatternIncludes = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.includes', 'Search Include Patterns') }); this.inputPatternIncludes.setIsGlobPattern(includesUsePattern); this.inputPatternIncludes.setValue(patternIncludes); this.inputPatternIncludes .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternIncludes.inputFocusTracker); }); //pattern exclusion list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.excludes', "files to exclude"); builder.element('h4', { text: title }); const configuration = this.configurationService.getConfiguration<ISearchConfiguration>(); this.inputPatternExclusions = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns') }, configuration.search.useRipgrep); this.inputPatternExclusions.setIsGlobPattern(exclusionsUsePattern); this.inputPatternExclusions.setValue(patternExclusions); this.inputPatternExclusions.setUseIgnoreFiles(useIgnoreFiles); this.inputPatternExclusions .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternExclusions.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternExclusions.inputFocusTracker); }); // add hint if we have global exclusion this.inputPatternGlobalExclusionsContainer = builder.div({ 'class': 'file-types global-exclude disabled' }, (builder) => { let title = nls.localize('global.searchScope.folders', "files excluded through settings"); builder.element('h4', { text: title }); this.inputPatternGlobalExclusions = new InputBox(builder.getContainer(), this.contextViewService, { actions: [this.instantiationService.createInstance(ConfigureGlobalExclusionsAction)], ariaLabel: nls.localize('label.global.excludes', 'Configured Search Exclude Patterns') }); this.inputPatternGlobalExclusions.inputElement.readOnly = true; $(this.inputPatternGlobalExclusions.inputElement).attr('aria-readonly', 'true'); $(this.inputPatternGlobalExclusions.inputElement).addClass('disabled'); }).hide(); }).getHTMLElement(); this.messages = builder.div({ 'class': 'messages' }).hide().clone(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.createSearchResultsView(builder); this.actionRegistry = <any>{}; let actions: Action[] = [new CollapseAllAction(this), new RefreshAction(this), new ClearSearchResultsAction(this)]; actions.forEach((action) => { this.actionRegistry[action.id] = action; }); if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '') { this.toggleFileTypes(true, true, true); } this.updateGlobalPatternExclusions(this.configurationService.getConfiguration<ISearchConfiguration>()); this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event))); return TPromise.as(null); } public get searchAndReplaceWidget(): SearchWidget { return this.searchWidget; } private createSearchWidget(builder: Builder): void { let contentPattern = this.viewletSettings['query.contentPattern'] || ''; let isRegex = this.viewletSettings['query.regex'] === true; let isWholeWords = this.viewletSettings['query.wholeWords'] === true; let isCaseSensitive = this.viewletSettings['query.caseSensitive'] === true; this.searchWidget = new SearchWidget(builder, this.contextViewService, { value: contentPattern, isRegex: isRegex, isCaseSensitive: isCaseSensitive, isWholeWords: isWholeWords }, this.contextKeyService, this.keybindingService, this.instantiationService); if (this.storageService.getBoolean(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) { this.searchWidget.toggleReplace(true); } this.toUnbind.push(this.searchWidget); this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh))); this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch())); this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard))); this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled())); this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => { this.viewModel.replaceActive = state; this.tree.refresh(); })); this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => { this.viewModel.replaceString = this.searchWidget.getReplaceValue(); this.delayedRefresh.trigger(() => this.tree.refresh()); })); this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll())); this.trackInputBox(this.searchWidget.searchInputFocusTracker); this.trackInputBox(this.searchWidget.replaceInputFocusTracker); } private trackInputBox(inputFocusTracker: dom.IFocusTracker): void { this.toUnbind.push(inputFocusTracker.addFocusListener(() => { this.inputBoxFocussed.set(true); })); this.toUnbind.push(inputFocusTracker.addBlurListener(() => { this.inputBoxFocussed.set(this.searchWidget.searchInputHasFocus() || this.searchWidget.replaceInputHasFocus() || this.inputPatternIncludes.inputHasFocus() || this.inputPatternExclusions.inputHasFocus()); })); } private onReplaceToggled(): void { this.layout(this.size); this.storageService.store(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, this.searchAndReplaceWidget.isReplaceShown(), StorageScope.WORKSPACE); } private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> { return this.refreshTree(event).then(() => { this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty()); this.updateSearchResultCount(); }); } private refreshTree(event?: IChangeEvent): TPromise<any> { if (!event) { return this.tree.refresh(this.viewModel.searchResult); } if (event.added || event.removed) { return this.tree.refresh(this.viewModel.searchResult).then(() => { if (event.added) { event.elements.forEach(element => { this.autoExpandFileMatch(element, true); }); } }); } else { if (event.elements.length === 1) { return this.tree.refresh(event.elements[0]); } else { return this.tree.refresh(event.elements); } } } private replaceAll(): void { if (this.viewModel.searchResult.count() === 0) { return; } let progressRunner = this.progressService.show(100); let occurrences = this.viewModel.searchResult.count(); let fileCount = this.viewModel.searchResult.fileCount(); let replaceValue = this.searchWidget.getReplaceValue() || ''; let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue); let confirmation = { title: nls.localize('replaceAll.confirmation.title', "Replace All"), message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue), primaryButton: nls.localize('replaceAll.confirm.button', "Replace") }; if (this.messageService.confirm(confirmation)) { this.searchWidget.setReplaceAllActionState(false); this.viewModel.searchResult.replaceAll(progressRunner).then(() => { progressRunner.done(); this.clearMessage() .p({ text: afterReplaceAllMessage }); }, (error) => { progressRunner.done(); errors.isPromiseCanceledError(error); this.messageService.show(Severity.Error, error); }); } } private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount); } private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount); } private clearMessage(): Builder { return this.messages.empty().show() .asContainer().div({ 'class': 'message' }) .asContainer(); } private createSearchResultsView(builder: Builder): void { builder.div({ 'class': 'results' }, (div) => { this.results = div; this.results.addClass('show-file-icons'); let dataSource = new SearchDataSource(); let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this); this.tree = new Tree(div.getHTMLElement(), { dataSource: dataSource, renderer: renderer, sorter: new SearchSorter(), filter: new SearchFilter(), controller: new SearchController(this, this.instantiationService), accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider) }, { ariaLabel: nls.localize('treeAriaLabel', "Search Results"), keyboardSupport: false }); this.tree.setInput(this.viewModel.searchResult); this.toUnbind.push(renderer); this.toUnbind.push(this.listService.register(this.tree)); let focusToSelectionDelayHandle: number; let lastFocusToSelection: number; const focusToSelection = (originalEvent: KeyboardEvent | MouseEvent) => { lastFocusToSelection = Date.now(); const focus = this.tree.getFocus(); let payload: any; if (focus instanceof Match) { payload = { origin: 'keyboard', originalEvent, preserveFocus: true }; } this.tree.setSelection([focus], payload); focusToSelectionDelayHandle = void 0; }; this.toUnbind.push(this.tree.addListener2('focus', (event: any) => { let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; // debounce setting selection so that we are not too quickly opening // when the user is pressing and holding the key to move focus if (focusToSelectionDelayHandle || (Date.now() - lastFocusToSelection <= 75)) { window.clearTimeout(focusToSelectionDelayHandle); focusToSelectionDelayHandle = window.setTimeout(() => focusToSelection(originalEvent), 300); } else { focusToSelection(originalEvent); } } })); this.toUnbind.push(this.tree.addListener2('selection', (event: any) => { let element: any; let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { element = this.tree.getFocus(); } else { element = event.selection[0]; } let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; let doubleClick = (event.payload && event.payload.origin === 'mouse' && originalEvent && originalEvent.detail === 2); if (doubleClick && originalEvent) { originalEvent.preventDefault(); // focus moves to editor, we need to prevent default } let sideBySide = (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey)); let focusEditor = (keyboard && (!event.payload || !event.payload.preserveFocus)) || doubleClick; if (element instanceof Match) { let selectedMatch: Match = element; if (this.currentSelectedFileMatch) { this.currentSelectedFileMatch.setSelectedMatch(null); } this.currentSelectedFileMatch = selectedMatch.parent(); this.currentSelectedFileMatch.setSelectedMatch(selectedMatch); if (!event.payload.preventEditorOpen) { this.onFocus(selectedMatch, !focusEditor, sideBySide, doubleClick); } } })); }); } private updateGlobalPatternExclusions(configuration: ISearchConfiguration): void { if (this.inputPatternGlobalExclusionsContainer) { let excludes = getExcludes(configuration); if (excludes) { let exclusions = Object.getOwnPropertyNames(excludes).filter(exclude => excludes[exclude] === true || typeof excludes[exclude].when === 'string').map(exclude => { if (excludes[exclude] === true) { return exclude; } return nls.localize('globLabel', "{0} when {1}", exclude, excludes[exclude].when); }); if (exclusions.length) { const values = exclusions.join(', '); this.inputPatternGlobalExclusions.value = values; this.inputPatternGlobalExclusions.inputElement.title = values; this.inputPatternGlobalExclusionsContainer.show(); } else { this.inputPatternGlobalExclusionsContainer.hide(); } } } } public selectCurrentMatch(): void { const focused = this.tree.getFocus(); const eventPayload = { focusEditor: true }; this.tree.setSelection([focused], eventPayload); } public selectNextMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); // Expand the initial selected node, if needed if (selected instanceof FileMatch) { if (!this.tree.isExpanded(selected)) { this.tree.expand(selected); } } let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let next = navigator.next(); if (!next) { // Reached the end - get a new navigator from the root. // .first and .last only work when subTreeOnly = true. Maybe there's a simpler way. navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); next = navigator.first(); } // Expand and go past FileMatch nodes if (!(next instanceof Match)) { if (!this.tree.isExpanded(next)) { this.tree.expand(next); } // Select the FileMatch's first child next = navigator.next(); } // Reveal the newly selected element const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(next, eventPayload); this.tree.setSelection([next], eventPayload); this.tree.reveal(next); this.selectCurrentMatchEmitter.fire(); } public selectPreviousMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let prev = navigator.previous(); // Expand and go past FileMatch nodes if (!(prev instanceof Match)) { prev = navigator.previous(); if (!prev) { // Wrap around. Get a new tree starting from the root navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); prev = navigator.last(); // This is complicated because .last will set the navigator to the last FileMatch, // so expand it and FF to its last child this.tree.expand(prev); let tmp; while (tmp = navigator.next()) { prev = tmp; } } if (!(prev instanceof Match)) { // There is a second non-Match result, which must be a collapsed FileMatch. // Expand it then select its last child. navigator.next(); this.tree.expand(prev); prev = navigator.previous(); } } // Reveal the newly selected element if (prev) { const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(prev, eventPayload); this.tree.setSelection([prev], eventPayload); this.tree.reveal(prev); this.selectCurrentMatchEmitter.fire(); } } public setVisible(visible: boolean): TPromise<void> { let promise: TPromise<void>; this.viewletVisible.set(visible); if (visible) { promise = super.setVisible(visible); this.tree.onVisible(); } else { this.tree.onHidden(); promise = super.setVisible(visible); } // Enable highlights if there are searchresults if (this.viewModel) { this.viewModel.searchResult.toggleHighlights(visible); } // Open focused element from results in case the editor area is otherwise empty if (visible && !this.editorService.getActiveEditor()) { let focus = this.tree.getFocus(); if (focus) { this.onFocus(focus, true); } } return promise; } public focus(): void { super.focus(); let selectedText = this.getSearchTextFromEditor(); if (selectedText) { this.searchWidget.searchInput.setValue(selectedText); } this.searchWidget.focus(); } public focusNextInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { if (this.searchWidget.isReplaceShown()) { this.searchWidget.focus(true, true); } else { this.moveFocusFromSearchOrReplace(); } return; } if (this.searchWidget.replaceInputHasFocus()) { this.moveFocusFromSearchOrReplace(); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.selectTreeIfNotSelected(); return; } } private moveFocusFromSearchOrReplace() { if (this.showsFileTypes()) { this.toggleFileTypes(true, this.showsFileTypes()); } else { this.selectTreeIfNotSelected(); } } public focusPreviousInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { return; } if (this.searchWidget.replaceInputHasFocus()) { this.searchWidget.focus(true); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.searchWidget.focus(true, true); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); return; } } public moveFocusFromResults(): void { if (this.showsFileTypes()) { this.toggleFileTypes(true, true, false, true); } else { this.searchWidget.focus(true, true); } } private reLayout(): void { if (this.isDisposed) { return; } this.searchWidget.setWidth(this.size.width - 25 /* container margin */); this.inputPatternExclusions.setWidth(this.size.width - 28 /* container margin */); this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */); this.inputPatternGlobalExclusions.width = this.size.width - 28 /* container margin */ - 24 /* actions */; const messagesSize = this.messages.isHidden() ? 0 : dom.getTotalHeight(this.messages.getHTMLElement()); const searchResultContainerSize = this.size.height - messagesSize - dom.getTotalHeight(this.searchWidgetsContainer.getContainer()); this.results.style({ height: searchResultContainerSize + 'px' }); this.tree.layout(searchResultContainerSize); } public layout(dimension: Dimension): void { this.size = dimension; this.reLayout(); } public getControl(): ITree { return this.tree; } public clearSearchResults(): void { this.viewModel.searchResult.clear(); this.showEmptyStage(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.searchWidget.clear(); this.viewModel.cancelSearch(); } public cancelSearch(): boolean { if (this.viewModel.cancelSearch()) { this.searchWidget.focus(); return true; } return false; } private selectTreeIfNotSelected(): void { if (this.tree.getInput()) { this.tree.DOMFocus(); let selection = this.tree.getSelection(); if (selection.length === 0) { this.tree.focusNext(); } } } private getSearchTextFromEditor(): string { if (!this.editorService.getActiveEditor()) { return null; } let editorControl: any = this.editorService.getActiveEditor().getControl(); if (!editorControl || !isFunction(editorControl.getEditorType) || editorControl.getEditorType() !== EditorType.ICodeEditor) { // Substitute for (editor instanceof ICodeEditor) return null; } let range = editorControl.getSelection(); if (range && !range.isEmpty() && range.startLineNumber === range.endLineNumber) { let searchText = editorControl.getModel().getLineContent(range.startLineNumber); searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1); return searchText; } return null; } private showsFileTypes(): boolean { return dom.hasClass(this.queryDetails, 'more'); } public toggleCaseSensitive(): void { this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive()); this.onQueryChanged(true, true); } public toggleWholeWords(): void { this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords()); this.onQueryChanged(true, true); } public toggleRegex(): void { this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex()); this.onQueryChanged(true, true); } public toggleFileTypes(moveFocus?: boolean, show?: boolean, skipLayout?: boolean, reverse?: boolean): void { let cls = 'more'; show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show); skipLayout = Boolean(skipLayout); if (show) { dom.addClass(this.queryDetails, cls); if (moveFocus) { if (reverse) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); } else { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); } } } else { dom.removeClass(this.queryDetails, cls); if (moveFocus) { this.searchWidget.focus(); } } if (!skipLayout && this.size) { this.layout(this.size); } } public searchInFolder(resource: URI): void { const workspace = this.contextService.getWorkspace(); if (!workspace) { return; } if (isEqual(workspace.resource.fsPath, resource.fsPath)) { this.inputPatternIncludes.setValue(''); this.searchWidget.focus(); return; } if (!this.showsFileTypes()) { this.toggleFileTypes(true, true); } const workspaceRelativePath = this.contextService.toWorkspaceRelativePath(resource); if (workspaceRelativePath) { this.inputPatternIncludes.setIsGlobPattern(false); this.inputPatternIncludes.setValue(workspaceRelativePath); this.searchWidget.focus(false); } } public onQueryChanged(rerunQuery: boolean, preserveFocus?: boolean): void { const isRegex = this.searchWidget.searchInput.getRegex(); const isWholeWords = this.searchWidget.searchInput.getWholeWords(); const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive(); const contentPattern = this.searchWidget.searchInput.getValue(); const patternExcludes = this.inputPatternExclusions.getValue().trim(); const exclusionsUsePattern = this.inputPatternExclusions.isGlobPattern(); const patternIncludes = this.inputPatternIncludes.getValue().trim(); const includesUsePattern = this.inputPatternIncludes.isGlobPattern(); const useIgnoreFiles = this.inputPatternExclusions.useIgnoreFiles(); // store memento this.viewletSettings['query.contentPattern'] = contentPattern; this.viewletSettings['query.regex'] = isRegex; this.viewletSettings['query.wholeWords'] = isWholeWords; this.viewletSettings['query.caseSensitive'] = isCaseSensitive; this.viewletSettings['query.folderExclusions'] = patternExcludes; this.viewletSettings['query.exclusionsUsePattern'] = exclusionsUsePattern; this.viewletSettings['query.folderIncludes'] = patternIncludes; this.viewletSettings['query.includesUsePattern'] = includesUsePattern; this.viewletSettings['query.useIgnoreFiles'] = useIgnoreFiles; if (!rerunQuery) { return; } if (contentPattern.length === 0) { return; } // Validate regex is OK if (isRegex) { let regExp: RegExp; try { regExp = new RegExp(contentPattern); } catch (e) { return; // malformed regex } if (strings.regExpLeadsToEndlessLoop(regExp)) { return; // endless regex } } let content = { pattern: contentPattern, isRegExp: isRegex, isCaseSensitive: isCaseSensitive, isWordMatch: isWholeWords }; let excludes: IExpression = this.inputPatternExclusions.getGlob(); let includes: IExpression = this.inputPatternIncludes.getGlob(); let options: IQueryOptions = { folderResources: this.contextService.hasWorkspace() ? [this.contextService.getWorkspace().resource] : [], extraFileResources: getOutOfWorkspaceEditorResources(this.editorGroupService, this.contextService), excludePattern: excludes, maxResults: SearchViewlet.MAX_TEXT_RESULTS, includePattern: includes, useIgnoreFiles }; this.onQueryTriggered(this.queryBuilder.text(content, options), patternExcludes, patternIncludes); if (!preserveFocus) { this.searchWidget.focus(false); // focus back to input field } } private autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void { let length = fileMatch.matches().length; if (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) { this.tree.expand(fileMatch).done(null, errors.onUnexpectedError); } else { this.tree.collapse(fileMatch).done(null, errors.onUnexpectedError); } } private onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void { this.viewModel.cancelSearch(); // Progress total is 100.0% for more progress bar granularity let progressTotal = 1000; let progressWorked = 0; let progressRunner = query.useRipgrep ? this.progressService.show(/*infinite=*/true) : this.progressService.show(progressTotal); this.loading = true; this.searchWidget.searchInput.clearMessage(); this.showEmptyStage(); let handledMatches: { [id: string]: boolean } = Object.create(null); let autoExpand = (alwaysExpandIfOneResult: boolean) => { // Auto-expand / collapse based on number of matches: // - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file // - expand file results if we have more than one file result and less than 10 matches on a file let matches = this.viewModel.searchResult.matches(); matches.forEach((match) => { if (handledMatches[match.id()]) { return; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile) } handledMatches[match.id()] = true; this.autoExpandFileMatch(match, alwaysExpandIfOneResult); }); }; let isDone = false; let onComplete = (completed?: ISearchComplete) => { isDone = true; // Complete up to 100% as needed if (completed && !query.useRipgrep) { progressRunner.worked(progressTotal - progressWorked); setTimeout(() => progressRunner.done(), 200); } else { progressRunner.done(); } this.onSearchResultsChanged().then(() => autoExpand(true)); this.viewModel.replaceString = this.searchWidget.getReplaceValue(); let hasResults = !this.viewModel.searchResult.isEmpty(); this.loading = false; this.actionRegistry['refresh'].enabled = true; this.actionRegistry['vs.tree.collapse'].enabled = hasResults; this.actionRegistry['clearSearchResults'].enabled = hasResults; if (completed && completed.limitHit) { this.searchWidget.searchInput.showMessage({ content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."), type: MessageType.WARNING }); } if (!hasResults) { let hasExcludes = !!excludePattern; let hasIncludes = !!includePattern; let message: string; if (!completed) { message = nls.localize('searchCanceled', "Search was canceled before any results could be found - "); } else if (hasIncludes && hasExcludes) { message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePattern, excludePattern); } else if (hasIncludes) { message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePattern); } else if (hasExcludes) { message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePattern); } else { message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions - "); } // Indicate as status to ARIA aria.status(message); this.tree.onHidden(); this.results.hide(); const div = this.clearMessage(); const p = $(div).p({ text: message }); if (!completed) { $(p).a({ 'class': ['pointer', 'prominent'], text: nls.localize('rerunSearch.message', "Search again") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.onQueryChanged(true); }); } else if (hasIncludes || hasExcludes) { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('rerunSearchInAll.message', "Search again in all files") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.inputPatternExclusions.setValue(''); this.inputPatternIncludes.setValue(''); this.onQueryChanged(true); }); } else { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openSettings.message', "Open Settings") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); if (this.contextService.hasWorkspace()) { this.preferencesService.openWorkspaceSettings().done(() => null, errors.onUnexpectedError); } else { this.preferencesService.openGlobalSettings().done(() => null, errors.onUnexpectedError); } }); } if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(div); } } else { this.viewModel.searchResult.toggleHighlights(true); // show highlights // Indicate final search result count for ARIA aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount())); } }; let onError = (e: any) => { if (errors.isPromiseCanceledError(e)) { onComplete(null); } else { this.loading = false; isDone = true; progressRunner.done(); this.messageService.show(2 /* ERROR */, e); } }; let total: number = 0; let worked: number = 0; let visibleMatches = 0; let onProgress = (p: ISearchProgressItem) => { // Progress if (p.total) { total = p.total; } if (p.worked) { worked = p.worked; } }; // Handle UI updates in an interval to show frequent progress and results let uiRefreshHandle = setInterval(() => { if (isDone) { window.clearInterval(uiRefreshHandle); return; } if (!query.useRipgrep) { // Progress bar update let fakeProgress = true; if (total > 0 && worked > 0) { let ratio = Math.round((worked / total) * progressTotal); if (ratio > progressWorked) { // never show less progress than what we have already progressRunner.worked(ratio - progressWorked); progressWorked = ratio; fakeProgress = false; } } // Fake progress up to 90%, or when actual progress beats it const fakeMax = 900; const fakeMultiplier = 12; if (fakeProgress && progressWorked < fakeMax) { // Linearly decrease the rate of fake progress. // 1 is the smallest allowed amount of progress. const fakeAmt = Math.round((fakeMax - progressWorked) / fakeMax * fakeMultiplier) || 1; progressWorked += fakeAmt; progressRunner.worked(fakeAmt); } } // Search result tree update const fileCount = this.viewModel.searchResult.fileCount(); if (visibleMatches !== fileCount) { visibleMatches = fileCount; this.tree.refresh().then(() => { autoExpand(false); }).done(null, errors.onUnexpectedError); this.updateSearchResultCount(); } if (fileCount > 0) { // since we have results now, enable some actions if (!this.actionRegistry['vs.tree.collapse'].enabled) { this.actionRegistry['vs.tree.collapse'].enabled = true; } } }, 100); this.searchWidget.setReplaceAllActionState(false); // this.replaceService.disposeAllReplacePreviews(); this.viewModel.search(query).done(onComplete, onError, query.useRipgrep ? undefined : onProgress); } private updateSearchResultCount(): void { const fileCount = this.viewModel.searchResult.fileCount(); const msgWasHidden = this.messages.isHidden(); if (fileCount > 0) { const div = this.clearMessage(); $(div).p({ text: this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount) }); if (msgWasHidden) { this.reLayout(); } } else if (!msgWasHidden) { this.messages.hide(); } } private buildResultCountMessage(resultCount: number, fileCount: number): string { if (resultCount === 1 && fileCount === 1) { return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount); } else if (resultCount === 1) { return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount); } else if (fileCount === 1) { return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount); } else { return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount); } } private searchWithoutFolderMessage(div: Builder): void { $(div).p({ text: nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ") }) .asContainer().a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openFolder', "Open Folder") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); const actionClass = env.isMacintosh ? OpenFileFolderAction : OpenFolderAction; const action = this.instantiationService.createInstance<string, string, IAction>(actionClass, actionClass.ID, actionClass.LABEL); this.actionRunner.run(action).done(() => { action.dispose(); }, err => { action.dispose(); errors.onUnexpectedError(err); }); }); } private showEmptyStage(): void { // disable 'result'-actions this.actionRegistry['refresh'].enabled = false; this.actionRegistry['vs.tree.collapse'].enabled = false; this.actionRegistry['clearSearchResults'].enabled = false; // clean up ui // this.replaceService.disposeAllReplacePreviews(); this.messages.hide(); this.results.show(); this.tree.onVisible(); this.currentSelectedFileMatch = null; } private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { if (!(lineMatch instanceof Match)) { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); return TPromise.as(true); } this.telemetryService.publicLog('searchResultChosen'); return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ? this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) : this.open(lineMatch, preserveFocus, sideBySide, pinned); } public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { let selection = this.getSelectionFrom(element); let resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource(); return this.editorService.openEditor({ resource: resource, options: { preserveFocus, pinned, selection, revealIfVisible: !sideBySide } }, sideBySide).then(editor => { if (editor && element instanceof Match && preserveFocus) { this.viewModel.searchResult.rangeHighlightDecorations.highlightRange({ resource, range: element.range() }, <ICommonCodeEditor>editor.getControl()); } else { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); } }, errors.onUnexpectedError); } private getSelectionFrom(element: FileMatchOrMatch): any { let match: Match = null; if (element instanceof Match) { match = element; } if (element instanceof FileMatch && element.count() > 0) { match = element.matches()[element.matches().length - 1]; } if (match) { let range = match.range(); if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) { let replaceString = match.replaceString; return { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.startLineNumber, endColumn: range.startColumn + replaceString.length }; } return range; } return void 0; } private onUntitledDidChangeDirty(resource: URI): void { if (!this.viewModel) { return; } // remove search results from this resource as it got disposed if (!this.untitledEditorService.isDirty(resource)) { let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (resource.toString() === matches[i].resource().toString()) { this.viewModel.searchResult.remove(matches[i]); } } } } private onFilesChanged(e: FileChangesEvent): void { if (!this.viewModel) { return; } let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (e.contains(matches[i].resource(), FileChangeType.DELETED)) { this.viewModel.searchResult.remove(matches[i]); } } } public getActions(): IAction[] { return [ this.actionRegistry['refresh'], this.actionRegistry['vs.tree.collapse'], this.actionRegistry['clearSearchResults'] ]; } public dispose(): void { this.isDisposed = true; this.toDispose = lifecycle.dispose(this.toDispose); if (this.tree) { this.tree.dispose(); } this.searchWidget.dispose(); this.inputPatternIncludes.dispose(); this.inputPatternExclusions.dispose(); this.viewModel.dispose(); super.dispose(); } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { let matchHighlightColor = theme.getColor(editorFindMatchHighlight); if (matchHighlightColor) { collector.addRule(`.search-viewlet .findInFileMatch { background-color: ${matchHighlightColor}; }`); collector.addRule(`.search-viewlet .highlight { background-color: ${matchHighlightColor}; }`); } });
src/vs/workbench/parts/search/browser/searchViewlet.ts
1
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.9520235657691956, 0.02669372782111168, 0.00016320229042321444, 0.00017327874957118183, 0.1502130776643753 ]
{ "id": 3, "code_window": [ "\n", "\t\treturn 'root';\n", "\t}\n", "\n", "\tpublic getChildren(tree: ITree, element: any): TPromise<any[]> {\n", "\t\tlet value: any[] = [];\n", "\n", "\t\tif (element instanceof FileMatch) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tprivate _getChildren(element: any): any[] {\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 44 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const { app, BrowserWindow, ipcMain } = require('electron'); const { tmpdir } = require('os'); const { join } = require('path'); const optimist = require('optimist') .describe('grep', 'only run tests matching <pattern>').string('grep').alias('grep', 'g').string('g') .describe('run', 'only run tests from <file>').string('run') .describe('debug', 'open dev tools, keep window open, reuse app data').string('debug'); const argv = optimist.argv; const { debug, grep, run } = argv; if (!debug) { app.setPath('userData', join(tmpdir(), `vscode-tests-${Date.now()}`)); } app.on('ready', () => { const win = new BrowserWindow({ height: 600, width: 800, webPreferences: { webSecurity: false } }); win.webContents.on('did-finish-load', () => { win.show(); if (debug) { win.webContents.openDevTools('right'); } win.webContents.send('run', { grep, run }); }); win.loadURL(`file://${__dirname}/renderer.html`); const _failures = []; ipcMain.on('fail', (e, test) => { _failures.push(test); process.stdout.write('X'); }); ipcMain.on('pass', () => { process.stdout.write('.'); }); ipcMain.on('done', () => { console.log(`\nDone with ${_failures.length} failures.\n`); for (const fail of _failures) { console.error(fail.title); console.error(fail.stack); console.error('\n'); } if (!debug) { app.exit(_failures.length > 0 ? 1 : 0); } }); });
test/electron/index.js
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0001746237394399941, 0.00017337608733214438, 0.00017253948317375034, 0.00017348324763588607, 7.997963962225185e-7 ]
{ "id": 3, "code_window": [ "\n", "\t\treturn 'root';\n", "\t}\n", "\n", "\tpublic getChildren(tree: ITree, element: any): TPromise<any[]> {\n", "\t\tlet value: any[] = [];\n", "\n", "\t\tif (element instanceof FileMatch) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tprivate _getChildren(element: any): any[] {\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 44 }
/*--------------------------------------------------------------------------------------------- * 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 { IDisposable, dispose } from 'vs/base/common/lifecycle'; import * as dom from 'vs/base/browser/dom'; import { ScrollableElementCreationOptions, ScrollableElementChangeOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; import { IOverviewRulerLayoutInfo, ScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; import { INewScrollPosition } from 'vs/editor/common/editorCommon'; import { ClassNames } from 'vs/editor/browser/editorBrowser'; import { ViewPart, PartFingerprint, PartFingerprints } from 'vs/editor/browser/view/viewPart'; import { Scrollable } from 'vs/base/common/scrollable'; import { ViewContext } from 'vs/editor/common/view/viewContext'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { RenderingContext, RestrictedRenderingContext } from 'vs/editor/common/view/renderingContext'; import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; export class EditorScrollbar extends ViewPart { private scrollable: Scrollable; private toDispose: IDisposable[]; private scrollbar: ScrollableElement; private scrollbarDomNode: FastDomNode<HTMLElement>; constructor( context: ViewContext, scrollable: Scrollable, linesContent: FastDomNode<HTMLElement>, viewDomNode: FastDomNode<HTMLElement>, overflowGuardDomNode: FastDomNode<HTMLElement> ) { super(context); this.toDispose = []; this.scrollable = scrollable; const viewInfo = this._context.configuration.editor.viewInfo; const configScrollbarOpts = viewInfo.scrollbar; let scrollbarOptions: ScrollableElementCreationOptions = { canUseTranslate3d: viewInfo.canUseTranslate3d, listenOnDomNode: viewDomNode.domNode, className: ClassNames.SCROLLABLE_ELEMENT + ' ' + viewInfo.theme, useShadows: false, lazyRender: true, vertical: configScrollbarOpts.vertical, horizontal: configScrollbarOpts.horizontal, verticalHasArrows: configScrollbarOpts.verticalHasArrows, horizontalHasArrows: configScrollbarOpts.horizontalHasArrows, verticalScrollbarSize: configScrollbarOpts.verticalScrollbarSize, verticalSliderSize: configScrollbarOpts.verticalSliderSize, horizontalScrollbarSize: configScrollbarOpts.horizontalScrollbarSize, horizontalSliderSize: configScrollbarOpts.horizontalSliderSize, handleMouseWheel: configScrollbarOpts.handleMouseWheel, arrowSize: configScrollbarOpts.arrowSize, mouseWheelScrollSensitivity: configScrollbarOpts.mouseWheelScrollSensitivity, }; this.scrollbar = new ScrollableElement(linesContent.domNode, scrollbarOptions, this.scrollable); PartFingerprints.write(this.scrollbar.getDomNode(), PartFingerprint.ScrollableElement); this.toDispose.push(this.scrollbar); this.scrollbarDomNode = createFastDomNode(this.scrollbar.getDomNode()); this.scrollbarDomNode.setPosition('absolute'); this._setLayout(); // When having a zone widget that calls .focus() on one of its dom elements, // the browser will try desperately to reveal that dom node, unexpectedly // changing the .scrollTop of this.linesContent let onBrowserDesperateReveal = (domNode: HTMLElement, lookAtScrollTop: boolean, lookAtScrollLeft: boolean) => { const scrollState = this.scrollable.getState(); let newScrollPosition: INewScrollPosition = {}; if (lookAtScrollTop) { let deltaTop = domNode.scrollTop; if (deltaTop) { newScrollPosition.scrollTop = scrollState.scrollTop + deltaTop; domNode.scrollTop = 0; } } if (lookAtScrollLeft) { let deltaLeft = domNode.scrollLeft; if (deltaLeft) { newScrollPosition.scrollLeft = scrollState.scrollLeft + deltaLeft; domNode.scrollLeft = 0; } } this.scrollable.updateState(newScrollPosition); }; // I've seen this happen both on the view dom node & on the lines content dom node. this.toDispose.push(dom.addDisposableListener(viewDomNode.domNode, 'scroll', (e: Event) => onBrowserDesperateReveal(viewDomNode.domNode, true, true))); this.toDispose.push(dom.addDisposableListener(linesContent.domNode, 'scroll', (e: Event) => onBrowserDesperateReveal(linesContent.domNode, true, false))); this.toDispose.push(dom.addDisposableListener(overflowGuardDomNode.domNode, 'scroll', (e: Event) => onBrowserDesperateReveal(overflowGuardDomNode.domNode, true, false))); } public dispose(): void { this.toDispose = dispose(this.toDispose); } private _setLayout(): void { const layoutInfo = this._context.configuration.editor.layoutInfo; this.scrollbarDomNode.setLeft(layoutInfo.contentLeft); this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimapWidth); this.scrollbarDomNode.setHeight(layoutInfo.contentHeight); } public getOverviewRulerLayoutInfo(): IOverviewRulerLayoutInfo { return this.scrollbar.getOverviewRulerLayoutInfo(); } public getDomNode(): HTMLElement { return this.scrollbarDomNode.domNode; } public delegateVerticalScrollbarMouseDown(browserEvent: MouseEvent): void { this.scrollbar.delegateVerticalScrollbarMouseDown(browserEvent); } public getVerticalSliderVerticalCenter(): number { return this.scrollbar.getVerticalSliderVerticalCenter(); } // --- begin event handlers public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { const viewInfo = this._context.configuration.editor.viewInfo; this.scrollbar.updateClassName(ClassNames.SCROLLABLE_ELEMENT + ' ' + viewInfo.theme); if (e.viewInfo.scrollbar || e.viewInfo.canUseTranslate3d) { let newOpts: ScrollableElementChangeOptions = { canUseTranslate3d: viewInfo.canUseTranslate3d, handleMouseWheel: viewInfo.scrollbar.handleMouseWheel, mouseWheelScrollSensitivity: viewInfo.scrollbar.mouseWheelScrollSensitivity }; this.scrollbar.updateOptions(newOpts); } if (e.layoutInfo) { this._setLayout(); } return true; } public onCursorPositionChanged(e: viewEvents.ViewCursorPositionChangedEvent): boolean { return false; } public onCursorSelectionChanged(e: viewEvents.ViewCursorSelectionChangedEvent): boolean { return false; } public onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean { return false; } public onFlushed(e: viewEvents.ViewFlushedEvent): boolean { return false; } public onFocusChanged(e: viewEvents.ViewFocusChangedEvent): boolean { return false; } public onLineMappingChanged(e: viewEvents.ViewLineMappingChangedEvent): boolean { return false; } public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean { return false; } public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean { return false; } public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean { return false; } public onRevealRangeRequest(e: viewEvents.ViewRevealRangeRequestEvent): boolean { return false; } public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean { return true; } public onScrollRequest(e: viewEvents.ViewScrollRequestEvent): boolean { return false; } public onTokensChanged(e: viewEvents.ViewTokensChangedEvent): boolean { return false; } public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean { return false; } // --- end event handlers public prepareRender(ctx: RenderingContext): void { // Nothing to do } public render(ctx: RestrictedRenderingContext): void { this.scrollbar.renderNow(); } }
src/vs/editor/browser/viewParts/editorScrollbar/editorScrollbar.ts
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.000175393681274727, 0.00017135079542640597, 0.0001646134041948244, 0.00017189905338454992, 0.000003100287131019286 ]
{ "id": 3, "code_window": [ "\n", "\t\treturn 'root';\n", "\t}\n", "\n", "\tpublic getChildren(tree: ITree, element: any): TPromise<any[]> {\n", "\t\tlet value: any[] = [];\n", "\n", "\t\tif (element instanceof FileMatch) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tprivate _getChildren(element: any): any[] {\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 44 }
/*--------------------------------------------------------------------------------------------- * 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. { "araLabelEditorActions": "編輯器動作", "close": "關閉", "closeAll": "全部關閉", "closeOthers": "關閉其他", "closeRight": "關到右側", "keepOpen": "保持開啟", "showOpenedEditors": "顯示開啟的編輯器" }
i18n/cht/src/vs/workbench/browser/parts/editor/titleControl.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00017529705655761063, 0.00017135596135631204, 0.00016741486615501344, 0.00017135596135631204, 0.0000039410952012985945 ]
{ "id": 4, "code_window": [ "\t\tif (element instanceof FileMatch) {\n", "\t\t\tvalue = element.matches();\n", "\t\t} else if (element instanceof SearchResult) {\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\treturn element.matches();\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * 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/searchviewlet'; import nls = require('vs/nls'); import { TPromise } from 'vs/base/common/winjs.base'; import { Emitter, debounceEvent } from 'vs/base/common/event'; import { EditorType, ICommonCodeEditor } from 'vs/editor/common/editorCommon'; import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import aria = require('vs/base/browser/ui/aria/aria'); import { IExpression } from 'vs/base/common/glob'; import env = require('vs/base/common/platform'); import { isFunction } from 'vs/base/common/types'; import { Delayer } from 'vs/base/common/async'; import URI from 'vs/base/common/uri'; import strings = require('vs/base/common/strings'); import dom = require('vs/base/browser/dom'); import { IAction, Action } from 'vs/base/common/actions'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import { FindInput } from 'vs/base/browser/ui/findinput/findInput'; import { ITree } from 'vs/base/parts/tree/browser/tree'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { Scope } from 'vs/workbench/common/memento'; import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { getOutOfWorkspaceEditorResources } from 'vs/workbench/common/editor'; import { FileChangeType, FileChangesEvent, IFileService, isEqual } from 'vs/platform/files/common/files'; import { Viewlet } from 'vs/workbench/browser/viewlet'; import { Match, FileMatch, SearchModel, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService } from 'vs/workbench/parts/search/common/searchModel'; import { QueryBuilder } from 'vs/workbench/parts/search/common/searchQuery'; import { MessageType, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { getExcludes, ISearchProgressItem, ISearchComplete, ISearchQuery, IQueryOptions, ISearchConfiguration } from 'vs/platform/search/common/search'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IMessageService } from 'vs/platform/message/common/message'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { KeyCode } from 'vs/base/common/keyCodes'; import { PatternInputWidget } from 'vs/workbench/parts/search/browser/patternInputWidget'; import { SearchRenderer, SearchDataSource, SearchSorter, SearchController, SearchAccessibilityProvider, SearchFilter } from 'vs/workbench/parts/search/browser/searchResultsView'; import { SearchWidget } from 'vs/workbench/parts/search/browser/searchWidget'; import { RefreshAction, CollapseAllAction, ClearSearchResultsAction, ConfigureGlobalExclusionsAction } from 'vs/workbench/parts/search/browser/searchActions'; import { IReplaceService } from 'vs/workbench/parts/search/common/replace'; import Severity from 'vs/base/common/severity'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { OpenFolderAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/fileActions'; import * as Constants from 'vs/workbench/parts/search/common/constants'; import { IListService } from 'vs/platform/list/browser/listService'; import { IThemeService, ITheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { editorFindMatchHighlight } from 'vs/platform/theme/common/colorRegistry'; export class SearchViewlet extends Viewlet { private static MAX_TEXT_RESULTS = 2048; private static SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace'; private isDisposed: boolean; private toDispose: lifecycle.IDisposable[]; private loading: boolean; private queryBuilder: QueryBuilder; private viewModel: SearchModel; private callOnModelChange: lifecycle.IDisposable[]; private viewletVisible: IContextKey<boolean>; private inputBoxFocussed: IContextKey<boolean>; private actionRegistry: { [key: string]: Action; }; private tree: ITree; private viewletSettings: any; private domNode: Builder; private messages: Builder; private searchWidgetsContainer: Builder; private searchWidget: SearchWidget; private size: Dimension; private queryDetails: HTMLElement; private inputPatternExclusions: PatternInputWidget; private inputPatternGlobalExclusions: InputBox; private inputPatternGlobalExclusionsContainer: Builder; private inputPatternIncludes: PatternInputWidget; private results: Builder; private currentSelectedFileMatch: FileMatch; private selectCurrentMatchEmitter: Emitter<string>; private delayedRefresh: Delayer<void>; constructor( @ITelemetryService telemetryService: ITelemetryService, @IFileService private fileService: IFileService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IProgressService private progressService: IProgressService, @IMessageService private messageService: IMessageService, @IStorageService private storageService: IStorageService, @IContextViewService private contextViewService: IContextViewService, @IInstantiationService private instantiationService: IInstantiationService, @IConfigurationService private configurationService: IConfigurationService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService, @IContextKeyService private contextKeyService: IContextKeyService, @IKeybindingService private keybindingService: IKeybindingService, @IReplaceService private replaceService: IReplaceService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IPreferencesService private preferencesService: IPreferencesService, @IListService private listService: IListService, @IThemeService protected themeService: IThemeService ) { super(Constants.VIEWLET_ID, telemetryService, themeService); this.toDispose = []; this.viewletVisible = Constants.SearchViewletVisibleKey.bindTo(contextKeyService); this.inputBoxFocussed = Constants.InputBoxFocussedKey.bindTo(this.contextKeyService); this.callOnModelChange = []; this.queryBuilder = this.instantiationService.createInstance(QueryBuilder); this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE); this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e))); this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); this.selectCurrentMatchEmitter = new Emitter<string>(); debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true) (() => this.selectCurrentMatch()); this.delayedRefresh = new Delayer<void>(250); } private onConfigurationUpdated(configuration: any): void { this.updateGlobalPatternExclusions(configuration); } public create(parent: Builder): TPromise<void> { super.create(parent); this.viewModel = this.searchWorkbenchService.searchModel; let builder: Builder; this.domNode = parent.div({ 'class': 'search-viewlet' }, (div) => { builder = div; }); builder.div({ 'class': ['search-widgets-container'] }, (div) => { this.searchWidgetsContainer = div; }); this.createSearchWidget(this.searchWidgetsContainer); let filePatterns = this.viewletSettings['query.filePatterns'] || ''; let patternExclusions = this.viewletSettings['query.folderExclusions'] || ''; let exclusionsUsePattern = this.viewletSettings['query.exclusionsUsePattern']; let includesUsePattern = this.viewletSettings['query.includesUsePattern']; let patternIncludes = this.viewletSettings['query.folderIncludes'] || ''; let useIgnoreFiles = this.viewletSettings['query.useIgnoreFiles']; this.queryDetails = this.searchWidgetsContainer.div({ 'class': ['query-details'] }, (builder) => { builder.div({ 'class': 'more', 'tabindex': 0, 'role': 'button', 'title': nls.localize('moreSearch', "Toggle Search Details") }) .on(dom.EventType.CLICK, (e) => { dom.EventHelper.stop(e); this.toggleFileTypes(true); }).on(dom.EventType.KEY_UP, (e: KeyboardEvent) => { let event = new StandardKeyboardEvent(e); if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { dom.EventHelper.stop(e); this.toggleFileTypes(); } }); //folder includes list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.includes', "files to include"); builder.element('h4', { text: title }); this.inputPatternIncludes = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.includes', 'Search Include Patterns') }); this.inputPatternIncludes.setIsGlobPattern(includesUsePattern); this.inputPatternIncludes.setValue(patternIncludes); this.inputPatternIncludes .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternIncludes.inputFocusTracker); }); //pattern exclusion list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.excludes', "files to exclude"); builder.element('h4', { text: title }); const configuration = this.configurationService.getConfiguration<ISearchConfiguration>(); this.inputPatternExclusions = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns') }, configuration.search.useRipgrep); this.inputPatternExclusions.setIsGlobPattern(exclusionsUsePattern); this.inputPatternExclusions.setValue(patternExclusions); this.inputPatternExclusions.setUseIgnoreFiles(useIgnoreFiles); this.inputPatternExclusions .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternExclusions.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternExclusions.inputFocusTracker); }); // add hint if we have global exclusion this.inputPatternGlobalExclusionsContainer = builder.div({ 'class': 'file-types global-exclude disabled' }, (builder) => { let title = nls.localize('global.searchScope.folders', "files excluded through settings"); builder.element('h4', { text: title }); this.inputPatternGlobalExclusions = new InputBox(builder.getContainer(), this.contextViewService, { actions: [this.instantiationService.createInstance(ConfigureGlobalExclusionsAction)], ariaLabel: nls.localize('label.global.excludes', 'Configured Search Exclude Patterns') }); this.inputPatternGlobalExclusions.inputElement.readOnly = true; $(this.inputPatternGlobalExclusions.inputElement).attr('aria-readonly', 'true'); $(this.inputPatternGlobalExclusions.inputElement).addClass('disabled'); }).hide(); }).getHTMLElement(); this.messages = builder.div({ 'class': 'messages' }).hide().clone(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.createSearchResultsView(builder); this.actionRegistry = <any>{}; let actions: Action[] = [new CollapseAllAction(this), new RefreshAction(this), new ClearSearchResultsAction(this)]; actions.forEach((action) => { this.actionRegistry[action.id] = action; }); if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '') { this.toggleFileTypes(true, true, true); } this.updateGlobalPatternExclusions(this.configurationService.getConfiguration<ISearchConfiguration>()); this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event))); return TPromise.as(null); } public get searchAndReplaceWidget(): SearchWidget { return this.searchWidget; } private createSearchWidget(builder: Builder): void { let contentPattern = this.viewletSettings['query.contentPattern'] || ''; let isRegex = this.viewletSettings['query.regex'] === true; let isWholeWords = this.viewletSettings['query.wholeWords'] === true; let isCaseSensitive = this.viewletSettings['query.caseSensitive'] === true; this.searchWidget = new SearchWidget(builder, this.contextViewService, { value: contentPattern, isRegex: isRegex, isCaseSensitive: isCaseSensitive, isWholeWords: isWholeWords }, this.contextKeyService, this.keybindingService, this.instantiationService); if (this.storageService.getBoolean(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) { this.searchWidget.toggleReplace(true); } this.toUnbind.push(this.searchWidget); this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh))); this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch())); this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard))); this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled())); this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => { this.viewModel.replaceActive = state; this.tree.refresh(); })); this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => { this.viewModel.replaceString = this.searchWidget.getReplaceValue(); this.delayedRefresh.trigger(() => this.tree.refresh()); })); this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll())); this.trackInputBox(this.searchWidget.searchInputFocusTracker); this.trackInputBox(this.searchWidget.replaceInputFocusTracker); } private trackInputBox(inputFocusTracker: dom.IFocusTracker): void { this.toUnbind.push(inputFocusTracker.addFocusListener(() => { this.inputBoxFocussed.set(true); })); this.toUnbind.push(inputFocusTracker.addBlurListener(() => { this.inputBoxFocussed.set(this.searchWidget.searchInputHasFocus() || this.searchWidget.replaceInputHasFocus() || this.inputPatternIncludes.inputHasFocus() || this.inputPatternExclusions.inputHasFocus()); })); } private onReplaceToggled(): void { this.layout(this.size); this.storageService.store(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, this.searchAndReplaceWidget.isReplaceShown(), StorageScope.WORKSPACE); } private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> { return this.refreshTree(event).then(() => { this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty()); this.updateSearchResultCount(); }); } private refreshTree(event?: IChangeEvent): TPromise<any> { if (!event) { return this.tree.refresh(this.viewModel.searchResult); } if (event.added || event.removed) { return this.tree.refresh(this.viewModel.searchResult).then(() => { if (event.added) { event.elements.forEach(element => { this.autoExpandFileMatch(element, true); }); } }); } else { if (event.elements.length === 1) { return this.tree.refresh(event.elements[0]); } else { return this.tree.refresh(event.elements); } } } private replaceAll(): void { if (this.viewModel.searchResult.count() === 0) { return; } let progressRunner = this.progressService.show(100); let occurrences = this.viewModel.searchResult.count(); let fileCount = this.viewModel.searchResult.fileCount(); let replaceValue = this.searchWidget.getReplaceValue() || ''; let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue); let confirmation = { title: nls.localize('replaceAll.confirmation.title', "Replace All"), message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue), primaryButton: nls.localize('replaceAll.confirm.button', "Replace") }; if (this.messageService.confirm(confirmation)) { this.searchWidget.setReplaceAllActionState(false); this.viewModel.searchResult.replaceAll(progressRunner).then(() => { progressRunner.done(); this.clearMessage() .p({ text: afterReplaceAllMessage }); }, (error) => { progressRunner.done(); errors.isPromiseCanceledError(error); this.messageService.show(Severity.Error, error); }); } } private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount); } private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount); } private clearMessage(): Builder { return this.messages.empty().show() .asContainer().div({ 'class': 'message' }) .asContainer(); } private createSearchResultsView(builder: Builder): void { builder.div({ 'class': 'results' }, (div) => { this.results = div; this.results.addClass('show-file-icons'); let dataSource = new SearchDataSource(); let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this); this.tree = new Tree(div.getHTMLElement(), { dataSource: dataSource, renderer: renderer, sorter: new SearchSorter(), filter: new SearchFilter(), controller: new SearchController(this, this.instantiationService), accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider) }, { ariaLabel: nls.localize('treeAriaLabel', "Search Results"), keyboardSupport: false }); this.tree.setInput(this.viewModel.searchResult); this.toUnbind.push(renderer); this.toUnbind.push(this.listService.register(this.tree)); let focusToSelectionDelayHandle: number; let lastFocusToSelection: number; const focusToSelection = (originalEvent: KeyboardEvent | MouseEvent) => { lastFocusToSelection = Date.now(); const focus = this.tree.getFocus(); let payload: any; if (focus instanceof Match) { payload = { origin: 'keyboard', originalEvent, preserveFocus: true }; } this.tree.setSelection([focus], payload); focusToSelectionDelayHandle = void 0; }; this.toUnbind.push(this.tree.addListener2('focus', (event: any) => { let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; // debounce setting selection so that we are not too quickly opening // when the user is pressing and holding the key to move focus if (focusToSelectionDelayHandle || (Date.now() - lastFocusToSelection <= 75)) { window.clearTimeout(focusToSelectionDelayHandle); focusToSelectionDelayHandle = window.setTimeout(() => focusToSelection(originalEvent), 300); } else { focusToSelection(originalEvent); } } })); this.toUnbind.push(this.tree.addListener2('selection', (event: any) => { let element: any; let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { element = this.tree.getFocus(); } else { element = event.selection[0]; } let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; let doubleClick = (event.payload && event.payload.origin === 'mouse' && originalEvent && originalEvent.detail === 2); if (doubleClick && originalEvent) { originalEvent.preventDefault(); // focus moves to editor, we need to prevent default } let sideBySide = (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey)); let focusEditor = (keyboard && (!event.payload || !event.payload.preserveFocus)) || doubleClick; if (element instanceof Match) { let selectedMatch: Match = element; if (this.currentSelectedFileMatch) { this.currentSelectedFileMatch.setSelectedMatch(null); } this.currentSelectedFileMatch = selectedMatch.parent(); this.currentSelectedFileMatch.setSelectedMatch(selectedMatch); if (!event.payload.preventEditorOpen) { this.onFocus(selectedMatch, !focusEditor, sideBySide, doubleClick); } } })); }); } private updateGlobalPatternExclusions(configuration: ISearchConfiguration): void { if (this.inputPatternGlobalExclusionsContainer) { let excludes = getExcludes(configuration); if (excludes) { let exclusions = Object.getOwnPropertyNames(excludes).filter(exclude => excludes[exclude] === true || typeof excludes[exclude].when === 'string').map(exclude => { if (excludes[exclude] === true) { return exclude; } return nls.localize('globLabel', "{0} when {1}", exclude, excludes[exclude].when); }); if (exclusions.length) { const values = exclusions.join(', '); this.inputPatternGlobalExclusions.value = values; this.inputPatternGlobalExclusions.inputElement.title = values; this.inputPatternGlobalExclusionsContainer.show(); } else { this.inputPatternGlobalExclusionsContainer.hide(); } } } } public selectCurrentMatch(): void { const focused = this.tree.getFocus(); const eventPayload = { focusEditor: true }; this.tree.setSelection([focused], eventPayload); } public selectNextMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); // Expand the initial selected node, if needed if (selected instanceof FileMatch) { if (!this.tree.isExpanded(selected)) { this.tree.expand(selected); } } let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let next = navigator.next(); if (!next) { // Reached the end - get a new navigator from the root. // .first and .last only work when subTreeOnly = true. Maybe there's a simpler way. navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); next = navigator.first(); } // Expand and go past FileMatch nodes if (!(next instanceof Match)) { if (!this.tree.isExpanded(next)) { this.tree.expand(next); } // Select the FileMatch's first child next = navigator.next(); } // Reveal the newly selected element const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(next, eventPayload); this.tree.setSelection([next], eventPayload); this.tree.reveal(next); this.selectCurrentMatchEmitter.fire(); } public selectPreviousMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let prev = navigator.previous(); // Expand and go past FileMatch nodes if (!(prev instanceof Match)) { prev = navigator.previous(); if (!prev) { // Wrap around. Get a new tree starting from the root navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); prev = navigator.last(); // This is complicated because .last will set the navigator to the last FileMatch, // so expand it and FF to its last child this.tree.expand(prev); let tmp; while (tmp = navigator.next()) { prev = tmp; } } if (!(prev instanceof Match)) { // There is a second non-Match result, which must be a collapsed FileMatch. // Expand it then select its last child. navigator.next(); this.tree.expand(prev); prev = navigator.previous(); } } // Reveal the newly selected element if (prev) { const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(prev, eventPayload); this.tree.setSelection([prev], eventPayload); this.tree.reveal(prev); this.selectCurrentMatchEmitter.fire(); } } public setVisible(visible: boolean): TPromise<void> { let promise: TPromise<void>; this.viewletVisible.set(visible); if (visible) { promise = super.setVisible(visible); this.tree.onVisible(); } else { this.tree.onHidden(); promise = super.setVisible(visible); } // Enable highlights if there are searchresults if (this.viewModel) { this.viewModel.searchResult.toggleHighlights(visible); } // Open focused element from results in case the editor area is otherwise empty if (visible && !this.editorService.getActiveEditor()) { let focus = this.tree.getFocus(); if (focus) { this.onFocus(focus, true); } } return promise; } public focus(): void { super.focus(); let selectedText = this.getSearchTextFromEditor(); if (selectedText) { this.searchWidget.searchInput.setValue(selectedText); } this.searchWidget.focus(); } public focusNextInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { if (this.searchWidget.isReplaceShown()) { this.searchWidget.focus(true, true); } else { this.moveFocusFromSearchOrReplace(); } return; } if (this.searchWidget.replaceInputHasFocus()) { this.moveFocusFromSearchOrReplace(); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.selectTreeIfNotSelected(); return; } } private moveFocusFromSearchOrReplace() { if (this.showsFileTypes()) { this.toggleFileTypes(true, this.showsFileTypes()); } else { this.selectTreeIfNotSelected(); } } public focusPreviousInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { return; } if (this.searchWidget.replaceInputHasFocus()) { this.searchWidget.focus(true); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.searchWidget.focus(true, true); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); return; } } public moveFocusFromResults(): void { if (this.showsFileTypes()) { this.toggleFileTypes(true, true, false, true); } else { this.searchWidget.focus(true, true); } } private reLayout(): void { if (this.isDisposed) { return; } this.searchWidget.setWidth(this.size.width - 25 /* container margin */); this.inputPatternExclusions.setWidth(this.size.width - 28 /* container margin */); this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */); this.inputPatternGlobalExclusions.width = this.size.width - 28 /* container margin */ - 24 /* actions */; const messagesSize = this.messages.isHidden() ? 0 : dom.getTotalHeight(this.messages.getHTMLElement()); const searchResultContainerSize = this.size.height - messagesSize - dom.getTotalHeight(this.searchWidgetsContainer.getContainer()); this.results.style({ height: searchResultContainerSize + 'px' }); this.tree.layout(searchResultContainerSize); } public layout(dimension: Dimension): void { this.size = dimension; this.reLayout(); } public getControl(): ITree { return this.tree; } public clearSearchResults(): void { this.viewModel.searchResult.clear(); this.showEmptyStage(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.searchWidget.clear(); this.viewModel.cancelSearch(); } public cancelSearch(): boolean { if (this.viewModel.cancelSearch()) { this.searchWidget.focus(); return true; } return false; } private selectTreeIfNotSelected(): void { if (this.tree.getInput()) { this.tree.DOMFocus(); let selection = this.tree.getSelection(); if (selection.length === 0) { this.tree.focusNext(); } } } private getSearchTextFromEditor(): string { if (!this.editorService.getActiveEditor()) { return null; } let editorControl: any = this.editorService.getActiveEditor().getControl(); if (!editorControl || !isFunction(editorControl.getEditorType) || editorControl.getEditorType() !== EditorType.ICodeEditor) { // Substitute for (editor instanceof ICodeEditor) return null; } let range = editorControl.getSelection(); if (range && !range.isEmpty() && range.startLineNumber === range.endLineNumber) { let searchText = editorControl.getModel().getLineContent(range.startLineNumber); searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1); return searchText; } return null; } private showsFileTypes(): boolean { return dom.hasClass(this.queryDetails, 'more'); } public toggleCaseSensitive(): void { this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive()); this.onQueryChanged(true, true); } public toggleWholeWords(): void { this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords()); this.onQueryChanged(true, true); } public toggleRegex(): void { this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex()); this.onQueryChanged(true, true); } public toggleFileTypes(moveFocus?: boolean, show?: boolean, skipLayout?: boolean, reverse?: boolean): void { let cls = 'more'; show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show); skipLayout = Boolean(skipLayout); if (show) { dom.addClass(this.queryDetails, cls); if (moveFocus) { if (reverse) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); } else { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); } } } else { dom.removeClass(this.queryDetails, cls); if (moveFocus) { this.searchWidget.focus(); } } if (!skipLayout && this.size) { this.layout(this.size); } } public searchInFolder(resource: URI): void { const workspace = this.contextService.getWorkspace(); if (!workspace) { return; } if (isEqual(workspace.resource.fsPath, resource.fsPath)) { this.inputPatternIncludes.setValue(''); this.searchWidget.focus(); return; } if (!this.showsFileTypes()) { this.toggleFileTypes(true, true); } const workspaceRelativePath = this.contextService.toWorkspaceRelativePath(resource); if (workspaceRelativePath) { this.inputPatternIncludes.setIsGlobPattern(false); this.inputPatternIncludes.setValue(workspaceRelativePath); this.searchWidget.focus(false); } } public onQueryChanged(rerunQuery: boolean, preserveFocus?: boolean): void { const isRegex = this.searchWidget.searchInput.getRegex(); const isWholeWords = this.searchWidget.searchInput.getWholeWords(); const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive(); const contentPattern = this.searchWidget.searchInput.getValue(); const patternExcludes = this.inputPatternExclusions.getValue().trim(); const exclusionsUsePattern = this.inputPatternExclusions.isGlobPattern(); const patternIncludes = this.inputPatternIncludes.getValue().trim(); const includesUsePattern = this.inputPatternIncludes.isGlobPattern(); const useIgnoreFiles = this.inputPatternExclusions.useIgnoreFiles(); // store memento this.viewletSettings['query.contentPattern'] = contentPattern; this.viewletSettings['query.regex'] = isRegex; this.viewletSettings['query.wholeWords'] = isWholeWords; this.viewletSettings['query.caseSensitive'] = isCaseSensitive; this.viewletSettings['query.folderExclusions'] = patternExcludes; this.viewletSettings['query.exclusionsUsePattern'] = exclusionsUsePattern; this.viewletSettings['query.folderIncludes'] = patternIncludes; this.viewletSettings['query.includesUsePattern'] = includesUsePattern; this.viewletSettings['query.useIgnoreFiles'] = useIgnoreFiles; if (!rerunQuery) { return; } if (contentPattern.length === 0) { return; } // Validate regex is OK if (isRegex) { let regExp: RegExp; try { regExp = new RegExp(contentPattern); } catch (e) { return; // malformed regex } if (strings.regExpLeadsToEndlessLoop(regExp)) { return; // endless regex } } let content = { pattern: contentPattern, isRegExp: isRegex, isCaseSensitive: isCaseSensitive, isWordMatch: isWholeWords }; let excludes: IExpression = this.inputPatternExclusions.getGlob(); let includes: IExpression = this.inputPatternIncludes.getGlob(); let options: IQueryOptions = { folderResources: this.contextService.hasWorkspace() ? [this.contextService.getWorkspace().resource] : [], extraFileResources: getOutOfWorkspaceEditorResources(this.editorGroupService, this.contextService), excludePattern: excludes, maxResults: SearchViewlet.MAX_TEXT_RESULTS, includePattern: includes, useIgnoreFiles }; this.onQueryTriggered(this.queryBuilder.text(content, options), patternExcludes, patternIncludes); if (!preserveFocus) { this.searchWidget.focus(false); // focus back to input field } } private autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void { let length = fileMatch.matches().length; if (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) { this.tree.expand(fileMatch).done(null, errors.onUnexpectedError); } else { this.tree.collapse(fileMatch).done(null, errors.onUnexpectedError); } } private onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void { this.viewModel.cancelSearch(); // Progress total is 100.0% for more progress bar granularity let progressTotal = 1000; let progressWorked = 0; let progressRunner = query.useRipgrep ? this.progressService.show(/*infinite=*/true) : this.progressService.show(progressTotal); this.loading = true; this.searchWidget.searchInput.clearMessage(); this.showEmptyStage(); let handledMatches: { [id: string]: boolean } = Object.create(null); let autoExpand = (alwaysExpandIfOneResult: boolean) => { // Auto-expand / collapse based on number of matches: // - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file // - expand file results if we have more than one file result and less than 10 matches on a file let matches = this.viewModel.searchResult.matches(); matches.forEach((match) => { if (handledMatches[match.id()]) { return; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile) } handledMatches[match.id()] = true; this.autoExpandFileMatch(match, alwaysExpandIfOneResult); }); }; let isDone = false; let onComplete = (completed?: ISearchComplete) => { isDone = true; // Complete up to 100% as needed if (completed && !query.useRipgrep) { progressRunner.worked(progressTotal - progressWorked); setTimeout(() => progressRunner.done(), 200); } else { progressRunner.done(); } this.onSearchResultsChanged().then(() => autoExpand(true)); this.viewModel.replaceString = this.searchWidget.getReplaceValue(); let hasResults = !this.viewModel.searchResult.isEmpty(); this.loading = false; this.actionRegistry['refresh'].enabled = true; this.actionRegistry['vs.tree.collapse'].enabled = hasResults; this.actionRegistry['clearSearchResults'].enabled = hasResults; if (completed && completed.limitHit) { this.searchWidget.searchInput.showMessage({ content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."), type: MessageType.WARNING }); } if (!hasResults) { let hasExcludes = !!excludePattern; let hasIncludes = !!includePattern; let message: string; if (!completed) { message = nls.localize('searchCanceled', "Search was canceled before any results could be found - "); } else if (hasIncludes && hasExcludes) { message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePattern, excludePattern); } else if (hasIncludes) { message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePattern); } else if (hasExcludes) { message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePattern); } else { message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions - "); } // Indicate as status to ARIA aria.status(message); this.tree.onHidden(); this.results.hide(); const div = this.clearMessage(); const p = $(div).p({ text: message }); if (!completed) { $(p).a({ 'class': ['pointer', 'prominent'], text: nls.localize('rerunSearch.message', "Search again") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.onQueryChanged(true); }); } else if (hasIncludes || hasExcludes) { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('rerunSearchInAll.message', "Search again in all files") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.inputPatternExclusions.setValue(''); this.inputPatternIncludes.setValue(''); this.onQueryChanged(true); }); } else { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openSettings.message', "Open Settings") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); if (this.contextService.hasWorkspace()) { this.preferencesService.openWorkspaceSettings().done(() => null, errors.onUnexpectedError); } else { this.preferencesService.openGlobalSettings().done(() => null, errors.onUnexpectedError); } }); } if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(div); } } else { this.viewModel.searchResult.toggleHighlights(true); // show highlights // Indicate final search result count for ARIA aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount())); } }; let onError = (e: any) => { if (errors.isPromiseCanceledError(e)) { onComplete(null); } else { this.loading = false; isDone = true; progressRunner.done(); this.messageService.show(2 /* ERROR */, e); } }; let total: number = 0; let worked: number = 0; let visibleMatches = 0; let onProgress = (p: ISearchProgressItem) => { // Progress if (p.total) { total = p.total; } if (p.worked) { worked = p.worked; } }; // Handle UI updates in an interval to show frequent progress and results let uiRefreshHandle = setInterval(() => { if (isDone) { window.clearInterval(uiRefreshHandle); return; } if (!query.useRipgrep) { // Progress bar update let fakeProgress = true; if (total > 0 && worked > 0) { let ratio = Math.round((worked / total) * progressTotal); if (ratio > progressWorked) { // never show less progress than what we have already progressRunner.worked(ratio - progressWorked); progressWorked = ratio; fakeProgress = false; } } // Fake progress up to 90%, or when actual progress beats it const fakeMax = 900; const fakeMultiplier = 12; if (fakeProgress && progressWorked < fakeMax) { // Linearly decrease the rate of fake progress. // 1 is the smallest allowed amount of progress. const fakeAmt = Math.round((fakeMax - progressWorked) / fakeMax * fakeMultiplier) || 1; progressWorked += fakeAmt; progressRunner.worked(fakeAmt); } } // Search result tree update const fileCount = this.viewModel.searchResult.fileCount(); if (visibleMatches !== fileCount) { visibleMatches = fileCount; this.tree.refresh().then(() => { autoExpand(false); }).done(null, errors.onUnexpectedError); this.updateSearchResultCount(); } if (fileCount > 0) { // since we have results now, enable some actions if (!this.actionRegistry['vs.tree.collapse'].enabled) { this.actionRegistry['vs.tree.collapse'].enabled = true; } } }, 100); this.searchWidget.setReplaceAllActionState(false); // this.replaceService.disposeAllReplacePreviews(); this.viewModel.search(query).done(onComplete, onError, query.useRipgrep ? undefined : onProgress); } private updateSearchResultCount(): void { const fileCount = this.viewModel.searchResult.fileCount(); const msgWasHidden = this.messages.isHidden(); if (fileCount > 0) { const div = this.clearMessage(); $(div).p({ text: this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount) }); if (msgWasHidden) { this.reLayout(); } } else if (!msgWasHidden) { this.messages.hide(); } } private buildResultCountMessage(resultCount: number, fileCount: number): string { if (resultCount === 1 && fileCount === 1) { return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount); } else if (resultCount === 1) { return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount); } else if (fileCount === 1) { return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount); } else { return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount); } } private searchWithoutFolderMessage(div: Builder): void { $(div).p({ text: nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ") }) .asContainer().a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openFolder', "Open Folder") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); const actionClass = env.isMacintosh ? OpenFileFolderAction : OpenFolderAction; const action = this.instantiationService.createInstance<string, string, IAction>(actionClass, actionClass.ID, actionClass.LABEL); this.actionRunner.run(action).done(() => { action.dispose(); }, err => { action.dispose(); errors.onUnexpectedError(err); }); }); } private showEmptyStage(): void { // disable 'result'-actions this.actionRegistry['refresh'].enabled = false; this.actionRegistry['vs.tree.collapse'].enabled = false; this.actionRegistry['clearSearchResults'].enabled = false; // clean up ui // this.replaceService.disposeAllReplacePreviews(); this.messages.hide(); this.results.show(); this.tree.onVisible(); this.currentSelectedFileMatch = null; } private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { if (!(lineMatch instanceof Match)) { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); return TPromise.as(true); } this.telemetryService.publicLog('searchResultChosen'); return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ? this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) : this.open(lineMatch, preserveFocus, sideBySide, pinned); } public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { let selection = this.getSelectionFrom(element); let resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource(); return this.editorService.openEditor({ resource: resource, options: { preserveFocus, pinned, selection, revealIfVisible: !sideBySide } }, sideBySide).then(editor => { if (editor && element instanceof Match && preserveFocus) { this.viewModel.searchResult.rangeHighlightDecorations.highlightRange({ resource, range: element.range() }, <ICommonCodeEditor>editor.getControl()); } else { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); } }, errors.onUnexpectedError); } private getSelectionFrom(element: FileMatchOrMatch): any { let match: Match = null; if (element instanceof Match) { match = element; } if (element instanceof FileMatch && element.count() > 0) { match = element.matches()[element.matches().length - 1]; } if (match) { let range = match.range(); if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) { let replaceString = match.replaceString; return { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.startLineNumber, endColumn: range.startColumn + replaceString.length }; } return range; } return void 0; } private onUntitledDidChangeDirty(resource: URI): void { if (!this.viewModel) { return; } // remove search results from this resource as it got disposed if (!this.untitledEditorService.isDirty(resource)) { let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (resource.toString() === matches[i].resource().toString()) { this.viewModel.searchResult.remove(matches[i]); } } } } private onFilesChanged(e: FileChangesEvent): void { if (!this.viewModel) { return; } let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (e.contains(matches[i].resource(), FileChangeType.DELETED)) { this.viewModel.searchResult.remove(matches[i]); } } } public getActions(): IAction[] { return [ this.actionRegistry['refresh'], this.actionRegistry['vs.tree.collapse'], this.actionRegistry['clearSearchResults'] ]; } public dispose(): void { this.isDisposed = true; this.toDispose = lifecycle.dispose(this.toDispose); if (this.tree) { this.tree.dispose(); } this.searchWidget.dispose(); this.inputPatternIncludes.dispose(); this.inputPatternExclusions.dispose(); this.viewModel.dispose(); super.dispose(); } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { let matchHighlightColor = theme.getColor(editorFindMatchHighlight); if (matchHighlightColor) { collector.addRule(`.search-viewlet .findInFileMatch { background-color: ${matchHighlightColor}; }`); collector.addRule(`.search-viewlet .highlight { background-color: ${matchHighlightColor}; }`); } });
src/vs/workbench/parts/search/browser/searchViewlet.ts
1
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.004056119360029697, 0.00030697137117385864, 0.00016237293311860412, 0.00016989362484309822, 0.0005306728417053819 ]
{ "id": 4, "code_window": [ "\t\tif (element instanceof FileMatch) {\n", "\t\t\tvalue = element.matches();\n", "\t\t} else if (element instanceof SearchResult) {\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\treturn element.matches();\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IThreadService } from 'vs/workbench/services/thread/common/threadService'; import { MainContext, MainThreadOutputServiceShape } from './extHost.protocol'; import * as vscode from 'vscode'; export class ExtHostOutputChannel implements vscode.OutputChannel { private static _idPool = 1; private _proxy: MainThreadOutputServiceShape; private _name: string; private _id: string; private _disposed: boolean; constructor(name: string, proxy: MainThreadOutputServiceShape) { this._name = name; this._id = 'extension-output-#' + (ExtHostOutputChannel._idPool++); this._proxy = proxy; } get name(): string { return this._name; } dispose(): void { if (!this._disposed) { this._proxy.$dispose(this._id, this._name).then(() => { this._disposed = true; }); } } append(value: string): void { this._proxy.$append(this._id, this._name, value); } appendLine(value: string): void { this.append(value + '\n'); } clear(): void { this._proxy.$clear(this._id, this._name); } show(columnOrPreserveFocus?: vscode.ViewColumn | boolean, preserveFocus?: boolean): void { if (typeof columnOrPreserveFocus === 'boolean') { preserveFocus = columnOrPreserveFocus; } this._proxy.$reveal(this._id, this._name, preserveFocus); } hide(): void { this._proxy.$close(this._id); } } export class ExtHostOutputService { private _proxy: MainThreadOutputServiceShape; constructor(threadService: IThreadService) { this._proxy = threadService.get(MainContext.MainThreadOutputService); } createOutputChannel(name: string): vscode.OutputChannel { name = name.trim(); if (!name) { throw new Error('illegal argument `name`. must not be falsy'); } else { return new ExtHostOutputChannel(name, this._proxy); } } }
src/vs/workbench/api/node/extHostOutputService.ts
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0001760390878189355, 0.00016949596465565264, 0.00016517769836355, 0.0001695171231403947, 0.0000034997181046492187 ]
{ "id": 4, "code_window": [ "\t\tif (element instanceof FileMatch) {\n", "\t\t\tvalue = element.matches();\n", "\t\t} else if (element instanceof SearchResult) {\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\treturn element.matches();\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 48 }
<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="#F6F6F6" d="M16 5.5c0-3-2.5-5.5-5.5-5.5C7.6 0 5.3 2.2 5 5c-2.8.2-5 2.6-5 5.5 0 3 2.5 5.5 5.5 5.5 2.9 0 5.2-2.2 5.5-5 2.8-.3 5-2.6 5-5.5z"/><g fill="#424242"><path d="M10.5 1C8.2 1 6.3 2.8 6 5c.3 0 .7.1 1 .2C7.2 3.4 8.7 2 10.5 2 12.4 2 14 3.6 14 5.5c0 1.8-1.4 3.3-3.2 3.5.1.3.2.6.2 1 2.3-.2 4-2.1 4-4.5C15 3 13 1 10.5 1z"/><circle cx="5.5" cy="10.5" r="4.5"/></g></svg>
src/vs/workbench/parts/debug/browser/media/breakpoints-activate.svg
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00016842599143274128, 0.00016842599143274128, 0.00016842599143274128, 0.00016842599143274128, 0 ]
{ "id": 4, "code_window": [ "\t\tif (element instanceof FileMatch) {\n", "\t\t\tvalue = element.matches();\n", "\t\t} else if (element instanceof SearchResult) {\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\treturn element.matches();\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * 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. { "araLabelEditorActions": "Azioni editor", "close": "Chiudi", "inputDecoration": "{0} {1}", "loadingLabel": "Caricamento...", "splitEditor": "Dividi editor" }
i18n/ita/src/vs/workbench/browser/parts/editor/sideBySideEditorControl.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00017598504200577736, 0.00017596298130229115, 0.00017594090604688972, 0.00017596298130229115, 2.206798122017517e-8 ]
{ "id": 5, "code_window": [ "\t\t} else if (element instanceof SearchResult) {\n", "\t\t\tvalue = element.matches();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn element.matches();\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import strings = require('vs/base/common/strings'); import platform = require('vs/base/common/platform'); import errors = require('vs/base/common/errors'); import paths = require('vs/base/common/paths'); import dom = require('vs/base/browser/dom'); import { $ } from 'vs/base/browser/builder'; import { TPromise } from 'vs/base/common/winjs.base'; import { IAction, IActionRunner } from 'vs/base/common/actions'; import { ActionsRenderer } from 'vs/base/parts/tree/browser/actionsRenderer'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { FileLabel } from 'vs/workbench/browser/labels'; import { LeftRightWidget, IRenderer } from 'vs/base/browser/ui/leftRightWidget/leftRightWidget'; import { ITree, IElementCallback, IDataSource, ISorter, IAccessibilityProvider, IFilter } from 'vs/base/parts/tree/browser/tree'; import { ClickBehavior, DefaultController } from 'vs/base/parts/tree/browser/treeDefaults'; import { ContributableActionProvider } from 'vs/workbench/browser/actionBarRegistry'; import { Match, SearchResult, FileMatch, FileMatchOrMatch, SearchModel } from 'vs/workbench/parts/search/common/searchModel'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { Range } from 'vs/editor/common/core/range'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { SearchViewlet } from 'vs/workbench/parts/search/browser/searchViewlet'; import { RemoveAction, ReplaceAllAction, ReplaceAction } from 'vs/workbench/parts/search/browser/searchActions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; export class SearchDataSource implements IDataSource { public getId(tree: ITree, element: any): string { if (element instanceof FileMatch) { return element.id(); } if (element instanceof Match) { return element.id(); } return 'root'; } public getChildren(tree: ITree, element: any): TPromise<any[]> { let value: any[] = []; if (element instanceof FileMatch) { value = element.matches(); } else if (element instanceof SearchResult) { value = element.matches(); } return TPromise.as(value); } public hasChildren(tree: ITree, element: any): boolean { return element instanceof FileMatch || element instanceof SearchResult; } public getParent(tree: ITree, element: any): TPromise<any> { let value: any = null; if (element instanceof Match) { value = element.parent(); } else if (element instanceof FileMatch) { value = element.parent(); } return TPromise.as(value); } } export class SearchSorter implements ISorter { public compare(tree: ITree, elementA: FileMatchOrMatch, elementB: FileMatchOrMatch): number { if (elementA instanceof FileMatch && elementB instanceof FileMatch) { return elementA.resource().fsPath.localeCompare(elementB.resource().fsPath) || elementA.name().localeCompare(elementB.name()); } if (elementA instanceof Match && elementB instanceof Match) { return Range.compareRangesUsingStarts(elementA.range(), elementB.range()); } return undefined; } } class SearchActionProvider extends ContributableActionProvider { constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) { super(); } public hasActions(tree: ITree, element: any): boolean { let input = <SearchResult>tree.getInput(); return element instanceof FileMatch || (input.searchModel.isReplaceActive() || element instanceof Match) || super.hasActions(tree, element); } public getActions(tree: ITree, element: any): TPromise<IAction[]> { return super.getActions(tree, element).then(actions => { let input = <SearchResult>tree.getInput(); if (element instanceof FileMatch) { actions.unshift(new RemoveAction(tree, element)); if (input.searchModel.isReplaceActive() && element.count() > 0) { actions.unshift(this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet)); } } if (element instanceof Match) { if (input.searchModel.isReplaceActive()) { actions.unshift(this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet), new RemoveAction(tree, element)); } } return actions; }); } } export class SearchRenderer extends ActionsRenderer { constructor(actionRunner: IActionRunner, viewlet: SearchViewlet, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IInstantiationService private instantiationService: IInstantiationService) { super({ actionProvider: instantiationService.createInstance(SearchActionProvider, viewlet), actionRunner: actionRunner }); } public getContentHeight(tree: ITree, element: any): number { return 22; } public renderContents(tree: ITree, element: FileMatchOrMatch, domElement: HTMLElement, previousCleanupFn: IElementCallback): IElementCallback { // File if (element instanceof FileMatch) { let fileMatch = <FileMatch>element; let container = $('.filematch'); let leftRenderer: IRenderer; let rightRenderer: IRenderer; let widget: LeftRightWidget; leftRenderer = (left: HTMLElement): any => { const label = this.instantiationService.createInstance(FileLabel, left, void 0); label.setFile(fileMatch.resource()); return () => label.dispose(); }; rightRenderer = (right: HTMLElement) => { let len = fileMatch.count(); new CountBadge(right, len, len > 1 ? nls.localize('searchMatches', "{0} matches found", len) : nls.localize('searchMatch', "{0} match found", len)); return null; }; widget = new LeftRightWidget(container, leftRenderer, rightRenderer); container.appendTo(domElement); return widget.dispose.bind(widget); } // Match else if (element instanceof Match) { dom.addClass(domElement, 'linematch'); let match = <Match>element; let elements: string[] = []; let preview = match.preview(); elements.push('<span>'); elements.push(strings.escape(preview.before)); let searchModel: SearchModel = (<SearchResult>tree.getInput()).searchModel; let showReplaceText = searchModel.isReplaceActive() && !!searchModel.replaceString; elements.push('</span><span class="' + (showReplaceText ? 'replace ' : '') + 'findInFileMatch">'); elements.push(strings.escape(preview.inside)); if (showReplaceText) { elements.push('</span><span class="replaceMatch">'); elements.push(strings.escape(match.replaceString)); } elements.push('</span><span>'); elements.push(strings.escape(preview.after)); elements.push('</span>'); $('a.plain') .innerHtml(elements.join(strings.empty)) .title((preview.before + (showReplaceText ? match.replaceString : preview.inside) + preview.after).trim().substr(0, 999)) .appendTo(domElement); } return null; } } export class SearchAccessibilityProvider implements IAccessibilityProvider { constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) { } public getAriaLabel(tree: ITree, element: FileMatchOrMatch): string { if (element instanceof FileMatch) { const path = this.contextService.toWorkspaceRelativePath(element.resource()) || element.resource().fsPath; return nls.localize('fileMatchAriaLabel', "{0} matches in file {1} of folder {2}, Search result", element.count(), element.name(), paths.dirname(path)); } if (element instanceof Match) { let match = <Match>element; let input = <SearchResult>tree.getInput(); if (input.searchModel.isReplaceActive()) { let preview = match.preview(); return nls.localize('replacePreviewResultAria', "Replace preview result, {0}", preview.before + match.replaceString + preview.after); } return nls.localize('searchResultAria', "{0}, Search result", match.text()); } return undefined; } } export class SearchController extends DefaultController { constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) { super({ clickBehavior: ClickBehavior.ON_MOUSE_DOWN, keyboardSupport: false }); // TODO@Rob these should be commands // Up (from results to inputs) this.downKeyBindingDispatcher.set(KeyCode.UpArrow, this.onUp.bind(this)); // Open to side this.upKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.WinCtrl | KeyCode.Enter : KeyMod.CtrlCmd | KeyCode.Enter, this.onEnter.bind(this)); // Delete this.downKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.CtrlCmd | KeyCode.Backspace : KeyCode.Delete, (tree: ITree, event: any) => { this.onDelete(tree, event); }); // Cancel search this.downKeyBindingDispatcher.set(KeyCode.Escape, (tree: ITree, event: any) => { this.onEscape(tree, event); }); // Replace / Replace All this.downKeyBindingDispatcher.set(ReplaceAllAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplaceAll(tree, event); }); this.downKeyBindingDispatcher.set(ReplaceAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplace(tree, event); }); } protected onEscape(tree: ITree, event: IKeyboardEvent): boolean { if (this.viewlet.cancelSearch()) { return true; } return super.onEscape(tree, event); } private onDelete(tree: ITree, event: IKeyboardEvent): boolean { let input = <SearchResult>tree.getInput(); let result = false; let element = tree.getFocus(); if (element instanceof FileMatch || (element instanceof Match && input.searchModel.isReplaceActive())) { new RemoveAction(tree, element).run().done(null, errors.onUnexpectedError); result = true; } return result; } private onReplace(tree: ITree, event: IKeyboardEvent): boolean { let input = <SearchResult>tree.getInput(); let result = false; let element = tree.getFocus(); if (element instanceof Match && input.searchModel.isReplaceActive()) { this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError); result = true; } return result; } private onReplaceAll(tree: ITree, event: IKeyboardEvent): boolean { let result = false; let element = tree.getFocus(); if (element instanceof FileMatch && element.count() > 0) { this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError); result = true; } return result; } protected onUp(tree: ITree, event: IKeyboardEvent): boolean { if (tree.getNavigator().first() === tree.getFocus()) { this.viewlet.moveFocusFromResults(); return true; } return false; } } export class SearchFilter implements IFilter { public isVisible(tree: ITree, element: any): boolean { return !(element instanceof FileMatch) || element.matches().length > 0; } }
src/vs/workbench/parts/search/browser/searchResultsView.ts
1
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.9955522418022156, 0.07066994905471802, 0.0001657983084442094, 0.0009246225235983729, 0.24322576820850372 ]
{ "id": 5, "code_window": [ "\t\t} else if (element instanceof SearchResult) {\n", "\t\t\tvalue = element.matches();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn element.matches();\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * 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. { "extensionHostProcess.crash": "El host de extensiones finalizó inesperadamente. Recargue la ventana para recuperarlo.", "extensionHostProcess.error": "Error del host de extensiones: {0}", "extensionHostProcess.startupFail": "El host de extensiones no se inició en 10 segundos, lo cual puede ser un problema.", "extensionHostProcess.startupFailDebug": "El host de extensiones no se inició en 10 segundos, puede que se detenga en la primera línea y necesita un depurador para continuar." }
i18n/esn/src/vs/workbench/electron-browser/extensionHost.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00018063858442474157, 0.00017541648412588984, 0.0001701943838270381, 0.00017541648412588984, 0.0000052221002988517284 ]
{ "id": 5, "code_window": [ "\t\t} else if (element instanceof SearchResult) {\n", "\t\t\tvalue = element.matches();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn element.matches();\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 50 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><style type="text/css">.st0{opacity:0;fill:#262626;} .st1{fill:#262626;} .st2{fill:#C5C5C5;}</style><g id="outline"><rect class="st0" width="16" height="16"/><path class="st1" d="M16 4.022v-3.022h-16.014v3.022h3.046l-3.043 7.945h-.004v.01l.015 1.023h-.014v1.991h16.014v-3.023h-1v-7.946h1zm-5.914 5.301c0 .233-.023.441-.066.595-.047.164-.099.247-.127.284l-.078.069-.151.026-.115-.017-.139-.137c-.031-.078-.112-.332-.112-.566 0-.254.091-.561.126-.656l.069-.141.109-.082.178-.027c.077 0 .117.014.177.056l.087.179.051.237-.009.18zm-3.695-5.301v2.893l-1.116-2.893h1.116zm-3.026 7.02h1.573l.351.926h-2.254l.33-.926zm8.635-4.354c-.206-.2-.431-.38-.695-.512-.396-.198-.853-.298-1.355-.298-.215 0-.423.02-.621.058v-1.914h2.671v2.666z"/></g><g id="icon_x5F_bg"><rect x="13" y="4" class="st2" width="1" height="8"/><path class="st2" d="M11.225 8.387c-.078-.299-.199-.562-.36-.786s-.365-.401-.609-.53-.534-.193-.866-.193c-.198 0-.38.024-.547.073-.165.049-.316.117-.453.205-.136.088-.257.194-.365.318l-.179.258v-3.154h-.893v7.422h.893v-.575l.126.175c.087.102.189.19.304.269.117.078.249.14.398.186.149.046.314.068.498.068.353 0 .666-.071.937-.212.272-.143.499-.338.682-.586.183-.25.321-.543.414-.879.093-.338.14-.703.14-1.097-.001-.342-.04-.663-.12-.962zm-1.479-.607c.151.071.282.176.39.314.109.14.194.313.255.517.051.174.082.371.089.587l-.007.125c0 .327-.033.62-.1.869-.067.246-.161.453-.278.614-.117.162-.26.285-.421.366-.322.162-.76.166-1.069.015-.153-.075-.286-.175-.393-.296-.085-.096-.156-.216-.218-.367 0 0-.179-.447-.179-.947 0-.5.179-1.002.179-1.002.062-.177.136-.318.224-.43.114-.143.256-.259.424-.345.168-.086.365-.129.587-.129.19 0 .364.037.517.109z"/><rect x=".987" y="2" class="st2" width="14.013" height="1.023"/><rect x=".987" y="12.968" class="st2" width="14.013" height="1.023"/><path class="st2" d="M1.991 12.031l.728-2.031h2.219l.778 2.031h1.082l-2.485-7.158h-.941l-2.441 7.086-.025.072h1.085zm1.827-5.609h.022l.914 2.753h-1.841l.905-2.753z"/></g></svg>
src/vs/base/browser/ui/findinput/whole-word-dark.svg
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00026740043540485203, 0.00026740043540485203, 0.00026740043540485203, 0.00026740043540485203, 0 ]
{ "id": 5, "code_window": [ "\t\t} else if (element instanceof SearchResult) {\n", "\t\t\tvalue = element.matches();\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn element.matches();\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * 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/editorstatus'; import nls = require('vs/nls'); import { TPromise } from 'vs/base/common/winjs.base'; import { $, append, runAtThisOrScheduleAtNextAnimationFrame } from 'vs/base/browser/dom'; import strings = require('vs/base/common/strings'); import paths = require('vs/base/common/paths'); import types = require('vs/base/common/types'); import uri from 'vs/base/common/uri'; import errors = require('vs/base/common/errors'); import { IStatusbarItem } from 'vs/workbench/browser/parts/statusbar/statusbar'; import { Action } from 'vs/base/common/actions'; import { language, LANGUAGE_DEFAULT } from 'vs/base/common/platform'; import { IMode } from 'vs/editor/common/modes'; import { UntitledEditorInput } from 'vs/workbench/common/editor/untitledEditorInput'; import { IFileEditorInput, EncodingMode, IEncodingSupport, toResource, SideBySideEditorInput } from 'vs/workbench/common/editor'; import { IDisposable, combinedDisposable, dispose } from 'vs/base/common/lifecycle'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { IConfigurationEditingService, ConfigurationTarget } from 'vs/workbench/services/configuration/common/configurationEditing'; import { IEditorAction, ICommonCodeEditor, IModelContentChangedEvent, IModelOptionsChangedEvent, IModelLanguageChangedEvent, ICursorPositionChangedEvent, EndOfLineSequence, EditorType, IModel, IDiffEditorModel, IEditor } from 'vs/editor/common/editorCommon'; import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { TrimTrailingWhitespaceAction } from 'vs/editor/contrib/linesOperations/common/linesOperations'; import { IndentUsingSpaces, IndentUsingTabs, DetectIndentation, IndentationToSpacesAction, IndentationToTabsAction } from 'vs/editor/contrib/indentation/common/indentation'; import { BaseBinaryResourceEditor } from 'vs/workbench/browser/parts/editor/binaryEditor'; import { BinaryResourceDiffEditor } from 'vs/workbench/browser/parts/editor/binaryDiffEditor'; import { IEditor as IBaseEditor, IEditorInput } from 'vs/platform/editor/common/editor'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IQuickOpenService, IPickOpenEntry, IFilePickOpenEntry } from 'vs/platform/quickOpen/common/quickOpen'; import { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration'; import { IFilesConfiguration, SUPPORTED_ENCODINGS } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IModelService } from 'vs/editor/common/services/modelService'; import { Selection } from 'vs/editor/common/core/selection'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { getCodeEditor as getEditorWidget } from 'vs/editor/common/services/codeEditorService'; import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences'; function getCodeEditor(editorWidget: IEditor): ICommonCodeEditor { if (editorWidget) { if (editorWidget.getEditorType() === EditorType.IDiffEditor) { return (<IDiffEditor>editorWidget).getModifiedEditor(); } if (editorWidget.getEditorType() === EditorType.ICodeEditor) { return (<ICodeEditor>editorWidget); } } return null; } function getTextModel(editorWidget: IEditor): IModel { // make sure to resolve any possible diff editors to their modified side editorWidget = getCodeEditor(editorWidget); return editorWidget ? <IModel>editorWidget.getModel() : null; } function toEditorWithEncodingSupport(input: IEditorInput): IEncodingSupport { if (input instanceof SideBySideEditorInput) { input = input.master; } if (input instanceof UntitledEditorInput) { return input; } let encodingSupport = input as IFileEditorInput; if (types.areFunctions(encodingSupport.setEncoding, encodingSupport.getEncoding)) { return encodingSupport; } return null; } interface IEditorSelectionStatus { selections?: Selection[]; charactersSelected?: number; } class StateChange { _stateChangeBrand: void; indentation: boolean; selectionStatus: boolean; mode: boolean; encoding: boolean; EOL: boolean; tabFocusMode: boolean; metadata: boolean; constructor() { this.indentation = false; this.selectionStatus = false; this.mode = false; this.encoding = false; this.EOL = false; this.tabFocusMode = false; this.metadata = false; } public combine(other: StateChange) { this.indentation = this.indentation || other.indentation; this.selectionStatus = this.selectionStatus || other.selectionStatus; this.mode = this.mode || other.mode; this.encoding = this.encoding || other.encoding; this.EOL = this.EOL || other.EOL; this.tabFocusMode = this.tabFocusMode || other.tabFocusMode; this.metadata = this.metadata || other.metadata; } } interface StateDelta { selectionStatus?: string; mode?: string; encoding?: string; EOL?: string; indentation?: string; tabFocusMode?: boolean; metadata?: string; } class State { private _selectionStatus: string; public get selectionStatus(): string { return this._selectionStatus; } private _mode: string; public get mode(): string { return this._mode; } private _encoding: string; public get encoding(): string { return this._encoding; } private _EOL: string; public get EOL(): string { return this._EOL; } private _indentation: string; public get indentation(): string { return this._indentation; } private _tabFocusMode: boolean; public get tabFocusMode(): boolean { return this._tabFocusMode; } private _metadata: string; public get metadata(): string { return this._metadata; } constructor() { this._selectionStatus = null; this._mode = null; this._encoding = null; this._EOL = null; this._tabFocusMode = false; this._metadata = null; } public update(update: StateDelta): StateChange { const e = new StateChange(); let somethingChanged = false; if (typeof update.selectionStatus !== 'undefined') { if (this._selectionStatus !== update.selectionStatus) { this._selectionStatus = update.selectionStatus; somethingChanged = true; e.selectionStatus = true; } } if (typeof update.indentation !== 'undefined') { if (this._indentation !== update.indentation) { this._indentation = update.indentation; somethingChanged = true; e.indentation = true; } } if (typeof update.mode !== 'undefined') { if (this._mode !== update.mode) { this._mode = update.mode; somethingChanged = true; e.mode = true; } } if (typeof update.encoding !== 'undefined') { if (this._encoding !== update.encoding) { this._encoding = update.encoding; somethingChanged = true; e.encoding = true; } } if (typeof update.EOL !== 'undefined') { if (this._EOL !== update.EOL) { this._EOL = update.EOL; somethingChanged = true; e.EOL = true; } } if (typeof update.tabFocusMode !== 'undefined') { if (this._tabFocusMode !== update.tabFocusMode) { this._tabFocusMode = update.tabFocusMode; somethingChanged = true; e.tabFocusMode = true; } } if (typeof update.metadata !== 'undefined') { if (this._metadata !== update.metadata) { this._metadata = update.metadata; somethingChanged = true; e.metadata = true; } } if (somethingChanged) { return e; } return null; } } const nlsSingleSelectionRange = nls.localize('singleSelectionRange', "Ln {0}, Col {1} ({2} selected)"); const nlsSingleSelection = nls.localize('singleSelection', "Ln {0}, Col {1}"); const nlsMultiSelectionRange = nls.localize('multiSelectionRange', "{0} selections ({1} characters selected)"); const nlsMultiSelection = nls.localize('multiSelection', "{0} selections"); const nlsEOLLF = nls.localize('endOfLineLineFeed', "LF"); const nlsEOLCRLF = nls.localize('endOfLineCarriageReturnLineFeed', "CRLF"); const nlsTabFocusMode = nls.localize('tabFocusModeEnabled', "Tab moves focus"); function _setDisplay(el: HTMLElement, desiredValue: string): void { if (el.style.display !== desiredValue) { el.style.display = desiredValue; } } function show(el: HTMLElement): void { _setDisplay(el, ''); } function hide(el: HTMLElement): void { _setDisplay(el, 'none'); } export class EditorStatus implements IStatusbarItem { private state: State; private element: HTMLElement; private tabFocusModeElement: HTMLElement; private indentationElement: HTMLElement; private selectionElement: HTMLElement; private encodingElement: HTMLElement; private eolElement: HTMLElement; private modeElement: HTMLElement; private metadataElement: HTMLElement; private toDispose: IDisposable[]; private activeEditorListeners: IDisposable[]; private delayedRender: IDisposable; private toRender: StateChange; constructor( @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IQuickOpenService private quickOpenService: IQuickOpenService, @IInstantiationService private instantiationService: IInstantiationService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IModeService private modeService: IModeService, @ITextFileService private textFileService: ITextFileService ) { this.toDispose = []; this.activeEditorListeners = []; this.state = new State(); } public render(container: HTMLElement): IDisposable { this.element = append(container, $('.editor-statusbar-item')); this.tabFocusModeElement = append(this.element, $('a.editor-status-tabfocusmode.status-bar-info')); this.tabFocusModeElement.title = nls.localize('disableTabMode', "Disable Accessibility Mode"); this.tabFocusModeElement.onclick = () => this.onTabFocusModeClick(); this.tabFocusModeElement.textContent = nlsTabFocusMode; hide(this.tabFocusModeElement); this.selectionElement = append(this.element, $('a.editor-status-selection')); this.selectionElement.title = nls.localize('gotoLine', "Go to Line"); this.selectionElement.onclick = () => this.onSelectionClick(); hide(this.selectionElement); this.indentationElement = append(this.element, $('a.editor-status-indentation')); this.indentationElement.title = nls.localize('indentation', "Indentation"); this.indentationElement.onclick = () => this.onIndentationClick(); hide(this.indentationElement); this.encodingElement = append(this.element, $('a.editor-status-encoding')); this.encodingElement.title = nls.localize('selectEncoding', "Select Encoding"); this.encodingElement.onclick = () => this.onEncodingClick(); hide(this.encodingElement); this.eolElement = append(this.element, $('a.editor-status-eol')); this.eolElement.title = nls.localize('selectEOL', "Select End of Line Sequence"); this.eolElement.onclick = () => this.onEOLClick(); hide(this.eolElement); this.modeElement = append(this.element, $('a.editor-status-mode')); this.modeElement.title = nls.localize('selectLanguageMode', "Select Language Mode"); this.modeElement.onclick = () => this.onModeClick(); hide(this.modeElement); this.metadataElement = append(this.element, $('span.editor-status-metadata')); this.metadataElement.title = nls.localize('fileInfo', "File Information"); hide(this.metadataElement); this.delayedRender = null; this.toRender = null; this.toDispose.push( { dispose: () => { if (this.delayedRender) { this.delayedRender.dispose(); this.delayedRender = null; } } }, this.editorGroupService.onEditorsChanged(() => this.onEditorsChanged()), this.untitledEditorService.onDidChangeEncoding(r => this.onResourceEncodingChange(r)), this.textFileService.models.onModelEncodingChanged(e => this.onResourceEncodingChange(e.resource)), TabFocus.onDidChangeTabFocus(e => this.onTabFocusModeChange()) ); return combinedDisposable(this.toDispose); } private updateState(update: StateDelta): void { const changed = this.state.update(update); if (!changed) { // Nothing really changed return; } if (!this.toRender) { this.toRender = changed; this.delayedRender = runAtThisOrScheduleAtNextAnimationFrame(() => { this.delayedRender = null; const toRender = this.toRender; this.toRender = null; this._renderNow(toRender); }); } else { this.toRender.combine(changed); } } private _renderNow(changed: StateChange): void { if (changed.tabFocusMode) { if (this.state.tabFocusMode && this.state.tabFocusMode === true) { show(this.tabFocusModeElement); } else { hide(this.tabFocusModeElement); } } if (changed.indentation) { if (this.state.indentation) { this.indentationElement.textContent = this.state.indentation; show(this.indentationElement); } else { hide(this.indentationElement); } } if (changed.selectionStatus) { if (this.state.selectionStatus) { this.selectionElement.textContent = this.state.selectionStatus; show(this.selectionElement); } else { hide(this.selectionElement); } } if (changed.encoding) { if (this.state.encoding) { this.encodingElement.textContent = this.state.encoding; show(this.encodingElement); } else { hide(this.encodingElement); } } if (changed.EOL) { if (this.state.EOL) { this.eolElement.textContent = this.state.EOL === '\r\n' ? nlsEOLCRLF : nlsEOLLF; show(this.eolElement); } else { hide(this.eolElement); } } if (changed.mode) { if (this.state.mode) { this.modeElement.textContent = this.state.mode; show(this.modeElement); } else { hide(this.modeElement); } } if (changed.metadata) { if (this.state.metadata) { this.metadataElement.textContent = this.state.metadata; show(this.metadataElement); } else { hide(this.metadataElement); } } } private getSelectionLabel(info: IEditorSelectionStatus): string { if (!info || !info.selections) { return null; } if (info.selections.length === 1) { if (info.charactersSelected) { return strings.format(nlsSingleSelectionRange, info.selections[0].positionLineNumber, info.selections[0].positionColumn, info.charactersSelected); } return strings.format(nlsSingleSelection, info.selections[0].positionLineNumber, info.selections[0].positionColumn); } if (info.charactersSelected) { return strings.format(nlsMultiSelectionRange, info.selections.length, info.charactersSelected); } if (info.selections.length > 0) { return strings.format(nlsMultiSelection, info.selections.length); } return null; } private onModeClick(): void { const action = this.instantiationService.createInstance(ChangeModeAction, ChangeModeAction.ID, ChangeModeAction.LABEL); action.run().done(null, errors.onUnexpectedError); action.dispose(); } private onIndentationClick(): void { const action = this.instantiationService.createInstance(ChangeIndentationAction, ChangeIndentationAction.ID, ChangeIndentationAction.LABEL); action.run().done(null, errors.onUnexpectedError); action.dispose(); } private onSelectionClick(): void { this.quickOpenService.show(':'); // "Go to line" } private onEOLClick(): void { const action = this.instantiationService.createInstance(ChangeEOLAction, ChangeEOLAction.ID, ChangeEOLAction.LABEL); action.run().done(null, errors.onUnexpectedError); action.dispose(); } private onEncodingClick(): void { const action = this.instantiationService.createInstance(ChangeEncodingAction, ChangeEncodingAction.ID, ChangeEncodingAction.LABEL); action.run().done(null, errors.onUnexpectedError); action.dispose(); } private onTabFocusModeClick(): void { TabFocus.setTabFocusMode(false); } private onEditorsChanged(): void { const activeEditor = this.editorService.getActiveEditor(); let control: IEditor = getEditorWidget(activeEditor); // Update all states this.onSelectionChange(control); this.onModeChange(control); this.onEOLChange(control); this.onEncodingChange(activeEditor); this.onIndentationChange(control); this.onMetadataChange(activeEditor); // Dispose old active editor listeners dispose(this.activeEditorListeners); // Attach new listeners to active editor if (control) { // Hook Listener for Selection changes this.activeEditorListeners.push(control.onDidChangeCursorPosition((event: ICursorPositionChangedEvent) => { this.onSelectionChange(control); })); // Hook Listener for mode changes this.activeEditorListeners.push(control.onDidChangeModelLanguage((event: IModelLanguageChangedEvent) => { this.onModeChange(control); })); // Hook Listener for content changes this.activeEditorListeners.push(control.onDidChangeModelRawContent((event: IModelContentChangedEvent) => { this.onEOLChange(control); })); // Hook Listener for content options changes this.activeEditorListeners.push(control.onDidChangeModelOptions((event: IModelOptionsChangedEvent) => { this.onIndentationChange(control); })); } // Handle binary editors else if (activeEditor instanceof BaseBinaryResourceEditor || activeEditor instanceof BinaryResourceDiffEditor) { this.activeEditorListeners.push(activeEditor.onMetadataChanged(metadata => { this.onMetadataChange(activeEditor); })); } } private onModeChange(editorWidget?: IEditor): void { let info: StateDelta = { mode: null }; // We only support text based editors if (editorWidget) { const textModel = getTextModel(editorWidget); if (textModel) { // Compute mode const modeId = textModel.getLanguageIdentifier().language; info = { mode: this.modeService.getLanguageName(modeId) }; } } this.updateState(info); } private onIndentationChange(editorWidget?: IEditor): void { const update: StateDelta = { indentation: null }; if (editorWidget) { if (editorWidget.getEditorType() === EditorType.IDiffEditor) { editorWidget = (<IDiffEditor>editorWidget).getModifiedEditor(); } const model = (<ICommonCodeEditor>editorWidget).getModel(); if (model) { const modelOpts = model.getOptions(); update.indentation = ( modelOpts.insertSpaces ? nls.localize('spacesSize', "Spaces: {0}", modelOpts.tabSize) : nls.localize({ key: 'tabSize', comment: ['Tab corresponds to the tab key'] }, "Tab Size: {0}", modelOpts.tabSize) ); } } this.updateState(update); } private onMetadataChange(editor: IBaseEditor): void { const update: StateDelta = { metadata: null }; if (editor instanceof BaseBinaryResourceEditor || editor instanceof BinaryResourceDiffEditor) { update.metadata = editor.getMetadata(); } this.updateState(update); } private onSelectionChange(editorWidget?: IEditor): void { const info: IEditorSelectionStatus = {}; // We only support text based editors if (editorWidget) { // Compute selection(s) info.selections = editorWidget.getSelections() || []; // Compute selection length info.charactersSelected = 0; const textModel = getTextModel(editorWidget); if (textModel) { info.selections.forEach(selection => { info.charactersSelected += textModel.getValueLengthInRange(selection); }); } // Compute the visible column for one selection. This will properly handle tabs and their configured widths if (info.selections.length === 1) { const visibleColumn = editorWidget.getVisibleColumnFromPosition(editorWidget.getPosition()); let selectionClone = info.selections[0].clone(); // do not modify the original position we got from the editor selectionClone = new Selection( selectionClone.selectionStartLineNumber, selectionClone.selectionStartColumn, selectionClone.positionLineNumber, visibleColumn ); info.selections[0] = selectionClone; } } this.updateState({ selectionStatus: this.getSelectionLabel(info) }); } private onEOLChange(editorWidget?: IEditor): void { const info: StateDelta = { EOL: null }; const codeEditor = getCodeEditor(editorWidget); if (codeEditor && !codeEditor.getConfiguration().readOnly) { const codeEditorModel = codeEditor.getModel(); if (codeEditorModel) { info.EOL = codeEditorModel.getEOL(); } } this.updateState(info); } private onEncodingChange(e: IBaseEditor): void { if (e && !this.isActiveEditor(e)) { return; } const info: StateDelta = { encoding: null }; // We only support text based editors if (getEditorWidget(e)) { const encodingSupport: IEncodingSupport = toEditorWithEncodingSupport(e.input); if (encodingSupport) { const rawEncoding = encodingSupport.getEncoding(); const encodingInfo = SUPPORTED_ENCODINGS[rawEncoding]; if (encodingInfo) { info.encoding = encodingInfo.labelShort; // if we have a label, take it from there } else { info.encoding = rawEncoding; // otherwise use it raw } } } this.updateState(info); } private onResourceEncodingChange(resource: uri): void { const activeEditor = this.editorService.getActiveEditor(); if (activeEditor) { const activeResource = toResource(activeEditor.input, { supportSideBySide: true, filter: ['file', 'untitled'] }); if (activeResource.toString() === resource.toString()) { return this.onEncodingChange(<IBaseEditor>activeEditor); // only update if the encoding changed for the active resource } } } private onTabFocusModeChange(): void { const info: StateDelta = { tabFocusMode: TabFocus.getTabFocusMode() }; this.updateState(info); } private isActiveEditor(e: IBaseEditor): boolean { const activeEditor = this.editorService.getActiveEditor(); return activeEditor && e && activeEditor === e; } } function isWritableCodeEditor(e: IBaseEditor): boolean { let editorWidget: IEditor = getEditorWidget(e); if (!editorWidget) { return false; } if (editorWidget.getEditorType() === EditorType.IDiffEditor) { editorWidget = (<IDiffEditor>editorWidget).getModifiedEditor(); } return (editorWidget.getEditorType() === EditorType.ICodeEditor && !(<ICodeEditor>editorWidget).getConfiguration().readOnly); } export class ShowLanguageExtensionsAction extends Action { static ID = 'workbench.action.showLanguageExtensions'; constructor( private fileExtension: string, @ICommandService private commandService: ICommandService, @IExtensionGalleryService galleryService: IExtensionGalleryService ) { super(ShowLanguageExtensionsAction.ID, nls.localize('showLanguageExtensions', "Search Marketplace Extensions for '{0}'...", fileExtension)); this.enabled = galleryService.isEnabled(); } run(): TPromise<void> { return this.commandService.executeCommand('workbench.extensions.action.showLanguageExtensions', this.fileExtension).then(() => void 0); } } export class ChangeModeAction extends Action { public static ID = 'workbench.action.editor.changeLanguageMode'; public static LABEL = nls.localize('changeMode', "Change Language Mode"); private static FILE_ASSOCIATION_KEY = 'files.associations'; constructor( actionId: string, actionLabel: string, @IModeService private modeService: IModeService, @IModelService private modelService: IModelService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IConfigurationEditingService private configurationEditingService: IConfigurationEditingService, @IMessageService private messageService: IMessageService, @IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService, @IQuickOpenService private quickOpenService: IQuickOpenService, @IPreferencesService private preferencesService: IPreferencesService, @IInstantiationService private instantiationService: IInstantiationService, @ICommandService private commandService: ICommandService, @IConfigurationEditingService private configurationEditService: IConfigurationEditingService ) { super(actionId, actionLabel); } public run(): TPromise<any> { let activeEditor = this.editorService.getActiveEditor(); const editorWidget = getEditorWidget(activeEditor); if (!editorWidget) { return this.quickOpenService.pick([{ label: nls.localize('noEditor', "No text editor active at this time") }]); } const textModel = getTextModel(editorWidget); const fileResource = toResource(activeEditor.input, { supportSideBySide: true, filter: 'file' }); // Compute mode let currentModeId: string; let modeId; if (textModel) { modeId = textModel.getLanguageIdentifier().language; currentModeId = this.modeService.getLanguageName(modeId); } // All languages are valid picks const languages = this.modeService.getRegisteredLanguageNames(); const picks: IPickOpenEntry[] = languages.sort().map((lang, index) => { let description: string; if (currentModeId === lang) { description = nls.localize('languageDescription', "({0}) - Configured Language", this.modeService.getModeIdForLanguageName(lang.toLowerCase())); } else { description = nls.localize('languageDescriptionConfigured', "({0})", this.modeService.getModeIdForLanguageName(lang.toLowerCase())); } // construct a fake resource to be able to show nice icons if any let fakeResource: uri; const extensions = this.modeService.getExtensions(lang); if (extensions && extensions.length) { fakeResource = uri.file(extensions[0]); } else { const filenames = this.modeService.getFilenames(lang); if (filenames && filenames.length) { fakeResource = uri.file(filenames[0]); } } return <IFilePickOpenEntry>{ label: lang, resource: fakeResource, description }; }); if (fileResource) { picks[0].separator = { border: true, label: nls.localize('languagesPicks', "languages (identifier)") }; } // Offer action to configure via settings let configureModeAssociations: IPickOpenEntry; let configureModeSettings: IPickOpenEntry; let galleryAction: Action; if (fileResource) { const ext = paths.extname(fileResource.fsPath) || paths.basename(fileResource.fsPath); galleryAction = this.instantiationService.createInstance(ShowLanguageExtensionsAction, ext); if (galleryAction.enabled) { picks.unshift(galleryAction); } configureModeSettings = { label: nls.localize('configureModeSettings', "Configure '{0}' language based settings...", currentModeId) }; picks.unshift(configureModeSettings); configureModeAssociations = { label: nls.localize('configureAssociationsExt', "Configure File Association for '{0}'...", ext) }; picks.unshift(configureModeAssociations); } // Offer to "Auto Detect" const autoDetectMode: IPickOpenEntry = { label: nls.localize('autoDetect', "Auto Detect") }; if (fileResource) { picks.unshift(autoDetectMode); } return this.quickOpenService.pick(picks, { placeHolder: nls.localize('pickLanguage', "Select Language Mode") }).then(pick => { if (!pick) { return; } if (pick === galleryAction) { galleryAction.run(); return; } // User decided to permanently configure associations, return right after if (pick === configureModeAssociations) { this.configureFileAssociation(fileResource); return; } // User decided to configure settings for current language if (pick === configureModeSettings) { this.preferencesService.configureSettingsForLanguage(modeId); return; } // Change mode for active editor activeEditor = this.editorService.getActiveEditor(); const editorWidget: IEditor = getEditorWidget(activeEditor); if (editorWidget) { const models: IModel[] = []; const textModel = getTextModel(editorWidget); if (textModel) { models.push(textModel); } // Support for original side of diff const model = editorWidget.getModel(); if (model && !!(<IDiffEditorModel>model).original) { models.push((<IDiffEditorModel>model).original); } // Find mode let mode: TPromise<IMode>; if (pick === autoDetectMode) { mode = this.modeService.getOrCreateModeByFilenameOrFirstLine(toResource(activeEditor.input, { supportSideBySide: true, filter: ['file', 'untitled'] }).fsPath, textModel.getLineContent(1)); } else { mode = this.modeService.getOrCreateModeByLanguageName(pick.label); } // Change mode models.forEach(textModel => { this.modelService.setMode(textModel, mode); }); } }); } private configureFileAssociation(resource: uri): void { const extension = paths.extname(resource.fsPath); const basename = paths.basename(resource.fsPath); const currentAssociation = this.modeService.getModeIdByFilenameOrFirstLine(basename); const languages = this.modeService.getRegisteredLanguageNames(); const picks: IPickOpenEntry[] = languages.sort().map((lang, index) => { const id = this.modeService.getModeIdForLanguageName(lang.toLowerCase()); return <IPickOpenEntry>{ id, label: lang, description: (id === currentAssociation) ? nls.localize('currentAssociation', "Current Association") : void 0 }; }); TPromise.timeout(50 /* quick open is sensitive to being opened so soon after another */).done(() => { this.quickOpenService.pick(picks, { placeHolder: nls.localize('pickLanguageToConfigure', "Select Language Mode to Associate with '{0}'", extension || basename) }).done(language => { if (language) { const fileAssociationsConfig = this.configurationService.lookup(ChangeModeAction.FILE_ASSOCIATION_KEY); let associationKey: string; if (extension && basename[0] !== '.') { associationKey = `*${extension}`; // only use "*.ext" if the file path is in the form of <name>.<ext> } else { associationKey = basename; // otherwise use the basename (e.g. .gitignore, Dockerfile) } // If the association is already being made in the workspace, make sure to target workspace settings let target = ConfigurationTarget.USER; if (fileAssociationsConfig.workspace && !!fileAssociationsConfig.workspace[associationKey]) { target = ConfigurationTarget.WORKSPACE; } // Make sure to write into the value of the target and not the merged value from USER and WORKSPACE config let currentAssociations = (target === ConfigurationTarget.WORKSPACE) ? fileAssociationsConfig.workspace : fileAssociationsConfig.user; if (!currentAssociations) { currentAssociations = Object.create(null); } currentAssociations[associationKey] = language.id; // Write config this.configurationEditingService.writeConfiguration(target, { key: ChangeModeAction.FILE_ASSOCIATION_KEY, value: currentAssociations }).done(null, (error) => this.messageService.show(Severity.Error, error.toString())); } }); }); } } export interface IChangeEOLEntry extends IPickOpenEntry { eol: EndOfLineSequence; } class ChangeIndentationAction extends Action { public static ID = 'workbench.action.editor.changeIndentation'; public static LABEL = nls.localize('changeIndentation', "Change Indentation"); constructor( actionId: string, actionLabel: string, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IQuickOpenService private quickOpenService: IQuickOpenService ) { super(actionId, actionLabel); } public run(): TPromise<any> { const activeEditor = this.editorService.getActiveEditor(); const control = getEditorWidget(activeEditor); if (!control) { return this.quickOpenService.pick([{ label: nls.localize('noEditor', "No text editor active at this time") }]); } if (!isWritableCodeEditor(activeEditor)) { return this.quickOpenService.pick([{ label: nls.localize('noWritableCodeEditor', "The active code editor is read-only.") }]); } const picks = [ control.getAction(IndentUsingSpaces.ID), control.getAction(IndentUsingTabs.ID), control.getAction(DetectIndentation.ID), control.getAction(IndentationToSpacesAction.ID), control.getAction(IndentationToTabsAction.ID), control.getAction(TrimTrailingWhitespaceAction.ID) ].map((a: IEditorAction) => { return { id: a.id, label: a.label, detail: (language === LANGUAGE_DEFAULT) ? null : a.alias, run: () => { control.focus(); a.run(); } }; }); (<IPickOpenEntry>picks[0]).separator = { label: nls.localize('indentView', "change view") }; (<IPickOpenEntry>picks[3]).separator = { label: nls.localize('indentConvert', "convert file"), border: true }; return this.quickOpenService.pick(picks, { placeHolder: nls.localize('pickAction', "Select Action"), matchOnDetail: true }).then(action => action && action.run()); } } export class ChangeEOLAction extends Action { public static ID = 'workbench.action.editor.changeEOL'; public static LABEL = nls.localize('changeEndOfLine', "Change End of Line Sequence"); constructor( actionId: string, actionLabel: string, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IQuickOpenService private quickOpenService: IQuickOpenService ) { super(actionId, actionLabel); } public run(): TPromise<any> { let activeEditor = this.editorService.getActiveEditor(); const editorWidget = getEditorWidget(activeEditor); if (!editorWidget) { return this.quickOpenService.pick([{ label: nls.localize('noEditor', "No text editor active at this time") }]); } if (!isWritableCodeEditor(activeEditor)) { return this.quickOpenService.pick([{ label: nls.localize('noWritableCodeEditor', "The active code editor is read-only.") }]); } const textModel = getTextModel(editorWidget); const EOLOptions: IChangeEOLEntry[] = [ { label: nlsEOLLF, eol: EndOfLineSequence.LF }, { label: nlsEOLCRLF, eol: EndOfLineSequence.CRLF }, ]; const selectedIndex = (textModel && textModel.getEOL() === '\n') ? 0 : 1; return this.quickOpenService.pick(EOLOptions, { placeHolder: nls.localize('pickEndOfLine', "Select End of Line Sequence"), autoFocus: { autoFocusIndex: selectedIndex } }).then(eol => { if (eol) { activeEditor = this.editorService.getActiveEditor(); const editorWidget = getEditorWidget(activeEditor); if (editorWidget && isWritableCodeEditor(activeEditor)) { const textModel = getTextModel(editorWidget); textModel.setEOL(eol.eol); } } }); } } export class ChangeEncodingAction extends Action { public static ID = 'workbench.action.editor.changeEncoding'; public static LABEL = nls.localize('changeEncoding', "Change File Encoding"); constructor( actionId: string, actionLabel: string, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IQuickOpenService private quickOpenService: IQuickOpenService, @IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService ) { super(actionId, actionLabel); } public run(): TPromise<any> { let activeEditor = this.editorService.getActiveEditor(); if (!getEditorWidget(activeEditor) || !activeEditor.input) { return this.quickOpenService.pick([{ label: nls.localize('noEditor', "No text editor active at this time") }]); } let encodingSupport: IEncodingSupport = toEditorWithEncodingSupport(activeEditor.input); if (!encodingSupport) { return this.quickOpenService.pick([{ label: nls.localize('noFileEditor', "No file active at this time") }]); } let pickActionPromise: TPromise<IPickOpenEntry>; let saveWithEncodingPick: IPickOpenEntry; let reopenWithEncodingPick: IPickOpenEntry; if (language === LANGUAGE_DEFAULT) { saveWithEncodingPick = { label: nls.localize('saveWithEncoding', "Save with Encoding") }; reopenWithEncodingPick = { label: nls.localize('reopenWithEncoding', "Reopen with Encoding") }; } else { saveWithEncodingPick = { label: nls.localize('saveWithEncoding', "Save with Encoding"), detail: 'Save with Encoding', }; reopenWithEncodingPick = { label: nls.localize('reopenWithEncoding', "Reopen with Encoding"), detail: 'Reopen with Encoding' }; } if (encodingSupport instanceof UntitledEditorInput) { pickActionPromise = TPromise.as(saveWithEncodingPick); } else if (!isWritableCodeEditor(activeEditor)) { pickActionPromise = TPromise.as(reopenWithEncodingPick); } else { pickActionPromise = this.quickOpenService.pick([reopenWithEncodingPick, saveWithEncodingPick], { placeHolder: nls.localize('pickAction', "Select Action"), matchOnDetail: true }); } return pickActionPromise.then(action => { if (!action) { return undefined; } return TPromise.timeout(50 /* quick open is sensitive to being opened so soon after another */).then(() => { const configuration = this.configurationService.getConfiguration<IFilesConfiguration>(); const isReopenWithEncoding = (action === reopenWithEncodingPick); const configuredEncoding = configuration && configuration.files && configuration.files.encoding; let directMatchIndex: number; let aliasMatchIndex: number; // All encodings are valid picks const picks: IPickOpenEntry[] = Object.keys(SUPPORTED_ENCODINGS) .sort((k1, k2) => { if (k1 === configuredEncoding) { return -1; } else if (k2 === configuredEncoding) { return 1; } return SUPPORTED_ENCODINGS[k1].order - SUPPORTED_ENCODINGS[k2].order; }) .filter(k => { return !isReopenWithEncoding || !SUPPORTED_ENCODINGS[k].encodeOnly; // hide those that can only be used for encoding if we are about to decode }) .map((key, index) => { if (key === encodingSupport.getEncoding()) { directMatchIndex = index; } else if (SUPPORTED_ENCODINGS[key].alias === encodingSupport.getEncoding()) { aliasMatchIndex = index; } return { id: key, label: SUPPORTED_ENCODINGS[key].labelLong }; }); return this.quickOpenService.pick(picks, { placeHolder: isReopenWithEncoding ? nls.localize('pickEncodingForReopen', "Select File Encoding to Reopen File") : nls.localize('pickEncodingForSave', "Select File Encoding to Save with"), autoFocus: { autoFocusIndex: typeof directMatchIndex === 'number' ? directMatchIndex : typeof aliasMatchIndex === 'number' ? aliasMatchIndex : void 0 } }).then(encoding => { if (encoding) { activeEditor = this.editorService.getActiveEditor(); encodingSupport = toEditorWithEncodingSupport(activeEditor.input); if (encodingSupport && encodingSupport.getEncoding() !== encoding.id) { encodingSupport.setEncoding(encoding.id, isReopenWithEncoding ? EncodingMode.Decode : EncodingMode.Encode); // Set new encoding } } }); }); }); } }
src/vs/workbench/browser/parts/editor/editorStatus.ts
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0001872390421340242, 0.0001704647293081507, 0.0001647603785386309, 0.0001700732100289315, 0.0000035332664083398413 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\n", "\t\treturn TPromise.as(value);\n", "\t}\n", "\n", "\tpublic hasChildren(tree: ITree, element: any): boolean {\n", "\t\treturn element instanceof FileMatch || element instanceof SearchResult;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn [];\n", "\t}\n", "\n", "\tpublic getChildren(tree: ITree, element: any): TPromise<any[]> {\n", "\t\treturn TPromise.as(this._getChildren(element));\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import strings = require('vs/base/common/strings'); import platform = require('vs/base/common/platform'); import errors = require('vs/base/common/errors'); import paths = require('vs/base/common/paths'); import dom = require('vs/base/browser/dom'); import { $ } from 'vs/base/browser/builder'; import { TPromise } from 'vs/base/common/winjs.base'; import { IAction, IActionRunner } from 'vs/base/common/actions'; import { ActionsRenderer } from 'vs/base/parts/tree/browser/actionsRenderer'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { FileLabel } from 'vs/workbench/browser/labels'; import { LeftRightWidget, IRenderer } from 'vs/base/browser/ui/leftRightWidget/leftRightWidget'; import { ITree, IElementCallback, IDataSource, ISorter, IAccessibilityProvider, IFilter } from 'vs/base/parts/tree/browser/tree'; import { ClickBehavior, DefaultController } from 'vs/base/parts/tree/browser/treeDefaults'; import { ContributableActionProvider } from 'vs/workbench/browser/actionBarRegistry'; import { Match, SearchResult, FileMatch, FileMatchOrMatch, SearchModel } from 'vs/workbench/parts/search/common/searchModel'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { Range } from 'vs/editor/common/core/range'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { SearchViewlet } from 'vs/workbench/parts/search/browser/searchViewlet'; import { RemoveAction, ReplaceAllAction, ReplaceAction } from 'vs/workbench/parts/search/browser/searchActions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; export class SearchDataSource implements IDataSource { public getId(tree: ITree, element: any): string { if (element instanceof FileMatch) { return element.id(); } if (element instanceof Match) { return element.id(); } return 'root'; } public getChildren(tree: ITree, element: any): TPromise<any[]> { let value: any[] = []; if (element instanceof FileMatch) { value = element.matches(); } else if (element instanceof SearchResult) { value = element.matches(); } return TPromise.as(value); } public hasChildren(tree: ITree, element: any): boolean { return element instanceof FileMatch || element instanceof SearchResult; } public getParent(tree: ITree, element: any): TPromise<any> { let value: any = null; if (element instanceof Match) { value = element.parent(); } else if (element instanceof FileMatch) { value = element.parent(); } return TPromise.as(value); } } export class SearchSorter implements ISorter { public compare(tree: ITree, elementA: FileMatchOrMatch, elementB: FileMatchOrMatch): number { if (elementA instanceof FileMatch && elementB instanceof FileMatch) { return elementA.resource().fsPath.localeCompare(elementB.resource().fsPath) || elementA.name().localeCompare(elementB.name()); } if (elementA instanceof Match && elementB instanceof Match) { return Range.compareRangesUsingStarts(elementA.range(), elementB.range()); } return undefined; } } class SearchActionProvider extends ContributableActionProvider { constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) { super(); } public hasActions(tree: ITree, element: any): boolean { let input = <SearchResult>tree.getInput(); return element instanceof FileMatch || (input.searchModel.isReplaceActive() || element instanceof Match) || super.hasActions(tree, element); } public getActions(tree: ITree, element: any): TPromise<IAction[]> { return super.getActions(tree, element).then(actions => { let input = <SearchResult>tree.getInput(); if (element instanceof FileMatch) { actions.unshift(new RemoveAction(tree, element)); if (input.searchModel.isReplaceActive() && element.count() > 0) { actions.unshift(this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet)); } } if (element instanceof Match) { if (input.searchModel.isReplaceActive()) { actions.unshift(this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet), new RemoveAction(tree, element)); } } return actions; }); } } export class SearchRenderer extends ActionsRenderer { constructor(actionRunner: IActionRunner, viewlet: SearchViewlet, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IInstantiationService private instantiationService: IInstantiationService) { super({ actionProvider: instantiationService.createInstance(SearchActionProvider, viewlet), actionRunner: actionRunner }); } public getContentHeight(tree: ITree, element: any): number { return 22; } public renderContents(tree: ITree, element: FileMatchOrMatch, domElement: HTMLElement, previousCleanupFn: IElementCallback): IElementCallback { // File if (element instanceof FileMatch) { let fileMatch = <FileMatch>element; let container = $('.filematch'); let leftRenderer: IRenderer; let rightRenderer: IRenderer; let widget: LeftRightWidget; leftRenderer = (left: HTMLElement): any => { const label = this.instantiationService.createInstance(FileLabel, left, void 0); label.setFile(fileMatch.resource()); return () => label.dispose(); }; rightRenderer = (right: HTMLElement) => { let len = fileMatch.count(); new CountBadge(right, len, len > 1 ? nls.localize('searchMatches', "{0} matches found", len) : nls.localize('searchMatch', "{0} match found", len)); return null; }; widget = new LeftRightWidget(container, leftRenderer, rightRenderer); container.appendTo(domElement); return widget.dispose.bind(widget); } // Match else if (element instanceof Match) { dom.addClass(domElement, 'linematch'); let match = <Match>element; let elements: string[] = []; let preview = match.preview(); elements.push('<span>'); elements.push(strings.escape(preview.before)); let searchModel: SearchModel = (<SearchResult>tree.getInput()).searchModel; let showReplaceText = searchModel.isReplaceActive() && !!searchModel.replaceString; elements.push('</span><span class="' + (showReplaceText ? 'replace ' : '') + 'findInFileMatch">'); elements.push(strings.escape(preview.inside)); if (showReplaceText) { elements.push('</span><span class="replaceMatch">'); elements.push(strings.escape(match.replaceString)); } elements.push('</span><span>'); elements.push(strings.escape(preview.after)); elements.push('</span>'); $('a.plain') .innerHtml(elements.join(strings.empty)) .title((preview.before + (showReplaceText ? match.replaceString : preview.inside) + preview.after).trim().substr(0, 999)) .appendTo(domElement); } return null; } } export class SearchAccessibilityProvider implements IAccessibilityProvider { constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) { } public getAriaLabel(tree: ITree, element: FileMatchOrMatch): string { if (element instanceof FileMatch) { const path = this.contextService.toWorkspaceRelativePath(element.resource()) || element.resource().fsPath; return nls.localize('fileMatchAriaLabel', "{0} matches in file {1} of folder {2}, Search result", element.count(), element.name(), paths.dirname(path)); } if (element instanceof Match) { let match = <Match>element; let input = <SearchResult>tree.getInput(); if (input.searchModel.isReplaceActive()) { let preview = match.preview(); return nls.localize('replacePreviewResultAria', "Replace preview result, {0}", preview.before + match.replaceString + preview.after); } return nls.localize('searchResultAria', "{0}, Search result", match.text()); } return undefined; } } export class SearchController extends DefaultController { constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) { super({ clickBehavior: ClickBehavior.ON_MOUSE_DOWN, keyboardSupport: false }); // TODO@Rob these should be commands // Up (from results to inputs) this.downKeyBindingDispatcher.set(KeyCode.UpArrow, this.onUp.bind(this)); // Open to side this.upKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.WinCtrl | KeyCode.Enter : KeyMod.CtrlCmd | KeyCode.Enter, this.onEnter.bind(this)); // Delete this.downKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.CtrlCmd | KeyCode.Backspace : KeyCode.Delete, (tree: ITree, event: any) => { this.onDelete(tree, event); }); // Cancel search this.downKeyBindingDispatcher.set(KeyCode.Escape, (tree: ITree, event: any) => { this.onEscape(tree, event); }); // Replace / Replace All this.downKeyBindingDispatcher.set(ReplaceAllAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplaceAll(tree, event); }); this.downKeyBindingDispatcher.set(ReplaceAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplace(tree, event); }); } protected onEscape(tree: ITree, event: IKeyboardEvent): boolean { if (this.viewlet.cancelSearch()) { return true; } return super.onEscape(tree, event); } private onDelete(tree: ITree, event: IKeyboardEvent): boolean { let input = <SearchResult>tree.getInput(); let result = false; let element = tree.getFocus(); if (element instanceof FileMatch || (element instanceof Match && input.searchModel.isReplaceActive())) { new RemoveAction(tree, element).run().done(null, errors.onUnexpectedError); result = true; } return result; } private onReplace(tree: ITree, event: IKeyboardEvent): boolean { let input = <SearchResult>tree.getInput(); let result = false; let element = tree.getFocus(); if (element instanceof Match && input.searchModel.isReplaceActive()) { this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError); result = true; } return result; } private onReplaceAll(tree: ITree, event: IKeyboardEvent): boolean { let result = false; let element = tree.getFocus(); if (element instanceof FileMatch && element.count() > 0) { this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError); result = true; } return result; } protected onUp(tree: ITree, event: IKeyboardEvent): boolean { if (tree.getNavigator().first() === tree.getFocus()) { this.viewlet.moveFocusFromResults(); return true; } return false; } } export class SearchFilter implements IFilter { public isVisible(tree: ITree, element: any): boolean { return !(element instanceof FileMatch) || element.matches().length > 0; } }
src/vs/workbench/parts/search/browser/searchResultsView.ts
1
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.9916976690292358, 0.14712610840797424, 0.00016623569536022842, 0.0016063574003055692, 0.3317371606826782 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\n", "\t\treturn TPromise.as(value);\n", "\t}\n", "\n", "\tpublic hasChildren(tree: ITree, element: any): boolean {\n", "\t\treturn element instanceof FileMatch || element instanceof SearchResult;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn [];\n", "\t}\n", "\n", "\tpublic getChildren(tree: ITree, element: any): TPromise<any[]> {\n", "\t\treturn TPromise.as(this._getChildren(element));\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 53 }
-------------------------------------------------------------------------------------------------- | HW Code combination | Key | KeyCode combination | UI label | -------------------------------------------------------------------------------------------------- | KeyA | a | A | A | | Shift+KeyA | A | Shift+A | Shift+A | | Ctrl+Alt+KeyA | --- | Ctrl+Alt+A | Ctrl+Alt+A | | Ctrl+Shift+Alt+KeyA | --- | Ctrl+Shift+Alt+A | Ctrl+Shift+Alt+A | -------------------------------------------------------------------------------------------------- | KeyB | b | B | B | | Shift+KeyB | B | Shift+B | Shift+B | | Ctrl+Alt+KeyB | --- | Ctrl+Alt+B | Ctrl+Alt+B | | Ctrl+Shift+Alt+KeyB | --- | Ctrl+Shift+Alt+B | Ctrl+Shift+Alt+B | -------------------------------------------------------------------------------------------------- | KeyC | c | C | C | | Shift+KeyC | C | Shift+C | Shift+C | | Ctrl+Alt+KeyC | --- | Ctrl+Alt+C | Ctrl+Alt+C | | Ctrl+Shift+Alt+KeyC | --- | Ctrl+Shift+Alt+C | Ctrl+Shift+Alt+C | -------------------------------------------------------------------------------------------------- | KeyD | d | D | D | | Shift+KeyD | D | Shift+D | Shift+D | | Ctrl+Alt+KeyD | --- | Ctrl+Alt+D | Ctrl+Alt+D | | Ctrl+Shift+Alt+KeyD | --- | Ctrl+Shift+Alt+D | Ctrl+Shift+Alt+D | -------------------------------------------------------------------------------------------------- | KeyE | e | E | E | | Shift+KeyE | E | Shift+E | Shift+E | | Ctrl+Alt+KeyE | --- | Ctrl+Alt+E | Ctrl+Alt+E | | Ctrl+Shift+Alt+KeyE | --- | Ctrl+Shift+Alt+E | Ctrl+Shift+Alt+E | -------------------------------------------------------------------------------------------------- | KeyF | f | F | F | | Shift+KeyF | F | Shift+F | Shift+F | | Ctrl+Alt+KeyF | --- | Ctrl+Alt+F | Ctrl+Alt+F | | Ctrl+Shift+Alt+KeyF | --- | Ctrl+Shift+Alt+F | Ctrl+Shift+Alt+F | -------------------------------------------------------------------------------------------------- | HW Code combination | Key | KeyCode combination | UI label | -------------------------------------------------------------------------------------------------- | KeyG | g | G | G | | Shift+KeyG | G | Shift+G | Shift+G | | Ctrl+Alt+KeyG | --- | Ctrl+Alt+G | Ctrl+Alt+G | | Ctrl+Shift+Alt+KeyG | --- | Ctrl+Shift+Alt+G | Ctrl+Shift+Alt+G | -------------------------------------------------------------------------------------------------- | KeyH | h | H | H | | Shift+KeyH | H | Shift+H | Shift+H | | Ctrl+Alt+KeyH | --- | Ctrl+Alt+H | Ctrl+Alt+H | | Ctrl+Shift+Alt+KeyH | --- | Ctrl+Shift+Alt+H | Ctrl+Shift+Alt+H | -------------------------------------------------------------------------------------------------- | KeyI | i | I | I | | Shift+KeyI | I | Shift+I | Shift+I | | Ctrl+Alt+KeyI | --- | Ctrl+Alt+I | Ctrl+Alt+I | | Ctrl+Shift+Alt+KeyI | --- | Ctrl+Shift+Alt+I | Ctrl+Shift+Alt+I | -------------------------------------------------------------------------------------------------- | KeyJ | j | J | J | | Shift+KeyJ | J | Shift+J | Shift+J | | Ctrl+Alt+KeyJ | --- | Ctrl+Alt+J | Ctrl+Alt+J | | Ctrl+Shift+Alt+KeyJ | --- | Ctrl+Shift+Alt+J | Ctrl+Shift+Alt+J | -------------------------------------------------------------------------------------------------- | KeyK | k | K | K | | Shift+KeyK | K | Shift+K | Shift+K | | Ctrl+Alt+KeyK | --- | Ctrl+Alt+K | Ctrl+Alt+K | | Ctrl+Shift+Alt+KeyK | --- | Ctrl+Shift+Alt+K | Ctrl+Shift+Alt+K | -------------------------------------------------------------------------------------------------- | KeyL | l | L | L | | Shift+KeyL | L | Shift+L | Shift+L | | Ctrl+Alt+KeyL | --- | Ctrl+Alt+L | Ctrl+Alt+L | | Ctrl+Shift+Alt+KeyL | --- | Ctrl+Shift+Alt+L | Ctrl+Shift+Alt+L | -------------------------------------------------------------------------------------------------- | HW Code combination | Key | KeyCode combination | UI label | -------------------------------------------------------------------------------------------------- | KeyM | m | M | M | | Shift+KeyM | M | Shift+M | Shift+M | | Ctrl+Alt+KeyM | --- | Ctrl+Alt+M | Ctrl+Alt+M | | Ctrl+Shift+Alt+KeyM | --- | Ctrl+Shift+Alt+M | Ctrl+Shift+Alt+M | -------------------------------------------------------------------------------------------------- | KeyN | n | N | N | | Shift+KeyN | N | Shift+N | Shift+N | | Ctrl+Alt+KeyN | --- | Ctrl+Alt+N | Ctrl+Alt+N | | Ctrl+Shift+Alt+KeyN | --- | Ctrl+Shift+Alt+N | Ctrl+Shift+Alt+N | -------------------------------------------------------------------------------------------------- | KeyO | o | O | O | | Shift+KeyO | O | Shift+O | Shift+O | | Ctrl+Alt+KeyO | --- | Ctrl+Alt+O | Ctrl+Alt+O | | Ctrl+Shift+Alt+KeyO | --- | Ctrl+Shift+Alt+O | Ctrl+Shift+Alt+O | -------------------------------------------------------------------------------------------------- | KeyP | p | P | P | | Shift+KeyP | P | Shift+P | Shift+P | | Ctrl+Alt+KeyP | --- | Ctrl+Alt+P | Ctrl+Alt+P | | Ctrl+Shift+Alt+KeyP | --- | Ctrl+Shift+Alt+P | Ctrl+Shift+Alt+P | -------------------------------------------------------------------------------------------------- | KeyQ | q | Q | Q | | Shift+KeyQ | Q | Shift+Q | Shift+Q | | Ctrl+Alt+KeyQ | --- | Ctrl+Alt+Q | Ctrl+Alt+Q | | Ctrl+Shift+Alt+KeyQ | --- | Ctrl+Shift+Alt+Q | Ctrl+Shift+Alt+Q | -------------------------------------------------------------------------------------------------- | KeyR | r | R | R | | Shift+KeyR | R | Shift+R | Shift+R | | Ctrl+Alt+KeyR | --- | Ctrl+Alt+R | Ctrl+Alt+R | | Ctrl+Shift+Alt+KeyR | --- | Ctrl+Shift+Alt+R | Ctrl+Shift+Alt+R | -------------------------------------------------------------------------------------------------- | HW Code combination | Key | KeyCode combination | UI label | -------------------------------------------------------------------------------------------------- | KeyS | s | S | S | | Shift+KeyS | S | Shift+S | Shift+S | | Ctrl+Alt+KeyS | --- | Ctrl+Alt+S | Ctrl+Alt+S | | Ctrl+Shift+Alt+KeyS | --- | Ctrl+Shift+Alt+S | Ctrl+Shift+Alt+S | -------------------------------------------------------------------------------------------------- | KeyT | t | T | T | | Shift+KeyT | T | Shift+T | Shift+T | | Ctrl+Alt+KeyT | --- | Ctrl+Alt+T | Ctrl+Alt+T | | Ctrl+Shift+Alt+KeyT | --- | Ctrl+Shift+Alt+T | Ctrl+Shift+Alt+T | -------------------------------------------------------------------------------------------------- | KeyU | u | U | U | | Shift+KeyU | U | Shift+U | Shift+U | | Ctrl+Alt+KeyU | --- | Ctrl+Alt+U | Ctrl+Alt+U | | Ctrl+Shift+Alt+KeyU | --- | Ctrl+Shift+Alt+U | Ctrl+Shift+Alt+U | -------------------------------------------------------------------------------------------------- | KeyV | v | V | V | | Shift+KeyV | V | Shift+V | Shift+V | | Ctrl+Alt+KeyV | --- | Ctrl+Alt+V | Ctrl+Alt+V | | Ctrl+Shift+Alt+KeyV | --- | Ctrl+Shift+Alt+V | Ctrl+Shift+Alt+V | -------------------------------------------------------------------------------------------------- | KeyW | w | W | W | | Shift+KeyW | W | Shift+W | Shift+W | | Ctrl+Alt+KeyW | --- | Ctrl+Alt+W | Ctrl+Alt+W | | Ctrl+Shift+Alt+KeyW | --- | Ctrl+Shift+Alt+W | Ctrl+Shift+Alt+W | -------------------------------------------------------------------------------------------------- | KeyX | x | X | X | | Shift+KeyX | X | Shift+X | Shift+X | | Ctrl+Alt+KeyX | --- | Ctrl+Alt+X | Ctrl+Alt+X | | Ctrl+Shift+Alt+KeyX | --- | Ctrl+Shift+Alt+X | Ctrl+Shift+Alt+X | -------------------------------------------------------------------------------------------------- | HW Code combination | Key | KeyCode combination | UI label | -------------------------------------------------------------------------------------------------- | KeyY | y | Y | Y | | Shift+KeyY | Y | Shift+Y | Shift+Y | | Ctrl+Alt+KeyY | --- | Ctrl+Alt+Y | Ctrl+Alt+Y | | Ctrl+Shift+Alt+KeyY | --- | Ctrl+Shift+Alt+Y | Ctrl+Shift+Alt+Y | -------------------------------------------------------------------------------------------------- | KeyZ | z | Z | Z | | Shift+KeyZ | Z | Shift+Z | Shift+Z | | Ctrl+Alt+KeyZ | --- | Ctrl+Alt+Z | Ctrl+Alt+Z | | Ctrl+Shift+Alt+KeyZ | --- | Ctrl+Shift+Alt+Z | Ctrl+Shift+Alt+Z | -------------------------------------------------------------------------------------------------- | Digit1 | 1 | 1 | 1 | | Shift+Digit1 | ! | Shift+1 | Shift+1 | | Ctrl+Alt+Digit1 | --- | Ctrl+Alt+1 | Ctrl+Alt+1 | | Ctrl+Shift+Alt+Digit1 | --- | Ctrl+Shift+Alt+1 | Ctrl+Shift+Alt+1 | -------------------------------------------------------------------------------------------------- | Digit2 | 2 | 2 | 2 | | Shift+Digit2 | @ | Shift+2 | Shift+2 | | Ctrl+Alt+Digit2 | --- | Ctrl+Alt+2 | Ctrl+Alt+2 | | Ctrl+Shift+Alt+Digit2 | --- | Ctrl+Shift+Alt+2 | Ctrl+Shift+Alt+2 | -------------------------------------------------------------------------------------------------- | Digit3 | 3 | 3 | 3 | | Shift+Digit3 | # | Shift+3 | Shift+3 | | Ctrl+Alt+Digit3 | --- | Ctrl+Alt+3 | Ctrl+Alt+3 | | Ctrl+Shift+Alt+Digit3 | --- | Ctrl+Shift+Alt+3 | Ctrl+Shift+Alt+3 | -------------------------------------------------------------------------------------------------- | Digit4 | 4 | 4 | 4 | | Shift+Digit4 | $ | Shift+4 | Shift+4 | | Ctrl+Alt+Digit4 | --- | Ctrl+Alt+4 | Ctrl+Alt+4 | | Ctrl+Shift+Alt+Digit4 | --- | Ctrl+Shift+Alt+4 | Ctrl+Shift+Alt+4 | -------------------------------------------------------------------------------------------------- | HW Code combination | Key | KeyCode combination | UI label | -------------------------------------------------------------------------------------------------- | Digit5 | 5 | 5 | 5 | | Shift+Digit5 | % | Shift+5 | Shift+5 | | Ctrl+Alt+Digit5 | --- | Ctrl+Alt+5 | Ctrl+Alt+5 | | Ctrl+Shift+Alt+Digit5 | --- | Ctrl+Shift+Alt+5 | Ctrl+Shift+Alt+5 | -------------------------------------------------------------------------------------------------- | Digit6 | 6 | 6 | 6 | | Shift+Digit6 | ^ | Shift+6 | Shift+6 | | Ctrl+Alt+Digit6 | --- | Ctrl+Alt+6 | Ctrl+Alt+6 | | Ctrl+Shift+Alt+Digit6 | --- | Ctrl+Shift+Alt+6 | Ctrl+Shift+Alt+6 | -------------------------------------------------------------------------------------------------- | Digit7 | 7 | 7 | 7 | | Shift+Digit7 | & | Shift+7 | Shift+7 | | Ctrl+Alt+Digit7 | --- | Ctrl+Alt+7 | Ctrl+Alt+7 | | Ctrl+Shift+Alt+Digit7 | --- | Ctrl+Shift+Alt+7 | Ctrl+Shift+Alt+7 | -------------------------------------------------------------------------------------------------- | Digit8 | 8 | 8 | 8 | | Shift+Digit8 | * | Shift+8 | Shift+8 | | Ctrl+Alt+Digit8 | --- | Ctrl+Alt+8 | Ctrl+Alt+8 | | Ctrl+Shift+Alt+Digit8 | --- | Ctrl+Shift+Alt+8 | Ctrl+Shift+Alt+8 | -------------------------------------------------------------------------------------------------- | Digit9 | 9 | 9 | 9 | | Shift+Digit9 | ( | Shift+9 | Shift+9 | | Ctrl+Alt+Digit9 | --- | Ctrl+Alt+9 | Ctrl+Alt+9 | | Ctrl+Shift+Alt+Digit9 | --- | Ctrl+Shift+Alt+9 | Ctrl+Shift+Alt+9 | -------------------------------------------------------------------------------------------------- | Digit0 | 0 | 0 | 0 | | Shift+Digit0 | ) | Shift+0 | Shift+0 | | Ctrl+Alt+Digit0 | --- | Ctrl+Alt+0 | Ctrl+Alt+0 | | Ctrl+Shift+Alt+Digit0 | --- | Ctrl+Shift+Alt+0 | Ctrl+Shift+Alt+0 | -------------------------------------------------------------------------------------------------- | HW Code combination | Key | KeyCode combination | UI label | -------------------------------------------------------------------------------------------------- | Minus | - | - | - | | Shift+Minus | _ | Shift+- | Shift+- | | Ctrl+Alt+Minus | --- | Ctrl+Alt+- | Ctrl+Alt+- | | Ctrl+Shift+Alt+Minus | --- | Ctrl+Shift+Alt+- | Ctrl+Shift+Alt+- | -------------------------------------------------------------------------------------------------- | Equal | = | = | = | | Shift+Equal | + | Shift+= | Shift+= | | Ctrl+Alt+Equal | --- | Ctrl+Alt+= | Ctrl+Alt+= | | Ctrl+Shift+Alt+Equal | --- | Ctrl+Shift+Alt+= | Ctrl+Shift+Alt+= | -------------------------------------------------------------------------------------------------- | BracketLeft | [ | [ | [ | | Shift+BracketLeft | { | Shift+[ | Shift+[ | | Ctrl+Alt+BracketLeft | --- | Ctrl+Alt+[ | Ctrl+Alt+[ | | Ctrl+Shift+Alt+BracketLeft | --- | Ctrl+Shift+Alt+[ | Ctrl+Shift+Alt+[ | -------------------------------------------------------------------------------------------------- | BracketRight | ] | ] | ] | | Shift+BracketRight | } | Shift+] | Shift+] | | Ctrl+Alt+BracketRight | --- | Ctrl+Alt+] | Ctrl+Alt+] | | Ctrl+Shift+Alt+BracketRight | --- | Ctrl+Shift+Alt+] | Ctrl+Shift+Alt+] | -------------------------------------------------------------------------------------------------- | Backslash | \ | \ | \ | | Shift+Backslash | | | Shift+\ | Shift+\ | | Ctrl+Alt+Backslash | --- | Ctrl+Alt+\ | Ctrl+Alt+\ | | Ctrl+Shift+Alt+Backslash | --- | Ctrl+Shift+Alt+\ | Ctrl+Shift+Alt+\ | -------------------------------------------------------------------------------------------------- | IntlHash | --- | undefined | undefined | | Shift+IntlHash | --- | Shift+undefined | Shift+undefined | | Ctrl+Alt+IntlHash | --- | Ctrl+Alt+undefined | Ctrl+Alt+undefined | | Ctrl+Shift+Alt+IntlHash | --- | Ctrl+Shift+Alt+undefined | Ctrl+Shift+Alt+undefined | -------------------------------------------------------------------------------------------------- | HW Code combination | Key | KeyCode combination | UI label | -------------------------------------------------------------------------------------------------- | Semicolon | ; | ; | ; | | Shift+Semicolon | : | Shift+; | Shift+; | | Ctrl+Alt+Semicolon | --- | Ctrl+Alt+; | Ctrl+Alt+; | | Ctrl+Shift+Alt+Semicolon | --- | Ctrl+Shift+Alt+; | Ctrl+Shift+Alt+; | -------------------------------------------------------------------------------------------------- | Quote | ' | ' | ' | | Shift+Quote | " | Shift+' | Shift+' | | Ctrl+Alt+Quote | --- | Ctrl+Alt+' | Ctrl+Alt+' | | Ctrl+Shift+Alt+Quote | --- | Ctrl+Shift+Alt+' | Ctrl+Shift+Alt+' | -------------------------------------------------------------------------------------------------- | Backquote | ` | ` | ` | | Shift+Backquote | ~ | Shift+` | Shift+` | | Ctrl+Alt+Backquote | --- | Ctrl+Alt+` | Ctrl+Alt+` | | Ctrl+Shift+Alt+Backquote | --- | Ctrl+Shift+Alt+` | Ctrl+Shift+Alt+` | -------------------------------------------------------------------------------------------------- | Comma | , | , | , | | Shift+Comma | < | Shift+, | Shift+, | | Ctrl+Alt+Comma | --- | Ctrl+Alt+, | Ctrl+Alt+, | | Ctrl+Shift+Alt+Comma | --- | Ctrl+Shift+Alt+, | Ctrl+Shift+Alt+, | -------------------------------------------------------------------------------------------------- | Period | . | . | . | | Shift+Period | > | Shift+. | Shift+. | | Ctrl+Alt+Period | --- | Ctrl+Alt+. | Ctrl+Alt+. | | Ctrl+Shift+Alt+Period | --- | Ctrl+Shift+Alt+. | Ctrl+Shift+Alt+. | -------------------------------------------------------------------------------------------------- | Slash | / | / | / | | Shift+Slash | ? | Shift+/ | Shift+/ | | Ctrl+Alt+Slash | --- | Ctrl+Alt+/ | Ctrl+Alt+/ | | Ctrl+Shift+Alt+Slash | --- | Ctrl+Shift+Alt+/ | Ctrl+Shift+Alt+/ | -------------------------------------------------------------------------------------------------- | HW Code combination | Key | KeyCode combination | UI label | -------------------------------------------------------------------------------------------------- | IntlBackslash | \ | OEM_102 | \ | | Shift+IntlBackslash | | | Shift+OEM_102 | Shift+\ | | Ctrl+Alt+IntlBackslash | --- | Ctrl+Alt+OEM_102 | Ctrl+Alt+\ | | Ctrl+Shift+Alt+IntlBackslash | --- | Ctrl+Shift+Alt+OEM_102 | Ctrl+Shift+Alt+\ | --------------------------------------------------------------------------------------------------
src/vs/workbench/services/keybinding/test/win_en_us.txt
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0002107204491039738, 0.00016948602569755167, 0.00016445291112177074, 0.00016698411491233855, 0.000008647827598906588 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\n", "\t\treturn TPromise.as(value);\n", "\t}\n", "\n", "\tpublic hasChildren(tree: ITree, element: any): boolean {\n", "\t\treturn element instanceof FileMatch || element instanceof SearchResult;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn [];\n", "\t}\n", "\n", "\tpublic getChildren(tree: ITree, element: any): TPromise<any[]> {\n", "\t\treturn TPromise.as(this._getChildren(element));\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * 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. { "DebugConfig.failed": "Non è possibile creare il file 'launch.json' all'interno della cartella '.vscode' ({0}).", "app.launch.json.compound.name": "Nome dell'elemento compounds. Viene visualizzato nel menu a discesa della configurazione di avvio.", "app.launch.json.compounds": "Elenco degli elementi compounds. Ogni elemento compounds fa riferimento a più configurazioni che verranno avviate insieme.", "app.launch.json.compounds.configurations": "Nomi delle configurazioni che verranno avviate per questo elemento compounds.", "app.launch.json.configurations": "Elenco delle configurazioni. Aggiungere nuove configurazioni o modificare quelle esistenti con IntelliSense.", "app.launch.json.title": "Avvia", "app.launch.json.version": "Versione di questo formato di file.", "debugNoType": "L'adattatore di debug 'type' non può essere omesso e deve essere di tipo 'string'.", "selectDebug": "Seleziona ambiente", "vscode.extension.contributes.breakpoints": "Punti di interruzione per contributes.", "vscode.extension.contributes.breakpoints.language": "Consente i punti di interruzione per questo linguaggio.", "vscode.extension.contributes.debuggers": "Adattatori di debug per contributes.", "vscode.extension.contributes.debuggers.adapterExecutableCommand": "Se è specificato, Visual Studio Code chiamerà questo comando per determinare il percorso eseguibile della scheda di debug e gli argomenti da passare.", "vscode.extension.contributes.debuggers.args": "Argomenti facoltativi da passare all'adattatore.", "vscode.extension.contributes.debuggers.configurationAttributes": "Configurazioni dello schema JSON per la convalida di 'launch.json'.", "vscode.extension.contributes.debuggers.configurationSnippets": "Frammenti per l'aggiunta di nuove configurazioni in 'launch.json'.", "vscode.extension.contributes.debuggers.initialConfigurations": "Configurazioni per generare la versione iniziale di 'launch.json'.", "vscode.extension.contributes.debuggers.label": "Nome visualizzato per questo adattatore di debug.", "vscode.extension.contributes.debuggers.languages": "Elenco dei linguaggi. per cui l'estensione di debug può essere considerata il \"debugger predefinito\".", "vscode.extension.contributes.debuggers.linux": "Impostazioni specifiche di Linux.", "vscode.extension.contributes.debuggers.linux.runtime": "Runtime usato per Linux.", "vscode.extension.contributes.debuggers.osx": "Impostazioni specifiche di OS X.", "vscode.extension.contributes.debuggers.osx.runtime": "Runtime usato per OS X.", "vscode.extension.contributes.debuggers.program": "Percorso del programma dell'adattatore di debug. Il percorso è assoluto o relativo alla cartella delle estensioni.", "vscode.extension.contributes.debuggers.runtime": "Runtime facoltativo nel caso in cui l'attributo del programma non sia un eseguibile ma richieda un runtime.", "vscode.extension.contributes.debuggers.runtimeArgs": "Argomenti del runtime facoltativo.", "vscode.extension.contributes.debuggers.startSessionCommand": "Se è specificato, Visual Studio Code chiamerà questo comando per le azioni \"debug\" o \"run\" previste come destinazione di questa estensione.", "vscode.extension.contributes.debuggers.type": "Identificatore univoco per questo adattatore di debug.", "vscode.extension.contributes.debuggers.variables": "Mapping tra le variabili interattive, ad esempio ${action.pickProcess}, in `launch.json` e un comando.", "vscode.extension.contributes.debuggers.windows": "Impostazioni specifiche di Windows.", "vscode.extension.contributes.debuggers.windows.runtime": "Runtime usato per Windows." }
i18n/ita/src/vs/workbench/parts/debug/electron-browser/debugConfigurationManager.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0001712830417091027, 0.00016873257118277252, 0.000164997938554734, 0.0001693246595095843, 0.0000023164154754340416 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\n", "\t\treturn TPromise.as(value);\n", "\t}\n", "\n", "\tpublic hasChildren(tree: ITree, element: any): boolean {\n", "\t\treturn element instanceof FileMatch || element instanceof SearchResult;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn [];\n", "\t}\n", "\n", "\tpublic getChildren(tree: ITree, element: any): TPromise<any[]> {\n", "\t\treturn TPromise.as(this._getChildren(element));\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * 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. { "markdown.preview.doubleClickToSwitchToEditor.desc": "Двойной щелчок в области предварительного просмотра Markdown в редакторе.", "markdown.preview.fontFamily.desc": "Определяет семейство шрифтов, используемое в области предварительного просмотра файла Markdown.", "markdown.preview.fontSize.desc": "Определяет размер шрифта (в пикселях), используемый в области предварительного просмотра файла Markdown.", "markdown.preview.lineHeight.desc": "Определяет высоту строки, используемую в области предварительного просмотра файла Markdown. Это значение задается относительно размера шрифта.", "markdown.preview.markEditorSelection.desc": "Выделение выбранного в текущем редакторе в предпросмотре Markdown.", "markdown.preview.scrollEditorWithPreview.desc": "При прокрутке предпросмотра Markdown обновите представление в редакторе.", "markdown.preview.scrollPreviewWithEditorSelection.desc": "Прокрутка предпросмотра Markdown до выбранной строки в редакторе.", "markdown.preview.title": "Открыть область предварительного просмотра", "markdown.previewFrontMatter.dec": "Определяет обработку титульных листов YAML в области предварительного просмотра файла Markdown. Значение \"скрыть\" удаляет титульные листы. В противном случае титульные листы обрабатываются как содержимое файла Markdown.", "markdown.previewSide.title": "Открыть область предварительного просмотра сбоку", "markdown.showPreviewSecuritySelector.title": "Изменить параметры безопасности для предварительного просмотра Markdown", "markdown.showSource.title": "Показать источник", "markdown.styles.dec": "Список URL-адресов или локальных путей к таблицам стилей CSS, используемых из области предварительного просмотра файла Markdown. Относительные пути интерпретируются относительно папки, открытой в проводнике. Если папка не открыта, они интерпретируются относительно расположения файла Markdown. Все символы \"\" должны записываться в виде \"\\\"." }
i18n/rus/extensions/markdown/package.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00515543669462204, 0.002017310122027993, 0.00017702055629342794, 0.0007194725912995636, 0.0022300139535218477 ]
{ "id": 7, "code_window": [ "\n", "\t\treturn TPromise.as(value);\n", "\t}\n", "}\n", "\n", "export class SearchSorter implements ISorter {\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tpublic shouldAutoexpand(tree: ITree, element: any): boolean {\n", "\t\tconst numChildren = this._getChildren(element).length;\n", "\t\treturn numChildren > 0 && numChildren < SearchDataSource.AUTOEXPAND_CHILD_LIMIT;\n", "\t}\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/searchviewlet'; import nls = require('vs/nls'); import { TPromise } from 'vs/base/common/winjs.base'; import { Emitter, debounceEvent } from 'vs/base/common/event'; import { EditorType, ICommonCodeEditor } from 'vs/editor/common/editorCommon'; import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import aria = require('vs/base/browser/ui/aria/aria'); import { IExpression } from 'vs/base/common/glob'; import env = require('vs/base/common/platform'); import { isFunction } from 'vs/base/common/types'; import { Delayer } from 'vs/base/common/async'; import URI from 'vs/base/common/uri'; import strings = require('vs/base/common/strings'); import dom = require('vs/base/browser/dom'); import { IAction, Action } from 'vs/base/common/actions'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import { FindInput } from 'vs/base/browser/ui/findinput/findInput'; import { ITree } from 'vs/base/parts/tree/browser/tree'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { Scope } from 'vs/workbench/common/memento'; import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { getOutOfWorkspaceEditorResources } from 'vs/workbench/common/editor'; import { FileChangeType, FileChangesEvent, IFileService, isEqual } from 'vs/platform/files/common/files'; import { Viewlet } from 'vs/workbench/browser/viewlet'; import { Match, FileMatch, SearchModel, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService } from 'vs/workbench/parts/search/common/searchModel'; import { QueryBuilder } from 'vs/workbench/parts/search/common/searchQuery'; import { MessageType, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { getExcludes, ISearchProgressItem, ISearchComplete, ISearchQuery, IQueryOptions, ISearchConfiguration } from 'vs/platform/search/common/search'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IMessageService } from 'vs/platform/message/common/message'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { KeyCode } from 'vs/base/common/keyCodes'; import { PatternInputWidget } from 'vs/workbench/parts/search/browser/patternInputWidget'; import { SearchRenderer, SearchDataSource, SearchSorter, SearchController, SearchAccessibilityProvider, SearchFilter } from 'vs/workbench/parts/search/browser/searchResultsView'; import { SearchWidget } from 'vs/workbench/parts/search/browser/searchWidget'; import { RefreshAction, CollapseAllAction, ClearSearchResultsAction, ConfigureGlobalExclusionsAction } from 'vs/workbench/parts/search/browser/searchActions'; import { IReplaceService } from 'vs/workbench/parts/search/common/replace'; import Severity from 'vs/base/common/severity'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { OpenFolderAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/fileActions'; import * as Constants from 'vs/workbench/parts/search/common/constants'; import { IListService } from 'vs/platform/list/browser/listService'; import { IThemeService, ITheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { editorFindMatchHighlight } from 'vs/platform/theme/common/colorRegistry'; export class SearchViewlet extends Viewlet { private static MAX_TEXT_RESULTS = 2048; private static SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace'; private isDisposed: boolean; private toDispose: lifecycle.IDisposable[]; private loading: boolean; private queryBuilder: QueryBuilder; private viewModel: SearchModel; private callOnModelChange: lifecycle.IDisposable[]; private viewletVisible: IContextKey<boolean>; private inputBoxFocussed: IContextKey<boolean>; private actionRegistry: { [key: string]: Action; }; private tree: ITree; private viewletSettings: any; private domNode: Builder; private messages: Builder; private searchWidgetsContainer: Builder; private searchWidget: SearchWidget; private size: Dimension; private queryDetails: HTMLElement; private inputPatternExclusions: PatternInputWidget; private inputPatternGlobalExclusions: InputBox; private inputPatternGlobalExclusionsContainer: Builder; private inputPatternIncludes: PatternInputWidget; private results: Builder; private currentSelectedFileMatch: FileMatch; private selectCurrentMatchEmitter: Emitter<string>; private delayedRefresh: Delayer<void>; constructor( @ITelemetryService telemetryService: ITelemetryService, @IFileService private fileService: IFileService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IProgressService private progressService: IProgressService, @IMessageService private messageService: IMessageService, @IStorageService private storageService: IStorageService, @IContextViewService private contextViewService: IContextViewService, @IInstantiationService private instantiationService: IInstantiationService, @IConfigurationService private configurationService: IConfigurationService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService, @IContextKeyService private contextKeyService: IContextKeyService, @IKeybindingService private keybindingService: IKeybindingService, @IReplaceService private replaceService: IReplaceService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IPreferencesService private preferencesService: IPreferencesService, @IListService private listService: IListService, @IThemeService protected themeService: IThemeService ) { super(Constants.VIEWLET_ID, telemetryService, themeService); this.toDispose = []; this.viewletVisible = Constants.SearchViewletVisibleKey.bindTo(contextKeyService); this.inputBoxFocussed = Constants.InputBoxFocussedKey.bindTo(this.contextKeyService); this.callOnModelChange = []; this.queryBuilder = this.instantiationService.createInstance(QueryBuilder); this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE); this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e))); this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); this.selectCurrentMatchEmitter = new Emitter<string>(); debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true) (() => this.selectCurrentMatch()); this.delayedRefresh = new Delayer<void>(250); } private onConfigurationUpdated(configuration: any): void { this.updateGlobalPatternExclusions(configuration); } public create(parent: Builder): TPromise<void> { super.create(parent); this.viewModel = this.searchWorkbenchService.searchModel; let builder: Builder; this.domNode = parent.div({ 'class': 'search-viewlet' }, (div) => { builder = div; }); builder.div({ 'class': ['search-widgets-container'] }, (div) => { this.searchWidgetsContainer = div; }); this.createSearchWidget(this.searchWidgetsContainer); let filePatterns = this.viewletSettings['query.filePatterns'] || ''; let patternExclusions = this.viewletSettings['query.folderExclusions'] || ''; let exclusionsUsePattern = this.viewletSettings['query.exclusionsUsePattern']; let includesUsePattern = this.viewletSettings['query.includesUsePattern']; let patternIncludes = this.viewletSettings['query.folderIncludes'] || ''; let useIgnoreFiles = this.viewletSettings['query.useIgnoreFiles']; this.queryDetails = this.searchWidgetsContainer.div({ 'class': ['query-details'] }, (builder) => { builder.div({ 'class': 'more', 'tabindex': 0, 'role': 'button', 'title': nls.localize('moreSearch', "Toggle Search Details") }) .on(dom.EventType.CLICK, (e) => { dom.EventHelper.stop(e); this.toggleFileTypes(true); }).on(dom.EventType.KEY_UP, (e: KeyboardEvent) => { let event = new StandardKeyboardEvent(e); if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { dom.EventHelper.stop(e); this.toggleFileTypes(); } }); //folder includes list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.includes', "files to include"); builder.element('h4', { text: title }); this.inputPatternIncludes = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.includes', 'Search Include Patterns') }); this.inputPatternIncludes.setIsGlobPattern(includesUsePattern); this.inputPatternIncludes.setValue(patternIncludes); this.inputPatternIncludes .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternIncludes.inputFocusTracker); }); //pattern exclusion list builder.div({ 'class': 'file-types' }, (builder) => { let title = nls.localize('searchScope.excludes', "files to exclude"); builder.element('h4', { text: title }); const configuration = this.configurationService.getConfiguration<ISearchConfiguration>(); this.inputPatternExclusions = new PatternInputWidget(builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns') }, configuration.search.useRipgrep); this.inputPatternExclusions.setIsGlobPattern(exclusionsUsePattern); this.inputPatternExclusions.setValue(patternExclusions); this.inputPatternExclusions.setUseIgnoreFiles(useIgnoreFiles); this.inputPatternExclusions .on(FindInput.OPTION_CHANGE, (e) => { this.onQueryChanged(false); }); this.inputPatternExclusions.onSubmit(() => this.onQueryChanged(true)); this.trackInputBox(this.inputPatternExclusions.inputFocusTracker); }); // add hint if we have global exclusion this.inputPatternGlobalExclusionsContainer = builder.div({ 'class': 'file-types global-exclude disabled' }, (builder) => { let title = nls.localize('global.searchScope.folders', "files excluded through settings"); builder.element('h4', { text: title }); this.inputPatternGlobalExclusions = new InputBox(builder.getContainer(), this.contextViewService, { actions: [this.instantiationService.createInstance(ConfigureGlobalExclusionsAction)], ariaLabel: nls.localize('label.global.excludes', 'Configured Search Exclude Patterns') }); this.inputPatternGlobalExclusions.inputElement.readOnly = true; $(this.inputPatternGlobalExclusions.inputElement).attr('aria-readonly', 'true'); $(this.inputPatternGlobalExclusions.inputElement).addClass('disabled'); }).hide(); }).getHTMLElement(); this.messages = builder.div({ 'class': 'messages' }).hide().clone(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.createSearchResultsView(builder); this.actionRegistry = <any>{}; let actions: Action[] = [new CollapseAllAction(this), new RefreshAction(this), new ClearSearchResultsAction(this)]; actions.forEach((action) => { this.actionRegistry[action.id] = action; }); if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '') { this.toggleFileTypes(true, true, true); } this.updateGlobalPatternExclusions(this.configurationService.getConfiguration<ISearchConfiguration>()); this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event))); return TPromise.as(null); } public get searchAndReplaceWidget(): SearchWidget { return this.searchWidget; } private createSearchWidget(builder: Builder): void { let contentPattern = this.viewletSettings['query.contentPattern'] || ''; let isRegex = this.viewletSettings['query.regex'] === true; let isWholeWords = this.viewletSettings['query.wholeWords'] === true; let isCaseSensitive = this.viewletSettings['query.caseSensitive'] === true; this.searchWidget = new SearchWidget(builder, this.contextViewService, { value: contentPattern, isRegex: isRegex, isCaseSensitive: isCaseSensitive, isWholeWords: isWholeWords }, this.contextKeyService, this.keybindingService, this.instantiationService); if (this.storageService.getBoolean(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) { this.searchWidget.toggleReplace(true); } this.toUnbind.push(this.searchWidget); this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh))); this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch())); this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard))); this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled())); this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => { this.viewModel.replaceActive = state; this.tree.refresh(); })); this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => { this.viewModel.replaceString = this.searchWidget.getReplaceValue(); this.delayedRefresh.trigger(() => this.tree.refresh()); })); this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll())); this.trackInputBox(this.searchWidget.searchInputFocusTracker); this.trackInputBox(this.searchWidget.replaceInputFocusTracker); } private trackInputBox(inputFocusTracker: dom.IFocusTracker): void { this.toUnbind.push(inputFocusTracker.addFocusListener(() => { this.inputBoxFocussed.set(true); })); this.toUnbind.push(inputFocusTracker.addBlurListener(() => { this.inputBoxFocussed.set(this.searchWidget.searchInputHasFocus() || this.searchWidget.replaceInputHasFocus() || this.inputPatternIncludes.inputHasFocus() || this.inputPatternExclusions.inputHasFocus()); })); } private onReplaceToggled(): void { this.layout(this.size); this.storageService.store(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, this.searchAndReplaceWidget.isReplaceShown(), StorageScope.WORKSPACE); } private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> { return this.refreshTree(event).then(() => { this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty()); this.updateSearchResultCount(); }); } private refreshTree(event?: IChangeEvent): TPromise<any> { if (!event) { return this.tree.refresh(this.viewModel.searchResult); } if (event.added || event.removed) { return this.tree.refresh(this.viewModel.searchResult).then(() => { if (event.added) { event.elements.forEach(element => { this.autoExpandFileMatch(element, true); }); } }); } else { if (event.elements.length === 1) { return this.tree.refresh(event.elements[0]); } else { return this.tree.refresh(event.elements); } } } private replaceAll(): void { if (this.viewModel.searchResult.count() === 0) { return; } let progressRunner = this.progressService.show(100); let occurrences = this.viewModel.searchResult.count(); let fileCount = this.viewModel.searchResult.fileCount(); let replaceValue = this.searchWidget.getReplaceValue() || ''; let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue); let confirmation = { title: nls.localize('replaceAll.confirmation.title', "Replace All"), message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue), primaryButton: nls.localize('replaceAll.confirm.button', "Replace") }; if (this.messageService.confirm(confirmation)) { this.searchWidget.setReplaceAllActionState(false); this.viewModel.searchResult.replaceAll(progressRunner).then(() => { progressRunner.done(); this.clearMessage() .p({ text: afterReplaceAllMessage }); }, (error) => { progressRunner.done(); errors.isPromiseCanceledError(error); this.messageService.show(Severity.Error, error); }); } } private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file'.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount); } private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file'?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount); } private clearMessage(): Builder { return this.messages.empty().show() .asContainer().div({ 'class': 'message' }) .asContainer(); } private createSearchResultsView(builder: Builder): void { builder.div({ 'class': 'results' }, (div) => { this.results = div; this.results.addClass('show-file-icons'); let dataSource = new SearchDataSource(); let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this); this.tree = new Tree(div.getHTMLElement(), { dataSource: dataSource, renderer: renderer, sorter: new SearchSorter(), filter: new SearchFilter(), controller: new SearchController(this, this.instantiationService), accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider) }, { ariaLabel: nls.localize('treeAriaLabel', "Search Results"), keyboardSupport: false }); this.tree.setInput(this.viewModel.searchResult); this.toUnbind.push(renderer); this.toUnbind.push(this.listService.register(this.tree)); let focusToSelectionDelayHandle: number; let lastFocusToSelection: number; const focusToSelection = (originalEvent: KeyboardEvent | MouseEvent) => { lastFocusToSelection = Date.now(); const focus = this.tree.getFocus(); let payload: any; if (focus instanceof Match) { payload = { origin: 'keyboard', originalEvent, preserveFocus: true }; } this.tree.setSelection([focus], payload); focusToSelectionDelayHandle = void 0; }; this.toUnbind.push(this.tree.addListener2('focus', (event: any) => { let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; // debounce setting selection so that we are not too quickly opening // when the user is pressing and holding the key to move focus if (focusToSelectionDelayHandle || (Date.now() - lastFocusToSelection <= 75)) { window.clearTimeout(focusToSelectionDelayHandle); focusToSelectionDelayHandle = window.setTimeout(() => focusToSelection(originalEvent), 300); } else { focusToSelection(originalEvent); } } })); this.toUnbind.push(this.tree.addListener2('selection', (event: any) => { let element: any; let keyboard = event.payload && event.payload.origin === 'keyboard'; if (keyboard) { element = this.tree.getFocus(); } else { element = event.selection[0]; } let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent; let doubleClick = (event.payload && event.payload.origin === 'mouse' && originalEvent && originalEvent.detail === 2); if (doubleClick && originalEvent) { originalEvent.preventDefault(); // focus moves to editor, we need to prevent default } let sideBySide = (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey)); let focusEditor = (keyboard && (!event.payload || !event.payload.preserveFocus)) || doubleClick; if (element instanceof Match) { let selectedMatch: Match = element; if (this.currentSelectedFileMatch) { this.currentSelectedFileMatch.setSelectedMatch(null); } this.currentSelectedFileMatch = selectedMatch.parent(); this.currentSelectedFileMatch.setSelectedMatch(selectedMatch); if (!event.payload.preventEditorOpen) { this.onFocus(selectedMatch, !focusEditor, sideBySide, doubleClick); } } })); }); } private updateGlobalPatternExclusions(configuration: ISearchConfiguration): void { if (this.inputPatternGlobalExclusionsContainer) { let excludes = getExcludes(configuration); if (excludes) { let exclusions = Object.getOwnPropertyNames(excludes).filter(exclude => excludes[exclude] === true || typeof excludes[exclude].when === 'string').map(exclude => { if (excludes[exclude] === true) { return exclude; } return nls.localize('globLabel', "{0} when {1}", exclude, excludes[exclude].when); }); if (exclusions.length) { const values = exclusions.join(', '); this.inputPatternGlobalExclusions.value = values; this.inputPatternGlobalExclusions.inputElement.title = values; this.inputPatternGlobalExclusionsContainer.show(); } else { this.inputPatternGlobalExclusionsContainer.hide(); } } } } public selectCurrentMatch(): void { const focused = this.tree.getFocus(); const eventPayload = { focusEditor: true }; this.tree.setSelection([focused], eventPayload); } public selectNextMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); // Expand the initial selected node, if needed if (selected instanceof FileMatch) { if (!this.tree.isExpanded(selected)) { this.tree.expand(selected); } } let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let next = navigator.next(); if (!next) { // Reached the end - get a new navigator from the root. // .first and .last only work when subTreeOnly = true. Maybe there's a simpler way. navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); next = navigator.first(); } // Expand and go past FileMatch nodes if (!(next instanceof Match)) { if (!this.tree.isExpanded(next)) { this.tree.expand(next); } // Select the FileMatch's first child next = navigator.next(); } // Reveal the newly selected element const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(next, eventPayload); this.tree.setSelection([next], eventPayload); this.tree.reveal(next); this.selectCurrentMatchEmitter.fire(); } public selectPreviousMatch(): void { const [selected]: FileMatchOrMatch[] = this.tree.getSelection(); let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false); let prev = navigator.previous(); // Expand and go past FileMatch nodes if (!(prev instanceof Match)) { prev = navigator.previous(); if (!prev) { // Wrap around. Get a new tree starting from the root navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true); prev = navigator.last(); // This is complicated because .last will set the navigator to the last FileMatch, // so expand it and FF to its last child this.tree.expand(prev); let tmp; while (tmp = navigator.next()) { prev = tmp; } } if (!(prev instanceof Match)) { // There is a second non-Match result, which must be a collapsed FileMatch. // Expand it then select its last child. navigator.next(); this.tree.expand(prev); prev = navigator.previous(); } } // Reveal the newly selected element if (prev) { const eventPayload = { preventEditorOpen: true }; this.tree.setFocus(prev, eventPayload); this.tree.setSelection([prev], eventPayload); this.tree.reveal(prev); this.selectCurrentMatchEmitter.fire(); } } public setVisible(visible: boolean): TPromise<void> { let promise: TPromise<void>; this.viewletVisible.set(visible); if (visible) { promise = super.setVisible(visible); this.tree.onVisible(); } else { this.tree.onHidden(); promise = super.setVisible(visible); } // Enable highlights if there are searchresults if (this.viewModel) { this.viewModel.searchResult.toggleHighlights(visible); } // Open focused element from results in case the editor area is otherwise empty if (visible && !this.editorService.getActiveEditor()) { let focus = this.tree.getFocus(); if (focus) { this.onFocus(focus, true); } } return promise; } public focus(): void { super.focus(); let selectedText = this.getSearchTextFromEditor(); if (selectedText) { this.searchWidget.searchInput.setValue(selectedText); } this.searchWidget.focus(); } public focusNextInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { if (this.searchWidget.isReplaceShown()) { this.searchWidget.focus(true, true); } else { this.moveFocusFromSearchOrReplace(); } return; } if (this.searchWidget.replaceInputHasFocus()) { this.moveFocusFromSearchOrReplace(); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.selectTreeIfNotSelected(); return; } } private moveFocusFromSearchOrReplace() { if (this.showsFileTypes()) { this.toggleFileTypes(true, this.showsFileTypes()); } else { this.selectTreeIfNotSelected(); } } public focusPreviousInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { return; } if (this.searchWidget.replaceInputHasFocus()) { this.searchWidget.focus(true); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.searchWidget.focus(true, true); return; } if (this.inputPatternExclusions.inputHasFocus()) { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); return; } } public moveFocusFromResults(): void { if (this.showsFileTypes()) { this.toggleFileTypes(true, true, false, true); } else { this.searchWidget.focus(true, true); } } private reLayout(): void { if (this.isDisposed) { return; } this.searchWidget.setWidth(this.size.width - 25 /* container margin */); this.inputPatternExclusions.setWidth(this.size.width - 28 /* container margin */); this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */); this.inputPatternGlobalExclusions.width = this.size.width - 28 /* container margin */ - 24 /* actions */; const messagesSize = this.messages.isHidden() ? 0 : dom.getTotalHeight(this.messages.getHTMLElement()); const searchResultContainerSize = this.size.height - messagesSize - dom.getTotalHeight(this.searchWidgetsContainer.getContainer()); this.results.style({ height: searchResultContainerSize + 'px' }); this.tree.layout(searchResultContainerSize); } public layout(dimension: Dimension): void { this.size = dimension; this.reLayout(); } public getControl(): ITree { return this.tree; } public clearSearchResults(): void { this.viewModel.searchResult.clear(); this.showEmptyStage(); if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(this.clearMessage()); } this.searchWidget.clear(); this.viewModel.cancelSearch(); } public cancelSearch(): boolean { if (this.viewModel.cancelSearch()) { this.searchWidget.focus(); return true; } return false; } private selectTreeIfNotSelected(): void { if (this.tree.getInput()) { this.tree.DOMFocus(); let selection = this.tree.getSelection(); if (selection.length === 0) { this.tree.focusNext(); } } } private getSearchTextFromEditor(): string { if (!this.editorService.getActiveEditor()) { return null; } let editorControl: any = this.editorService.getActiveEditor().getControl(); if (!editorControl || !isFunction(editorControl.getEditorType) || editorControl.getEditorType() !== EditorType.ICodeEditor) { // Substitute for (editor instanceof ICodeEditor) return null; } let range = editorControl.getSelection(); if (range && !range.isEmpty() && range.startLineNumber === range.endLineNumber) { let searchText = editorControl.getModel().getLineContent(range.startLineNumber); searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1); return searchText; } return null; } private showsFileTypes(): boolean { return dom.hasClass(this.queryDetails, 'more'); } public toggleCaseSensitive(): void { this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive()); this.onQueryChanged(true, true); } public toggleWholeWords(): void { this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords()); this.onQueryChanged(true, true); } public toggleRegex(): void { this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex()); this.onQueryChanged(true, true); } public toggleFileTypes(moveFocus?: boolean, show?: boolean, skipLayout?: boolean, reverse?: boolean): void { let cls = 'more'; show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show); skipLayout = Boolean(skipLayout); if (show) { dom.addClass(this.queryDetails, cls); if (moveFocus) { if (reverse) { this.inputPatternExclusions.focus(); this.inputPatternExclusions.select(); } else { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); } } } else { dom.removeClass(this.queryDetails, cls); if (moveFocus) { this.searchWidget.focus(); } } if (!skipLayout && this.size) { this.layout(this.size); } } public searchInFolder(resource: URI): void { const workspace = this.contextService.getWorkspace(); if (!workspace) { return; } if (isEqual(workspace.resource.fsPath, resource.fsPath)) { this.inputPatternIncludes.setValue(''); this.searchWidget.focus(); return; } if (!this.showsFileTypes()) { this.toggleFileTypes(true, true); } const workspaceRelativePath = this.contextService.toWorkspaceRelativePath(resource); if (workspaceRelativePath) { this.inputPatternIncludes.setIsGlobPattern(false); this.inputPatternIncludes.setValue(workspaceRelativePath); this.searchWidget.focus(false); } } public onQueryChanged(rerunQuery: boolean, preserveFocus?: boolean): void { const isRegex = this.searchWidget.searchInput.getRegex(); const isWholeWords = this.searchWidget.searchInput.getWholeWords(); const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive(); const contentPattern = this.searchWidget.searchInput.getValue(); const patternExcludes = this.inputPatternExclusions.getValue().trim(); const exclusionsUsePattern = this.inputPatternExclusions.isGlobPattern(); const patternIncludes = this.inputPatternIncludes.getValue().trim(); const includesUsePattern = this.inputPatternIncludes.isGlobPattern(); const useIgnoreFiles = this.inputPatternExclusions.useIgnoreFiles(); // store memento this.viewletSettings['query.contentPattern'] = contentPattern; this.viewletSettings['query.regex'] = isRegex; this.viewletSettings['query.wholeWords'] = isWholeWords; this.viewletSettings['query.caseSensitive'] = isCaseSensitive; this.viewletSettings['query.folderExclusions'] = patternExcludes; this.viewletSettings['query.exclusionsUsePattern'] = exclusionsUsePattern; this.viewletSettings['query.folderIncludes'] = patternIncludes; this.viewletSettings['query.includesUsePattern'] = includesUsePattern; this.viewletSettings['query.useIgnoreFiles'] = useIgnoreFiles; if (!rerunQuery) { return; } if (contentPattern.length === 0) { return; } // Validate regex is OK if (isRegex) { let regExp: RegExp; try { regExp = new RegExp(contentPattern); } catch (e) { return; // malformed regex } if (strings.regExpLeadsToEndlessLoop(regExp)) { return; // endless regex } } let content = { pattern: contentPattern, isRegExp: isRegex, isCaseSensitive: isCaseSensitive, isWordMatch: isWholeWords }; let excludes: IExpression = this.inputPatternExclusions.getGlob(); let includes: IExpression = this.inputPatternIncludes.getGlob(); let options: IQueryOptions = { folderResources: this.contextService.hasWorkspace() ? [this.contextService.getWorkspace().resource] : [], extraFileResources: getOutOfWorkspaceEditorResources(this.editorGroupService, this.contextService), excludePattern: excludes, maxResults: SearchViewlet.MAX_TEXT_RESULTS, includePattern: includes, useIgnoreFiles }; this.onQueryTriggered(this.queryBuilder.text(content, options), patternExcludes, patternIncludes); if (!preserveFocus) { this.searchWidget.focus(false); // focus back to input field } } private autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void { let length = fileMatch.matches().length; if (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) { this.tree.expand(fileMatch).done(null, errors.onUnexpectedError); } else { this.tree.collapse(fileMatch).done(null, errors.onUnexpectedError); } } private onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void { this.viewModel.cancelSearch(); // Progress total is 100.0% for more progress bar granularity let progressTotal = 1000; let progressWorked = 0; let progressRunner = query.useRipgrep ? this.progressService.show(/*infinite=*/true) : this.progressService.show(progressTotal); this.loading = true; this.searchWidget.searchInput.clearMessage(); this.showEmptyStage(); let handledMatches: { [id: string]: boolean } = Object.create(null); let autoExpand = (alwaysExpandIfOneResult: boolean) => { // Auto-expand / collapse based on number of matches: // - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file // - expand file results if we have more than one file result and less than 10 matches on a file let matches = this.viewModel.searchResult.matches(); matches.forEach((match) => { if (handledMatches[match.id()]) { return; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile) } handledMatches[match.id()] = true; this.autoExpandFileMatch(match, alwaysExpandIfOneResult); }); }; let isDone = false; let onComplete = (completed?: ISearchComplete) => { isDone = true; // Complete up to 100% as needed if (completed && !query.useRipgrep) { progressRunner.worked(progressTotal - progressWorked); setTimeout(() => progressRunner.done(), 200); } else { progressRunner.done(); } this.onSearchResultsChanged().then(() => autoExpand(true)); this.viewModel.replaceString = this.searchWidget.getReplaceValue(); let hasResults = !this.viewModel.searchResult.isEmpty(); this.loading = false; this.actionRegistry['refresh'].enabled = true; this.actionRegistry['vs.tree.collapse'].enabled = hasResults; this.actionRegistry['clearSearchResults'].enabled = hasResults; if (completed && completed.limitHit) { this.searchWidget.searchInput.showMessage({ content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."), type: MessageType.WARNING }); } if (!hasResults) { let hasExcludes = !!excludePattern; let hasIncludes = !!includePattern; let message: string; if (!completed) { message = nls.localize('searchCanceled', "Search was canceled before any results could be found - "); } else if (hasIncludes && hasExcludes) { message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePattern, excludePattern); } else if (hasIncludes) { message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePattern); } else if (hasExcludes) { message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePattern); } else { message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions - "); } // Indicate as status to ARIA aria.status(message); this.tree.onHidden(); this.results.hide(); const div = this.clearMessage(); const p = $(div).p({ text: message }); if (!completed) { $(p).a({ 'class': ['pointer', 'prominent'], text: nls.localize('rerunSearch.message', "Search again") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.onQueryChanged(true); }); } else if (hasIncludes || hasExcludes) { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('rerunSearchInAll.message', "Search again in all files") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.inputPatternExclusions.setValue(''); this.inputPatternIncludes.setValue(''); this.onQueryChanged(true); }); } else { $(p).a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openSettings.message', "Open Settings") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); if (this.contextService.hasWorkspace()) { this.preferencesService.openWorkspaceSettings().done(() => null, errors.onUnexpectedError); } else { this.preferencesService.openGlobalSettings().done(() => null, errors.onUnexpectedError); } }); } if (!this.contextService.hasWorkspace()) { this.searchWithoutFolderMessage(div); } } else { this.viewModel.searchResult.toggleHighlights(true); // show highlights // Indicate final search result count for ARIA aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount())); } }; let onError = (e: any) => { if (errors.isPromiseCanceledError(e)) { onComplete(null); } else { this.loading = false; isDone = true; progressRunner.done(); this.messageService.show(2 /* ERROR */, e); } }; let total: number = 0; let worked: number = 0; let visibleMatches = 0; let onProgress = (p: ISearchProgressItem) => { // Progress if (p.total) { total = p.total; } if (p.worked) { worked = p.worked; } }; // Handle UI updates in an interval to show frequent progress and results let uiRefreshHandle = setInterval(() => { if (isDone) { window.clearInterval(uiRefreshHandle); return; } if (!query.useRipgrep) { // Progress bar update let fakeProgress = true; if (total > 0 && worked > 0) { let ratio = Math.round((worked / total) * progressTotal); if (ratio > progressWorked) { // never show less progress than what we have already progressRunner.worked(ratio - progressWorked); progressWorked = ratio; fakeProgress = false; } } // Fake progress up to 90%, or when actual progress beats it const fakeMax = 900; const fakeMultiplier = 12; if (fakeProgress && progressWorked < fakeMax) { // Linearly decrease the rate of fake progress. // 1 is the smallest allowed amount of progress. const fakeAmt = Math.round((fakeMax - progressWorked) / fakeMax * fakeMultiplier) || 1; progressWorked += fakeAmt; progressRunner.worked(fakeAmt); } } // Search result tree update const fileCount = this.viewModel.searchResult.fileCount(); if (visibleMatches !== fileCount) { visibleMatches = fileCount; this.tree.refresh().then(() => { autoExpand(false); }).done(null, errors.onUnexpectedError); this.updateSearchResultCount(); } if (fileCount > 0) { // since we have results now, enable some actions if (!this.actionRegistry['vs.tree.collapse'].enabled) { this.actionRegistry['vs.tree.collapse'].enabled = true; } } }, 100); this.searchWidget.setReplaceAllActionState(false); // this.replaceService.disposeAllReplacePreviews(); this.viewModel.search(query).done(onComplete, onError, query.useRipgrep ? undefined : onProgress); } private updateSearchResultCount(): void { const fileCount = this.viewModel.searchResult.fileCount(); const msgWasHidden = this.messages.isHidden(); if (fileCount > 0) { const div = this.clearMessage(); $(div).p({ text: this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount) }); if (msgWasHidden) { this.reLayout(); } } else if (!msgWasHidden) { this.messages.hide(); } } private buildResultCountMessage(resultCount: number, fileCount: number): string { if (resultCount === 1 && fileCount === 1) { return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount); } else if (resultCount === 1) { return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount); } else if (fileCount === 1) { return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount); } else { return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount); } } private searchWithoutFolderMessage(div: Builder): void { $(div).p({ text: nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ") }) .asContainer().a({ 'class': ['pointer', 'prominent'], 'tabindex': '0', text: nls.localize('openFolder', "Open Folder") }).on(dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); const actionClass = env.isMacintosh ? OpenFileFolderAction : OpenFolderAction; const action = this.instantiationService.createInstance<string, string, IAction>(actionClass, actionClass.ID, actionClass.LABEL); this.actionRunner.run(action).done(() => { action.dispose(); }, err => { action.dispose(); errors.onUnexpectedError(err); }); }); } private showEmptyStage(): void { // disable 'result'-actions this.actionRegistry['refresh'].enabled = false; this.actionRegistry['vs.tree.collapse'].enabled = false; this.actionRegistry['clearSearchResults'].enabled = false; // clean up ui // this.replaceService.disposeAllReplacePreviews(); this.messages.hide(); this.results.show(); this.tree.onVisible(); this.currentSelectedFileMatch = null; } private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { if (!(lineMatch instanceof Match)) { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); return TPromise.as(true); } this.telemetryService.publicLog('searchResultChosen'); return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ? this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) : this.open(lineMatch, preserveFocus, sideBySide, pinned); } public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> { let selection = this.getSelectionFrom(element); let resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource(); return this.editorService.openEditor({ resource: resource, options: { preserveFocus, pinned, selection, revealIfVisible: !sideBySide } }, sideBySide).then(editor => { if (editor && element instanceof Match && preserveFocus) { this.viewModel.searchResult.rangeHighlightDecorations.highlightRange({ resource, range: element.range() }, <ICommonCodeEditor>editor.getControl()); } else { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); } }, errors.onUnexpectedError); } private getSelectionFrom(element: FileMatchOrMatch): any { let match: Match = null; if (element instanceof Match) { match = element; } if (element instanceof FileMatch && element.count() > 0) { match = element.matches()[element.matches().length - 1]; } if (match) { let range = match.range(); if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) { let replaceString = match.replaceString; return { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.startLineNumber, endColumn: range.startColumn + replaceString.length }; } return range; } return void 0; } private onUntitledDidChangeDirty(resource: URI): void { if (!this.viewModel) { return; } // remove search results from this resource as it got disposed if (!this.untitledEditorService.isDirty(resource)) { let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (resource.toString() === matches[i].resource().toString()) { this.viewModel.searchResult.remove(matches[i]); } } } } private onFilesChanged(e: FileChangesEvent): void { if (!this.viewModel) { return; } let matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (e.contains(matches[i].resource(), FileChangeType.DELETED)) { this.viewModel.searchResult.remove(matches[i]); } } } public getActions(): IAction[] { return [ this.actionRegistry['refresh'], this.actionRegistry['vs.tree.collapse'], this.actionRegistry['clearSearchResults'] ]; } public dispose(): void { this.isDisposed = true; this.toDispose = lifecycle.dispose(this.toDispose); if (this.tree) { this.tree.dispose(); } this.searchWidget.dispose(); this.inputPatternIncludes.dispose(); this.inputPatternExclusions.dispose(); this.viewModel.dispose(); super.dispose(); } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { let matchHighlightColor = theme.getColor(editorFindMatchHighlight); if (matchHighlightColor) { collector.addRule(`.search-viewlet .findInFileMatch { background-color: ${matchHighlightColor}; }`); collector.addRule(`.search-viewlet .highlight { background-color: ${matchHighlightColor}; }`); } });
src/vs/workbench/parts/search/browser/searchViewlet.ts
1
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.9988617897033691, 0.014551833271980286, 0.00016435241559520364, 0.00017049633606802672, 0.11892429739236832 ]
{ "id": 7, "code_window": [ "\n", "\t\treturn TPromise.as(value);\n", "\t}\n", "}\n", "\n", "export class SearchSorter implements ISorter {\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tpublic shouldAutoexpand(tree: ITree, element: any): boolean {\n", "\t\tconst numChildren = this._getChildren(element).length;\n", "\t\treturn numChildren > 0 && numChildren < SearchDataSource.AUTOEXPAND_CHILD_LIMIT;\n", "\t}\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "debugAdapterCrash": "偵錯配接器處理序已意外終止", "moreInfo": "詳細資訊", "stoppingDebugAdapter": "{0}。正在停止偵錯配接器。", "unableToLaunchDebugAdapter": "無法從 '{0}' 啟動偵錯配接器。", "unableToLaunchDebugAdapterNoArgs": "無法啟動偵錯配接器。" }
i18n/cht/src/vs/workbench/parts/debug/electron-browser/rawDebugSession.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0001740137377055362, 0.00017146457685157657, 0.00016891540144570172, 0.00017146457685157657, 0.000002549168129917234 ]
{ "id": 7, "code_window": [ "\n", "\t\treturn TPromise.as(value);\n", "\t}\n", "}\n", "\n", "export class SearchSorter implements ISorter {\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tpublic shouldAutoexpand(tree: ITree, element: any): boolean {\n", "\t\tconst numChildren = this._getChildren(element).length;\n", "\t\treturn numChildren > 0 && numChildren < SearchDataSource.AUTOEXPAND_CHILD_LIMIT;\n", "\t}\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "breakpointDirtydHover": "未验证的断点。对文件进行了修改,请重启调试会话。", "breakpointDisabledHover": "已禁用断点", "breakpointHover": "断点", "breakpointUnsupported": "不受此调试类型支持的条件断点", "breakpointUnverifieddHover": "未验证的断点" }
i18n/chs/src/vs/workbench/parts/debug/browser/debugEditorModelManager.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00017353818111587316, 0.0001720080617815256, 0.0001704779569990933, 0.0001720080617815256, 0.000001530112058389932 ]
{ "id": 7, "code_window": [ "\n", "\t\treturn TPromise.as(value);\n", "\t}\n", "}\n", "\n", "export class SearchSorter implements ISorter {\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tpublic shouldAutoexpand(tree: ITree, element: any): boolean {\n", "\t\tconst numChildren = this._getChildren(element).length;\n", "\t\treturn numChildren > 0 && numChildren < SearchDataSource.AUTOEXPAND_CHILD_LIMIT;\n", "\t}\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchResultsView.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "columnBreakpoint": "Ajouter un point d'arrêt de colonne", "columnBreakpointAction": "Déboguer : point d'arrêt de colonne", "conditionalBreakpointEditorAction": "Déboguer : ajouter un point d'arrêt conditionnel...", "debugAddToWatch": "Déboguer : ajouter à la fenêtre Espion", "debugEvaluate": "Déboguer : évaluer", "runToCursor": "Exécuter jusqu'au curseur", "showDebugHover": "Déboguer : afficher par pointage", "toggleBreakpointAction": "Déboguer : activer/désactiver un point d'arrêt" }
i18n/fra/src/vs/workbench/parts/debug/browser/debugEditorActions.i18n.json
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.00017616046534385532, 0.00017491396283730865, 0.00017366746033076197, 0.00017491396283730865, 0.0000012465025065466762 ]
{ "id": 8, "code_window": [ "\t}\n", "\n", "\tprivate refreshTree(event?: IChangeEvent): TPromise<any> {\n", "\t\tif (!event) {\n", "\t\t\treturn this.tree.refresh(this.viewModel.searchResult);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tif (!event || event.added || event.removed) {\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts", "type": "replace", "edit_start_line_idx": 331 }
/*--------------------------------------------------------------------------------------------- * 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 Touch = require('vs/base/browser/touch'); import Events = require('vs/base/common/eventEmitter'); import Mouse = require('vs/base/browser/mouseEvent'); import Keyboard = require('vs/base/browser/keyboardEvent'); import { INavigator } from 'vs/base/common/iterator'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import Event from 'vs/base/common/event'; export interface ITree extends Events.IEventEmitter { emit(eventType: string, data?: any): void; onDOMFocus: Event<void>; onDOMBlur: Event<void>; onHighlightChange: Event<void>; onDispose: Event<void>; /** * Returns the tree's DOM element. */ getHTMLElement(): HTMLElement; /** * Lays out the tree. * Provide a specific height to save an (expensive) height computation. */ layout(height?: number): void; /** * Notifies the tree that is has become visible. */ onVisible(): void; /** * Notifies the tree that is has become hidden. */ onHidden(): void; /** * Sets the input of the tree. */ setInput(element: any): WinJS.Promise; /** * Returns the tree's input. */ getInput(): any; /** * Sets DOM focus on the tree. */ DOMFocus(): void; /** * Returns whether the tree has DOM focus. */ isDOMFocused(): boolean; /** * Removes DOM focus from the tree. */ DOMBlur(): void; /** * Refreshes an element. * Provide no arguments and it will refresh the input element. */ refresh(element?: any, recursive?: boolean): WinJS.Promise; /** * Refreshes all given elements. */ refreshAll(elements: any[], recursive?: boolean): WinJS.Promise; /** * Expands an element. * The returned promise returns a boolean for whether the element was expanded or not. */ expand(element: any): WinJS.Promise; /** * Expands several elements. * The returned promise returns a boolean array for whether the elements were expanded or not. */ expandAll(elements?: any[]): WinJS.Promise; /** * Collapses an element. * The returned promise returns a boolean for whether the element was collapsed or not. */ collapse(element: any, recursive?: boolean): WinJS.Promise; /** * Collapses several elements. * Provide no arguments and it will recursively collapse all elements in the tree * The returned promise returns a boolean for whether the elements were collapsed or not. */ collapseAll(elements?: any[], recursive?: boolean): WinJS.Promise; /** * Toggles an element's expansion state. */ toggleExpansion(element: any): WinJS.Promise; /** * Toggles several element's expansion state. */ toggleExpansionAll(elements: any[]): WinJS.Promise; /** * Returns whether an element is expanded or not. */ isExpanded(element: any): boolean; /** * Returns a list of the currently expanded elements. */ getExpandedElements(): any[]; /** * Reveals an element in the tree. The relativeTop is a value between 0 and 1. The closer to 0 the more the * element will scroll up to the top. */ reveal(element: any, relativeTop?: number): WinJS.Promise; /** * Returns the relative top position of any given element, if visible. * If not visible, returns a negative number or a number > 1. * Useful when calling `reveal(element, relativeTop)`. */ getRelativeTop(element: any): number; /** * Returns a number between 0 and 1 representing how much the tree is scroll down. 0 means all the way * to the top; 1 means all the way down. */ getScrollPosition(): number; /** * Sets the scroll position with a number between 0 and 1 representing how much the tree is scroll down. 0 means all the way * to the top; 1 means all the way down. */ setScrollPosition(pos: number): void; /** * Returns the total height of the tree's content. */ getContentHeight(): number; /** * Sets the tree's highlight to be the given element. * Provide no arguments and it clears the tree's highlight. */ setHighlight(element?: any, eventPayload?: any): void; /** * Returns the currently highlighted element. */ getHighlight(includeHidden?: boolean): any; /** * Returns whether an element is highlighted or not. */ isHighlighted(element: any): boolean; /** * Clears the highlight. */ clearHighlight(eventPayload?: any): void; /** * Selects an element. */ select(element: any, eventPayload?: any): void; /** * Selects a range of elements. */ selectRange(fromElement: any, toElement: any, eventPayload?: any): void; /** * Deselects a range of elements. */ deselectRange(fromElement: any, toElement: any, eventPayload?: any): void; /** * Selects several elements. */ selectAll(elements: any[], eventPayload?: any): void; /** * Deselects an element. */ deselect(element: any, eventPayload?: any): void; /** * Deselects several elements. */ deselectAll(elements: any[], eventPayload?: any): void; /** * Replaces the current selection with the given elements. */ setSelection(elements: any[], eventPayload?: any): void; /** * Toggles the element's selection. */ toggleSelection(element: any, eventPayload?: any): void; /** * Returns the currently selected elements. */ getSelection(includeHidden?: boolean): any[]; /** * Returns whether an element is selected or not. */ isSelected(element: any): boolean; /** * Selects the next `count`-nth element, in visible order. */ selectNext(count?: number, clearSelection?: boolean, eventPayload?: any): void; /** * Selects the previous `count`-nth element, in visible order. */ selectPrevious(count?: number, clearSelection?: boolean, eventPayload?: any): void; /** * Selects the currently selected element's parent. */ selectParent(clearSelection?: boolean, eventPayload?: any): void; /** * Clears the selection. */ clearSelection(eventPayload?: any): void; /** * Sets the focused element. */ setFocus(element?: any, eventPayload?: any): void; /** * Returns whether an element is focused or not. */ isFocused(element: any): boolean; /** * Returns focused element. */ getFocus(includeHidden?: boolean): any; /** * Focuses the next `count`-nth element, in visible order. */ focusNext(count?: number, eventPayload?: any): void; /** * Focuses the previous `count`-nth element, in visible order. */ focusPrevious(count?: number, eventPayload?: any): void; /** * Focuses the currently focused element's parent. */ focusParent(eventPayload?: any): void; /** * Focuses the first child of the currently focused element. */ focusFirstChild(eventPayload?: any): void; /** * Focuses the second element, in visible order. */ focusFirst(eventPayload?: any): void; /** * Focuses the nth element, in visible order. */ focusNth(index: number, eventPayload?: any): void; /** * Focuses the last element, in visible order. */ focusLast(eventPayload?: any): void; /** * Focuses the element at the end of the next page, in visible order. */ focusNextPage(eventPayload?: any): void; /** * Focuses the element at the beginning of the previous page, in visible order. */ focusPreviousPage(eventPayload?: any): void; /** * Clears the focus. */ clearFocus(eventPayload?: any): void; /** * Adds the trait to elements. */ addTraits(trait: string, elements: any[]): void; /** * Removes the trait from elements. */ removeTraits(trait: string, elements: any[]): void; /** * Toggles the element's trait. */ toggleTrait(trait: string, element: any): void; /** * Returns whether the element has the trait or not. */ hasTrait(trait: string, element: any): boolean; /** * Returns a navigator which allows to discover the visible and * expanded elements in the tree. */ getNavigator(fromElement?: any, subTreeOnly?: boolean): INavigator<any>; /** * Disposes the tree */ dispose(): void; } export interface IDataSource { /** * Returns the unique identifier of the given element. * No more than one element may use a given identifier. */ getId(tree: ITree, element: any): string; /** * Returns a boolean value indicating whether the element has children. */ hasChildren(tree: ITree, element: any): boolean; /** * Returns the element's children as an array in a promise. */ getChildren(tree: ITree, element: any): WinJS.Promise; /** * Returns the element's parent in a promise. */ getParent(tree: ITree, element: any): WinJS.Promise; } export interface IRenderer { /** * Returns the element's height in the tree, in pixels. */ getHeight(tree: ITree, element: any): number; /** * Returns a template ID for a given element. This will be used as an identifier * for the next 3 methods. */ getTemplateId(tree: ITree, element: any): string; /** * Renders the template in a DOM element. This method should render all the DOM * structure for an hypothetical element leaving its contents blank. It should * return an object bag which will be passed along to `renderElement` and used * to fill in those blanks. * * You should do all DOM creating and object allocation in this method. It * will be called only a few times. */ renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any; /** * Renders an element, given an object bag returned by `renderTemplate`. * This method should do as little as possible and ideally it should only fill * in the blanks left by `renderTemplate`. * * Try to make this method do as little possible, since it will be called very * often. */ renderElement(tree: ITree, element: any, templateId: string, templateData: any): void; /** * Disposes a template that was once rendered. */ disposeTemplate(tree: ITree, templateId: string, templateData: any): void; } export interface IAccessibilityProvider { /** * Given an element in the tree, return the ARIA label that should be associated with the * item. This helps screen readers to provide a meaningful label for the currently focused * tree element. * * Returning null will not disable ARIA for the element. Instead it is up to the screen reader * to compute a meaningful label based on the contents of the element in the DOM * * See also: https://www.w3.org/TR/wai-aria/states_and_properties#aria-label */ getAriaLabel(tree: ITree, element: any): string; } export /* abstract */ class ContextMenuEvent { private _posx: number; private _posy: number; private _target: HTMLElement; constructor(posx: number, posy: number, target: HTMLElement) { this._posx = posx; this._posy = posy; this._target = target; } public preventDefault(): void { // no-op } public stopPropagation(): void { // no-op } public get posx(): number { return this._posx; } public get posy(): number { return this._posy; } public get target(): HTMLElement { return this._target; } } export class MouseContextMenuEvent extends ContextMenuEvent { private originalEvent: Mouse.IMouseEvent; constructor(originalEvent: Mouse.IMouseEvent) { super(originalEvent.posx, originalEvent.posy, originalEvent.target); this.originalEvent = originalEvent; } public preventDefault(): void { this.originalEvent.preventDefault(); } public stopPropagation(): void { this.originalEvent.stopPropagation(); } } export class KeyboardContextMenuEvent extends ContextMenuEvent { private originalEvent: Keyboard.IKeyboardEvent; constructor(posx: number, posy: number, originalEvent: Keyboard.IKeyboardEvent) { super(posx, posy, originalEvent.target); this.originalEvent = originalEvent; } public preventDefault(): void { this.originalEvent.preventDefault(); } public stopPropagation(): void { this.originalEvent.stopPropagation(); } } export interface IController { /** * Called when an element is clicked. */ onClick(tree: ITree, element: any, event: Mouse.IMouseEvent): boolean; /** * Called when an element is requested for a context menu. */ onContextMenu(tree: ITree, element: any, event: ContextMenuEvent): boolean; /** * Called when an element is tapped. */ onTap(tree: ITree, element: any, event: Touch.GestureEvent): boolean; /** * Called when a key is pressed down while selecting elements. */ onKeyDown(tree: ITree, event: Keyboard.IKeyboardEvent): boolean; /** * Called when a key is released while selecting elements. */ onKeyUp(tree: ITree, event: Keyboard.IKeyboardEvent): boolean; /** * Called when a mouse button is pressed down on an element. */ onMouseDown?(tree: ITree, element: any, event: Mouse.IMouseEvent): boolean; /** * Called when a mouse button goes up on an element. */ onMouseUp?(tree: ITree, element: any, event: Mouse.IMouseEvent): boolean; } export enum DragOverEffect { COPY, MOVE } export enum DragOverBubble { BUBBLE_DOWN, BUBBLE_UP } export interface IDragOverReaction { accept: boolean; effect?: DragOverEffect; bubble?: DragOverBubble; autoExpand?: boolean; } export const DRAG_OVER_REJECT: IDragOverReaction = { accept: false }; export const DRAG_OVER_ACCEPT: IDragOverReaction = { accept: true }; export const DRAG_OVER_ACCEPT_BUBBLE_UP: IDragOverReaction = { accept: true, bubble: DragOverBubble.BUBBLE_UP }; export const DRAG_OVER_ACCEPT_BUBBLE_DOWN = (autoExpand = false) => ({ accept: true, bubble: DragOverBubble.BUBBLE_DOWN, autoExpand }); export const DRAG_OVER_ACCEPT_BUBBLE_UP_COPY: IDragOverReaction = { accept: true, bubble: DragOverBubble.BUBBLE_UP, effect: DragOverEffect.COPY }; export const DRAG_OVER_ACCEPT_BUBBLE_DOWN_COPY = (autoExpand = false) => ({ accept: true, bubble: DragOverBubble.BUBBLE_DOWN, effect: DragOverEffect.COPY }); export interface IDragAndDropData { update(event: Mouse.DragMouseEvent): void; getData(): any; } export interface IDragAndDrop { /** * Returns a uri if the given element should be allowed to drag. * Returns null, otherwise. */ getDragURI(tree: ITree, element: any): string; /** * Returns a label to display when dragging the element. */ getDragLabel?(tree: ITree, elements: any[]): string; /** * Sent when the drag operation is starting. */ onDragStart(tree: ITree, data: IDragAndDropData, originalEvent: Mouse.DragMouseEvent): void; /** * Returns a DragOverReaction indicating whether sources can be * dropped into target or some parent of the target. */ onDragOver(tree: ITree, data: IDragAndDropData, targetElement: any, originalEvent: Mouse.DragMouseEvent): IDragOverReaction; /** * Handles the action of dropping sources into target. */ drop(tree: ITree, data: IDragAndDropData, targetElement: any, originalEvent: Mouse.DragMouseEvent): void; } export interface IFilter { /** * Returns whether the given element should be visible. */ isVisible(tree: ITree, element: any): boolean; } export interface IElementCallback { (tree: ITree, element: any): void; } export type ICallback = () => void; export interface ISorter { /** * Compare two elements in the viewer to define the sorting order. */ compare(tree: ITree, element: any, otherElement: any): number; } // Events export interface ISelectionEvent { selection: any[]; payload?: any; } export interface IFocusEvent { focus: any; payload?: any; } export interface IHighlightEvent { highlight: any; payload?: any; } // Options export interface ITreeConfiguration { dataSource: IDataSource; renderer?: IRenderer; controller?: IController; dnd?: IDragAndDrop; filter?: IFilter; sorter?: ISorter; accessibilityProvider?: IAccessibilityProvider; } export interface ITreeOptions { twistiePixels?: number; showTwistie?: boolean; indentPixels?: number; verticalScrollMode?: ScrollbarVisibility; alwaysFocused?: boolean; autoExpandSingleChildren?: boolean; useShadows?: boolean; paddingOnRow?: boolean; ariaLabel?: string; keyboardSupport?: boolean; } export interface ITreeContext extends ITreeConfiguration { tree: ITree; options: ITreeOptions; }
src/vs/base/parts/tree/browser/tree.ts
1
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.0057525914162397385, 0.00037889060331508517, 0.000165759731316939, 0.0001759236620273441, 0.0007243587169796228 ]
{ "id": 8, "code_window": [ "\t}\n", "\n", "\tprivate refreshTree(event?: IChangeEvent): TPromise<any> {\n", "\t\tif (!event) {\n", "\t\t\treturn this.tree.refresh(this.viewModel.searchResult);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tif (!event || event.added || event.removed) {\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts", "type": "replace", "edit_start_line_idx": 331 }
/*--------------------------------------------------------------------------------------------- * 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 nls from 'vs/nls'; import Severity from 'vs/base/common/severity'; import { TPromise } from 'vs/base/common/winjs.base'; import { IExtensionDescription, IExtensionService, IExtensionsStatus, ExtensionPointContribution } from 'vs/platform/extensions/common/extensions'; import { IExtensionPoint } from 'vs/platform/extensions/common/extensionsRegistry'; const hasOwnProperty = Object.hasOwnProperty; export abstract class ActivatedExtension { activationFailed: boolean; constructor(activationFailed: boolean) { this.activationFailed = activationFailed; } } export interface IActivatedExtensionMap<T extends ActivatedExtension> { [extensionId: string]: T; } interface IActivatingExtensionMap { [extensionId: string]: TPromise<void>; } export abstract class AbstractExtensionService<T extends ActivatedExtension> implements IExtensionService { public _serviceBrand: any; private _activatingExtensions: IActivatingExtensionMap; protected _activatedExtensions: IActivatedExtensionMap<T>; private _onReady: TPromise<boolean>; private _onReadyC: (v: boolean) => void; private _isReady: boolean; protected _registry: ExtensionDescriptionRegistry; constructor(isReadyByDefault: boolean) { if (isReadyByDefault) { this._isReady = true; this._onReady = TPromise.as(true); this._onReadyC = (v: boolean) => { /*no-op*/ }; } else { this._isReady = false; this._onReady = new TPromise<boolean>((c, e, p) => { this._onReadyC = c; }, () => { console.warn('You should really not try to cancel this ready promise!'); }); } this._activatingExtensions = {}; this._activatedExtensions = {}; this._registry = new ExtensionDescriptionRegistry(); } protected _triggerOnReady(): void { this._isReady = true; this._onReadyC(true); } public onReady(): TPromise<boolean> { return this._onReady; } public readExtensionPointContributions<T>(extPoint: IExtensionPoint<T>): TPromise<ExtensionPointContribution<T>[]> { return this.onReady().then(() => { let availableExtensions = this._registry.getAllExtensionDescriptions(); let result: ExtensionPointContribution<T>[] = [], resultLen = 0; for (let i = 0, len = availableExtensions.length; i < len; i++) { let desc = availableExtensions[i]; if (desc.contributes && hasOwnProperty.call(desc.contributes, extPoint.name)) { result[resultLen++] = new ExtensionPointContribution<T>(desc, desc.contributes[extPoint.name]); } } return result; }); } public getExtensions(): TPromise<IExtensionDescription[]> { return this.onReady().then(() => { return this._registry.getAllExtensionDescriptions(); }); } public getExtensionsStatus(): { [id: string]: IExtensionsStatus } { return null; } public isActivated(extensionId: string): boolean { return hasOwnProperty.call(this._activatedExtensions, extensionId); } public activateByEvent(activationEvent: string): TPromise<void> { if (this._isReady) { return this._activateByEvent(activationEvent); } else { return this._onReady.then(() => this._activateByEvent(activationEvent)); } } private _activateByEvent(activationEvent: string): TPromise<void> { let activateExtensions = this._registry.getExtensionDescriptionsForActivationEvent(activationEvent); return this._activateExtensions(activateExtensions, 0); } public activateById(extensionId: string): TPromise<void> { return this._onReady.then(() => { let desc = this._registry.getExtensionDescription(extensionId); if (!desc) { throw new Error('Extension `' + extensionId + '` is not known'); } return this._activateExtensions([desc], 0); }); } /** * Handle semantics related to dependencies for `currentExtension`. * semantics: `redExtensions` must wait for `greenExtensions`. */ private _handleActivateRequest(currentExtension: IExtensionDescription, greenExtensions: { [id: string]: IExtensionDescription; }, redExtensions: IExtensionDescription[]): void { let depIds = (typeof currentExtension.extensionDependencies === 'undefined' ? [] : currentExtension.extensionDependencies); let currentExtensionGetsGreenLight = true; for (let j = 0, lenJ = depIds.length; j < lenJ; j++) { let depId = depIds[j]; let depDesc = this._registry.getExtensionDescription(depId); if (!depDesc) { // Error condition 1: unknown dependency this._showMessage(Severity.Error, nls.localize('unknownDep', "Extension `{1}` failed to activate. Reason: unknown dependency `{0}`.", depId, currentExtension.id)); this._activatedExtensions[currentExtension.id] = this._createFailedExtension(); return; } if (hasOwnProperty.call(this._activatedExtensions, depId)) { let dep = this._activatedExtensions[depId]; if (dep.activationFailed) { // Error condition 2: a dependency has already failed activation this._showMessage(Severity.Error, nls.localize('failedDep1', "Extension `{1}` failed to activate. Reason: dependency `{0}` failed to activate.", depId, currentExtension.id)); this._activatedExtensions[currentExtension.id] = this._createFailedExtension(); return; } } else { // must first wait for the dependency to activate currentExtensionGetsGreenLight = false; greenExtensions[depId] = depDesc; } } if (currentExtensionGetsGreenLight) { greenExtensions[currentExtension.id] = currentExtension; } else { redExtensions.push(currentExtension); } } private _activateExtensions(extensionDescriptions: IExtensionDescription[], recursionLevel: number): TPromise<void> { // console.log(recursionLevel, '_activateExtensions: ', extensionDescriptions.map(p => p.id)); if (extensionDescriptions.length === 0) { return TPromise.as(void 0); } extensionDescriptions = extensionDescriptions.filter((p) => !hasOwnProperty.call(this._activatedExtensions, p.id)); if (extensionDescriptions.length === 0) { return TPromise.as(void 0); } if (recursionLevel > 10) { // More than 10 dependencies deep => most likely a dependency loop for (let i = 0, len = extensionDescriptions.length; i < len; i++) { // Error condition 3: dependency loop this._showMessage(Severity.Error, nls.localize('failedDep2', "Extension `{0}` failed to activate. Reason: more than 10 levels of dependencies (most likely a dependency loop).", extensionDescriptions[i].id)); this._activatedExtensions[extensionDescriptions[i].id] = this._createFailedExtension(); } return TPromise.as(void 0); } let greenMap: { [id: string]: IExtensionDescription; } = Object.create(null), red: IExtensionDescription[] = []; for (let i = 0, len = extensionDescriptions.length; i < len; i++) { this._handleActivateRequest(extensionDescriptions[i], greenMap, red); } // Make sure no red is also green for (let i = 0, len = red.length; i < len; i++) { if (greenMap[red[i].id]) { delete greenMap[red[i].id]; } } let green = Object.keys(greenMap).map(id => greenMap[id]); // console.log('greenExtensions: ', green.map(p => p.id)); // console.log('redExtensions: ', red.map(p => p.id)); if (red.length === 0) { // Finally reached only leafs! return TPromise.join(green.map((p) => this._activateExtension(p))).then(_ => void 0); } return this._activateExtensions(green, recursionLevel + 1).then(_ => { return this._activateExtensions(red, recursionLevel + 1); }); } protected _activateExtension(extensionDescription: IExtensionDescription): TPromise<void> { if (hasOwnProperty.call(this._activatedExtensions, extensionDescription.id)) { return TPromise.as(void 0); } if (hasOwnProperty.call(this._activatingExtensions, extensionDescription.id)) { return this._activatingExtensions[extensionDescription.id]; } this._activatingExtensions[extensionDescription.id] = this._actualActivateExtension(extensionDescription).then(null, (err) => { this._showMessage(Severity.Error, nls.localize('activationError', "Activating extension `{0}` failed: {1}.", extensionDescription.id, err.message)); console.error('Activating extension `' + extensionDescription.id + '` failed: ', err.message); console.log('Here is the error stack: ', err.stack); // Treat the extension as being empty return this._createFailedExtension(); }).then((x: T) => { this._activatedExtensions[extensionDescription.id] = x; delete this._activatingExtensions[extensionDescription.id]; }); return this._activatingExtensions[extensionDescription.id]; } protected abstract _showMessage(severity: Severity, message: string): void; protected abstract _createFailedExtension(): T; protected abstract _actualActivateExtension(extensionDescription: IExtensionDescription): TPromise<T>; } interface IExtensionDescriptionMap { [extensionId: string]: IExtensionDescription; } export class ExtensionDescriptionRegistry { private _extensionsMap: IExtensionDescriptionMap; private _extensionsArr: IExtensionDescription[]; private _activationMap: { [activationEvent: string]: IExtensionDescription[]; }; constructor() { this._extensionsMap = {}; this._extensionsArr = []; this._activationMap = {}; } public registerExtensions(extensionDescriptions: IExtensionDescription[]): void { for (let i = 0, len = extensionDescriptions.length; i < len; i++) { let extensionDescription = extensionDescriptions[i]; if (hasOwnProperty.call(this._extensionsMap, extensionDescription.id)) { // No overwriting allowed! console.error('Extension `' + extensionDescription.id + '` is already registered'); continue; } this._extensionsMap[extensionDescription.id] = extensionDescription; this._extensionsArr.push(extensionDescription); if (Array.isArray(extensionDescription.activationEvents)) { for (let j = 0, lenJ = extensionDescription.activationEvents.length; j < lenJ; j++) { let activationEvent = extensionDescription.activationEvents[j]; this._activationMap[activationEvent] = this._activationMap[activationEvent] || []; this._activationMap[activationEvent].push(extensionDescription); } } } } public getExtensionDescriptionsForActivationEvent(activationEvent: string): IExtensionDescription[] { if (!hasOwnProperty.call(this._activationMap, activationEvent)) { return []; } return this._activationMap[activationEvent].slice(0); } public getAllExtensionDescriptions(): IExtensionDescription[] { return this._extensionsArr.slice(0); } public getExtensionDescription(extensionId: string): IExtensionDescription { if (!hasOwnProperty.call(this._extensionsMap, extensionId)) { return null; } return this._extensionsMap[extensionId]; } }
src/vs/platform/extensions/common/abstractExtensionService.ts
0
https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154
[ 0.004220406990498304, 0.00032720196759328246, 0.00016354795661754906, 0.00017144480079878122, 0.0007141629466786981 ]