michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: "use strict"; michael@0: michael@0: const promise = require("devtools/toolkit/deprecated-sync-thenables"); michael@0: michael@0: loader.lazyGetter(this, "AutocompletePopup", () => require("devtools/shared/autocomplete-popup").AutocompletePopup); michael@0: michael@0: // Maximum number of selector suggestions shown in the panel. michael@0: const MAX_SUGGESTIONS = 15; michael@0: michael@0: /** michael@0: * Converts any input box on a page to a CSS selector search and suggestion box. michael@0: * michael@0: * @constructor michael@0: * @param InspectorPanel aInspector michael@0: * The InspectorPanel whose `walker` attribute should be used for michael@0: * document traversal. michael@0: * @param nsiInputElement aInputNode michael@0: * The input element to which the panel will be attached and from where michael@0: * search input will be taken. michael@0: */ michael@0: function SelectorSearch(aInspector, aInputNode) { michael@0: this.inspector = aInspector; michael@0: this.searchBox = aInputNode; michael@0: this.panelDoc = this.searchBox.ownerDocument; michael@0: michael@0: // initialize variables. michael@0: this._lastSearched = null; michael@0: this._lastValidSearch = ""; michael@0: this._lastToLastValidSearch = null; michael@0: this._searchResults = null; michael@0: this._searchSuggestions = {}; michael@0: this._searchIndex = 0; michael@0: michael@0: // bind! michael@0: this._showPopup = this._showPopup.bind(this); michael@0: this._onHTMLSearch = this._onHTMLSearch.bind(this); michael@0: this._onSearchKeypress = this._onSearchKeypress.bind(this); michael@0: this._onListBoxKeypress = this._onListBoxKeypress.bind(this); michael@0: michael@0: // Options for the AutocompletePopup. michael@0: let options = { michael@0: panelId: "inspector-searchbox-panel", michael@0: listBoxId: "searchbox-panel-listbox", michael@0: autoSelect: true, michael@0: position: "before_start", michael@0: direction: "ltr", michael@0: theme: "auto", michael@0: onClick: this._onListBoxKeypress, michael@0: onKeypress: this._onListBoxKeypress michael@0: }; michael@0: this.searchPopup = new AutocompletePopup(this.panelDoc, options); michael@0: michael@0: // event listeners. michael@0: this.searchBox.addEventListener("command", this._onHTMLSearch, true); michael@0: this.searchBox.addEventListener("keypress", this._onSearchKeypress, true); michael@0: michael@0: // For testing, we need to be able to wait for the most recent node request michael@0: // to finish. Tests can watch this promise for that. michael@0: this._lastQuery = promise.resolve(null); michael@0: } michael@0: michael@0: exports.SelectorSearch = SelectorSearch; michael@0: michael@0: SelectorSearch.prototype = { michael@0: michael@0: get walker() this.inspector.walker, michael@0: michael@0: // The possible states of the query. michael@0: States: { michael@0: CLASS: "class", michael@0: ID: "id", michael@0: TAG: "tag", michael@0: }, michael@0: michael@0: // The current state of the query. michael@0: _state: null, michael@0: michael@0: // The query corresponding to last state computation. michael@0: _lastStateCheckAt: null, michael@0: michael@0: /** michael@0: * Computes the state of the query. State refers to whether the query michael@0: * currently requires a class suggestion, or a tag, or an Id suggestion. michael@0: * This getter will effectively compute the state by traversing the query michael@0: * character by character each time the query changes. michael@0: * michael@0: * @example michael@0: * '#f' requires an Id suggestion, so the state is States.ID michael@0: * 'div > .foo' requires class suggestion, so state is States.CLASS michael@0: */ michael@0: get state() { michael@0: if (!this.searchBox || !this.searchBox.value) { michael@0: return null; michael@0: } michael@0: michael@0: let query = this.searchBox.value; michael@0: if (this._lastStateCheckAt == query) { michael@0: // If query is the same, return early. michael@0: return this._state; michael@0: } michael@0: this._lastStateCheckAt = query; michael@0: michael@0: this._state = null; michael@0: let subQuery = ""; michael@0: // Now we iterate over the query and decide the state character by character. michael@0: // The logic here is that while iterating, the state can go from one to michael@0: // another with some restrictions. Like, if the state is Class, then it can michael@0: // never go to Tag state without a space or '>' character; Or like, a Class michael@0: // state with only '.' cannot go to an Id state without any [a-zA-Z] after michael@0: // the '.' which means that '.#' is a selector matching a class name '#'. michael@0: // Similarily for '#.' which means a selctor matching an id '.'. michael@0: for (let i = 1; i <= query.length; i++) { michael@0: // Calculate the state. michael@0: subQuery = query.slice(0, i); michael@0: let [secondLastChar, lastChar] = subQuery.slice(-2); michael@0: switch (this._state) { michael@0: case null: michael@0: // This will happen only in the first iteration of the for loop. michael@0: lastChar = secondLastChar; michael@0: case this.States.TAG: michael@0: this._state = lastChar == "." michael@0: ? this.States.CLASS michael@0: : lastChar == "#" michael@0: ? this.States.ID michael@0: : this.States.TAG; michael@0: break; michael@0: michael@0: case this.States.CLASS: michael@0: if (subQuery.match(/[\.]+[^\.]*$/)[0].length > 2) { michael@0: // Checks whether the subQuery has atleast one [a-zA-Z] after the '.'. michael@0: this._state = (lastChar == " " || lastChar == ">") michael@0: ? this.States.TAG michael@0: : lastChar == "#" michael@0: ? this.States.ID michael@0: : this.States.CLASS; michael@0: } michael@0: break; michael@0: michael@0: case this.States.ID: michael@0: if (subQuery.match(/[#]+[^#]*$/)[0].length > 2) { michael@0: // Checks whether the subQuery has atleast one [a-zA-Z] after the '#'. michael@0: this._state = (lastChar == " " || lastChar == ">") michael@0: ? this.States.TAG michael@0: : lastChar == "." michael@0: ? this.States.CLASS michael@0: : this.States.ID; michael@0: } michael@0: break; michael@0: } michael@0: } michael@0: return this._state; michael@0: }, michael@0: michael@0: /** michael@0: * Removes event listeners and cleans up references. michael@0: */ michael@0: destroy: function() { michael@0: // event listeners. michael@0: this.searchBox.removeEventListener("command", this._onHTMLSearch, true); michael@0: this.searchBox.removeEventListener("keypress", this._onSearchKeypress, true); michael@0: this.searchPopup.destroy(); michael@0: this.searchPopup = null; michael@0: this.searchBox = null; michael@0: this.panelDoc = null; michael@0: this._searchResults = null; michael@0: this._searchSuggestions = null; michael@0: }, michael@0: michael@0: _selectResult: function(index) { michael@0: return this._searchResults.item(index).then(node => { michael@0: this.inspector.selection.setNodeFront(node, "selectorsearch"); michael@0: }); michael@0: }, michael@0: michael@0: /** michael@0: * The command callback for the input box. This function is automatically michael@0: * invoked as the user is typing if the input box type is search. michael@0: */ michael@0: _onHTMLSearch: function() { michael@0: let query = this.searchBox.value; michael@0: if (query == this._lastSearched) { michael@0: return; michael@0: } michael@0: this._lastSearched = query; michael@0: this._searchResults = []; michael@0: this._searchIndex = 0; michael@0: michael@0: if (query.length == 0) { michael@0: this._lastValidSearch = ""; michael@0: this.searchBox.removeAttribute("filled"); michael@0: this.searchBox.classList.remove("devtools-no-search-result"); michael@0: if (this.searchPopup.isOpen) { michael@0: this.searchPopup.hidePopup(); michael@0: } michael@0: return; michael@0: } michael@0: michael@0: this.searchBox.setAttribute("filled", true); michael@0: let queryList = null; michael@0: michael@0: this._lastQuery = this.walker.querySelectorAll(this.walker.rootNode, query).then(list => { michael@0: return list; michael@0: }, (err) => { michael@0: // Failures are ok here, just use a null item list; michael@0: return null; michael@0: }).then(queryList => { michael@0: // Value has changed since we started this request, we're done. michael@0: if (query != this.searchBox.value) { michael@0: if (queryList) { michael@0: queryList.release(); michael@0: } michael@0: return promise.reject(null); michael@0: } michael@0: michael@0: this._searchResults = queryList || []; michael@0: if (this._searchResults && this._searchResults.length > 0) { michael@0: this._lastValidSearch = query; michael@0: // Even though the selector matched atleast one node, there is still michael@0: // possibility of suggestions. michael@0: if (query.match(/[\s>+]$/)) { michael@0: // If the query has a space or '>' at the end, create a selector to match michael@0: // the children of the selector inside the search box by adding a '*'. michael@0: this._lastValidSearch += "*"; michael@0: } michael@0: else if (query.match(/[\s>+][\.#a-zA-Z][\.#>\s+]*$/)) { michael@0: // If the query is a partial descendant selector which does not matches michael@0: // any node, remove the last incomplete part and add a '*' to match michael@0: // everything. For ex, convert 'foo > b' to 'foo > *' . michael@0: let lastPart = query.match(/[\s>+][\.#a-zA-Z][^>\s+]*$/)[0]; michael@0: this._lastValidSearch = query.slice(0, -1 * lastPart.length + 1) + "*"; michael@0: } michael@0: michael@0: if (!query.slice(-1).match(/[\.#\s>+]/)) { michael@0: // Hide the popup if we have some matching nodes and the query is not michael@0: // ending with [.# >] which means that the selector is not at the michael@0: // beginning of a new class, tag or id. michael@0: if (this.searchPopup.isOpen) { michael@0: this.searchPopup.hidePopup(); michael@0: } michael@0: this.searchBox.classList.remove("devtools-no-search-result"); michael@0: michael@0: return this._selectResult(0); michael@0: } michael@0: return this._selectResult(0).then(() => { michael@0: this.searchBox.classList.remove("devtools-no-search-result"); michael@0: }).then(() => this.showSuggestions()); michael@0: } michael@0: if (query.match(/[\s>+]$/)) { michael@0: this._lastValidSearch = query + "*"; michael@0: } michael@0: else if (query.match(/[\s>+][\.#a-zA-Z][\.#>\s+]*$/)) { michael@0: let lastPart = query.match(/[\s+>][\.#a-zA-Z][^>\s+]*$/)[0]; michael@0: this._lastValidSearch = query.slice(0, -1 * lastPart.length + 1) + "*"; michael@0: } michael@0: this.searchBox.classList.add("devtools-no-search-result"); michael@0: return this.showSuggestions(); michael@0: }); michael@0: }, michael@0: michael@0: /** michael@0: * Handles keypresses inside the input box. michael@0: */ michael@0: _onSearchKeypress: function(aEvent) { michael@0: let query = this.searchBox.value; michael@0: switch(aEvent.keyCode) { michael@0: case aEvent.DOM_VK_RETURN: michael@0: if (query == this._lastSearched && this._searchResults) { michael@0: this._searchIndex = (this._searchIndex + 1) % this._searchResults.length; michael@0: } michael@0: else { michael@0: this._onHTMLSearch(); michael@0: return; michael@0: } michael@0: break; michael@0: michael@0: case aEvent.DOM_VK_UP: michael@0: if (this.searchPopup.isOpen && this.searchPopup.itemCount > 0) { michael@0: this.searchPopup.focus(); michael@0: if (this.searchPopup.selectedIndex == this.searchPopup.itemCount - 1) { michael@0: this.searchPopup.selectedIndex = michael@0: Math.max(0, this.searchPopup.itemCount - 2); michael@0: } michael@0: else { michael@0: this.searchPopup.selectedIndex = this.searchPopup.itemCount - 1; michael@0: } michael@0: this.searchBox.value = this.searchPopup.selectedItem.label; michael@0: } michael@0: else if (--this._searchIndex < 0) { michael@0: this._searchIndex = this._searchResults.length - 1; michael@0: } michael@0: break; michael@0: michael@0: case aEvent.DOM_VK_DOWN: michael@0: if (this.searchPopup.isOpen && this.searchPopup.itemCount > 0) { michael@0: this.searchPopup.focus(); michael@0: this.searchPopup.selectedIndex = 0; michael@0: this.searchBox.value = this.searchPopup.selectedItem.label; michael@0: } michael@0: this._searchIndex = (this._searchIndex + 1) % this._searchResults.length; michael@0: break; michael@0: michael@0: case aEvent.DOM_VK_TAB: michael@0: if (this.searchPopup.isOpen && michael@0: this.searchPopup.getItemAtIndex(this.searchPopup.itemCount - 1) michael@0: .preLabel == query) { michael@0: this.searchPopup.selectedIndex = this.searchPopup.itemCount - 1; michael@0: this.searchBox.value = this.searchPopup.selectedItem.label; michael@0: this._onHTMLSearch(); michael@0: } michael@0: break; michael@0: michael@0: case aEvent.DOM_VK_BACK_SPACE: michael@0: case aEvent.DOM_VK_DELETE: michael@0: // need to throw away the lastValidSearch. michael@0: this._lastToLastValidSearch = null; michael@0: // This gets the most complete selector from the query. For ex. michael@0: // '.foo.ba' returns '.foo' , '#foo > .bar.baz' returns '#foo > .bar' michael@0: // '.foo +bar' returns '.foo +' and likewise. michael@0: this._lastValidSearch = (query.match(/(.*)[\.#][^\.# ]{0,}$/) || michael@0: query.match(/(.*[\s>+])[a-zA-Z][^\.# ]{0,}$/) || michael@0: ["",""])[1]; michael@0: return; michael@0: michael@0: default: michael@0: return; michael@0: } michael@0: michael@0: aEvent.preventDefault(); michael@0: aEvent.stopPropagation(); michael@0: if (this._searchResults && this._searchResults.length > 0) { michael@0: this._lastQuery = this._selectResult(this._searchIndex); michael@0: } michael@0: }, michael@0: michael@0: /** michael@0: * Handles keypress and mouse click on the suggestions richlistbox. michael@0: */ michael@0: _onListBoxKeypress: function(aEvent) { michael@0: switch(aEvent.keyCode || aEvent.button) { michael@0: case aEvent.DOM_VK_RETURN: michael@0: case aEvent.DOM_VK_TAB: michael@0: case 0: // left mouse button michael@0: aEvent.stopPropagation(); michael@0: aEvent.preventDefault(); michael@0: this.searchBox.value = this.searchPopup.selectedItem.label; michael@0: this.searchBox.focus(); michael@0: this._onHTMLSearch(); michael@0: break; michael@0: michael@0: case aEvent.DOM_VK_UP: michael@0: if (this.searchPopup.selectedIndex == 0) { michael@0: this.searchPopup.selectedIndex = -1; michael@0: aEvent.stopPropagation(); michael@0: aEvent.preventDefault(); michael@0: this.searchBox.focus(); michael@0: } michael@0: else { michael@0: let index = this.searchPopup.selectedIndex; michael@0: this.searchBox.value = this.searchPopup.getItemAtIndex(index - 1).label; michael@0: } michael@0: break; michael@0: michael@0: case aEvent.DOM_VK_DOWN: michael@0: if (this.searchPopup.selectedIndex == this.searchPopup.itemCount - 1) { michael@0: this.searchPopup.selectedIndex = -1; michael@0: aEvent.stopPropagation(); michael@0: aEvent.preventDefault(); michael@0: this.searchBox.focus(); michael@0: } michael@0: else { michael@0: let index = this.searchPopup.selectedIndex; michael@0: this.searchBox.value = this.searchPopup.getItemAtIndex(index + 1).label; michael@0: } michael@0: break; michael@0: michael@0: case aEvent.DOM_VK_BACK_SPACE: michael@0: aEvent.stopPropagation(); michael@0: aEvent.preventDefault(); michael@0: this.searchBox.focus(); michael@0: if (this.searchBox.selectionStart > 0) { michael@0: this.searchBox.value = michael@0: this.searchBox.value.substring(0, this.searchBox.selectionStart - 1); michael@0: } michael@0: this._lastToLastValidSearch = null; michael@0: let query = this.searchBox.value; michael@0: this._lastValidSearch = (query.match(/(.*)[\.#][^\.# ]{0,}$/) || michael@0: query.match(/(.*[\s>+])[a-zA-Z][^\.# ]{0,}$/) || michael@0: ["",""])[1]; michael@0: this._onHTMLSearch(); michael@0: break; michael@0: } michael@0: }, michael@0: michael@0: /** michael@0: * Populates the suggestions list and show the suggestion popup. michael@0: */ michael@0: _showPopup: function(aList, aFirstPart) { michael@0: let total = 0; michael@0: let query = this.searchBox.value; michael@0: let toLowerCase = false; michael@0: let items = []; michael@0: // In case of tagNames, change the case to small. michael@0: if (query.match(/.*[\.#][^\.#]{0,}$/) == null) { michael@0: toLowerCase = true; michael@0: } michael@0: for (let [value, count] of aList) { michael@0: // for cases like 'div ' or 'div >' or 'div+' michael@0: if (query.match(/[\s>+]$/)) { michael@0: value = query + value; michael@0: } michael@0: // for cases like 'div #a' or 'div .a' or 'div > d' and likewise michael@0: else if (query.match(/[\s>+][\.#a-zA-Z][^\s>+\.#]*$/)) { michael@0: let lastPart = query.match(/[\s>+][\.#a-zA-Z][^>\s+\.#]*$/)[0]; michael@0: value = query.slice(0, -1 * lastPart.length + 1) + value; michael@0: } michael@0: // for cases like 'div.class' or '#foo.bar' and likewise michael@0: else if (query.match(/[a-zA-Z][#\.][^#\.\s+>]*$/)) { michael@0: let lastPart = query.match(/[a-zA-Z][#\.][^#\.\s>+]*$/)[0]; michael@0: value = query.slice(0, -1 * lastPart.length + 1) + value; michael@0: } michael@0: let item = { michael@0: preLabel: query, michael@0: label: value, michael@0: count: count michael@0: }; michael@0: if (toLowerCase) { michael@0: item.label = value.toLowerCase(); michael@0: } michael@0: items.unshift(item); michael@0: if (++total > MAX_SUGGESTIONS - 1) { michael@0: break; michael@0: } michael@0: } michael@0: if (total > 0) { michael@0: this.searchPopup.setItems(items); michael@0: this.searchPopup.openPopup(this.searchBox); michael@0: } michael@0: else { michael@0: this.searchPopup.hidePopup(); michael@0: } michael@0: }, michael@0: michael@0: /** michael@0: * Suggests classes,ids and tags based on the user input as user types in the michael@0: * searchbox. michael@0: */ michael@0: showSuggestions: function() { michael@0: let query = this.searchBox.value; michael@0: let firstPart = ""; michael@0: if (this.state == this.States.TAG) { michael@0: // gets the tag that is being completed. For ex. 'div.foo > s' returns 's', michael@0: // 'di' returns 'di' and likewise. michael@0: firstPart = (query.match(/[\s>+]?([a-zA-Z]*)$/) || ["", query])[1]; michael@0: query = query.slice(0, query.length - firstPart.length); michael@0: } michael@0: else if (this.state == this.States.CLASS) { michael@0: // gets the class that is being completed. For ex. '.foo.b' returns 'b' michael@0: firstPart = query.match(/\.([^\.]*)$/)[1]; michael@0: query = query.slice(0, query.length - firstPart.length - 1); michael@0: } michael@0: else if (this.state == this.States.ID) { michael@0: // gets the id that is being completed. For ex. '.foo#b' returns 'b' michael@0: firstPart = query.match(/#([^#]*)$/)[1]; michael@0: query = query.slice(0, query.length - firstPart.length - 1); michael@0: } michael@0: // TODO: implement some caching so that over the wire request is not made michael@0: // everytime. michael@0: if (/[\s+>~]$/.test(query)) { michael@0: query += "*"; michael@0: } michael@0: this._currentSuggesting = query; michael@0: return this.walker.getSuggestionsForQuery(query, firstPart, this.state).then(result => { michael@0: if (this._currentSuggesting != result.query) { michael@0: // This means that this response is for a previous request and the user michael@0: // as since typed something extra leading to a new request. michael@0: return; michael@0: } michael@0: this._lastToLastValidSearch = this._lastValidSearch; michael@0: if (this.state == this.States.CLASS) { michael@0: firstPart = "." + firstPart; michael@0: } michael@0: else if (this.state == this.States.ID) { michael@0: firstPart = "#" + firstPart; michael@0: } michael@0: this._showPopup(result.suggestions, firstPart); michael@0: }); michael@0: } michael@0: };