Commit 6954e201 authored by Ken Rockot's avatar Ken Rockot Committed by Commit Bot

Migrate chrome://site-engagement to mojom modules

Bug: 1004256
Change-Id: Icf4818cd885e77549f50f01e3553c81034348381
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2506520
Commit-Queue: Ken Rockot <rockot@google.com>
Reviewed-by: default avatarcalamity <calamity@chromium.org>
Cr-Commit-Position: refs/heads/master@{#823278}
parent f961a376
......@@ -6417,7 +6417,7 @@ grit("dev_ui_browser_resources") {
"//chrome/browser/resources/web_app_internals:components",
"//chrome/browser/ui/webui/internals/web_app:mojo_bindings_js",
"//chrome/browser/ui/webui/interventions_internals:mojo_bindings_js",
"//components/site_engagement/core/mojom:mojo_bindings_js",
"//components/site_engagement/core/mojom:mojo_bindings_webui_js",
]
if (is_android) {
deps += [ "//chrome/browser/ui/webui/feed_internals:mojo_bindings_js" ]
......
......@@ -68,7 +68,7 @@ This file specifies browser resources for developer-facing chrome:// pages
<include name="IDR_SITE_ENGAGEMENT_HTML" file="resources\engagement\site_engagement.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
<include name="IDR_SITE_ENGAGEMENT_JS" file="resources\engagement\site_engagement.js" flattenhtml="true" type="BINDATA" />
<include name="IDR_SITE_ENGAGEMENT_DETAILS_MOJOM_LITE_JS" file="${root_gen_dir}\components\site_engagement\core\mojom\site_engagement_details.mojom-lite.js" use_base_dir="false" type="BINDATA" />
<include name="IDR_SITE_ENGAGEMENT_DETAILS_MOJOM_WEBUI_JS" file="${root_gen_dir}\mojom-webui\components\site_engagement\core\mojom\site_engagement_details.mojom-webui.js" use_base_dir="false" type="BINDATA" />
<if expr="is_android">
<include name="IDR_FEED_INTERNALS_HTML" file="resources\feed_internals\feed_internals.html" allowexternalscript="true" type="BINDATA" />
......
......@@ -5,12 +5,14 @@
import("//third_party/closure_compiler/compile_js.gni")
js_type_check("closure_compile") {
uses_js_modules = true
deps = [ ":site_engagement" ]
closure_flags = mojom_js_args
}
js_library("site_engagement") {
deps = [
"//components/site_engagement/core/mojom:mojo_bindings_js_library_for_compile",
"//components/site_engagement/core/mojom:mojo_bindings_webui_js",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:util",
]
......
......@@ -3,13 +3,10 @@
<title>Site Engagement</title>
<meta charset="utf-8">
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
<script src="chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js"></script>
<script src="chrome://resources/mojo/url/mojom/url.mojom-lite.js"></script>
<script src="chrome://resources/js/assert.js"></script>
<script src="chrome://resources/js/util.js"></script>
<script src="components/site_engagement/core/mojom/site_engagement_details.mojom-lite.js">
</script>
<script src="chrome://site-engagement/site_engagement.js"></script>
<script src="site_engagement.js" type="module"></script>
<style>
body {
font-family: 'Roboto', 'Noto', sans-serif;
......
......@@ -2,17 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js';
// Allow a function to be provided by tests, which will be called when
// the page has been populated with site engagement details.
let whenPageIsPopulatedForTest;
/** @type {function()} */
let disableAutoupdateForTests;
/** @type {mojom.SiteEngagementDetailsProviderRemote} */
let engagementDetailsProvider;
import {SiteEngagementDetails, SiteEngagementDetailsProvider, SiteEngagementDetailsProviderRemote} from './site_engagement_details.mojom-webui.js';
(function() {
let resolvePageIsPopulated = null;
......@@ -20,18 +12,18 @@ const pageIsPopulatedPromise = new Promise((resolve, reject) => {
resolvePageIsPopulated = resolve;
});
whenPageIsPopulatedForTest = function() {
const whenPageIsPopulatedForTest = function() {
return pageIsPopulatedPromise;
};
function initialize() {
engagementDetailsProvider = mojom.SiteEngagementDetailsProvider.getRemote();
const engagementDetailsProvider = SiteEngagementDetailsProvider.getRemote();
/** @type {?HTMLElement} */
const engagementTableBody = $('engagement-table-body');
/** @type {?number} */
let updateInterval = null;
/** @type {?Array<!mojom.SiteEngagementDetails>} */
/** @type {?Array<!SiteEngagementDetails>} */
let info = null;
/** @type {string} */
let sortKey = 'totalScore';
......@@ -64,7 +56,7 @@ function initialize() {
/**
* Creates a single row in the engagement table.
* @param {mojom.SiteEngagementDetails} info The info to create the row from.
* @param {SiteEngagementDetails} info The info to create the row from.
* @return {HTMLElement}
*/
function createRow(info) {
......@@ -114,7 +106,6 @@ function initialize() {
}
updateInterval = null;
}
disableAutoupdateForTests = disableAutoupdate;
function enableAutoupdate() {
if (updateInterval) {
......@@ -127,7 +118,7 @@ function initialize() {
* Sets the base engagement score when a score input is changed.
* Resets the length of engagement-bar-cell to match the new score.
* Also resets the update interval.
* @param {!url.mojom.Url} origin The origin of the engagement score to set.
* @param {!Url} origin The origin of the engagement score to set.
* @param {Event} e
*/
function handleBaseScoreChange(origin, e) {
......@@ -217,6 +208,12 @@ function initialize() {
updateEngagementTable();
enableAutoupdate();
// We explicitly set these on the global Window object so test code can use
// them.
window.whenPageIsPopulatedForTest = whenPageIsPopulatedForTest;
window.disableAutoupdateForTests = disableAutoupdate;
window.engagementDetailsProvider = engagementDetailsProvider;
}
document.addEventListener('DOMContentLoaded', initialize);
......
......@@ -22,6 +22,7 @@
#include "content/public/browser/web_ui_data_source.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "services/network/public/mojom/content_security_policy.mojom.h"
namespace {
......@@ -85,11 +86,12 @@ SiteEngagementUI::SiteEngagementUI(content::WebUI* web_ui)
// Set up the chrome://site-engagement/ source.
std::unique_ptr<content::WebUIDataSource> source(
content::WebUIDataSource::Create(chrome::kChromeUISiteEngagementHost));
source->OverrideContentSecurityPolicy(
network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self';");
source->AddResourcePath("site_engagement.js", IDR_SITE_ENGAGEMENT_JS);
source->AddResourcePath(
"components/site_engagement/core/mojom/"
"site_engagement_details.mojom-lite.js",
IDR_SITE_ENGAGEMENT_DETAILS_MOJOM_LITE_JS);
source->AddResourcePath("site_engagement_details.mojom-webui.js",
IDR_SITE_ENGAGEMENT_DETAILS_MOJOM_WEBUI_JS);
source->SetDefaultResource(IDR_SITE_ENGAGEMENT_HTML);
content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source.release());
}
......
......@@ -353,7 +353,6 @@ if (include_js_tests) {
sources = [
"bluetooth_internals_browsertest.js",
"cr_components/cr_components_mojo_browsertest.js",
"engagement/site_engagement_browsertest.js",
"interventions_internals_browsertest.js",
"media/media_engagement_browsertest.js",
"media/media_feeds_webui_browsertest.js",
......@@ -385,7 +384,10 @@ if (include_js_tests) {
js2gtest("browser_tests_js_mojo_webui") {
test_type = "mojo_webui"
sources = [ "downloads/downloads_browsertest.js" ]
sources = [
"downloads/downloads_browsertest.js",
"engagement/site_engagement_browsertest.js",
]
if (is_win || is_mac || is_linux || is_chromeos) {
sources += [ "discards/discards_browsertest.js" ]
}
......
......@@ -67,7 +67,8 @@ TEST_F('SiteEngagementBrowserTest', 'All', function() {
});
}
setup(function() {
setup(async function() {
await import('chrome://test/mojo_webui_test_support.js');
cells = getCells();
});
......
......@@ -6,6 +6,6 @@ import("//mojo/public/tools/bindings/mojom.gni")
mojom("mojo_bindings") {
sources = [ "site_engagement_details.mojom" ]
public_deps = [ "//url/mojom:url_mojom_gurl" ]
webui_module_path = "/"
}
......@@ -9,9 +9,11 @@ import {mojo} from '{{bindings_library_path}}';
{% for path, kinds in js_module_imports.items() -%}
import {
{%- for kind in kinds %}
{{kind.mojom_name}} as {{kind|name_in_js_module}},
{{kind.mojom_name}}Spec as {{kind|name_in_js_module}}Spec
{%- if not loop.last -%}, {% endif -%}
{%- for item in kind|imports_for_kind %}
{{item.name}} as {{item.alias}}
{%- if not loop.last -%},{% endif -%}
{%- endfor %}
{%- if not loop.last -%},{% endif -%}
{%- endfor %}
} from '{{path}}';
......
......@@ -207,10 +207,17 @@ _SHARED_MODULE_PREFIX = 'chrome://resources/mojo'
def _GetWebUiModulePath(module):
"""Returns the path to a WebUI module, from the perspective of a WebUI page
that makes it available. This is based on the corresponding mojom target's
webui_module_path value. Returns None if the target specifies no module
path. Otherwise, returned paths always end in a '/' and begin with either
`_SHARED_MODULE_PREFIX` or a '/'."""
path = module.metadata.get('webui_module_path')
if path is None:
return None
return path.strip('/')
if path is None or path == '/':
return path
if path.startswith(_SHARED_MODULE_PREFIX):
return path.rstrip('/') + '/'
return '/{}/'.format(path.strip('/'))
def JavaScriptPayloadSize(packed):
......@@ -329,6 +336,7 @@ class Generator(generator.Generator):
"field_type_in_js_module": self._GetFieldTypeInJsModule,
"get_relative_url": GetRelativeUrl,
"has_callbacks": mojom.HasCallbacks,
"imports_for_kind": self._GetImportsForKind,
"is_any_handle_or_interface_kind": mojom.IsAnyHandleOrInterfaceKind,
"is_array_kind": mojom.IsArrayKind,
"is_associated_interface_kind": mojom.IsAssociatedInterfaceKind,
......@@ -358,7 +366,6 @@ class Generator(generator.Generator):
"lite_js_import_name": self._LiteJavaScriptImportName,
"method_passes_associated_kinds": mojom.MethodPassesAssociatedKinds,
"namespace_declarations": self._NamespaceDeclarations,
"name_in_js_module": self._GetNameInJsModule,
"closure_type_with_nullability": self._ClosureTypeWithNullability,
"lite_closure_param_type": self._LiteClosureParamType,
"lite_closure_type": self._LiteClosureType,
......@@ -666,6 +673,27 @@ class Generator(generator.Generator):
qualifier += kind.parent_kind.name + '.'
return (qualifier + kind.name).replace('.', '_')
def _GetImportsForKind(self, kind):
qualified_name = self._GetNameInJsModule(kind)
def make_import(name, suffix=''):
class ImportInfo(object):
def __init__(self, name, alias):
self.name = name
self.alias = alias
return ImportInfo(name + suffix, qualified_name + suffix)
if (mojom.IsEnumKind(kind) or mojom.IsStructKind(kind)
or mojom.IsUnionKind(kind)):
return [make_import(kind.name), make_import(kind.name, 'Spec')]
if mojom.IsInterfaceKind(kind):
return [
make_import(kind.name, 'Remote'),
make_import(kind.name, 'PendingReceiver')
]
assert False, kind.name
def _JavaScriptType(self, kind):
name = []
if kind.module and kind.module.path != self.module.path:
......@@ -1007,24 +1035,31 @@ class Generator(generator.Generator):
def _GetJsModuleImports(self, for_webui_module=False):
this_module_path = _GetWebUiModulePath(self.module)
if this_module_path:
this_module_is_shared = this_module_path.startswith(_SHARED_MODULE_PREFIX)
this_module_is_shared = bool(
this_module_path and this_module_path.startswith(_SHARED_MODULE_PREFIX))
imports = dict()
for spec, kind in self.module.imported_kinds.items():
if for_webui_module:
assert this_module_path is not None
base_path = _GetWebUiModulePath(kind.module)
assert base_path is not None
import_path = '{}/{}-webui.js'.format(
base_path, os.path.basename(kind.module.path))
import_path = '{}{}-webui.js'.format(base_path,
os.path.basename(kind.module.path))
import_module_is_shared = import_path.startswith(_SHARED_MODULE_PREFIX)
if import_module_is_shared == this_module_is_shared:
# Either we're a non-shared resource importing another non-shared
# resource, or we're a shared resource importing another shared
# resource. In both cases, we assume a relative import path will
# suffice.
def strip_prefix(s, prefix):
if s.startswith(prefix):
return s[len(prefix):]
return s
import_path = urllib_request.pathname2url(
os.path.relpath(import_path.lstrip(_SHARED_MODULE_PREFIX),
this_module_path.lstrip(_SHARED_MODULE_PREFIX)))
os.path.relpath(
strip_prefix(import_path, _SHARED_MODULE_PREFIX),
strip_prefix(this_module_path, _SHARED_MODULE_PREFIX)))
if (not import_path.startswith('.')
and not import_path.startswith('/')):
import_path = './' + import_path
......
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