searchWidget.ts 12.8 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6 7 8
import * as nls from 'vs/nls';
import * as strings from 'vs/base/common/strings';
import * as dom from 'vs/base/browser/dom';
9 10 11
import { TPromise } from 'vs/base/common/winjs.base';
import { Widget } from 'vs/base/browser/ui/widget';
import { Action } from 'vs/base/common/actions';
S
Sandeep Somavarapu 已提交
12
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
13 14 15 16
import { FindInput, IFindInputOptions } from 'vs/base/browser/ui/findinput/findInput';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { Button } from 'vs/base/browser/ui/button/button';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
17
import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';
18
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
19
import { ContextKeyExpr, IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
20
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
21
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
22 23 24
import Event, { Emitter } from 'vs/base/common/event';
import { Builder } from 'vs/base/browser/builder';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
25
import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService';
26
import { isSearchViewletFocussed, appendKeyBindingLabel } from 'vs/workbench/parts/search/browser/searchActions';
A
Alex Dima 已提交
27
import { CONTEXT_FIND_WIDGET_NOT_VISIBLE } from 'vs/editor/contrib/find/common/findController';
28
import { HistoryNavigator } from 'vs/base/common/history';
29
import * as Constants from 'vs/workbench/parts/search/common/constants';
30 31 32 33 34 35 36 37

export interface ISearchWidgetOptions {
	value?:string;
	isRegex?:boolean;
	isCaseSensitive?:boolean;
	isWholeWords?:boolean;
}

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
class ReplaceAllAction extends Action {

	private static fgInstance:ReplaceAllAction= null;
	public static ID:string= 'search.action.replaceAll';

	static get INSTANCE():ReplaceAllAction {
		if (ReplaceAllAction.fgInstance === null) {
			ReplaceAllAction.fgInstance= new ReplaceAllAction();
		}
		return ReplaceAllAction.fgInstance;
	}

	private _searchWidget: SearchWidget= null;

	constructor() {
		super(ReplaceAllAction.ID, '', 'action-replace-all', false);
	}

	set searchWidget(searchWidget: SearchWidget) {
		this._searchWidget= searchWidget;
	}

	run():TPromise<any> {
		if (this._searchWidget) {
			return this._searchWidget.triggerReplaceAll();
		}
		return TPromise.as(null);
	}
}

68 69
export class SearchWidget extends Widget {

70
	private static REPLACE_ALL_DISABLED_LABEL= nls.localize('search.action.replaceAll.disabled.label', "Replace All (Submit Search to Enable)");
71
	private static REPLACE_ALL_ENABLED_LABEL=(keyBindingService2: IKeybindingService):string=>{
A
Alex Dima 已提交
72 73
		let keybindings = keyBindingService2.lookupKeybindings(ReplaceAllAction.ID);
		return appendKeyBindingLabel(nls.localize('search.action.replaceAll.enabled.label', "Replace All"), keybindings[0], keyBindingService2);
74
	};
S
Sandeep Somavarapu 已提交
75

76 77
	public domNode: HTMLElement;
	public searchInput: FindInput;
78
	private searchInputBoxFocussed: IContextKey<boolean>;
79 80
	private replaceInput: InputBox;

81 82 83
	public searchInputFocusTracker: dom.IFocusTracker;
	public replaceInputFocusTracker: dom.IFocusTracker;

S
Sandeep Somavarapu 已提交
84
	private replaceContainer: HTMLElement;
85
	private toggleReplaceButton: Button;
86
	private replaceAllAction: ReplaceAllAction;
A
Alex Dima 已提交
87
	private replaceActive: IContextKey<boolean>;
S
Sandeep Somavarapu 已提交
88
	private replaceActionBar: ActionBar;
89

90 91
	private searchHistory: HistoryNavigator<string>;

92 93 94 95 96 97 98 99 100
	private _onSearchSubmit = this._register(new Emitter<boolean>());
	public onSearchSubmit: Event<boolean> = this._onSearchSubmit.event;

	private _onSearchCancel = this._register(new Emitter<void>());
	public onSearchCancel: Event<void> = this._onSearchCancel.event;

	private _onReplaceToggled = this._register(new Emitter<void>());
	public onReplaceToggled: Event<void> = this._onReplaceToggled.event;

S
Sandeep Somavarapu 已提交
101 102
	private _onReplaceStateChange = this._register(new Emitter<boolean>());
	public onReplaceStateChange: Event<boolean> = this._onReplaceStateChange.event;
103 104 105 106 107 108 109 110

	private _onReplaceValueChanged = this._register(new Emitter<string>());
	public onReplaceValueChanged: Event<string> = this._onReplaceValueChanged.event;

	private _onReplaceAll = this._register(new Emitter<void>());
	public onReplaceAll: Event<void> = this._onReplaceAll.event;

	constructor(container: Builder, private contextViewService: IContextViewService, options: ISearchWidgetOptions= Object.create(null),
111
					private keyBindingService: IContextKeyService, private keyBindingService2: IKeybindingService, private instantiationService: IInstantiationService) {
112
		super();
113
		this.searchHistory = new HistoryNavigator<string>();
114 115
		this.replaceActive = Constants.ReplaceActiveKey.bindTo(this.keyBindingService);
		this.searchInputBoxFocussed = Constants.SearchInputBoxFocussedKey.bindTo(this.keyBindingService);
116 117 118 119
		this.render(container, options);
	}

	public focus(select:boolean= true, focusReplace: boolean= false):void {
120 121
		if ((!focusReplace && this.searchInput.inputBox.hasFocus())
					|| (focusReplace && this.replaceInput.hasFocus())) {
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
			return;
		}

		if (focusReplace && this.isReplaceShown()) {
			this.replaceInput.focus();
			if (select) {
				this.replaceInput.select();
			}
		} else {
			this.searchInput.focus();
			if (select) {
				this.searchInput.select();
			}
		}
	}

	public setWidth(width: number) {
		this.searchInput.setWidth(width - 2);
		this.replaceInput.width= width - 28;
	}

	public clear() {
		this.searchInput.clear();
		this.replaceInput.value= '';
S
Sandeep Somavarapu 已提交
146
		this.setReplaceAllActionState(false);
147 148 149
	}

	public isReplaceShown(): boolean {
S
Sandeep Somavarapu 已提交
150
		return !dom.hasClass(this.replaceContainer, 'disabled');
151 152 153
	}

	public getReplaceValue():string {
S
Sandeep Somavarapu 已提交
154
		return this.replaceInput.value;
155 156
	}

157 158 159
	public toggleReplace(show?:boolean): void {
		if (show === void 0 || show !== this.isReplaceShown()) {
			this.onToggleReplaceButton();
S
Sandeep Somavarapu 已提交
160 161 162
		}
	}

163 164 165 166 167 168 169 170 171 172 173 174 175 176
	public showNextSearchTerm() {
		let next = this.searchHistory.next();
		if (next) {
			this.searchInput.setValue(next);
		}
	}

	public showPreviousSearchTerm() {
		let previous = this.searchHistory.previous();
		if (previous) {
			this.searchInput.setValue(previous);
		}
	}

177 178 179 180 181 182 183 184
	public searchInputHasFocus(): boolean {
		return this.searchInputBoxFocussed.get();
	}

	public replaceInputHasFocus(): boolean {
		return this.replaceInput.hasFocus();
	}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
	private render(container: Builder, options: ISearchWidgetOptions): void {
		this.domNode = container.div({ 'class': 'search-widget' }).style({ position: 'relative' }).getHTMLElement();
		this.renderToggleReplaceButton(this.domNode);

		this.renderSearchInput(this.domNode, options);
		this.renderReplaceInput(this.domNode);
	}

	private renderToggleReplaceButton(parent: HTMLElement): void {
		this.toggleReplaceButton= this._register(new Button(parent));
		this.toggleReplaceButton.icon= 'toggle-replace-button collapse';
		this.toggleReplaceButton.addListener2('click', () => this.onToggleReplaceButton());
		this.toggleReplaceButton.getElement().title= nls.localize('search.replace.toggle.button.title', "Toggle Replace");
	}

	private renderSearchInput(parent: HTMLElement, options: ISearchWidgetOptions): void {
		let inputOptions: IFindInputOptions = {
			label: nls.localize('label.Search', 'Search: Type Search Term and press Enter to search or Escape to cancel'),
			validation: (value: string) => this.validatSearchInput(value),
			placeholder: nls.localize('search.placeHolder', "Search")
		};

J
Joao Moreno 已提交
207
		let searchInputContainer= dom.append(parent, dom.$('.search-container.input-box'));
208 209 210 211 212 213
		this.searchInput = this._register(new FindInput(searchInputContainer, this.contextViewService, inputOptions));
		this.searchInput.onKeyUp((keyboardEvent: IKeyboardEvent) => this.onSearchInputKeyUp(keyboardEvent));
		this.searchInput.setValue(options.value || '');
		this.searchInput.setRegex(!!options.isRegex);
		this.searchInput.setCaseSensitive(!!options.isCaseSensitive);
		this.searchInput.setWholeWords(!!options.isWholeWords);
214 215 216
		this._register(this.onSearchSubmit(() => {
			this.searchHistory.add(this.searchInput.getValue());
		}));
217 218 219 220 221 222 223 224

		this.searchInputFocusTracker = dom.trackFocus(this.searchInput.inputBox.inputElement);
		this._register(this.searchInputFocusTracker.addFocusListener(() => {
			this.searchInputBoxFocussed.set(true);
		}));
		this._register(this.searchInputFocusTracker.addBlurListener(() => {
			this.searchInputBoxFocussed.set(false);
		}));
225 226 227
	}

	private renderReplaceInput(parent: HTMLElement): void {
J
Joao Moreno 已提交
228 229
		this.replaceContainer = dom.append(parent, dom.$('.replace-container.disabled'));
		let replaceBox= dom.append(this.replaceContainer, dom.$('.input-box'));
S
Sandeep Somavarapu 已提交
230
		this.replaceInput = this._register(new InputBox(replaceBox, this.contextViewService, {
S
Sandeep Somavarapu 已提交
231
			ariaLabel: nls.localize('label.Replace', 'Replace: Type replace term and press Enter to preview or Escape to cancel'),
S
Sandeep Somavarapu 已提交
232
			placeholder: nls.localize('search.replace.placeHolder', "Replace")
233 234 235
		}));
		this.onkeyup(this.replaceInput.inputElement, (keyboardEvent) => this.onReplaceInputKeyUp(keyboardEvent));
		this.replaceInput.onDidChange(() => this._onReplaceValueChanged.fire());
S
Sandeep Somavarapu 已提交
236
		this.searchInput.inputBox.onDidChange(() => this.onSearchInputChanged());
S
Sandeep Somavarapu 已提交
237 238 239 240 241 242

		this.replaceAllAction = ReplaceAllAction.INSTANCE;
		this.replaceAllAction.searchWidget= this;
		this.replaceAllAction.label = SearchWidget.REPLACE_ALL_DISABLED_LABEL;
		this.replaceActionBar = this._register(new ActionBar(this.replaceContainer));
		this.replaceActionBar.push([this.replaceAllAction], { icon: true, label: false });
243 244

		this.replaceInputFocusTracker = dom.trackFocus(this.replaceInput.inputElement);
245 246
	}

247 248 249 250 251
	triggerReplaceAll(): TPromise<any> {
		this._onReplaceAll.fire();
		return TPromise.as(null);
	}

252
	private onToggleReplaceButton():void {
S
Sandeep Somavarapu 已提交
253
		dom.toggleClass(this.replaceContainer, 'disabled');
254 255
		dom.toggleClass(this.toggleReplaceButton.getElement(), 'collapse');
		dom.toggleClass(this.toggleReplaceButton.getElement(), 'expand');
256
		this.updateReplaceActiveState();
257
		this._onReplaceToggled.fire();
258 259 260 261 262
	}

	public setReplaceAllActionState(enabled:boolean):void {
		if (this.replaceAllAction.enabled !== enabled) {
			this.replaceAllAction.enabled= enabled;
A
Alex Dima 已提交
263
			this.replaceAllAction.label= enabled ? SearchWidget.REPLACE_ALL_ENABLED_LABEL(this.keyBindingService2) : SearchWidget.REPLACE_ALL_DISABLED_LABEL;
264 265 266 267 268
			this.updateReplaceActiveState();
		}
	}

	private isReplaceActive(): boolean {
A
Alex Dima 已提交
269
		return this.replaceActive.get();
270 271 272 273 274 275
	}

	private updateReplaceActiveState(): void {
		let currentState= this.isReplaceActive();
		let newState= this.isReplaceShown() && this.replaceAllAction.enabled;
		if (currentState !== newState) {
S
Sandeep Somavarapu 已提交
276 277
			this.replaceActive.set(newState);
			this._onReplaceStateChange.fire(newState);
278
		}
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	}

	private validatSearchInput(value: string): any {
		if (value.length === 0) {
			return null;
		}
		if (!this.searchInput.getRegex()) {
			return null;
		}
		let regExp: RegExp;
		try {
			regExp = new RegExp(value);
		} catch (e) {
			return { content: e.message };
		}
		if (strings.regExpLeadsToEndlessLoop(regExp)) {
			return { content: nls.localize('regexp.validationFailure', "Expression matches everything") };
		}
	}

S
Sandeep Somavarapu 已提交
299
	private onSearchInputChanged(): void {
S
Sandeep Somavarapu 已提交
300
		this.setReplaceAllActionState(false);
S
Sandeep Somavarapu 已提交
301 302
	}

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
	private onSearchInputKeyUp(keyboardEvent: IKeyboardEvent) {
		switch (keyboardEvent.keyCode) {
			case KeyCode.Enter:
				this.submitSearch();
				return;
			case KeyCode.Escape:
				this._onSearchCancel.fire();
				return;
			default:
				return;
		}
	}

	private onReplaceInputKeyUp(keyboardEvent: IKeyboardEvent) {
		switch (keyboardEvent.keyCode) {
			case KeyCode.Enter:
				this.submitSearch();
				return;
			case KeyCode.Escape:
				this.onToggleReplaceButton();
				this.searchInput.focus();
				return;
			default:
				return;
		}
	}

	private submitSearch(refresh: boolean= true): void {
		if (this.searchInput.getValue()) {
			this._onSearchSubmit.fire(refresh);
		}
	}

	public dispose(): void {
337 338
		this.setReplaceAllActionState(false);
		this.replaceAllAction.searchWidget= null;
S
Sandeep Somavarapu 已提交
339
		this.replaceActionBar = null;
340 341 342 343 344 345
		if (this.searchInputFocusTracker) {
			this.searchInputFocusTracker.dispose();
		}
		if (this.replaceInputFocusTracker) {
			this.replaceInputFocusTracker.dispose();
		}
346 347
		super.dispose();
	}
348 349 350
}

export function registerContributions() {
A
Alex Dima 已提交
351
	KeybindingsRegistry.registerCommandAndKeybindingRule({id: ReplaceAllAction.ID,
352
		weight: KeybindingsRegistry.WEIGHT.workbenchContrib(),
353
		when: ContextKeyExpr.and(ContextKeyExpr.has('searchViewletVisible'), Constants.ReplaceActiveKey, CONTEXT_FIND_WIDGET_NOT_VISIBLE),
354 355 356 357 358 359 360
		primary: KeyMod.Alt | KeyMod.CtrlCmd | KeyCode.Enter,
		handler: accessor => {
			if (isSearchViewletFocussed(accessor.get(IViewletService))) {
				ReplaceAllAction.INSTANCE.run();
			}
		}
	});
A
Alex Dima 已提交
361
}