Commit 3b5f228f authored by manuk's avatar manuk Committed by Commit Bot

[about-omnibox] formatting omnibox.js

Where appropriate, replaced `var`s with `let`s, `function`s with lambdas, closure function with braces, and construction functions with classes.

Change-Id: I45dcf2e7aa840242cf2b25cd73cf8a81bfe5b3da
Reviewed-on: https://chromium-review.googlesource.com/1239352
Commit-Queue: manuk hovanesian <manukh@chromium.org>
Reviewed-by: default avatarDemetrios Papadopoulos <dpapad@chromium.org>
Cr-Commit-Position: refs/heads/master@{#593684}
parent 45c7e3ea
...@@ -22,6 +22,7 @@ if (closure_compile) { ...@@ -22,6 +22,7 @@ if (closure_compile) {
"md_history:closure_compile", "md_history:closure_compile",
"media_router:closure_compile", "media_router:closure_compile",
"ntp4:closure_compile", "ntp4:closure_compile",
"omnibox:closure_compile",
"pdf:closure_compile", "pdf:closure_compile",
"print_preview:closure_compile", "print_preview:closure_compile",
"settings:closure_compile", "settings:closure_compile",
......
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
module.exports = {
'env': {
'browser': true,
'es6': true,
},
'rules': {
'no-var': 'error',
},
};
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//third_party/closure_compiler/compile_js.gni")
js_type_check("closure_compile") {
deps = [
":omnibox",
]
}
js_library("omnibox") {
deps = [
"//ui/webui/resources/js:util",
]
extra_deps = [ "//chrome/browser/ui/webui/omnibox:mojo_bindings_js" ]
externs_list = [
"$root_gen_dir/chrome/browser/ui/webui/omnibox/omnibox.mojom.externs.js",
"$externs_path/mojo.js",
]
}
...@@ -17,432 +17,426 @@ ...@@ -17,432 +17,426 @@
* are available, the Javascript formats them and displays them. * are available, the Javascript formats them and displays them.
*/ */
(function() { (function () {
/** /**
* Register our event handlers. * Register our event handlers.
*/ */
function initialize() { function initialize() {
$('omnibox-input-form').addEventListener('submit', startOmniboxQuery, false); $('omnibox-input-form').addEventListener('submit', startOmniboxQuery, false);
$('prevent-inline-autocomplete') $('prevent-inline-autocomplete')
.addEventListener('change', startOmniboxQuery); .addEventListener('change', startOmniboxQuery);
$('prefer-keyword').addEventListener('change', startOmniboxQuery); $('prefer-keyword').addEventListener('change', startOmniboxQuery);
$('page-classification').addEventListener('change', startOmniboxQuery); $('page-classification').addEventListener('change', startOmniboxQuery);
$('show-details').addEventListener('change', refresh); $('show-details').addEventListener('change', refresh);
$('show-incomplete-results').addEventListener('change', refresh); $('show-incomplete-results').addEventListener('change', refresh);
$('show-all-providers').addEventListener('change', refresh); $('show-all-providers').addEventListener('change', refresh);
} }
/** /**
* @type {OmniboxResultMojo} an array of all autocomplete results we've seen * @type {!Array<mojom.OmniboxResult>} an array of all autocomplete results we've seen
* for this query. We append to this list once for every call to * for this query. We append to this list once for every call to
* handleNewAutocompleteResult. See omnibox.mojom for details.. * handleNewAutocompleteResult. See omnibox.mojom for details..
*/ */
var progressiveAutocompleteResults = []; let progressiveAutocompleteResults = [];
/** /**
* @type {number} the value for cursor position we sent with the most * @type {number} the value for cursor position we sent with the most
* recent request. We need to remember this in order to display it * recent request. We need to remember this in order to display it
* in the output; otherwise it's hard or impossible to determine * in the output; otherwise it's hard or impossible to determine
* from screen captures or print-to-PDFs. * from screen captures or print-to-PDFs.
*/ */
var cursorPositionUsed = -1; let cursorPositionUsed = -1;
/** /**
* Extracts the input text from the text field and sends it to the * Extracts the input text from the text field and sends it to the
* C++ portion of chrome to handle. The C++ code will iteratively * C++ portion of chrome to handle. The C++ code will iteratively
* call handleNewAutocompleteResult as results come in. * call handleNewAutocompleteResult as results come in.
*/ */
function startOmniboxQuery(event) { function startOmniboxQuery(event) {
// First, clear the results of past calls (if any). // First, clear the results of past calls (if any).
progressiveAutocompleteResults = []; progressiveAutocompleteResults = [];
// Then, call chrome with a five-element list: // Then, call chrome with a five-element list:
// - first element: the value in the text box // - first element: the value in the text box
// - second element: the location of the cursor in the text box // - second element: the location of the cursor in the text box
// - third element: the value of prevent-inline-autocomplete // - third element: the value of prevent-inline-autocomplete
// - forth element: the value of prefer-keyword // - forth element: the value of prefer-keyword
// - fifth element: the value of page-classification // - fifth element: the value of page-classification
cursorPositionUsed = $('input-text').selectionEnd; cursorPositionUsed = $('input-text').selectionEnd;
browserProxy.startOmniboxQuery( browserProxy.startOmniboxQuery(
$('input-text').value, cursorPositionUsed, $('input-text').value, cursorPositionUsed,
$('prevent-inline-autocomplete').checked, $('prefer-keyword').checked, $('prevent-inline-autocomplete').checked, $('prefer-keyword').checked,
parseInt($('page-classification').value)); parseInt($('page-classification').value, 10));
// Cancel the submit action. i.e., don't submit the form. (We handle // Cancel the submit action. i.e., don't submit the form. (We handle
// display the results solely with Javascript.) // display the results solely with Javascript.)
event.preventDefault(); event.preventDefault();
} }
/** /**
* Returns a simple object with information about how to display an * Returns a simple object with information about how to display an
* autocomplete result data field. * autocomplete result data field.
* @param {string} header the label for the top of the column/table. */
* @param {string} urlLabelForHeader the URL that the header should point class PresentationInfoRecord {
* to (if non-empty). /**
* @param {string} propertyName the name of the property in the autocomplete * @param {string} header the label for the top of the column/table.
* result record that we lookup. * @param {string} url the URL that the header should point
* @param {boolean} displayAlways whether the property should be displayed * to (if non-empty).
* regardless of whether we're in detailed mode. * @param {string} propertyName the name of the property in the autocomplete
* @param {string} tooltip a description of the property that will be * result record that we lookup.
* presented as a tooltip when the mouse is hovered over the column title. * @param {boolean} displayAlways whether the property should be displayed
* @constructor * regardless of whether we're in detailed mode.
*/ * @param {string} tooltip a description of the property that will be
function PresentationInfoRecord( * presented as a tooltip when the mouse is hovered over the column title.
header, url, propertyName, displayAlways, tooltip) { */
this.header = header; constructor(header, url, propertyName, displayAlways, tooltip) {
this.urlLabelForHeader = url; this.header = header;
this.propertyName = propertyName; this.urlLabelForHeader = url;
this.displayAlways = displayAlways; this.propertyName = propertyName;
this.tooltip = tooltip; this.displayAlways = displayAlways;
} this.tooltip = tooltip;
}
}
/** /**
* A constant that's used to decide what autocomplete result * A constant that's used to decide what autocomplete result
* properties to output in what order. This is an array of * properties to output in what order. This is an array of
* PresentationInfoRecord() objects; for details see that * PresentationInfoRecord() objects; for details see that
* function. * function.
* @type {Array<Object>} * @type {!Array<!PresentationInfoRecord>}
* @const */
*/ const PROPERTY_OUTPUT_ORDER = [
var PROPERTY_OUTPUT_ORDER = [ new PresentationInfoRecord(
new PresentationInfoRecord( 'Provider', '', 'providerName', true,
'Provider', '', 'providerName', true, 'The AutocompleteProvider suggesting this result.'),
'The AutocompleteProvider suggesting this result.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Type', '', 'type', true, 'The type of the result.'),
'Type', '', 'type', true, 'The type of the result.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Relevance', '', 'relevance', true,
'Relevance', '', 'relevance', true, 'The result score. Higher is more relevant.'),
'The result score. Higher is more relevant.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Contents', '', 'contents', true,
'Contents', '', 'contents', true, 'The text that is presented identifying the result.'),
'The text that is presented identifying the result.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Can Be Default', '', 'allowedToBeDefaultMatch', false,
'Can Be Default', '', 'allowedToBeDefaultMatch', false, 'A green checkmark indicates that the result can be the default ' +
'A green checkmark indicates that the result can be the default ' + 'match (i.e., can be the match that pressing enter in the omnibox ' +
'match (i.e., can be the match that pressing enter in the omnibox ' + 'navigates to).'),
'navigates to).'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Starred', '', 'starred', false,
'Starred', '', 'starred', false, 'A green checkmark indicates that the result has been bookmarked.'),
'A green checkmark indicates that the result has been bookmarked.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Has tab match', '', 'hasTabMatch', false,
'Has tab match', '', 'hasTabMatch', false, 'A green checkmark indicates that the result URL matches an open tab.'),
'A green checkmark indicates that the result URL matches an open tab.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Description', '', 'description', false, 'The page title of the result.'),
'Description', '', 'description', false, 'The page title of the result.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'URL', '', 'destinationUrl', true, 'The URL for the result.'),
'URL', '', 'destinationUrl', true, 'The URL for the result.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Fill Into Edit', '', 'fillIntoEdit', false,
'Fill Into Edit', '', 'fillIntoEdit', false, 'The text shown in the omnibox when the result is selected.'),
'The text shown in the omnibox when the result is selected.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Inline Autocompletion', '', 'inlineAutocompletion', false,
'Inline Autocompletion', '', 'inlineAutocompletion', false, 'The text shown in the omnibox as a blue highlight selection ' +
'The text shown in the omnibox as a blue highlight selection ' + 'following the cursor, if this match is shown inline.'),
'following the cursor, if this match is shown inline.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Del', '', 'deletable', false,
'Del', '', 'deletable', false, 'A green checkmark indicates that the result can be deleted from ' +
'A green checkmark indicates that the result can be deleted from ' + 'the visit history.'),
'the visit history.'), new PresentationInfoRecord('Prev', '', 'fromPrevious', false, ''),
new PresentationInfoRecord('Prev', '', 'fromPrevious', false, ''), new PresentationInfoRecord(
new PresentationInfoRecord( 'Tran',
'Tran', 'http://code.google.com/codesearch#OAMlx_jo-ck/src/content/public/' +
'http://code.google.com/codesearch#OAMlx_jo-ck/src/content/public/' + 'common/page_transition_types.h&exact_package=chromium&l=24',
'common/page_transition_types.h&exact_package=chromium&l=24', 'transition', false, 'How the user got to the result.'),
'transition', false, 'How the user got to the result.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Done', '', 'providerDone', false,
'Done', '', 'providerDone', false, 'A green checkmark indicates that the provider is done looking for ' +
'A green checkmark indicates that the provider is done looking for ' + 'more results.'),
'more results.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Associated Keyword', '', 'associatedKeyword', false,
'Associated Keyword', '', 'associatedKeyword', false, 'If non-empty, a "press tab to search" hint will be shown and will ' +
'If non-empty, a "press tab to search" hint will be shown and will ' + 'engage this keyword.'),
'engage this keyword.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Keyword', '', 'keyword', false,
'Keyword', '', 'keyword', false, 'The keyword of the search engine to be used.'),
'The keyword of the search engine to be used.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Duplicates', '', 'duplicates', false,
'Duplicates', '', 'duplicates', false, 'The number of matches that have been marked as duplicates of this ' +
'The number of matches that have been marked as duplicates of this ' + 'match.'),
'match.'), new PresentationInfoRecord(
new PresentationInfoRecord( 'Additional Info', '', 'additionalInfo', false,
'Additional Info', '', 'additionalInfo', false, 'Provider-specific information about the result.'),
'Provider-specific information about the result.') ];
];
/** /**
* Returns an HTML Element of type table row that contains the * Returns an HTML Element of type table row that contains the
* headers we'll use for labeling the columns. If we're in * headers we'll use for labeling the columns. If we're in
* detailedMode, we use all the headers. If not, we only use ones * detailedMode, we use all the headers. If not, we only use ones
* marked displayAlways. * marked displayAlways.
*/ */
function createAutocompleteResultTableHeader() { function createAutocompleteResultTableHeader() {
var row = document.createElement('tr'); let row = document.createElement('tr');
var inDetailedMode = $('show-details').checked; let inDetailedMode = $('show-details').checked;
for (var i = 0; i < PROPERTY_OUTPUT_ORDER.length; i++) { PROPERTY_OUTPUT_ORDER.forEach(property => {
if (inDetailedMode || PROPERTY_OUTPUT_ORDER[i].displayAlways) { if (inDetailedMode || property.displayAlways) {
var headerCell = document.createElement('th'); let headerCell = document.createElement('th');
if (PROPERTY_OUTPUT_ORDER[i].urlLabelForHeader != '') { if (property.urlLabelForHeader !== '') {
// Wrap header text in URL. // Wrap header text in URL.
var linkNode = document.createElement('a'); let linkNode = document.createElement('a');
linkNode.href = PROPERTY_OUTPUT_ORDER[i].urlLabelForHeader; linkNode.href = property.urlLabelForHeader;
linkNode.textContent = PROPERTY_OUTPUT_ORDER[i].header; linkNode.textContent = property.header;
headerCell.appendChild(linkNode); headerCell.appendChild(linkNode);
} else { } else {
// Output header text without a URL. // Output header text without a URL.
headerCell.textContent = PROPERTY_OUTPUT_ORDER[i].header; headerCell.textContent = property.header;
headerCell.className = 'table-header'; headerCell.className = 'table-header';
headerCell.title = PROPERTY_OUTPUT_ORDER[i].tooltip; headerCell.title = property.tooltip;
}
row.appendChild(headerCell);
} }
row.appendChild(headerCell); });
} return row;
} }
return row;
}
/** /**
* @param {AutocompleteMatchMojo} autocompleteSuggestion the particular * @param {!Object} autocompleteSuggestion the particular
* autocomplete suggestion we're in the process of displaying. * autocomplete suggestion we're in the process of displaying.
* @param {string} propertyName the particular property of the autocomplete * @param {string} propertyName the particular property of the autocomplete
* suggestion that should go in this cell. * suggestion that should go in this cell.
* @return {HTMLTableCellElement} that contains the value within this * @return {Element} that contains the value within this
* autocompleteSuggestion associated with propertyName. * autocompleteSuggestion associated with propertyName.
*/ */
function createCellForPropertyAndRemoveProperty( function createCellForPropertyAndRemoveProperty(autocompleteSuggestion, propertyName) {
autocompleteSuggestion, propertyName) { let cell = document.createElement('td');
var cell = document.createElement('td'); if (propertyName in autocompleteSuggestion) {
if (propertyName in autocompleteSuggestion) { if (propertyName === 'additionalInfo') {
if (propertyName == 'additionalInfo') { // |additionalInfo| embeds a two-column table of provider-specific data
// |additionalInfo| embeds a two-column table of provider-specific data // within this cell. |additionalInfo| is an array of
// within this cell. |additionalInfo| is an array of // AutocompleteAdditionalInfo.
// AutocompleteAdditionalInfo. let additionalInfoTable = document.createElement('table');
var additionalInfoTable = document.createElement('table'); autocompleteSuggestion[propertyName].forEach(additionalInfo => {
for (var i = 0; i < autocompleteSuggestion[propertyName].length; i++) { let additionalInfoRow = document.createElement('tr');
var additionalInfo = autocompleteSuggestion[propertyName][i];
var additionalInfoRow = document.createElement('tr');
// Set the title (name of property) cell text. // Set the title (name of property) cell text.
var propertyCell = document.createElement('td'); let propertyCell = document.createElement('td');
propertyCell.textContent = additionalInfo.key + ':'; propertyCell.textContent = additionalInfo.key + ':';
propertyCell.className = 'additional-info-property'; propertyCell.className = 'additional-info-property';
additionalInfoRow.appendChild(propertyCell); additionalInfoRow.appendChild(propertyCell);
// Set the value of the property cell text. // Set the value of the property cell text.
var valueCell = document.createElement('td'); let valueCell = document.createElement('td');
valueCell.textContent = additionalInfo.value; valueCell.textContent = additionalInfo.value;
valueCell.className = 'additional-info-value'; valueCell.className = 'additional-info-value';
additionalInfoRow.appendChild(valueCell); additionalInfoRow.appendChild(valueCell);
additionalInfoTable.appendChild(additionalInfoRow); additionalInfoTable.appendChild(additionalInfoRow);
} });
cell.appendChild(additionalInfoTable); cell.appendChild(additionalInfoTable);
} else if (typeof autocompleteSuggestion[propertyName] == 'boolean') { } else if (typeof autocompleteSuggestion[propertyName] === 'boolean') {
// If this is a boolean, display a checkmark or an X instead of // If this is a boolean, display a checkmark or an X instead of
// the strings true or false. // the strings true or false.
cell.className = cell.className =
autocompleteSuggestion[propertyName] ? 'check-mark' : 'x-mark'; autocompleteSuggestion[propertyName] ? 'check-mark' : 'x-mark';
} else {
var text = String(autocompleteSuggestion[propertyName]);
// If it's a URL wrap it in an href.
var re = /^(http|https|ftp|chrome|file):\/\//;
if (re.test(text)) {
var aCell = document.createElement('a');
aCell.textContent = text;
aCell.href = text;
cell.appendChild(aCell);
} else { } else {
// All other data types (integer, strings, etc.) display their let text = String(autocompleteSuggestion[propertyName]);
// normal toString() output. // If it's a URL wrap it in an href.
cell.textContent = autocompleteSuggestion[propertyName]; let re = /^(http|https|ftp|chrome|file):\/\//;
if (re.test(text)) {
let aCell = document.createElement('a');
aCell.textContent = text;
aCell.href = text;
cell.appendChild(aCell);
} else {
// All other data types (integer, strings, etc.) display their
// normal toString() output.
cell.textContent = autocompleteSuggestion[propertyName];
}
} }
} } // else: if propertyName is undefined, we leave the cell blank
} // else: if propertyName is undefined, we leave the cell blank return cell;
return cell; }
}
/** /**
* Appends a paragraph node containing text to the parent node. * Appends a paragraph node containing text to the parent node.
*/ */
function addParagraph(parent, text) { function addParagraph(parent, text) {
var p = document.createElement('p'); let p = document.createElement('p');
p.textContent = text; p.textContent = text;
parent.appendChild(p); parent.appendChild(p);
} }
/** /**
* Appends some human-readable information about the provided * Appends some human-readable information about the provided
* autocomplete result to the HTML node with id omnibox-debug-text. * autocomplete result to the HTML node with id omnibox-debug-text.
* The current human-readable form is a few lines about general * The current human-readable form is a few lines about general
* autocomplete result statistics followed by a table with one line * autocomplete result statistics followed by a table with one line
* for each autocomplete match. The input parameter is an OmniboxResultMojo. * for each autocomplete match. The input parameter is an OmniboxResultMojo.
*/ */
function addResultToOutput(result) { function addResultToOutput(result) {
var output = $('omnibox-debug-text'); let output = $('omnibox-debug-text');
var inDetailedMode = $('show-details').checked; let inDetailedMode = $('show-details').checked;
var showIncompleteResults = $('show-incomplete-results').checked; let showIncompleteResults = $('show-incomplete-results').checked;
var showPerProviderResults = $('show-all-providers').checked; let showPerProviderResults = $('show-all-providers').checked;
// Output the result-level features in detailed mode and in // Output the result-level features in detailed mode and in
// show incomplete results mode. We do the latter because without // show incomplete results mode. We do the latter because without
// these result-level features, one can't make sense of each // these result-level features, one can't make sense of each
// batch of results. // batch of results.
if (inDetailedMode || showIncompleteResults) { if (inDetailedMode || showIncompleteResults) {
addParagraph(output, `cursor position = ${cursorPositionUsed}`); addParagraph(output, `cursor position = ${cursorPositionUsed}`);
addParagraph(output, `inferred input type = ${result.type}`); addParagraph(output, `inferred input type = ${result.type}`);
addParagraph( addParagraph(
output, `elapsed time = ${result.timeSinceOmniboxStartedMs}ms`); output, `elapsed time = ${result.timeSinceOmniboxStartedMs}ms`);
addParagraph(output, `all providers done = ${result.done}`); addParagraph(output, `all providers done = ${result.done}`);
var p = document.createElement('p'); let p = document.createElement('p');
p.textContent = `host = ${result.host}`; p.textContent = `host = ${result.host}`;
// The field isn't actually optional in the mojo object; instead it assumes // The field isn't actually optional in the mojo object; instead it assumes
// failed lookups are not typed hosts. Fix this to make it optional. // failed lookups are not typed hosts. Fix this to make it optional.
// http://crbug.com/863201 // http://crbug.com/863201
if ('isTypedHost' in result) { if ('isTypedHost' in result) {
// Only output the isTypedHost information if available. (It may // Only output the isTypedHost information if available. (It may
// be missing if the history database lookup failed.) // be missing if the history database lookup failed.)
p.textContent = p.textContent =
p.textContent + ` has isTypedHost = ${result.isTypedHost}`; p.textContent + ` has isTypedHost = ${result.isTypedHost}`;
}
output.appendChild(p);
} }
output.appendChild(p);
}
// Combined results go after the lines below. // Combined results go after the lines below.
var group = document.createElement('a'); let group = document.createElement('a');
group.className = 'group-separator'; group.className = 'group-separator';
group.textContent = 'Combined results.'; group.textContent = 'Combined results.';
output.appendChild(group); output.appendChild(group);
// Add combined/merged result table. // Add combined/merged result table.
var p = document.createElement('p'); let p = document.createElement('p');
p.appendChild(addResultTableToOutput(result.combinedResults)); p.appendChild(addResultTableToOutput(result.combinedResults));
output.appendChild(p); output.appendChild(p);
// Move forward only if you want to display per provider results. // Move forward only if you want to display per provider results.
if (!showPerProviderResults) { if (!showPerProviderResults) {
return; return;
} }
// Individual results go after the lines below. // Individual results go after the lines below.
var group = document.createElement('a'); group = document.createElement('a');
group.className = 'group-separator'; group.className = 'group-separator';
group.textContent = 'Results for individual providers.'; group.textContent = 'Results for individual providers.';
output.appendChild(group); output.appendChild(group);
// Add the per-provider result tables with labels. We do not append the // Add the per-provider result tables with labels. We do not append the
// combined/merged result table since we already have the per provider // combined/merged result table since we already have the per provider
// results. // results.
for (var i = 0; i < result.resultsByProvider.length; i++) { result.resultsByProvider.forEach(providerResults => {
var providerResults = result.resultsByProvider[i]; // If we have no results we do not display anything.
// If we have no results we do not display anything. if (providerResults.results.length === 0)
if (providerResults.results.length == 0) { return;
continue; let p = document.createElement('p');
} p.appendChild(addResultTableToOutput(providerResults.results));
var p = document.createElement('p'); output.appendChild(p);
p.appendChild(addResultTableToOutput(providerResults.results)); });
output.appendChild(p);
} }
}
/** /**
* @param {Object} result an array of AutocompleteMatchMojos. * @param {Object} result an array of AutocompleteMatchMojos.
* @return {HTMLTableCellElement} that is a user-readable HTML * @return {Element} that is a user-readable HTML
* representation of this object. * representation of this object.
*/ */
function addResultTableToOutput(result) { function addResultTableToOutput(result) {
var inDetailedMode = $('show-details').checked; let inDetailedMode = $('show-details').checked;
// Create a table to hold all the autocomplete items. // Create a table to hold all the autocomplete items.
var table = document.createElement('table'); let table = document.createElement('table');
table.className = 'autocomplete-results-table'; table.className = 'autocomplete-results-table';
table.appendChild(createAutocompleteResultTableHeader()); table.appendChild(createAutocompleteResultTableHeader());
// Loop over every autocomplete item and add it as a row in the table. // Loop over every autocomplete item and add it as a row in the table.
for (var i = 0; i < result.length; i++) { result.forEach(autocompleteSuggestion => {
var autocompleteSuggestion = result[i]; let row = document.createElement('tr');
var row = document.createElement('tr'); // Loop over all the columns/properties and output either them
// Loop over all the columns/properties and output either them // all (if we're in detailed mode) or only the ones marked displayAlways.
// all (if we're in detailed mode) or only the ones marked displayAlways. // Keep track of which properties we displayed.
// Keep track of which properties we displayed. let displayedProperties = {};
var displayedProperties = {}; PROPERTY_OUTPUT_ORDER.forEach(property => {
for (var j = 0; j < PROPERTY_OUTPUT_ORDER.length; j++) { if (inDetailedMode || property.displayAlways) {
if (inDetailedMode || PROPERTY_OUTPUT_ORDER[j].displayAlways) { row.appendChild(createCellForPropertyAndRemoveProperty(
row.appendChild(createCellForPropertyAndRemoveProperty( autocompleteSuggestion, property.propertyName));
autocompleteSuggestion, PROPERTY_OUTPUT_ORDER[j].propertyName)); displayedProperties[property.propertyName] = true;
displayedProperties[PROPERTY_OUTPUT_ORDER[j].propertyName] = true; }
} });
}
// Now, if we're in detailed mode, add all the properties that // Now, if we're in detailed mode, add all the properties that
// haven't already been output. (We know which properties have // haven't already been output. (We know which properties have
// already been output because we delete the property when we output // already been output because we delete the property when we output
// it. The only way we have properties left at this point if // it. The only way we have properties left at this point if
// we're in detailed mode and we're getting back properties // we're in detailed mode and we're getting back properties
// not listed in PROPERTY_OUTPUT_ORDER. Perhaps someone added // not listed in PROPERTY_OUTPUT_ORDER. Perhaps someone added
// something to the C++ code but didn't bother to update this // something to the C++ code but didn't bother to update this
// Javascript? In any case, we want to display them.) // Javascript? In any case, we want to display them.)
if (inDetailedMode) { if (inDetailedMode) {
for (var key in autocompleteSuggestion) { for (let key in autocompleteSuggestion) {
if (!displayedProperties[key] && if (!displayedProperties[key] &&
typeof autocompleteSuggestion[key] != 'function') { typeof autocompleteSuggestion[key] !== 'function') {
var cell = document.createElement('td'); let cell = document.createElement('td');
cell.textContent = key + '=' + autocompleteSuggestion[key]; cell.textContent = key + '=' + autocompleteSuggestion[key];
row.appendChild(cell); row.appendChild(cell);
}
} }
} }
}
table.appendChild(row); table.appendChild(row);
});
return table;
} }
return table;
}
/* Repaints the page based on the contents of the array /** Repaints the page based on the contents of the array
* progressiveAutocompleteResults, which represents consecutive * progressiveAutocompleteResults, which represents consecutive
* autocomplete results. We only display the last (most recent) * autocomplete results. We only display the last (most recent)
* entry unless we're asked to display incomplete results. For an * entry unless we're asked to display incomplete results. For an
* example of the output, play with chrome://omnibox/ * example of the output, play with chrome://omnibox/
*/ */
function refresh() { function refresh() {
// Erase whatever is currently being displayed. // Erase whatever is currently being displayed.
var output = $('omnibox-debug-text'); let output = $('omnibox-debug-text');
output.innerHTML = ''; output.innerHTML = '';
if (progressiveAutocompleteResults.length > 0) { // if we have results if (progressiveAutocompleteResults.length > 0) { // if we have results
// Display the results. // Display the results.
var showIncompleteResults = $('show-incomplete-results').checked; let showIncompleteResults = $('show-incomplete-results').checked;
var startIndex = let startIndex =
showIncompleteResults ? 0 : progressiveAutocompleteResults.length - 1; showIncompleteResults ? 0 : progressiveAutocompleteResults.length - 1;
for (var i = startIndex; i < progressiveAutocompleteResults.length; i++) { for (let i = startIndex; i < progressiveAutocompleteResults.length; i++) {
addResultToOutput(progressiveAutocompleteResults[i]); addResultToOutput(progressiveAutocompleteResults[i]);
}
} }
} }
}
// NOTE: Need to keep a global reference to the |pageImpl| such that it is not // NOTE: Need to keep a global reference to the |pageImpl| such that it is not
// garbage collected, which causes the pipe to close and future calls from C++ // garbage collected, which causes the pipe to close and future calls from C++
// to JS to get dropped. // to JS to get dropped.
var pageImpl = null; let pageImpl = null;
var browserProxy = null; let browserProxy = null;
function initializeProxies() { function initializeProxies() {
browserProxy = new mojom.OmniboxPageHandlerPtr; browserProxy = new mojom.OmniboxPageHandlerPtr;
Mojo.bindInterface( Mojo.bindInterface(
mojom.OmniboxPageHandler.name, mojo.makeRequest(browserProxy).handle); mojom.OmniboxPageHandler.name, mojo.makeRequest(browserProxy).handle);
/** @constructor */ class OmniboxPageImpl {
var OmniboxPageImpl = function(request) { constructor(request) {
this.binding_ = new mojo.Binding(mojom.OmniboxPage, this, request); this.binding_ = new mojo.Binding(mojom.OmniboxPage, this, request);
}; }
OmniboxPageImpl.prototype = { handleNewAutocompleteResult(result) {
/** @override */ progressiveAutocompleteResults.push(result);
handleNewAutocompleteResult: function(result) { refresh();
progressiveAutocompleteResults.push(result); }
refresh(); }
},
};
var client = new mojom.OmniboxPagePtr; let client = new mojom.OmniboxPagePtr;
pageImpl = new OmniboxPageImpl(mojo.makeRequest(client)); pageImpl = new OmniboxPageImpl(mojo.makeRequest(client));
browserProxy.setClientPage(client); browserProxy.setClientPage(client);
} }
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', () => {
initializeProxies(); initializeProxies();
initialize(); initialize();
}); });
})(); })();
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment