forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindBar.js
More file actions
1 lines (1 loc) · 15.9 KB
/
Copy pathFindBar.js
File metadata and controls
1 lines (1 loc) · 15.9 KB
1
define(function(require,exports,module){const _=require("thirdparty/lodash"),Mustache=require("thirdparty/mustache/mustache"),EventDispatcher=require("utils/EventDispatcher"),Commands=require("command/Commands"),KeyBindingManager=require("command/KeyBindingManager"),KeyEvent=require("utils/KeyEvent"),ModalBar=require("widgets/ModalBar").ModalBar,PreferencesManager=require("preferences/PreferencesManager"),MainViewManager=require("view/MainViewManager"),Strings=require("strings"),ViewUtils=require("utils/ViewUtils"),FindUtils=require("search/FindUtils"),FileUtils=require("file/FileUtils"),QuickSearchField=require("search/QuickSearchField").QuickSearchField,Metrics=require("utils/Metrics"),_searchBarTemplate=require("text!htmlContent/findreplace-bar.html");let intervalId=0,lastQueriedText="",lastTypedText="",lastTypedTextWasRegexp=!1,lastClosedQuery=null;const MAX_HISTORY_RESULTS=25,PREF_MAX_HISTORY="maxSearchHistory",INSTANT_SEARCH_INTERVAL_MS=50;function FindBar(options){var defaults={multifile:!1,replace:!1,queryPlaceholder:"",initialQuery:"",initialReplaceText:"",scopeLabel:""};this._options=_.extend(defaults,options),this._closed=!1,this._enabled=!0}function _updateHistory(whichHistory,searchVal){if(searchVal){let searchHistory=PreferencesManager.getViewState(whichHistory);const maxCount=PreferencesManager.get(PREF_MAX_HISTORY),searchQueryIndex=searchHistory.indexOf(searchVal);-1!==searchQueryIndex?searchHistory.splice(searchQueryIndex,1):searchHistory.length===maxCount&&searchHistory.pop(),searchHistory.unshift(searchVal),PreferencesManager.setViewState(whichHistory,searchHistory)}}EventDispatcher.makeEventDispatcher(FindBar.prototype),FindBar._addFindBar=function(findBar){FindBar._bars=FindBar._bars||[],FindBar._bars.push(findBar)},FindBar._removeFindBar=function(findBar){FindBar._bars&&_.pull(FindBar._bars,findBar)},FindBar._closeFindBars=function(){var bars=FindBar._bars;bars&&(bars.forEach(function(bar){bar.close(!0,!1)}),bars=[])},FindBar.prototype._options=null,FindBar.prototype._closed=!1,FindBar.prototype._enabled=!0,FindBar.prototype._modalBar=null,FindBar.prototype.$=function(selector){return this._modalBar?$(selector,this._modalBar.getRoot()):$()},FindBar.prototype._updateSearchBarFromPrefs=function(){this.$("#find-case-sensitive").toggleClass("active",!!PreferencesManager.getViewState("caseSensitive")),this.$("#find-regexp").toggleClass("active",!!PreferencesManager.getViewState("regexp"))},FindBar.prototype._updatePrefsFromSearchBar=function(){var isRegexp=this.$("#find-regexp").is(".active");PreferencesManager.setViewState("caseSensitive",this.$("#find-case-sensitive").is(".active")),PreferencesManager.setViewState("regexp",isRegexp),lastTypedTextWasRegexp=isRegexp},FindBar.prototype._addShortcutToTooltip=function($elem,commandId){const replaceShortcut=KeyBindingManager.getKeyBindingsDisplay(commandId);if(replaceShortcut){var oldTitle=$elem.attr("title");oldTitle=oldTitle?oldTitle+" ":"",$elem.attr("title",oldTitle+"("+replaceShortcut+")")}},FindBar.prototype._addElementToSearchHistory=function(searchVal,filterVal){_updateHistory("searchHistory",searchVal),_updateHistory("filterHistory",filterVal)},FindBar.prototype.open=function(){var self=this;FindBar._closeFindBars();let metricType="findBar";this._options.multifile&&(metricType="findInFiles.bar"),Metrics.countEvent(Metrics.EVENT_TYPE.SEARCH,metricType,"opened");var templateVars=_.clone(this._options);function _handleKeydown(e){e.keyCode===KeyEvent.DOM_VK_ESCAPE&&(e.stopPropagation(),e.preventDefault(),self.close())}function _keydownHookForCtrlSpace(event){const ctrlSpaceEvent=(!0===event.ctrlKey||!0===event.metaKey)&&event.keyCode===KeyEvent.DOM_VK_SPACE;if(ctrlSpaceEvent)return $("#find-what").is(":focus")?(self.showSearchHints(),event.stopPropagation(),event.preventDefault(),!0):!!$("#fif-filter-input").is(":focus")&&(self.showFilterHints(),event.stopPropagation(),event.preventDefault(),!0)}templateVars.Strings=Strings,templateVars.replaceBatchLabel=templateVars.multifile?Strings.BUTTON_REPLACE_ALL_IN_FILES:Strings.BUTTON_REPLACE_BATCH,templateVars.replaceAllLabel=Strings.BUTTON_REPLACE_ALL,self._addElementToSearchHistory(this._options.initialQuery),this._modalBar=new ModalBar(Mustache.render(_searchBarTemplate,templateVars),!!PreferencesManager.get("autoHideSearch")),window.document.body.addEventListener("keydown",_handleKeydown,!0),KeyBindingManager.addGlobalKeydownHook(_keydownHookForCtrlSpace),this._modalBar.on("close",function(event){KeyBindingManager.removeGlobalKeydownHook(_keydownHookForCtrlSpace),window.document.body.removeEventListener("keydown",_handleKeydown,!0),self.showError(null),self._modalBar=null,self._closed=!0,window.clearInterval(intervalId),intervalId=0,FindBar._removeFindBar(self),MainViewManager.focusActivePane(),self.trigger("close"),self.searchField&&self.searchField.destroy(),self.filterField&&self.filterField.destroy()}),FindBar._addFindBar(this);let executeSearchIfNeeded=function(){FindUtils.isInstantSearchDisabled()||self._closed||self.getQueryInfo().query===lastQueriedText||FindUtils.isWorkerSearchInProgress()||self._options.multifile&&(self.trigger("doFind"),lastQueriedText=self.getQueryInfo().query)};0===intervalId&&(intervalId=window.setInterval(executeSearchIfNeeded,50));var $root=this._modalBar.getRoot(),historyIndex=0;$root.on("input","#find-what",function(){self.trigger("queryChange");var queryInfo=self.getQueryInfo();lastTypedText=queryInfo.query,lastTypedTextWasRegexp=queryInfo.isRegexp}).on("click","#find-case-sensitive, #find-regexp",function(e){$(e.currentTarget).toggleClass("active"),self._updatePrefsFromSearchBar(),self.trigger("queryChange"),self._options.multifile&&self.trigger("doFind")}).on("click","#find-counter",function(e){$("#find-what").focus()}).on("focusin","#find-what",function(e){$(".find-what-wrapper").addClass("find-what-wrapper-focused")}).on("focusout","#find-what",function(e){$(".find-what-wrapper").removeClass("find-what-wrapper-focused"),setTimeout(()=>{self.searchField&&!$("#find-what").is(":focus")&&(self.searchField.destroy(),self.searchField=null)},250)}).on("focusout","#fif-filter-input",function(e){setTimeout(()=>{self.filterField&&!$("#fif-filter-input").is(":focus")&&(self.filterField.destroy(),self.filterField=null)},250)}).on("click",".search-input-container .dropdown-icon",function(e){self.searchField?(self.searchField.destroy(),self.searchField=null):self.showSearchHints(!0),self.$("#find-what").focus()}).on("click",".filter-container .filter-dropdown-icon",function(e){self.filterField?(self.filterField.destroy(),self.filterField=null):self.showFilterHints(!0),self.$("#fif-filter-input").focus()}).on("keydown","#find-what, #replace-with, #fif-filter-input",function(e){if(e.keyCode===KeyEvent.DOM_VK_RETURN){if(self._options.multifile&&e.shiftKey)return;e.preventDefault(),e.stopPropagation(),self._addElementToSearchHistory(self.$("#find-what").val(),self.$("#fif-filter-input").val()),self._options.multifile?$(e.target).is("#find-what")?self._options.replace?self.focusReplace():(Metrics.countEvent(Metrics.EVENT_TYPE.SEARCH,"findInFiles.bar","returnKey"),self.trigger("openSelectedFile")):(Metrics.countEvent(Metrics.EVENT_TYPE.SEARCH,"replaceBatchInFiles.bar","returnKey"),self.trigger("doReplaceBatch")):self.trigger("doFind",e.shiftKey),historyIndex=0}else if(e.keyCode===KeyEvent.DOM_VK_DOWN){if(e.preventDefault(),e.stopPropagation(),self._options.multifile)return void self.trigger("selectNextResult");self.trigger("doFind",!1)}else if(e.keyCode===KeyEvent.DOM_VK_UP){if(e.preventDefault(),e.stopPropagation(),self._options.multifile)return void self.trigger("selectPrevResult");self.trigger("doFind",!0)}else e.keyCode===KeyEvent.DOM_VK_PAGE_DOWN?(e.preventDefault(),e.stopPropagation(),self.trigger("selectNextPage")):e.keyCode===KeyEvent.DOM_VK_PAGE_UP&&(e.preventDefault(),e.stopPropagation(),self.trigger("selectPrevPage"))}).on("click",".close",function(){self.close()}),this._options.multifile||(this._addShortcutToTooltip($("#find-next"),Commands.CMD_FIND_NEXT),this._addShortcutToTooltip($("#find-prev"),Commands.CMD_FIND_PREVIOUS),$root.on("click","#find-next",function(e){self.trigger("doFind",!1)}).on("click","#find-prev",function(e){self.trigger("doFind",!0)})),this._options.replace&&(this._addShortcutToTooltip($("#replace-yes"),Commands.CMD_REPLACE),$root.on("click","#replace-yes",function(e){self.trigger("doReplace")}).on("click","#replace-batch",function(e){self.trigger("doReplaceBatch")}).on("click","#replace-all",function(e){self.trigger("doReplaceAll")}).on("keydown",function(e){e.keyCode!==KeyEvent.DOM_VK_TAB||e.ctrlKey||e.metaKey||e.altKey||("replace-with"!==e.target.id||e.shiftKey?"find-what"===e.target.id&&e.shiftKey&&(self.$("#replace-with").focus(),e.preventDefault()):(self.$("#find-what").focus(),e.preventDefault()))})),this._options.multifile&&FindUtils.isIndexingInProgress()&&this.showIndexingSpinner(),this._updateSearchBarFromPrefs(),this.focusQuery()},FindBar.prototype._showHintsInternal=function(positionElement,inputElemId,stateVarName,fieldName,dontFilterHistory){const self=this;self._dontFilterHistory=dontFilterHistory;let inputField=self.$(inputElemId);const maxCount=PreferencesManager.get(PREF_MAX_HISTORY);this[fieldName]=new QuickSearchField(inputField,{verticalAdjust:inputField.offset().top>0?0:this._modalBar.getRoot().outerHeight(),maxResults:maxCount,firstHighlightIndex:null,$positionEl:positionElement?self.$(positionElement):null,resultProvider:function(query){query=query||"";const asyncResult=new $.Deferred;let history=PreferencesManager.getViewState(stateVarName)||[];return self._dontFilterHistory||(history=history.filter(historyItem=>"string"==typeof historyItem&&historyItem.toLowerCase().includes(query.toLowerCase()))),self._dontFilterHistory=!1,asyncResult.resolve(history),asyncResult.promise()},formatter:function(item,query){const $li=$("<li></li>");return $li.text(item),$li},onCommit:function(selectedItem,query,itemIndex){if(selectedItem?(self.$(inputElemId).val(selectedItem),self.$(inputElemId).val(selectedItem).trigger("input")):query.length&&self[fieldName].setText(query),self.$(inputElemId).focus(),self[fieldName].destroy(),self[fieldName]=null,itemIndex){let history=PreferencesManager.getViewState(stateVarName)||[],deletedItem=history.splice(itemIndex,1);history.unshift(deletedItem[0]),PreferencesManager.setViewState(stateVarName,history)}},onDismiss:function(){self[fieldName]&&(self[fieldName].destroy(),self[fieldName]=null)},onDelete:function(deletedIndex){let history=PreferencesManager.getViewState(stateVarName)||[];history.splice(deletedIndex,1),PreferencesManager.setViewState(stateVarName,history)},onHighlight:function(selectedItem,query,explicit){},highlightZeroResults:!1,focusLastActiveElementOnClose:!0}),this[fieldName].setText(inputField.val())},FindBar.prototype.showSearchHints=function(dontFilterHistory){return this._showHintsInternal(".find-what-wrapper","#find-what","searchHistory","searchField",dontFilterHistory)},FindBar.prototype.showFilterHints=function(dontFilterHistory){return this._showHintsInternal(null,"#fif-filter-input","filterHistory","filterField",dontFilterHistory)},FindBar.prototype.close=function(suppressAnimation){lastQueriedText="",this._modalBar&&(lastClosedQuery={query:this.$("#find-what").val()||"",replaceText:this.getReplaceText(),isCaseSensitive:this.$("#find-case-sensitive").is(".active"),isRegexp:this.$("#find-regexp").is(".active")},this._addElementToSearchHistory($("#find-what").val(),$("#fif-filter-input").val()),this._modalBar.close(!0,!suppressAnimation))},FindBar.prototype.isClosed=function(){return this._closed},FindBar.prototype.getOptions=function(){return this._options},FindBar.prototype.getQueryInfo=function(usePlatformLineEndings=!0){const $findWhat=this.$("#find-what"),findTextArea=$findWhat[0];let query=$findWhat.val()||"";const lineEndings=FileUtils.sniffLineEndings(query);return usePlatformLineEndings&&lineEndings===FileUtils.LINE_ENDINGS_LF&&"win"===brackets.platform&&(query=query.replace(/\n/g,"\r\n")),{query:query,isCaseSensitive:this.$("#find-case-sensitive").is(".active"),isRegexp:this.$("#find-regexp").is(".active"),isQueryTextSelected:findTextArea.selectionStart!==findTextArea.selectionEnd}},FindBar.prototype.showError=function(error,isHTML,isFilterError){const $findError=this.$(".error"),$filterError=this.$(".error-filter"),$error=isFilterError?$filterError:$findError;$findError.hide(),$filterError.hide(),error&&(isHTML?$error.html(error):$error.text(error),$error.show())},FindBar.prototype.showFindCount=function(count){this.$("#find-counter").text(count).attr("title",count)},FindBar.prototype.showNoResults=function(showIndicator,showMessage){const $filterInput=this.$("#fif-filter-input"),$findWhat=this.$(".find-what-wrapper");$filterInput.removeClass("no-results"),$findWhat.removeClass("no-results");let $borderEl=$findWhat;$filterInput.is(":focus")&&($borderEl=$filterInput),ViewUtils.toggleClass($borderEl,"no-results",showIndicator);const noResultsMessage=showMessage?Strings.FIND_NO_RESULTS:"";this.showFindCount(noResultsMessage)},FindBar.prototype.getReplaceText=function(){return this.$("#replace-with").val()||""},FindBar.prototype.enable=function(enable){this.$("#find-what, #replace-with, #find-prev, #find-next, #find-case-sensitive, #find-regexp").prop("disabled",!enable),this._enabled=enable},FindBar.prototype.focus=function(enable){this.$("#fif-filter-input").is(":focus")||this.$("#find-what").focus()},FindBar.prototype.isEnabled=function(){return this._enabled},FindBar.prototype.isReplaceEnabled=function(){return this.$("#replace-yes").is(":enabled")},FindBar.prototype.enableNavigation=function(enable){this.isEnabled()&&this.$("#find-prev, #find-next").prop("disabled",!enable)},FindBar.prototype.enableReplace=function(enable){this.isEnabled&&this.$("#replace-yes, #replace-batch, #replace-all").prop("disabled",!enable)},FindBar.prototype._focus=function(selector){this.$(selector).focus().get(0).select()},FindBar.prototype.focusQuery=function(){this._focus("#find-what")},FindBar.prototype.focusReplace=function(){this._focus("#replace-with")},FindBar.prototype.showIndexingSpinner=function(){this.$("#indexing-spinner").removeClass("forced-hidden"),this.setIndexingMessage(Strings.FIND_IN_FILES_INDEXING)},FindBar.prototype.setIndexingMessage=function(message){this.$("#indexing-spinner-message").text(message)},FindBar.prototype.hideIndexingSpinner=function(){this.$("#indexing-spinner").addClass("forced-hidden")},FindBar.prototype.redoInstantSearch=function(){this.trigger("doFind")},FindBar._getInitialQueryFromSelection=function(editor){const selectionText=editor.document.getSelectedText(!0);return selectionText?selectionText.replace(/^\n*/,""):""},FindBar.getInitialQuery=function(currentFindBar,editor){var query,selection=editor?FindBar._getInitialQueryFromSelection(editor):"",replaceText="";if(currentFindBar&&!currentFindBar.isClosed()){var queryInfo=currentFindBar.getQueryInfo();query=!queryInfo.isRegexp&&selection||queryInfo.query,replaceText=currentFindBar.getReplaceText()}else{var openedFindBar=FindBar._bars&&_.find(FindBar._bars,function(bar){return!bar.isClosed()});const currentQueryInfo=openedFindBar&&openedFindBar.getQueryInfo();!openedFindBar&&selection?query=selection:openedFindBar&&selection&¤tQueryInfo&&!currentQueryInfo.isRegexp&¤tQueryInfo.isQueryTextSelected?(query=selection,replaceText=openedFindBar.getReplaceText()):openedFindBar?(query=openedFindBar.getQueryInfo().query,replaceText=openedFindBar.getReplaceText()):lastClosedQuery?(query=lastClosedQuery.query,replaceText=lastClosedQuery.replaceText):editor&&(query=!lastTypedTextWasRegexp&&selection||lastQueriedText||lastTypedText)}return{query:query,replaceText:replaceText}},PreferencesManager.stateManager.definePreference("caseSensitive","boolean",!1),PreferencesManager.stateManager.definePreference("regexp","boolean",!1),PreferencesManager.stateManager.definePreference("searchHistory","array",[]),PreferencesManager.stateManager.definePreference("filterHistory","array",[]),PreferencesManager.definePreference(PREF_MAX_HISTORY,"number",25,{description:Strings.FIND_HISTORY_MAX_COUNT}),exports.FindBar=FindBar});