Commit 4c1b499d authored by manuk's avatar manuk Committed by Commit Bot

[chrome:omnibox]: Refactoring HTML generation part 1/3, create OutputMatch helper class.

This is the first of 3 CL's to replace the global static helper functions which manipulate the DOM with classes. In this CL, we:

- Replaced the functions createCellForPropertyAndRemoveProperty and addResultTableToOutput with OutputMatch, which is responsible for generating individual HTML rows from individual omnibox matches.

- Moved the data class PresentationInfoRecord and the constants array of PresentationInfoRecord's PROPERTY_OUTPUT_ORDER from omnibox.js to omnibox_output.js as that's where it's now used.

Bug: 891303
Change-Id: If653e16763a3956b0576bf677ede1570626007d7
Reviewed-on: https://chromium-review.googlesource.com/c/1293757
Commit-Queue: manuk hovanesian <manukh@chromium.org>
Reviewed-by: default avatarDemetrios Papadopoulos <dpapad@chromium.org>
Reviewed-by: default avatarTommy Li <tommycli@chromium.org>
Cr-Commit-Position: refs/heads/master@{#603225}
parent cd3d77a6
...@@ -23,7 +23,10 @@ ...@@ -23,7 +23,10 @@
.x-mark { .x-mark {
background-position: center; background-position: center;
background-repeat: no-repeat; background-repeat: no-repeat;
background-size: contain;
font-size: 0; font-size: 0;
height: 16px;
width: 16px;
} }
.check-mark { .check-mark {
......
...@@ -26,36 +26,6 @@ ...@@ -26,36 +26,6 @@
*/ */
let cursorPosition = -1; let cursorPosition = -1;
/**
* Returns a simple object with information about how to display an
* autocomplete result data field.
*/
class PresentationInfoRecord {
/**
* @param {string} header the label for the top of the column/table.
* @param {string} url the URL that the header should point
* to (if non-empty).
* @param {string} propertyName the name of the property in the autocomplete
* result record that we lookup.
* @param {boolean} displayAlways whether the property should be displayed
* regardless of whether we're in detailed mode.
* @param {string} tooltip a description of the property that will be
* presented as a tooltip when the mouse is hovered over the column title.
*/
constructor(header, url, propertyName, displayAlways, tooltip) {
/** @type {string} */
this.header = header;
/** @type {string} */
this.url = url;
/** @type {string} */
this.propertyName = propertyName;
/** @type {boolean} */
this.displayAlways = displayAlways;
/** @type {string} */
this.tooltip = tooltip;
}
}
/** /**
* Tracks and aggregates responses from the C++ autocomplete controller. * Tracks and aggregates responses from the C++ autocomplete controller.
* Typically, the C++ controller returns 3 sets of results per query, unless * Typically, the C++ controller returns 3 sets of results per query, unless
...@@ -66,11 +36,11 @@ ...@@ -66,11 +36,11 @@
class OutputController { class OutputController {
constructor() { constructor() {
/** @private {!Array<mojom.OmniboxResult>} */ /** @private {!Array<mojom.OmniboxResult>} */
this.outputResultsGroups = []; this.outputResultsGroups_ = [];
} }
clear() { clear() {
this.outputResultsGroups = []; this.outputResultsGroups_ = [];
omniboxOutput.clearOutput(); omniboxOutput.clearOutput();
} }
...@@ -82,10 +52,11 @@ ...@@ -82,10 +52,11 @@
*/ */
/** @param {!mojom.OmniboxResult} response A response from C++ autocomplete controller */ /** @param {!mojom.OmniboxResult} response A response from C++ autocomplete controller */
add(response) { add(response) {
this.outputResultsGroups.push(response); this.outputResultsGroups_.push(response);
if (!omniboxInputs.$$('show-incomplete-results').checked) if (!omniboxInputs.$$('show-incomplete-results').checked)
omniboxOutput.clearOutput(); omniboxOutput.clearOutput();
addResultToOutput(this.outputResultsGroups[this.outputResultsGroups.length - 1]); addResultToOutput(
this.outputResultsGroups_[this.outputResultsGroups_.length - 1]);
} }
/* /*
...@@ -95,86 +66,14 @@ ...@@ -95,86 +66,14 @@
refresh() { refresh() {
omniboxOutput.clearOutput(); omniboxOutput.clearOutput();
if (omniboxInputs.$$('show-incomplete-results').checked) { if (omniboxInputs.$$('show-incomplete-results').checked) {
this.outputResultsGroups.forEach(addResultToOutput); this.outputResultsGroups_.forEach(addResultToOutput);
} else if (this.outputResultsGroups.length) { } else if (this.outputResultsGroups_.length) {
addResultToOutput( addResultToOutput(
this.outputResultsGroups[this.outputResultsGroups.length - 1]); this.outputResultsGroups_[this.outputResultsGroups_.length - 1]);
} }
} }
} }
/**
* A constant that's used to decide what autocomplete result
* properties to output in what order. This is an array of
* PresentationInfoRecord() objects; for details see that
* function.
* @type {!Array<!PresentationInfoRecord>}
*/
const PROPERTY_OUTPUT_ORDER = [
new PresentationInfoRecord(
'Provider', '', 'providerName', true,
'The AutocompleteProvider suggesting this result.'),
new PresentationInfoRecord(
'Type', '', 'type', true, 'The type of the result.'),
new PresentationInfoRecord(
'Relevance', '', 'relevance', true,
'The result score. Higher is more relevant.'),
new PresentationInfoRecord(
'Contents', '', 'contents', true,
'The text that is presented identifying the result.'),
new PresentationInfoRecord(
'Can Be Default', '', 'allowedToBeDefaultMatch', false,
'A green checkmark indicates that the result can be the default ' +
'match (i.e., can be the match that pressing enter in the ' +
'omnibox navigates to).'),
new PresentationInfoRecord(
'Starred', '', 'starred', false,
'A green checkmark indicates that the result has been bookmarked.'),
new PresentationInfoRecord(
'Has tab match', '', 'hasTabMatch', false,
'A green checkmark indicates that the result URL matches an open tab.'),
new PresentationInfoRecord(
'Description', '', 'description', false,
'The page title of the result.'),
new PresentationInfoRecord(
'URL', '', 'destinationUrl', true, 'The URL for the result.'),
new PresentationInfoRecord(
'Fill Into Edit', '', 'fillIntoEdit', false,
'The text shown in the omnibox when the result is selected.'),
new PresentationInfoRecord(
'Inline Autocompletion', '', 'inlineAutocompletion', false,
'The text shown in the omnibox as a blue highlight selection ' +
'following the cursor, if this match is shown inline.'),
new PresentationInfoRecord(
'Del', '', 'deletable', false,
'A green checkmark indicates that the result can be deleted from ' +
'the visit history.'),
new PresentationInfoRecord('Prev', '', 'fromPrevious', false, ''),
new PresentationInfoRecord(
'Tran',
'https://cs.chromium.org/chromium/src/ui/base/page_transition_types.h' +
'?q=page_transition_types.h&sq=package:chromium&dr=CSs&l=14',
'transition', false, 'How the user got to the result.'),
new PresentationInfoRecord(
'Done', '', 'providerDone', false,
'A green checkmark indicates that the provider is done looking for ' +
'more results.'),
new PresentationInfoRecord(
'Associated Keyword', '', 'associatedKeyword', false,
'If non-empty, a "press tab to search" hint will be shown and will ' +
'engage this keyword.'),
new PresentationInfoRecord(
'Keyword', '', 'keyword', false,
'The keyword of the search engine to be used.'),
new PresentationInfoRecord(
'Duplicates', '', 'duplicates', false,
'The number of matches that have been marked as duplicates of this ' +
'match.'),
new PresentationInfoRecord(
'Additional Info', '', 'additionalInfo', false,
'Provider-specific information about the result.'),
];
/** /**
* 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.
...@@ -193,7 +92,7 @@ ...@@ -193,7 +92,7 @@
addParagraph(`inferred input type = ${result.type}`); addParagraph(`inferred input type = ${result.type}`);
addParagraph(`elapsed time = ${result.timeSinceOmniboxStartedMs}ms`); addParagraph(`elapsed time = ${result.timeSinceOmniboxStartedMs}ms`);
addParagraph(`all providers done = ${result.done}`); addParagraph(`all providers done = ${result.done}`);
let p = document.createElement('p'); const 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.
...@@ -208,13 +107,13 @@ ...@@ -208,13 +107,13 @@
} }
// Combined results go after the lines below. // Combined results go after the lines below.
let group = document.createElement('a'); const group = document.createElement('a');
group.className = 'group-separator'; group.className = 'group-separator';
group.textContent = 'Combined results.'; group.textContent = 'Combined results.';
omniboxOutput.addOutput(group); omniboxOutput.addOutput(group);
// Add combined/merged result table. // Add combined/merged result table.
let p = document.createElement('p'); const p = document.createElement('p');
p.appendChild(addResultTableToOutput(result.combinedResults)); p.appendChild(addResultTableToOutput(result.combinedResults));
omniboxOutput.addOutput(p); omniboxOutput.addOutput(p);
...@@ -224,10 +123,10 @@ ...@@ -224,10 +123,10 @@
} }
// Individual results go after the lines below. // Individual results go after the lines below.
group = document.createElement('a'); const individualGroup = document.createElement('a');
group.className = 'group-separator'; individualGroup.className = 'group-separator';
group.textContent = 'Results for individual providers.'; individualGroup.textContent = 'Results for individual providers.';
omniboxOutput.addOutput(group); omniboxOutput.addOutput(individualGroup);
// 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
...@@ -236,7 +135,7 @@ ...@@ -236,7 +135,7 @@
// 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; return;
let p = document.createElement('p'); const p = document.createElement('p');
p.appendChild(addResultTableToOutput(providerResults.results)); p.appendChild(addResultTableToOutput(providerResults.results));
omniboxOutput.addOutput(p); omniboxOutput.addOutput(p);
}); });
...@@ -248,45 +147,15 @@ ...@@ -248,45 +147,15 @@
* representation of this object. * representation of this object.
*/ */
function addResultTableToOutput(result) { function addResultTableToOutput(result) {
let inDetailedMode = omniboxInputs.$$('show-details').checked; const inDetailedMode = omniboxInputs.$$('show-details').checked;
// Create a table to hold all the autocomplete items. // Create a table to hold all the autocomplete items.
let table = document.createElement('table'); const 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.
result.forEach(autocompleteSuggestion => { result.forEach(autocompleteSuggestion => {
let row = document.createElement('tr'); const row = new omnibox_output.OutputMatch(autocompleteSuggestion)
// Loop over all the columns/properties and output either them .render(inDetailedMode);
// all (if we're in detailed mode) or only the ones marked displayAlways.
// Keep track of which properties we displayed.
let displayedProperties = {};
PROPERTY_OUTPUT_ORDER.forEach(property => {
if (inDetailedMode || property.displayAlways) {
row.appendChild(createCellForPropertyAndRemoveProperty(
autocompleteSuggestion, property.propertyName));
displayedProperties[property.propertyName] = true;
}
});
// Now, if we're in detailed mode, add all the properties that
// haven't already been output. (We know which properties have
// already been output because we delete the property when we output
// it. The only way we have properties left at this point if
// we're in detailed mode and we're getting back properties
// not listed in PROPERTY_OUTPUT_ORDER. Perhaps someone added
// something to the C++ code but didn't bother to update this
// Javascript? In any case, we want to display them.)
if (inDetailedMode) {
for (let key in autocompleteSuggestion) {
if (!displayedProperties[key] &&
typeof autocompleteSuggestion[key] !== 'function') {
let cell = document.createElement('td');
cell.textContent = key + '=' + autocompleteSuggestion[key];
row.appendChild(cell);
}
}
}
table.appendChild(row); table.appendChild(row);
}); });
return table; return table;
...@@ -299,14 +168,14 @@ ...@@ -299,14 +168,14 @@
* marked displayAlways. * marked displayAlways.
*/ */
function createAutocompleteResultTableHeader() { function createAutocompleteResultTableHeader() {
let row = document.createElement('tr'); const row = document.createElement('tr');
let inDetailedMode = omniboxInputs.$$('show-details').checked; const inDetailedMode = omniboxInputs.$$('show-details').checked;
PROPERTY_OUTPUT_ORDER.forEach(property => { omnibox_output.PROPERTY_OUTPUT_ORDER.forEach(property => {
if (inDetailedMode || property.displayAlways) { if (inDetailedMode || property.displayAlways) {
let headerCell = document.createElement('th'); const headerCell = document.createElement('th');
if (property.url !== '') { if (property.url !== '') {
// Wrap header text in URL. // Wrap header text in URL.
let linkNode = document.createElement('a'); const linkNode = document.createElement('a');
linkNode.href = property.url; linkNode.href = property.url;
linkNode.textContent = property.header; linkNode.textContent = property.header;
headerCell.appendChild(linkNode); headerCell.appendChild(linkNode);
...@@ -322,74 +191,11 @@ ...@@ -322,74 +191,11 @@
return row; return row;
} }
/**
* @param {!Object} autocompleteSuggestion the particular
* autocomplete suggestion we're in the process of displaying.
* @param {string} propertyName the particular property of the autocomplete
* suggestion that should go in this cell.
* @return {Element} that contains the value within this
* autocompleteSuggestion associated with propertyName.
*/
function createCellForPropertyAndRemoveProperty(autocompleteSuggestion, propertyName) {
let cell = document.createElement('td');
if (propertyName in autocompleteSuggestion) {
if (propertyName === 'additionalInfo') {
// |additionalInfo| embeds a two-column table of provider-specific data
// within this cell. |additionalInfo| is an array of
// AutocompleteAdditionalInfo.
let additionalInfoTable = document.createElement('table');
autocompleteSuggestion[propertyName].forEach(additionalInfo => {
let additionalInfoRow = document.createElement('tr');
// Set the title (name of property) cell text.
let propertyCell = document.createElement('td');
propertyCell.textContent = additionalInfo.key + ':';
propertyCell.className = 'additional-info-property';
additionalInfoRow.appendChild(propertyCell);
// Set the value of the property cell text.
let valueCell = document.createElement('td');
valueCell.textContent = additionalInfo.value;
valueCell.className = 'additional-info-value';
additionalInfoRow.appendChild(valueCell);
additionalInfoTable.appendChild(additionalInfoRow);
});
cell.appendChild(additionalInfoTable);
} else if (typeof autocompleteSuggestion[propertyName] === 'boolean') {
// If this is a boolean, display a checkmark or an X instead of
// the strings true or false.
if (autocompleteSuggestion[propertyName]) {
cell.className = 'check-mark';
cell.textContent = 'true';
} else {
cell.className = 'x-mark';
cell.textContent = 'false';
}
} else {
let text = String(autocompleteSuggestion[propertyName]);
// If it's a URL wrap it in an href.
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
return cell;
}
/** /**
* Appends a paragraph node containing text to the parent node. * Appends a paragraph node containing text to the parent node.
*/ */
function addParagraph(text) { function addParagraph(text) {
let p = document.createElement('p'); const p = document.createElement('p');
p.textContent = text; p.textContent = text;
omniboxOutput.addOutput(p); omniboxOutput.addOutput(p);
} }
...@@ -401,7 +207,7 @@ ...@@ -401,7 +207,7 @@
Mojo.bindInterface( Mojo.bindInterface(
mojom.OmniboxPageHandler.name, mojom.OmniboxPageHandler.name,
mojo.makeRequest(this.pagehandlePtr_).handle); mojo.makeRequest(this.pagehandlePtr_).handle);
let client = new mojom.OmniboxPagePtr; const client = new mojom.OmniboxPagePtr;
// NOTE: Need to keep a global reference to the |binding_| such that it is // NOTE: Need to keep a global reference to the |binding_| such that it is
// not garbage collected, which causes the pipe to close and future calls // not garbage collected, which causes the pipe to close and future calls
// from C++ to JS to get dropped. // from C++ to JS to get dropped.
...@@ -442,18 +248,18 @@ ...@@ -442,18 +248,18 @@
} }
/** @type {BrowserProxy} */ /** @type {BrowserProxy} */
let browserProxy; const browserProxy = new BrowserProxy();
/** @type {OmniboxInputs} */ /** @type {OmniboxInputs} */
let omniboxInputs; let omniboxInputs;
/** @type {OmniboxOutput} */ /** @type {omnibox_output.OmniboxOutput} */
let omniboxOutput; let omniboxOutput;
/** @type {OutputController} */ /** @type {OutputController} */
let outputController = new OutputController(); const outputController = new OutputController();
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
browserProxy = new BrowserProxy();
omniboxInputs = /** @type {!OmniboxInputs} */ ($('omnibox-inputs')); omniboxInputs = /** @type {!OmniboxInputs} */ ($('omnibox-inputs'));
omniboxOutput = /** @type {!OmniboxOutput} */ ($('omnibox-output')); omniboxOutput =
/** @type {!omnibox_output.OmniboxOutput} */ ($('omnibox-output'));
omniboxInputs.addEventListener('query-inputs-changed', event => omniboxInputs.addEventListener('query-inputs-changed', event =>
browserProxy.makeRequest( browserProxy.makeRequest(
event.detail.inputText, event.detail.inputText,
......
...@@ -2,22 +2,17 @@ ...@@ -2,22 +2,17 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
// Helper class to be used as the super class of all Custom Elements in /**
// chrome://omnibox. Constructed with a string id of a <template> element. When * Helper class to be used as the super class of all custom elements in
// this element is added to the DOM, it instantiates its internal DOM from the * chrome://omnibox.
// corresponding <template> element. * @abstract
*/
class OmniboxElement extends HTMLElement { class OmniboxElement extends HTMLElement {
/** @param {string} templateId Template's HTML id attribute */ /** @param {string} templateId */
constructor(templateId) { constructor(templateId) {
super(); super();
/** @type {string} */
this.templateId = templateId;
}
/** @override */
connectedCallback() {
this.attachShadow({mode: 'open'}); this.attachShadow({mode: 'open'});
let template = $(this.templateId).content.cloneNode(true); const template = $(templateId).content.cloneNode(true);
this.shadowRoot.appendChild(template); this.shadowRoot.appendChild(template);
} }
......
...@@ -14,28 +14,29 @@ class OmniboxInputs extends OmniboxElement { ...@@ -14,28 +14,29 @@ class OmniboxInputs extends OmniboxElement {
/** @override */ /** @override */
connectedCallback() { connectedCallback() {
super.connectedCallback(); this.setupElementListeners_();
this.setupElementListeners();
} }
setupElementListeners() { /** @private */
const onQueryInputsChanged = this.onQueryInputsChanged.bind(this); setupElementListeners_() {
const onDisplayInputsChagned = this.onDisplayInputsChagned.bind(this); const onQueryInputsChanged = this.onQueryInputsChanged_.bind(this);
const onDisplayInputsChagned = this.onDisplayInputsChagned_.bind(this);
this.$$('input-text').addEventListener('input', onQueryInputsChanged); this.$$('input-text').addEventListener('input', onQueryInputsChanged);
[ [
this.$$('prevent-inline-autocomplete'), this.$$('prevent-inline-autocomplete'),
this.$$('prefer-keyword'), this.$$('prefer-keyword'),
this.$$('page-classification'), this.$$('page-classification'),
].forEach(element => element.addEventListener('change', onQueryInputsChanged)); ].forEach(elem => elem.addEventListener('change', onQueryInputsChanged));
[ [
this.$$('show-incomplete-results'), this.$$('show-incomplete-results'),
this.$$('show-details'), this.$$('show-details'),
this.$$('show-all-providers'), this.$$('show-all-providers'),
].forEach(element => element.addEventListener('change', onDisplayInputsChagned)); ].forEach(elem => elem.addEventListener('change', onDisplayInputsChagned));
} }
onQueryInputsChanged() { /** @private */
onQueryInputsChanged_() {
this.dispatchEvent(new CustomEvent('query-inputs-changed', { this.dispatchEvent(new CustomEvent('query-inputs-changed', {
detail: { detail: {
inputText: this.$$('input-text').value, inputText: this.$$('input-text').value,
...@@ -47,7 +48,8 @@ class OmniboxInputs extends OmniboxElement { ...@@ -47,7 +48,8 @@ class OmniboxInputs extends OmniboxElement {
})); }));
} }
onDisplayInputsChagned() { /** @private */
onDisplayInputsChagned_() {
this.dispatchEvent(new CustomEvent('display-inputs-changed')); this.dispatchEvent(new CustomEvent('display-inputs-changed'));
} }
} }
......
...@@ -2,25 +2,357 @@ ...@@ -2,25 +2,357 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
class OmniboxOutput extends OmniboxElement { cr.define('omnibox_output', function() {
/** @return {string} */ /**
static get is() { * Details how to display an autocomplete result data field.
return 'omnibox-output'; * @typedef {{
} * header: string,
* url: string,
* propertyName: string,
* displayAlways: boolean,
* tooltip: string,
* }}
*/
let PresentationInfoRecord;
constructor() { /**
super('omnibox-output-template'); * A constant that's used to decide what autocomplete result
} * properties to output in what order.
* @type {!Array<!PresentationInfoRecord>}
*/
const PROPERTY_OUTPUT_ORDER = [
{
header: 'Provider',
url: '',
propertyName: 'providerName',
displayAlways: true,
tooltip: 'The AutocompleteProvider suggesting this result.'
},
{
header: 'Type',
url: '',
propertyName: 'type',
displayAlways: true,
tooltip: 'The type of the result.'
},
{
header: 'Relevance',
url: '',
propertyName: 'relevance',
displayAlways: true,
tooltip: 'The result score. Higher is more relevant.'
},
{
header: 'Contents',
url: '',
propertyName: 'contents',
displayAlways: true,
tooltip: 'The text that is presented identifying the result.'
},
{
header: 'CanBeDefault',
url: '',
propertyName: 'allowedToBeDefaultMatch',
displayAlways: false,
tooltip:
'A green checkmark indicates that the result can be the default ' +
'match(i.e., can be the match that pressing enter in the omnibox' +
'navigates to).'
},
{
header: 'Starred',
url: '',
propertyName: 'starred',
displayAlways: false,
tooltip:
'A green checkmark indicates that the result has been bookmarked.'
},
{
header: 'Hastabmatch',
url: '',
propertyName: 'hasTabMatch',
displayAlways: false,
tooltip:
'A green checkmark indicates that the result URL matches an open' +
'tab.'
},
{
header: 'Description',
url: '',
propertyName: 'description',
displayAlways: false,
tooltip: 'The page title of the result.'
},
{
header: 'URL',
url: '',
propertyName: 'destinationUrl',
displayAlways: true,
tooltip: 'The URL for the result.'
},
{
header: 'FillIntoEdit',
url: '',
propertyName: 'fillIntoEdit',
displayAlways: false,
tooltip: 'The text shown in the omnibox when the result is selected.'
},
{
header: 'InlineAutocompletion',
url: '',
propertyName: 'inlineAutocompletion',
displayAlways: false,
tooltip: 'The text shown in the omnibox as a blue highlight selection ' +
'following the cursor, if this match is shown inline.'
},
{
header: 'Del',
url: '',
propertyName: 'deletable',
displayAlways: false,
tooltip:
'A green checkmark indicates that the result can be deleted from ' +
'the visit history.'
},
{
header: 'Prev',
url: '',
propertyName: 'fromPrevious',
displayAlways: false,
tooltip: ''
},
{
header: 'Tran',
url:
'https://cs.chromium.org/chromium/src/ui/base/page_transition_types.h?q=page_transition_types.h&sq=package:chromium&dr=CSs&l=14',
propertyName: 'transition',
displayAlways: false,
tooltip: 'How the user got to the result.'
},
{
header: 'Done',
url: '',
propertyName: 'providerDone',
displayAlways: false,
tooltip:
'A green checkmark indicates that the provider is done looking ' +
'for more results.'
},
{
header: 'AssociatedKeyword',
url: '',
propertyName: 'associatedKeyword',
displayAlways: false,
tooltip: 'If non-empty, a "press tab to search" hint will be shown and ' +
'will engage this keyword.'
},
{
header: 'Keyword',
url: '',
propertyName: 'keyword',
displayAlways: false,
tooltip: 'The keyword of the search engine to be used.'
},
{
header: 'Duplicates',
url: '',
propertyName: 'duplicates',
displayAlways: false,
tooltip: 'The number of matches that have been marked as duplicates of ' +
'this match..'
},
{
header: 'AdditionalInfo',
url: '',
propertyName: 'additionalInfo',
displayAlways: false,
tooltip: 'Provider-specific information about the result.'
}
];
class OmniboxOutput extends OmniboxElement {
/** @return {string} */
static get is() {
return 'omnibox-output';
}
constructor() {
super('omnibox-output-template');
}
/** @param {Element} element the element to the output */ /** @param {Element} element the element to the output */
addOutput(element) { addOutput(element) {
this.$$('contents').appendChild(element); this.$$('contents').appendChild(element);
}
clearOutput() {
while (this.$$('contents').firstChild)
this.$$('contents').removeChild(this.$$('contents').firstChild);
}
} }
clearOutput() { /** Helps track and render a single match. */
while (this.$$('contents').firstChild) class OutputMatch {
this.$$('contents').removeChild(this.$$('contents').firstChild); /** @param {!mojom.AutocompleteMatch} match */
constructor(match) {
/** @dict */
this.properties = {};
/** @dict */
this.additionalProperties = {};
Object.entries(match).forEach(propertyNameValueTuple => {
// TODO(manukh) replace with destructuring when the styleguide is
// updated
// https://chromium-review.googlesource.com/c/chromium/src/+/1271915
const propertyName = propertyNameValueTuple[0];
const propertyValue = propertyNameValueTuple[1];
if (PROPERTY_OUTPUT_ORDER.some(
displayProperty =>
displayProperty.propertyName === propertyName)) {
this.properties[propertyName] = propertyValue;
} else {
this.additionalProperties[propertyName] = propertyValue;
}
});
}
/**
* Creates a HTML Node representing this data.
* @param {boolean} showDetails
* @return {Node}
*/
render(showDetails) {
const match = document.createElement('tr');
OutputMatch.displayedProperties(showDetails)
.map(property => {
const value = this.properties[property.propertyName];
if (typeof value === 'object')
return OutputMatch.renderJsonProperty_(value);
if (typeof value === 'boolean')
return OutputMatch.renderBooleanProperty_(value);
return OutputMatch.renderTextProperty_(value);
})
.forEach(cell => match.appendChild(cell));
if (this.showAdditionalProperties(showDetails)) {
match.appendChild(
OutputMatch.renderJsonProperty_(this.additionalProperties));
}
return match;
}
/**
* TODO(manukh) replace these static render_ functions with subclasses when
* rendering becomes more substantial
* @private
* @param {string} propertyValue
* @return {Node}
*/
static renderTextProperty_(propertyValue) {
const cell = document.createElement('td');
cell.textContent = propertyValue;
return cell;
}
/**
* @private
* @param {Object} propertyValue
* @return {Node}
*/
static renderJsonProperty_(propertyValue) {
const cell = document.createElement('td');
const pre = document.createElement('pre');
pre.textContent = JSON.stringify(propertyValue, null, 2);
cell.appendChild(pre);
return cell;
}
/**
* @private
* @param {boolean} propertyValue
* @return {Node}
*/
static renderBooleanProperty_(propertyValue) {
const cell = document.createElement('td');
const icon = document.createElement('div');
icon.className = propertyValue ? 'check-mark' : 'x-mark';
icon.textContent = propertyValue;
cell.appendChild(icon);
return cell;
}
/**
* @private
* @param {boolean} showDetails
* @param {boolean} showAdditionalHeader
* @return {Node}
*/
static renderHeader_(showDetails, showAdditionalHeader) {
const row = document.createElement('tr');
const headerCells =
OutputMatch.displayedProperties(showDetails)
.map(
displayProperty => OutputMatch.renderHeaderCell_(
displayProperty.header, displayProperty.url,
displayProperty.tooltip));
if (showAdditionalHeader) {
headerCells.push(
OutputMatch.renderHeaderCell_('Additional Properties'));
}
headerCells.forEach(headerCell => row.appendChild(headerCell));
return row;
}
/**
* @private
* @param {string} name
* @param {string=} url
* @param {string=} tooltip
* @return {Node}
*/
static renderHeaderCell_(name, url, tooltip) {
const cell = document.createElement('th');
if (url) {
const link = document.createElement('a');
link.textContent = name;
link.href = url;
cell.appendChild(link);
} else {
cell.textContent = name;
}
cell.title = tooltip || '';
return cell;
}
/**
* @return {Array<PresentationInfoRecord>} Array representing which columns
* need to be displayed.
*/
static displayedProperties(showDetails) {
return showDetails ?
PROPERTY_OUTPUT_ORDER :
PROPERTY_OUTPUT_ORDER.filter(property => property.displayAlways);
}
/**
* @return {boolean} True if the additional properties column is required
* to be displayed for this result. False if the column can be hidden
* because this result does not have additional properties.
*/
showAdditionalProperties(showDetails) {
return showDetails && Object.keys(this.additionalProperties).length;
}
} }
}
window.customElements.define(OmniboxOutput.is, OmniboxOutput); window.customElements.define(OmniboxOutput.is, OmniboxOutput);
// TODO(manukh) remove PROPERTY_OUTPUT_ORDER from exports after the remaining
// OmniboxOutput classes are extracted
// TODO(manukh) use shorthand object creation if/when approved
// https://chromium.googlesource.com/chromium/src/+/master/styleguide/web/es6.md#object-literal-extensions
return {
PROPERTY_OUTPUT_ORDER: PROPERTY_OUTPUT_ORDER,
OmniboxOutput: OmniboxOutput,
OutputMatch: OutputMatch,
};
});
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