code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
<style include="history-clusters-shared-style cr-icons">
:host {
--indentation: 52px;
--search-query-margin: 10px;
display: block;
/* Implements the spacing between containers. */
padding-bottom: var(--cluster-padding-vertical);
}
:host([in-side-panel_]) {
--cr-icon-button-margin-start: 8px;
padding-bottom: 0;
padding-top: 8px;
}
:host([in-side-panel_][is-first]) {
padding-top: 0;
}
:host-context(.focus-outline-visible):host(:focus) #container {
box-shadow: inset 0 0 0 2px var(--cr-focus-outline-color);
}
:host([has-hidden-visits_]) #container {
/* For containers with a "Show More" button, add some additional spacing for
the pill button by adding a margin on the container. */
margin-bottom: var(--cluster-padding-vertical);
}
:host([in-side-panel_]) #container url-visit:last-of-type {
margin-bottom: 8px;
}
/* We need an inner container div to apply spacing between clusters. This is
because iron-list ignores the margin on the host element. */
:host(:not([in-side-panel_])) #container {
background-color: var(--cr-card-background-color);
border-radius: var(--cr-card-border-radius);
box-shadow: var(--cr-card-shadow);
padding: var(--cluster-padding-vertical) 0;
}
.label-row {
align-items: center;
display: flex;
flex-grow: 1;
justify-content: space-between;
min-height: 48px;
min-width: 0;
padding-inline-start: var(--cluster-padding-horizontal);
}
:host([in-side-panel_]) .label-row {
min-height: 44px;
padding-inline-start: 16px;
}
#label {
color: var(--cr-primary-text-color);
font-size: 1rem; /* 16px */
font-weight: 500;
}
:host([in-side-panel_]) #label {
font-size: .875rem; /* 14px */
line-height: calc(10/7); /* 20px */
margin-inline-end: 16px;
}
:host([in-side-panel_]) .timestamp {
font-size: .75rem; /* 12px */
line-height: calc(5/3); /* 20px */
}
.debug-info {
color: var(--cr-secondary-text-color);
}
#related-searches {
display: flex;
flex-wrap: wrap;
min-width: 0;
/* Top is a special 8px value. */
padding: 8px var(--cluster-padding-horizontal) var(--cluster-padding-vertical);
}
:host([in-side-panel_]) #related-searches {
margin-top: -8px;
padding: 0 16px var(--cluster-padding-vertical);
}
search-query {
margin-top: var(--search-query-margin);
}
search-query:not(:last-of-type) {
margin-inline-end: var(--search-query-margin);
}
</style>
<div id="container" on-visit-clicked="onVisitClicked_"
on-open-all-visits="onOpenAllVisits_"
on-remove-all-visits="onRemoveAllVisits_"
on-hide-visit="onHideVisit_"
on-remove-visit="onRemoveVisit_">
<div class="label-row">
<span id="label" class="truncate"></span>
<img is="cr-auto-img" auto-src="[[imageUrl_]]">
<div class="debug-info">[[cluster.debugInfo]]</div>
<div class="timestamp-and-menu">
<div class="timestamp">[[cluster.visits.0.relativeDate]]</div>
<cluster-menu></cluster-menu>
</div>
</div>
<template is="dom-repeat" items="[[cluster.visits]]">
<url-visit visit="[[item]]" query="[[query]]" from-persistence="[[cluster.fromPersistence]]">
</url-visit>
</template>
<div id="related-searches" hidden="[[!cluster.relatedSearches.length]]"
role="list" aria-label$="[[i18n('relatedSearchesHeader')]]"
on-related-search-clicked="onRelatedSearchClicked_" on-mousedown="clearSelection_">
<template is="dom-repeat" items="[[relatedSearches_]]">
<search-query search-query="[[item]]" index="[[index]]" role="listitem">
</search-query>
</template>
</div>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/cluster.html | HTML | unknown | 3,711 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './cluster_menu.js';
import './search_query.js';
import './history_clusters_shared_style.css.js';
import './shared_vars.css.js';
import './url_visit.js';
import 'chrome://resources/cr_elements/cr_icons.css.js';
import 'chrome://resources/polymer/v3_0/iron-collapse/iron-collapse.js';
import 'chrome://resources/cr_elements/cr_auto_img/cr_auto_img.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {assert} from 'chrome://resources/js/assert_ts.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BrowserProxyImpl} from './browser_proxy.js';
import {getTemplate} from './cluster.html.js';
import {Cluster, SearchQuery, URLVisit} from './history_cluster_types.mojom-webui.js';
import {ClusterAction, PageCallbackRouter, VisitAction} from './history_clusters.mojom-webui.js';
import {MetricsProxyImpl} from './metrics_proxy.js';
import {insertHighlightedTextWithMatchesIntoElement} from './utils.js';
/**
* @fileoverview This file provides a custom element displaying a cluster.
*/
declare global {
interface HTMLElementTagNameMap {
'history-cluster': HistoryClusterElement;
}
}
const HistoryClusterElementBase = I18nMixin(PolymerElement);
interface HistoryClusterElement {
$: {
label: HTMLElement,
container: HTMLElement,
};
}
class HistoryClusterElement extends HistoryClusterElementBase {
static get is() {
return 'history-cluster';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* The cluster displayed by this element.
*/
cluster: Object,
/**
* The index of the cluster.
*/
index: {
type: Number,
value: -1, // Initialized to an invalid value.
},
/**
* Whether the cluster is in the side panel.
*/
inSidePanel_: {
type: Boolean,
value: () => loadTimeData.getBoolean('inSidePanel'),
reflectToAttribute: true,
},
/**
* The current query for which related clusters are requested and shown.
*/
query: String,
/**
* The visible related searches.
*/
relatedSearches_: {
type: Object,
computed: `computeRelatedSearches_(cluster.relatedSearches.*)`,
},
/**
* The label for the cluster. This property is actually unused. The side
* effect of the compute function is used to insert the HTML elements for
* highlighting into this.$.label element.
*/
unusedLabel_: {
type: String,
computed: 'computeLabel_(cluster.label)',
},
/**
* The cluster's image URL in a form easily passed to cr-auto-img.
* Also notifies the outer iron-list of a resize.
*/
imageUrl_: {
type: String,
computed: `computeImageUrl_(cluster.imageUrl)`,
},
};
}
//============================================================================
// Properties
//============================================================================
cluster: Cluster;
index: number;
query: string;
private callbackRouter_: PageCallbackRouter;
private inSidePanel_: boolean;
private onVisitsHiddenListenerId_: number|null = null;
private onVisitsRemovedListenerId_: number|null = null;
private unusedLabel_: string;
//============================================================================
// Overridden methods
//============================================================================
constructor() {
super();
this.callbackRouter_ = BrowserProxyImpl.getInstance().callbackRouter;
// This element receives a tabindex, because it's an iron-list item.
// However, what we really want to do is to pass that focus onto an
// eligible child, so we want to set `delegatesFocus` to true. But
// delegatesFocus removes the text selection. So temporarily removing
// the delegatesFocus until that issue is fixed.
}
override connectedCallback() {
super.connectedCallback();
this.onVisitsHiddenListenerId_ =
this.callbackRouter_.onVisitsHidden.addListener(
this.onVisitsRemovedOrHidden_.bind(this));
this.onVisitsRemovedListenerId_ =
this.callbackRouter_.onVisitsRemoved.addListener(
this.onVisitsRemovedOrHidden_.bind(this));
}
override disconnectedCallback() {
super.disconnectedCallback();
assert(this.onVisitsHiddenListenerId_);
this.callbackRouter_.removeListener(this.onVisitsHiddenListenerId_);
this.onVisitsHiddenListenerId_ = null;
assert(this.onVisitsRemovedListenerId_);
this.callbackRouter_.removeListener(this.onVisitsRemovedListenerId_);
this.onVisitsRemovedListenerId_ = null;
}
//============================================================================
// Event handlers
//============================================================================
private onRelatedSearchClicked_() {
MetricsProxyImpl.getInstance().recordClusterAction(
ClusterAction.kRelatedSearchClicked, this.index);
}
/* Clears selection on non alt mouse clicks. Need to wait for browser to
* update the DOM fully. */
private clearSelection_(event: MouseEvent) {
this.onBrowserIdle_().then(() => {
if (window.getSelection() && !event.altKey) {
window.getSelection()?.empty();
}
});
}
private onVisitClicked_(event: CustomEvent<URLVisit>) {
MetricsProxyImpl.getInstance().recordClusterAction(
ClusterAction.kVisitClicked, this.index);
const visit = event.detail;
MetricsProxyImpl.getInstance().recordVisitAction(
VisitAction.kClicked, this.getVisitIndex_(visit),
MetricsProxyImpl.getVisitType(visit));
}
private onOpenAllVisits_() {
BrowserProxyImpl.getInstance().handler.openVisitUrlsInTabGroup(
this.cluster.visits);
MetricsProxyImpl.getInstance().recordClusterAction(
ClusterAction.kOpenedInTabGroup, this.index);
}
private onRemoveAllVisits_() {
// Pass event up with new detail of all this cluster's visits.
this.dispatchEvent(new CustomEvent('remove-visits', {
bubbles: true,
composed: true,
detail: this.cluster.visits,
}));
}
private onHideVisit_(event: CustomEvent<URLVisit>) {
// The actual hiding is handled in clusters.ts. This is just a good place to
// record the metric.
const visit = event.detail;
MetricsProxyImpl.getInstance().recordVisitAction(
VisitAction.kHidden, this.getVisitIndex_(visit),
MetricsProxyImpl.getVisitType(visit));
}
private onRemoveVisit_(event: CustomEvent<URLVisit>) {
// The actual removal is handled in clusters.ts. This is just a good place
// to record the metric.
const visit = event.detail;
MetricsProxyImpl.getInstance().recordVisitAction(
VisitAction.kDeleted, this.getVisitIndex_(visit),
MetricsProxyImpl.getVisitType(visit));
this.dispatchEvent(new CustomEvent('remove-visits', {
bubbles: true,
composed: true,
detail: [visit],
}));
}
//============================================================================
// Helper methods
//============================================================================
/**
* Returns a promise that resolves when the browser is idle.
*/
private onBrowserIdle_(): Promise<void> {
return new Promise(resolve => {
window.requestIdleCallback(() => {
resolve();
});
});
}
/**
* Called with the original remove or hide params when the last accepted
* request to browser to remove or hide visits succeeds. Since the same visit
* may appear in multiple Clusters, all Clusters receive this callback in
* order to get a chance to remove their matching visits.
*/
private onVisitsRemovedOrHidden_(removedVisits: URLVisit[]) {
const visitHasBeenRemoved = (visit: URLVisit) => {
return removedVisits.findIndex((removedVisit) => {
if (visit.normalizedUrl.url !== removedVisit.normalizedUrl.url) {
return false;
}
// Remove the visit element if any of the removed visit's raw timestamps
// matches the canonical raw timestamp.
const rawVisitTime = visit.rawVisitData.visitTime.internalValue;
return (removedVisit.rawVisitData.visitTime.internalValue ===
rawVisitTime) ||
removedVisit.duplicates.map(data => data.visitTime.internalValue)
.includes(rawVisitTime);
}) !== -1;
};
const allVisits = this.cluster.visits;
const remainingVisits = allVisits.filter(v => !visitHasBeenRemoved(v));
if (allVisits.length === remainingVisits.length) {
return;
}
if (!remainingVisits.length) {
// If all the visits are removed, fire an event to also remove this
// cluster from the list of clusters.
this.dispatchEvent(new CustomEvent('remove-cluster', {
bubbles: true,
composed: true,
detail: this.index,
}));
MetricsProxyImpl.getInstance().recordClusterAction(
ClusterAction.kDeleted, this.index);
} else {
this.set('cluster.visits', remainingVisits);
}
this.dispatchEvent(new CustomEvent('iron-resize', {
bubbles: true,
composed: true,
}));
}
private computeLabel_(): string {
if (!this.cluster.label) {
// This never happens unless we misconfigured our variations config.
// This sentinel string matches the Android UI.
return 'no_label';
}
insertHighlightedTextWithMatchesIntoElement(
this.$.label, this.cluster.label!, this.cluster.labelMatchPositions);
return this.cluster.label!;
}
private computeRelatedSearches_(): SearchQuery[] {
return this.cluster.relatedSearches.filter(
(query: SearchQuery, index: number) => {
return query && !(this.inSidePanel_ && index > 2);
});
}
private computeImageUrl_(): string {
if (!this.cluster.imageUrl) {
return '';
}
// iron-list can't handle our size changing because of loading an image
// without an explicit event. But we also can't send this until we have
// updated the image property, so send it on the next idle.
window.requestIdleCallback(() => {
this.dispatchEvent(new CustomEvent('iron-resize', {
bubbles: true,
composed: true,
}));
});
return this.cluster.imageUrl.url;
}
/**
* Returns the index of `visit` among the visits in the cluster. Returns -1
* if the visit is not found in the cluster at all.
*/
private getVisitIndex_(visit: URLVisit): number {
return this.cluster.visits.indexOf(visit);
}
}
customElements.define(HistoryClusterElement.is, HistoryClusterElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/cluster.ts | TypeScript | unknown | 11,092 |
<style include="history-clusters-shared-style">
#actionMenuButton {
--cr-icon-button-icon-size: 24px;
--cr-icon-button-margin-end: 8px;
}
</style>
<cr-icon-button id="actionMenuButton" class="icon-more-vert"
title$="[[i18n('actionMenuDescription')]]" aria-haspopup="menu"
on-click="onActionMenuButtonClick_">
</cr-icon-button>
<cr-lazy-render id="actionMenu">
<template>
<cr-action-menu role-description$="[[i18n('actionMenuDescription')]]">
<button id="openAllButton" class="dropdown-item"
on-click="onOpenAllButtonClick_">
[[i18n('openAllInTabGroup')]]
</button>
<button id="removeAllButton" class="dropdown-item"
on-click="onRemoveAllButtonClick_"
hidden="[[!allowDeletingHistory_]]">
[[i18n('removeAllFromHistory')]]
</button>
</cr-action-menu>
</template>
</cr-lazy-render>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/cluster_menu.html | HTML | unknown | 883 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './history_clusters_shared_style.css.js';
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.js';
import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cluster_menu.html.js';
import {URLVisit} from './history_cluster_types.mojom-webui.js';
/**
* @fileoverview This file provides a custom element displaying an action menu.
* It's meant to be flexible enough to be associated with either a specific
* visit, or the whole cluster, or the top visit of unlabelled cluster.
*/
declare global {
interface HTMLElementTagNameMap {
'cluster-menu': ClusterMenuElement;
}
}
const ClusterMenuElementBase = I18nMixin(PolymerElement);
interface ClusterMenuElement {
$: {
actionMenu: CrLazyRenderElement<CrActionMenuElement>,
actionMenuButton: HTMLElement,
};
}
class ClusterMenuElement extends ClusterMenuElementBase {
static get is() {
return 'cluster-menu';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* The visit associated with this menu.
*/
visit: Object,
/**
* Usually this is true, but this can be false if deleting history is
* prohibited by Enterprise policy.
*/
allowDeletingHistory_: {
type: Boolean,
value: () => loadTimeData.getBoolean('allowDeletingHistory'),
},
};
}
//============================================================================
// Properties
//============================================================================
visit: URLVisit;
private allowDeletingHistory_: boolean;
//============================================================================
// Event handlers
//============================================================================
private onActionMenuButtonClick_(event: Event) {
this.$.actionMenu.get().showAt(this.$.actionMenuButton);
event.preventDefault(); // Prevent default browser action (navigation).
}
private onOpenAllButtonClick_(event: Event) {
event.preventDefault(); // Prevent default browser action (navigation).
this.dispatchEvent(new CustomEvent('open-all-visits', {
bubbles: true,
composed: true,
}));
this.$.actionMenu.get().close();
}
private onRemoveAllButtonClick_(event: Event) {
event.preventDefault(); // Prevent default browser action (navigation).
this.dispatchEvent(new CustomEvent('remove-all-visits', {
bubbles: true,
composed: true,
}));
this.$.actionMenu.get().close();
}
}
customElements.define(ClusterMenuElement.is, ClusterMenuElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/cluster_menu.ts | TypeScript | unknown | 3,340 |
<style include="history-clusters-shared-style">
:host {
color: var(--cr-primary-text-color);
display: block;
font-size: 0.875rem; /* 14px */
overflow-y: auto;
}
:host([in-side-panel_]) cr-dialog::part(dialog) {
margin: 0 16px;
max-width: fit-content;
}
:host([in-side-panel_]) cr-toast {
margin: 16px; /* Optimized for default side panel */
}
#clusters {
margin: 0 auto;
max-width: var(--cluster-max-width);
min-width: var(--cluster-min-width);
padding: var(--first-cluster-padding-top) var(--cluster-padding-horizontal) 0;
}
:host([in-side-panel_]) #clusters {
min-width: 0;
padding: 8px 0 0;
}
:host([in-side-panel_]) history-cluster {
border-bottom: 4px solid var(--cr-separator-color);
}
:host([in-side-panel_]) history-cluster[is-last] {
border-bottom: none;
}
#placeholder {
align-items: center;
color: var(--md-loading-message-color);
display: flex;
flex: 1;
font-size: inherit;
font-weight: 500;
height: 100%;
justify-content: center;
}
#footer {
display: flex;
justify-content: center;
padding:
0 var(--cluster-padding-horizontal) var(--cluster-padding-vertical);
}
</style>
<div id="placeholder" hidden="[[!placeholderText_]]">
[[placeholderText_]]
</div>
<iron-list id="clusters" items="[[result_.clusters]]"
on-hide-visit="onHideVisit_" on-remove-visits="onRemoveVisits_"
hidden="[[!result_.clusters.length]]">
<!-- We must have a tabindex on these history-cluster elements, because
iron-list gets very confused handling arrow keys without them. Moreover,
we can't allow Tab to traverse all list elements because:
https://github.com/PolymerElements/iron-list/issues/546 -->
<template>
<history-cluster cluster="[[item]]" index="[[index]]"
query="[[result_.query]]" tabindex$="[[tabIndex]]"
on-remove-cluster="onRemoveCluster_" is-first$="[[!index]]"
is-last$="[[isLastCluster_(index, result_.clusters.*)]]">
</history-cluster>
</template>
</iron-list>
<div id="footer" hidden="[[getLoadMoreButtonHidden_(
result_, result_.clusters.*, result_.canLoadMore)]]">
<cr-button id="loadMoreButton" on-click="onLoadMoreButtonClick_"
hidden$="[[showSpinner_]]">
[[i18n('loadMoreButtonLabel')]]
</cr-button>
<iron-icon src="chrome://resources/images/throbber_small.svg"
hidden$="[[!showSpinner_]]"></iron-icon>
</div>
<iron-scroll-threshold id="scrollThreshold"
lower-threshold="500" on-lower-threshold="onScrolledToBottom_">
</iron-scroll-threshold>
<cr-lazy-render id="confirmationDialog">
<template>
<cr-dialog consume-keydown-event on-cancel="onConfirmationDialogCancel_">
<div slot="title">[[i18n('removeSelected')]]</div>
<div slot="body">[[i18n('deleteWarning')]]</div>
<div slot="button-container">
<cr-button class="cancel-button" on-click="onCancelButtonClick_">
[[i18n('cancel')]]
</cr-button>
<cr-button class="action-button" on-click="onRemoveButtonClick_">
[[i18n('deleteConfirm')]]
</cr-button>
</div>
</cr-dialog>
</template>
</cr-lazy-render>
<cr-lazy-render id="confirmationToast">
<template>
<cr-toast duration="5000">
<div>[[i18n('removeFromHistoryToast')]]</div>
</cr-toast>
</template>
</cr-lazy-render>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/clusters.html | HTML | unknown | 3,417 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './cluster.js';
import './history_clusters_shared_style.css.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import 'chrome://resources/cr_elements/cr_toast/cr_toast.js';
import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js';
import 'chrome://resources/polymer/v3_0/iron-scroll-threshold/iron-scroll-threshold.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import {CrToastElement} from 'chrome://resources/cr_elements/cr_toast/cr_toast.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {assert} from 'chrome://resources/js/assert_ts.js';
import {FocusOutlineManager} from 'chrome://resources/js/focus_outline_manager.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {Time} from 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-webui.js';
import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js';
import {IronListElement} from 'chrome://resources/polymer/v3_0/iron-list/iron-list.js';
import {IronScrollThresholdElement} from 'chrome://resources/polymer/v3_0/iron-scroll-threshold/iron-scroll-threshold.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BrowserProxyImpl} from './browser_proxy.js';
import {getTemplate} from './clusters.html.js';
import {Cluster, URLVisit} from './history_cluster_types.mojom-webui.js';
import {PageCallbackRouter, PageHandlerRemote, QueryResult} from './history_clusters.mojom-webui.js';
/**
* @fileoverview This file provides a custom element that requests and shows
* history clusters given a query. It handles loading more clusters using
* infinite scrolling as well as deletion of visits within the clusters.
*/
declare global {
interface HTMLElementTagNameMap {
'history-clusters': HistoryClustersElement;
}
interface Window {
// https://github.com/microsoft/TypeScript/issues/40807
requestIdleCallback(callback: () => void): void;
}
}
const HistoryClustersElementBase = I18nMixin(PolymerElement);
export interface HistoryClustersElement {
$: {
clusters: IronListElement,
confirmationDialog: CrLazyRenderElement<CrDialogElement>,
confirmationToast: CrLazyRenderElement<CrToastElement>,
scrollThreshold: IronScrollThresholdElement,
};
}
export class HistoryClustersElement extends HistoryClustersElementBase {
static get is() {
return 'history-clusters';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* Whether the clusters are in the side panel.
*/
inSidePanel_: {
type: Boolean,
value: () => loadTimeData.getBoolean('inSidePanel'),
reflectToAttribute: true,
},
/**
* The current query for which related clusters are requested and shown.
*/
query: {
type: String,
observer: 'onQueryChanged_',
value: '',
},
/**
* The placeholder text to show when the results are empty.
*/
placeholderText_: {
type: String,
computed: `computePlaceholderText_(result_.*)`,
},
/**
* The browser response to a request for the freshest clusters related to
* a given query until an optional given end time (or the present time).
*/
result_: Object,
/**
* Boolean determining if spinner shows instead of load more button.
*/
showSpinner_: {
type: Boolean,
value: false,
},
/**
* The list of visits to be removed. A non-empty array indicates a pending
* remove request to the browser.
*/
visitsToBeRemoved_: {
type: Object,
value: () => [],
},
};
}
//============================================================================
// Properties
//============================================================================
query: string;
private callbackRouter_: PageCallbackRouter;
private headerText_: string;
private inSidePanel_: boolean;
private onClustersQueryResultListenerId_: number|null = null;
private onClusterImageUpdatedListenerId_: number|null = null;
private onVisitsRemovedListenerId_: number|null = null;
private onHistoryDeletedListenerId_: number|null = null;
private onQueryChangedByUserListenerId_: number|null = null;
private pageHandler_: PageHandlerRemote;
private placeholderText_: string;
private result_: QueryResult;
private showSpinner_: boolean;
private visitsToBeRemoved_: URLVisit[];
//============================================================================
// Overridden methods
//============================================================================
constructor() {
super();
this.pageHandler_ = BrowserProxyImpl.getInstance().handler;
this.callbackRouter_ = BrowserProxyImpl.getInstance().callbackRouter;
}
override connectedCallback() {
super.connectedCallback();
// Register a per-document singleton focus outline manager. Some of our
// child elements depend on the CSS classes set by this singleton.
FocusOutlineManager.forDocument(document);
this.$.clusters.notifyResize();
this.$.clusters.scrollTarget = this;
this.$.scrollThreshold.scrollTarget = this;
this.onClustersQueryResultListenerId_ =
this.callbackRouter_.onClustersQueryResult.addListener(
this.onClustersQueryResult_.bind(this));
this.onClusterImageUpdatedListenerId_ =
this.callbackRouter_.onClusterImageUpdated.addListener(
this.onClusterImageUpdated_.bind(this));
this.onVisitsRemovedListenerId_ =
this.callbackRouter_.onVisitsRemoved.addListener(
this.onVisitsRemoved_.bind(this));
this.onHistoryDeletedListenerId_ =
this.callbackRouter_.onHistoryDeleted.addListener(
this.onHistoryDeleted_.bind(this));
this.onQueryChangedByUserListenerId_ =
this.callbackRouter_.onQueryChangedByUser.addListener(
this.onQueryChangedByUser_.bind(this));
if (this.inSidePanel_) {
this.pageHandler_.showSidePanelUI();
}
}
override disconnectedCallback() {
super.disconnectedCallback();
assert(this.onClustersQueryResultListenerId_);
this.callbackRouter_.removeListener(this.onClustersQueryResultListenerId_);
this.onClustersQueryResultListenerId_ = null;
assert(this.onVisitsRemovedListenerId_);
this.callbackRouter_.removeListener(this.onVisitsRemovedListenerId_);
this.onVisitsRemovedListenerId_ = null;
assert(this.onHistoryDeletedListenerId_);
this.callbackRouter_.removeListener(this.onHistoryDeletedListenerId_);
this.onHistoryDeletedListenerId_ = null;
assert(this.onQueryChangedByUserListenerId_);
this.callbackRouter_.removeListener(this.onQueryChangedByUserListenerId_);
this.onQueryChangedByUserListenerId_ = null;
}
//============================================================================
// Event handlers
//============================================================================
private onCancelButtonClick_() {
this.visitsToBeRemoved_ = [];
this.$.confirmationDialog.get().close();
}
private onConfirmationDialogCancel_() {
this.visitsToBeRemoved_ = [];
}
private onLoadMoreButtonClick_() {
if (this.result_ && this.result_.canLoadMore) {
this.showSpinner_ = true;
// Prevent sending further load-more requests until this one finishes.
this.set('result_.canLoadMore', false);
this.pageHandler_.loadMoreClusters(this.result_.query);
}
}
private onRemoveButtonClick_() {
this.pageHandler_.removeVisits(this.visitsToBeRemoved_).then(() => {
// The returned promise resolves with whether the request succeeded in the
// browser. That value may be used to show a toast but is ignored for now.
// Allow remove requests again.
this.visitsToBeRemoved_ = [];
});
this.$.confirmationDialog.get().close();
}
/**
* Called with `event` received from a visit requesting to be hidden.
*/
private onHideVisit_(event: CustomEvent<URLVisit>) {
this.pageHandler_.hideVisits([event.detail]);
}
/**
* Called with `event` received from a cluster requesting to be removed from
* the list when all its visits have been removed. Contains the cluster index.
*/
private onRemoveCluster_(event: CustomEvent<number>) {
const index = event.detail;
this.splice('result_.clusters', index, 1);
}
/**
* Called with `event` received from a visit requesting to be removed. `event`
* may contain the related visits of the said visit, if applicable.
*/
private onRemoveVisits_(event: CustomEvent<URLVisit[]>) {
// Return early if there is a pending remove request.
if (this.visitsToBeRemoved_.length) {
return;
}
this.visitsToBeRemoved_ = event.detail;
if (this.visitsToBeRemoved_.length > 1) {
this.$.confirmationDialog.get().showModal();
} else {
// Bypass the confirmation dialog if removing one visit only.
this.onRemoveButtonClick_();
}
}
/**
* Called when the scrollable area has been scrolled nearly to the bottom.
*/
private onScrolledToBottom_() {
this.$.scrollThreshold.clearTriggers();
if (this.shadowRoot!.querySelector(':focus-visible')) {
// If some element of ours is keyboard-focused, don't automatically load
// more clusters. It loses the user's position and messes up screen
// readers. Let the user manually click the "Load More" button, if needed.
// We use :focus-visible here, because :focus is triggered by mouse focus
// too. And `FocusOutlineManager.visible()` is too primitive. It's true
// on page load, and whenever the user is typing in the searchbox.
return;
}
this.onLoadMoreButtonClick_();
}
//============================================================================
// Helper methods
//============================================================================
private computePlaceholderText_(): string {
if (!this.result_) {
return '';
}
return this.result_.clusters.length ?
'' :
loadTimeData.getString(
this.result_.query ? 'noSearchResults' :
'historyClustersNoResults');
}
/**
* Returns true and hides the button unless we actually have more results to
* load. Note we don't actually hide this button based on keyboard-focus
* state. This is because if the user is using the mouse, more clusters are
* loaded before the user ever gets a chance to see this button.
*/
private getLoadMoreButtonHidden_(
_result: QueryResult, _resultClusters: Cluster[],
_resultCanLoadMore: Time): boolean {
return !this.result_ || this.result_.clusters.length === 0 ||
!this.result_.canLoadMore;
}
/**
* Returns whether the given index corresponds to the last cluster.
*/
private isLastCluster_(index: number): boolean {
return index === this.result_.clusters.length - 1;
}
/**
* Returns a promise that resolves when the browser is idle.
*/
private onBrowserIdle_(): Promise<void> {
return new Promise(resolve => {
window.requestIdleCallback(() => {
resolve();
});
});
}
private onClustersQueryResult_(result: QueryResult) {
if (result.isContinuation) {
// Do not replace the existing result when `result` contains a partial
// set of clusters that should be appended to the existing ones.
this.push('result_.clusters', ...result.clusters);
this.set('result_.canLoadMore', result.canLoadMore);
} else {
// Scroll to the top when `result` contains a new set of clusters.
this.scrollTop = 0;
this.result_ = result;
}
// Handle the "tall monitor" edge case: if the returned results are are
// shorter than the vertical viewport, the <history-clusters> element will
// not have a scrollbar, and the user will never be able to trigger the
// iron-scroll-threshold to request more results. Therefore, immediately
// request more results if there is no scrollbar to fill the viewport.
//
// This should happen quite rarely in the queryless state since the backend
// transparently tries to get at least ~100 visits to cluster.
//
// This is likely to happen very frequently in the search query state, since
// many clusters will not match the search query and will be discarded.
//
// Do this on browser idle to avoid jank and to give the DOM a chance to be
// updated with the results we just got.
this.onBrowserIdle_().then(() => {
if (this.scrollHeight <= this.clientHeight && this.result_.canLoadMore) {
this.onLoadMoreButtonClick_();
}
});
this.showSpinner_ = false;
}
/**
* Called when an image has become available for `clusterIndex`.
*/
private onClusterImageUpdated_(clusterIndex: number, imageUrl: Url) {
// TODO(tommycli): Make deletions handle `clusterIndex` properly.
this.set(`result_.clusters.${clusterIndex}.imageUrl`, imageUrl);
}
/**
* Called when the user entered search query changes. Also used to fetch the
* initial set of clusters when the page loads.
*/
private onQueryChanged_() {
this.onBrowserIdle_().then(() => {
if (this.result_ && this.result_.canLoadMore) {
// Prevent sending further load-more requests until this one finishes.
this.set('result_.canLoadMore', false);
}
this.pageHandler_.startQueryClusters(
this.query.trim(),
new URLSearchParams(window.location.search).has('recluster'));
});
}
/**
* Called with the original remove params when the last accepted request to
* browser to remove visits succeeds.
*/
private onVisitsRemoved_(removedVisits: URLVisit[]) {
// Show the confirmation toast once done removing one visit only; since a
// confirmation dialog was not shown prior to the action.
if (removedVisits.length === 1) {
this.$.confirmationToast.get().show();
}
}
/**
* Called when History is deleted from a different tab.
*/
private onHistoryDeleted_() {
// Just re-issue the existing query to "reload" the results and display
// the externally deleted History. It would be nice if we could save the
// user's scroll position, but History doesn't do that either.
this.onQueryChanged_();
}
/**
* Called when the query is changed by the user externally.
*/
private onQueryChangedByUser_(query: string) {
// Don't directly change the query, but instead let the containing element
// update the searchbox UI. That in turn will cause this object to issue
// a new query to the backend.
this.dispatchEvent(new CustomEvent('query-changed-by-user', {
bubbles: true,
composed: true,
detail: query,
}));
}
}
customElements.define(HistoryClustersElement.is, HistoryClustersElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/clusters.ts | TypeScript | unknown | 15,519 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #import=chrome://resources/cr_elements/cr_shared_style.css.js
* #import=chrome://resources/cr_elements/cr_shared_vars.css.js
* #import=./shared_vars.css.js
* #include=cr-shared-style cr-hidden-style
* #css_wrapper_metadata_end */
.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pill {
border: 1px solid var(--border-color);
border-radius: calc(var(--pill-height) / 2);
box-sizing: border-box;
font-size: 0.875rem; /* 14px */
height: var(--pill-height);
line-height: 1.5; /* 21px */
}
:host-context([chrome-refresh-2023]) .pill {
font-size: 0.75rem; /* 12px */
}
.pill-icon-start {
padding-inline-end: var(--pill-padding-text);
padding-inline-start: var(--pill-padding-icon);
}
.pill-icon-start .icon {
margin-inline-end: 8px;
}
:host-context([chrome-refresh-2023]) .pill-icon-start .icon {
margin-inline-end: 4px;
}
.pill-icon-end {
padding-inline-end: var(--pill-padding-icon);
padding-inline-start: var(--pill-padding-text);
}
.pill-icon-end .icon {
margin-inline-start: 8px;
}
.search-highlight-hit {
--search-highlight-hit-background-color: none;
--search-highlight-hit-color: none;
font-weight: 700;
}
.timestamp-and-menu {
align-items: center;
display: flex;
flex-shrink: 0;
}
.timestamp {
color: var(--cr-secondary-text-color);
flex-shrink: 0;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/history_clusters_shared_style.css | CSS | unknown | 1,547 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {BrowserProxyImpl} from './browser_proxy.js';
import {Annotation, URLVisit} from './history_cluster_types.mojom-webui.js';
import {ClusterAction, RelatedSearchAction, VisitAction, VisitType} from './history_clusters.mojom-webui.js';
/**
* @fileoverview This file provides an abstraction layer for logging metrics for
* mocking in tests.
*/
export interface MetricsProxy {
recordClusterAction(action: ClusterAction, index: number): void;
recordRelatedSearchAction(action: RelatedSearchAction, index: number): void;
recordToggledVisibility(visible: boolean): void;
recordVisitAction(action: VisitAction, index: number, type: VisitType): void;
}
export class MetricsProxyImpl implements MetricsProxy {
recordClusterAction(action: ClusterAction, index: number) {
BrowserProxyImpl.getInstance().handler.recordClusterAction(action, index);
}
recordRelatedSearchAction(action: RelatedSearchAction, index: number) {
BrowserProxyImpl.getInstance().handler.recordRelatedSearchAction(
action, index);
}
recordToggledVisibility(visible: boolean) {
BrowserProxyImpl.getInstance().handler.recordToggledVisibility(visible);
}
recordVisitAction(action: VisitAction, index: number, type: VisitType) {
BrowserProxyImpl.getInstance().handler.recordVisitAction(
action, index, type);
}
static getInstance(): MetricsProxy {
return instance || (instance = new MetricsProxyImpl());
}
static setInstance(obj: MetricsProxy) {
instance = obj;
}
/**
* Returns the VisitType based on whether this is a visit to the default
* search provider's results page.
*/
static getVisitType(visit: URLVisit): VisitType {
return visit.annotations.includes(Annotation.kSearchResultsPage) ?
VisitType.kSRP :
VisitType.kNonSRP;
}
}
let instance: MetricsProxy|null = null;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/metrics_proxy.ts | TypeScript | unknown | 2,000 |
<style>
:host {
align-items: center;
background-color: var(--entity-image-background-color);
background-position: center;
background-repeat: no-repeat;
border-radius: 5px;
display: flex;
flex-shrink: 0;
height: 36px;
justify-content: center;
margin-inline: 0 12px;
width: 36px;
}
:host([in-side-panel_]) {
margin-inline: 8px 16px;
}
#page-image {
border-radius: 5px;
max-height: 100%;
max-width: 100%;
}
:host([is-image-cover_]) #page-image {
height: 100%;
object-fit: cover;
width: 100%;
}
</style>
<template is="dom-if" if="[[imageUrl_]]">
<img id="page-image" is="cr-auto-img" auto-src="[[imageUrl_.url]]">
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/page_favicon.html | HTML | unknown | 716 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './shared_vars.css.js';
import 'chrome://resources/cr_elements/cr_auto_img/cr_auto_img.js';
import {PageImageServiceBrowserProxy} from 'chrome://resources/cr_components/page_image_service/browser_proxy.js';
import {ClientId as PageImageServiceClientId} from 'chrome://resources/cr_components/page_image_service/page_image_service.mojom-webui.js';
import {getFaviconForPageURL} from 'chrome://resources/js/icon.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './page_favicon.html.js';
/**
* @fileoverview This file provides a custom element displaying a page favicon.
*/
declare global {
interface HTMLElementTagNameMap {
'page-favicon': PageFavicon;
}
}
/**
* TODO(tommycli): This element should be renamed to reflect the reality that
* it's used to both render the visit's "important image" if it exists, and
* falls back to the favicon if it doesn't exist.
*/
class PageFavicon extends PolymerElement {
static get is() {
return 'page-favicon';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* Whether the cluster is in the side panel.
*/
inSidePanel_: {
type: Boolean,
value: () => loadTimeData.getBoolean('inSidePanel'),
reflectToAttribute: true,
},
/**
* The element's style attribute.
*/
style: {
type: String,
computed: `computeStyle_(url, imageUrl_)`,
reflectToAttribute: true,
},
/**
* The URL for which the favicon is shown.
*/
url: Object,
/**
* Whether this visit is known to sync already. Used for the purpose of
* fetching higher quality favicons in that case.
*/
isKnownToSync: Boolean,
/**
* The URL of the representative image for the page. Not every page has
* this defined, in which case we fallback to the favicon.
*/
imageUrl_: {
type: Object,
value: null,
},
isImageCover_: {
type: Boolean,
value: () => loadTimeData.getBoolean('isHistoryClustersImageCover'),
reflectToAttribute: true,
},
};
}
static get observers() {
return ['urlAndIsKnownToSyncChanged_(url, isKnownToSync)'];
}
//============================================================================
// Properties
//============================================================================
url: Url;
isKnownToSync: boolean;
private imageUrl_: Url|null;
//============================================================================
// Helper methods
//============================================================================
getImageUrlForTesting(): Url|null {
return this.imageUrl_;
}
private computeStyle_(): string {
if (this.imageUrl_ && this.imageUrl_.url) {
// Pages with a pre-set image URL don't show the favicon.
return '';
}
if (!this.url) {
return '';
}
return `background-image:${
getFaviconForPageURL(
this.url.url, this.isKnownToSync, '', /** --favicon-size */ 16)}`;
}
private async urlAndIsKnownToSyncChanged_() {
if (!this.url || !this.isKnownToSync ||
!loadTimeData.getBoolean('isHistoryClustersImagesEnabled')) {
this.imageUrl_ = null;
return;
}
// Fetch the representative image for this page, if possible.
const {result} =
await PageImageServiceBrowserProxy.getInstance()
.handler.getPageImageUrl(
PageImageServiceClientId.Journeys, this.url,
{suggestImages: true, optimizationGuideImages: true});
if (result) {
this.imageUrl_ = result.imageUrl;
} else {
// We must reset imageUrl_ to null, because sometimes the Virtual DOM will
// reuse the same element for the infinite scrolling list.
this.imageUrl_ = null;
}
}
}
customElements.define(PageFavicon.is, PageFavicon);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/page_favicon.ts | TypeScript | unknown | 4,344 |
<style include="history-clusters-shared-style">
:host {
display: block;
min-width: 0;
}
:host-context([chrome-refresh-2023]):host {
--border-color: var(--color-suggestion-chip-border,
var(--cr-fallback-color-tonal-outline));
--icon-color: var(--color-suggestion-chip-icon,
var(--cr-fallback-color-primary));
--pill-padding-text: 12px;
--pill-padding-icon: 8px;
--pill-height: 28px;
}
a {
align-items: center;
color: inherit;
display: flex;
outline: none;
text-decoration: none;
}
:host-context([chrome-refresh-2023]) a {
overflow: hidden;
position: relative;
}
:host(:hover) a {
background-color: var(--cr-hover-background-color);
}
:host(:active) a {
background-color: var(--cr-active-background-color);
}
:host-context([chrome-refresh-2023]):host(:hover) a {
background-color: transparent;
}
:host-context([chrome-refresh-2023]):host(:active) a {
background-color: transparent;
}
:host-context(.focus-outline-visible) a:focus {
box-shadow: inset 0 0 0 2px var(--cr-focus-outline-color);
}
:host-context([chrome-refresh-2023].focus-outline-visible) a:focus {
--pill-padding-icon: 9px;
--pill-padding-text: 13px;
border: none;
box-shadow: none;
outline: 2px solid var(--cr-focus-outline-color);
outline-offset: 0;
}
:host-context([chrome-refresh-2023]) span {
position: relative;
z-index: 1;
}
.icon {
--cr-icon-button-margin-start: 0;
--cr-icon-color: var(--icon-color);
--cr-icon-image: url(chrome://resources/images/icon_search.svg);
--cr-icon-ripple-margin: 0;
--cr-icon-ripple-size: 20px;
}
:host-context([chrome-refresh-2023]) .icon {
--cr-icon-ripple-size: 16px;
--cr-icon-size: 16px;
}
paper-ripple {
display: none;
}
:host-context([chrome-refresh-2023]) paper-ripple {
--paper-ripple-opacity: 1;
color: var(--cr-active-background-color);
display: block;
}
#hover-layer {
display: none;
}
:host-context([chrome-refresh-2023]):host(:hover) #hover-layer {
background: var(--cr-hover-background-color);
content: '';
display: block;
inset: 0;
pointer-events: none;
position: absolute;
}
</style>
<a id="searchQueryLink" class="pill pill-icon-start" href$="[[searchQuery.url.url]]"
on-click="onClick_" on-auxclick="onAuxClick_" on-keydown="onKeydown_">
<div id="hover-layer"></div>
<span class="icon cr-icon"></span>
<span class="truncate">[[searchQuery.query]]</span>
</a>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/search_query.html | HTML | unknown | 2,567 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './history_clusters_shared_style.css.js';
import {PaperRippleBehavior} from 'chrome://resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js';
import {mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BrowserProxyImpl} from './browser_proxy.js';
import {SearchQuery} from './history_cluster_types.mojom-webui.js';
import {RelatedSearchAction} from './history_clusters.mojom-webui.js';
import {MetricsProxyImpl} from './metrics_proxy.js';
import {getTemplate} from './search_query.html.js';
/**
* @fileoverview This file provides a custom element displaying a search query.
*/
interface SearchQueryElement {
$: {
searchQueryLink: HTMLElement,
};
}
declare global {
interface HTMLElementTagNameMap {
'search-query': SearchQueryElement;
}
}
const SearchQueryElementBase =
mixinBehaviors([PaperRippleBehavior], PolymerElement) as {
new (): PolymerElement & PaperRippleBehavior,
};
class SearchQueryElement extends SearchQueryElementBase {
static get is() {
return 'search-query';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* The index of the search query pill.
*/
index: {
type: Number,
value: -1, // Initialized to an invalid value.
},
/**
* The search query to display.
*/
searchQuery: Object,
};
}
//============================================================================
// Properties
//============================================================================
index: number;
searchQuery: SearchQuery;
/* eslint-disable-next-line @typescript-eslint/naming-convention */
override _rippleContainer: Element;
//============================================================================
// Event handlers
//============================================================================
override ready() {
super.ready();
if (document.documentElement.hasAttribute('chrome-refresh-2023')) {
this.addEventListener('pointerdown', this.onPointerDown_.bind(this));
this.addEventListener('pointercancel', this.onPointerCancel_.bind(this));
}
}
private onAuxClick_() {
MetricsProxyImpl.getInstance().recordRelatedSearchAction(
RelatedSearchAction.kClicked, this.index);
// Notify the parent <history-cluster> element of this event.
this.dispatchEvent(new CustomEvent('related-search-clicked', {
bubbles: true,
composed: true,
}));
}
private onClick_(event: MouseEvent) {
event.preventDefault(); // Prevent default browser action (navigation).
// To record metrics.
this.onAuxClick_();
this.openUrl_(event);
}
private onKeydown_(e: KeyboardEvent) {
// Disable ripple on Space.
this.noink = e.key === ' ';
// To be consistent with <history-list>, only handle Enter, and not Space.
if (e.key !== 'Enter') {
return;
}
this.getRipple().uiDownAction();
// To record metrics.
this.onAuxClick_();
this.openUrl_(e);
setTimeout(() => this.getRipple().uiUpAction(), 100);
}
private onPointerDown_() {
// Ensure ripple is visible.
this.noink = false;
this.ensureRipple();
}
private onPointerCancel_() {
this.getRipple().clear();
}
private openUrl_(event: MouseEvent|KeyboardEvent) {
BrowserProxyImpl.getInstance().handler.openHistoryCluster(
this.searchQuery.url, {
middleButton: false,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
});
}
// Overridden from PaperRippleBehavior
/* eslint-disable-next-line @typescript-eslint/naming-convention */
override _createRipple() {
this._rippleContainer = this.$.searchQueryLink;
const ripple = super._createRipple();
return ripple;
}
}
customElements.define(SearchQueryElement.is, SearchQueryElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/search_query.ts | TypeScript | unknown | 4,187 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=vars
* #import=chrome://resources/cr_elements/cr_shared_vars.css.js
* #import=chrome://resources/polymer/v3_0/paper-styles/color.js
* #css_wrapper_metadata_end */
/* Colors: */
html {
--annotation-background-color: var(--google-green-50);
--annotation-text-color: var(--google-green-600);
--border-color: var(--google-grey-300);
--entity-image-background-color: var(--google-grey-50);
--grey-fill-color: var(--google-grey-100);
--icon-color: var(--google-grey-600);
--url-color: var(--google-blue-600);
--side-panel-url-color: var(--google-grey-700);
}
@media (prefers-color-scheme: dark) {
html {
--annotation-background-color: var(--google-green-300);
--annotation-text-color: var(--google-grey-900);
--border-color: var(--google-grey-700);
--entity-image-background-color: var(--google-grey-800);
--grey-fill-color: var(--google-grey-700);
--icon-color: white;
--url-color: var(--google-blue-300);
--side-panel-url-color: var(--google-grey-500);
}
}
/* Sizes: */
html {
--card-max-width: 960px;
--card-min-width: 550px;
--card-padding-between: 16px;
--card-padding-side: 24px;
--first-card-padding-top: 24px;
--cluster-max-width: var(--card-max-width);
--cluster-min-width: var(--card-min-width);
--cluster-padding-horizontal: var(--card-padding-side);
--cluster-padding-vertical: var(--card-padding-between);
--favicon-margin: 16px;
--favicon-size: 16px;
--first-cluster-padding-top: var(--first-card-padding-top);
--pill-height: 34px;
--pill-padding-icon: 12px;
--pill-padding-text: 16px;
--top-visit-favicon-size: 24px;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/shared_vars.css | CSS | unknown | 1,785 |
<style include="history-clusters-shared-style cr-icons">
:host {
align-items: center;
cursor: pointer;
display: flex;
min-height: 64px;
}
:host(:hover) {
background-color: var(--cr-hover-background-color);
}
.suffix-icons {
display: flex;
opacity: 0; /* Hides the element while keeping it in tab order. */
position: absolute; /* Surrender its layout space to other elements. */
--cr-icon-button-margin-end: 8px;
}
:host(:hover) .suffix-icons,
.suffix-icons:focus-within {
opacity: 1;
position: static;
}
.hide-visit-icon {
--cr-icon-image: url(chrome://resources/cr_components/history_clusters/hide_source_gm_grey_24dp.svg);
}
#header {
align-items: center;
display: flex;
flex-grow: 1;
justify-content: space-between;
min-width: 0;
padding-inline-start: var(--cluster-padding-horizontal);
}
:host([in-side-panel_]) #header {
padding-inline-start: 8px;
}
a {
color: inherit;
text-decoration: none;
}
#link-container {
align-items: center;
display: flex;
margin-inline-end: var(--cluster-padding-horizontal);
min-width: 0;
outline: none;
padding-inline: 2px; /* So focus outline does not intersect text */
}
:host(:hover) #link-container {
margin-inline-end: 0;
}
:host-context(.focus-outline-visible) #link-container:focus {
box-shadow: inset 0 0 0 2px var(--cr-focus-outline-color);
}
#page-info {
display: flex;
flex-direction: column;
min-width: 0;
}
#title-and-annotations {
align-items: center;
display: flex;
line-height: 2; /* 32px */
}
.annotation {
align-items: center;
background-color: var(--annotation-background-color);
border-radius: 4px;
color: var(--annotation-text-color);
display: inline-flex;
flex-shrink: 0;
font-weight: 500;
margin-inline-start: 12px;
padding: 0 8px;
}
.annotation + .annotation {
margin-inline-start: 8px;
}
#title,
#url {
font-size: .875rem; /* 14px */
}
:host([in-side-panel_]) #title {
font-size: .8125rem; /* 13px */
line-height: calc(20/13); /* 20px */
}
#url {
color: var(--url-color);
line-height: 1.5; /* 24px */
}
:host([in-side-panel_]) #url {
color: var(--side-panel-url-color);
font-size: .75rem; /* 12px */
line-height: calc(5/3); /* 20px */
}
#debug-info {
color: var(--cr-secondary-text-color);
}
</style>
<div id="header" on-click="onClick_" on-auxclick="onClick_"
on-keydown="onKeydown_" on-contextmenu="onContextMenu_">
<a id="link-container" href="[[visit.normalizedUrl.url]]">
<page-favicon id="icon" url="[[visit.normalizedUrl]]"
is-known-to-sync="[[visit.isKnownToSync]]">
</page-favicon>
<div id="page-info">
<div id="title-and-annotations">
<span id="title" class="truncate"></span>
<template is="dom-repeat" items="[[annotations_]]">
<span class="annotation">[[item]]</span>
</template>
</div>
<span id="url" class="truncate"></span>
<span id="debug-info" hidden="[[!debugInfo_]]">[[debugInfo_]]</span>
</div>
</a>
<div class="suffix-icons">
<cr-icon-button class="hide-visit-icon"
title$="[[i18n('hideFromCluster')]]"
on-click="onHideSelfButtonClick_"
hidden="[[!showHideVisitIcon_]]"></cr-icon-button>
<cr-icon-button id="actionMenuButton" class="icon-more-vert"
title$="[[i18n('actionMenuDescription')]]" aria-haspopup="menu"
on-click="onActionMenuButtonClick_"
hidden="[[!showActionMenuButton_]]">
</cr-icon-button>
</div>
</div>
<cr-lazy-render id="actionMenu">
<template>
<cr-action-menu role-description="[[i18n('actionMenuDescription')]]">
<button id="hideSelfButton" class="dropdown-item" hidden="[[!showHideVisitMenu_]]"
on-click="onHideSelfButtonClick_">
[[i18n('hideFromCluster')]]
</button>
<button id="removeSelfButton" class="dropdown-item" hidden="[[!allowDeletingHistory_]]"
on-click="onRemoveSelfButtonClick_">
[[i18n('removeFromHistory')]]
</button>
</cr-action-menu>
</template>
</cr-lazy-render>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/url_visit.html | HTML | unknown | 4,234 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './page_favicon.js';
import './history_clusters_shared_style.css.js';
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.js';
import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BrowserProxyImpl} from './browser_proxy.js';
import {Annotation, URLVisit} from './history_cluster_types.mojom-webui.js';
import {getTemplate} from './url_visit.html.js';
import {insertHighlightedTextWithMatchesIntoElement} from './utils.js';
/**
* @fileoverview This file provides a custom element displaying a visit to a
* page within a cluster. A visit features the page favicon, title, a timestamp,
* as well as an action menu.
*/
/**
* Maps supported annotations to localized string identifiers.
*/
const annotationToStringId: Map<number, string> = new Map([
[Annotation.kBookmarked, 'bookmarked'],
]);
declare global {
interface HTMLElementTagNameMap {
'url-visit': VisitRowElement;
}
}
const ClusterMenuElementBase = I18nMixin(PolymerElement);
interface VisitRowElement {
$: {
actionMenu: CrLazyRenderElement<CrActionMenuElement>,
actionMenuButton: HTMLElement,
title: HTMLElement,
url: HTMLElement,
};
}
class VisitRowElement extends ClusterMenuElementBase {
static get is() {
return 'url-visit';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* The current query for which related clusters are requested and shown.
*/
query: String,
/**
* The visit to display.
*/
visit: Object,
/**
* Whether this visit is within a persisted cluster.
*/
fromPersistence: Boolean,
/**
* Annotations to show for the visit (e.g., whether page was bookmarked).
*/
annotations_: {
type: Object,
computed: 'computeAnnotations_(visit)',
},
/**
* True when the hide-visits feature is enabled, not showing the hide
* visits icon, and the visit is hide-able (i.e. belongs to a persisted
* cluster).
*/
showHideVisitMenu_: {
type: Boolean,
computed: 'computeShowHideVisitMenu_(fromPersistence)',
},
/**
* Similar to `showHideVisitMenu_`, but showing the icon instead of the
* menu button.
*/
showHideVisitIcon_: {
type: Boolean,
computed: 'computeShowHideVisitIcon_(fromPersistence)',
},
/**
* Usually this is true, but this can be false if deleting history is
* prohibited by Enterprise policy.
*/
allowDeletingHistory_: {
type: Boolean,
value: () => loadTimeData.getBoolean('allowDeletingHistory'),
},
/**
* The action menu is hidden when the menu would be empty; i.e., both the
* hide visits and delete visits buttons are disabled.
*/
showActionMenuButton_: {
type: Boolean,
computed: 'computeShowActionMenuButton_(showHideVisitMenu_)',
},
/**
* Debug info for the visit.
*/
debugInfo_: {
type: String,
computed: 'computeDebugInfo_(visit)',
},
/**
* Whether the cluster is in the side panel.
*/
inSidePanel_: {
type: Boolean,
value: () => loadTimeData.getBoolean('inSidePanel'),
reflectToAttribute: true,
},
/**
* Page title for the visit. This property is actually unused. The side
* effect of the compute function is used to insert the HTML elements for
* highlighting into this.$.title element.
*/
unusedTitle_: {
type: String,
computed: 'computeTitle_(visit)',
},
/**
* This property is actually unused. The side effect of the compute
* function is used to insert HTML elements for the highlighted
* `this.visit.urlForDisplay` URL into the `this.$.url` element.
*/
unusedUrlForDisplay_: {
type: String,
computed: 'computeUrlForDisplay_(visit)',
},
};
}
//============================================================================
// Properties
//============================================================================
query: string;
visit: URLVisit;
fromPersistence: boolean;
private annotations_: string[];
private showHideVisitMenu_: boolean;
private showHideVisitIcon_: boolean;
private allowDeletingHistory_: boolean;
private showActionMenuButton_: boolean;
private debugInfo_: string;
private inSidePanel_: boolean;
private unusedTitle_: string;
private unusedVisibleUrl_: string;
//============================================================================
// Event handlers
//============================================================================
private onAuxClick_() {
// Notify the parent <history-cluster> element of this event.
this.dispatchEvent(new CustomEvent('visit-clicked', {
bubbles: true,
composed: true,
detail: this.visit,
}));
}
private onClick_(event: MouseEvent) {
// Ignore previously handled events.
if (event.defaultPrevented) {
return;
}
event.preventDefault(); // Prevent default browser action (navigation).
// To record metrics.
this.onAuxClick_();
this.openUrl_(event);
}
private onContextMenu_(event: MouseEvent) {
// Because WebUI has a Blink-provided context menu that's suitable, and
// Side Panel always UIs always have a custom context menu.
if (!loadTimeData.getBoolean('inSidePanel')) {
return;
}
BrowserProxyImpl.getInstance().handler.showContextMenuForURL(
this.visit.normalizedUrl, {x: event.clientX, y: event.clientY});
}
private onKeydown_(e: KeyboardEvent) {
// To be consistent with <history-list>, only handle Enter, and not Space.
if (e.key !== 'Enter') {
return;
}
// To record metrics.
this.onAuxClick_();
this.openUrl_(e);
}
private onActionMenuButtonClick_(event: Event) {
this.$.actionMenu.get().showAt(this.$.actionMenuButton);
event.preventDefault(); // Prevent default browser action (navigation).
}
private onHideSelfButtonClick_(event: Event) {
this.emitMenuButtonClick_(event, 'hide-visit');
}
private onRemoveSelfButtonClick_(event: Event) {
this.emitMenuButtonClick_(event, 'remove-visit');
}
private emitMenuButtonClick_(event: Event, emitEventName: string) {
event.preventDefault(); // Prevent default browser action (navigation).
this.dispatchEvent(new CustomEvent(emitEventName, {
bubbles: true,
composed: true,
detail: this.visit,
}));
this.$.actionMenu.get().close();
}
//============================================================================
// Helper methods
//============================================================================
private computeAnnotations_(_visit: URLVisit): string[] {
// Disabling annotations until more appropriate design for annotations in
// the side panel is complete.
if (this.inSidePanel_) {
return [];
}
return this.visit.annotations
.map((annotation: number) => annotationToStringId.get(annotation))
.filter(
(id: string|undefined):
id is string => {
return !!id;
})
.map((id: string) => loadTimeData.getString(id));
}
private computeShowHideVisitMenu_(_fromPersistence: boolean): boolean {
// Show the hide menu item if the visit is hide-able and the hide icon is
// hidden.
return this.fromPersistence &&
loadTimeData.getBoolean('isHideVisitsEnabled') &&
!loadTimeData.getBoolean('isHideVisitsIconEnabled');
}
private computeShowHideVisitIcon_(_fromPersistence: boolean): boolean {
return this.fromPersistence &&
loadTimeData.getBoolean('isHideVisitsIconEnabled');
}
private computeShowActionMenuButton_(_showHideVisitMenu: boolean): boolean {
// Show the menu if either the hide or delete button is visible.
return this.showHideVisitMenu_ || this.allowDeletingHistory_;
}
private computeDebugInfo_(_visit: URLVisit): string {
if (!loadTimeData.getBoolean('isHistoryClustersDebug')) {
return '';
}
return JSON.stringify(this.visit.debugInfo);
}
private computeTitle_(_visit: URLVisit): string {
insertHighlightedTextWithMatchesIntoElement(
this.$.title, this.visit.pageTitle, this.visit.titleMatchPositions);
return this.visit.pageTitle;
}
private computeUrlForDisplay_(_visit: URLVisit): string {
insertHighlightedTextWithMatchesIntoElement(
this.$.url, this.visit.urlForDisplay,
this.visit.urlForDisplayMatchPositions);
return this.visit.urlForDisplay;
}
private openUrl_(event: MouseEvent|KeyboardEvent) {
BrowserProxyImpl.getInstance().handler.openHistoryCluster(
this.visit.normalizedUrl, {
middleButton: (event as MouseEvent).button === 1,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
});
}
}
customElements.define(VisitRowElement.is, VisitRowElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/url_visit.ts | TypeScript | unknown | 9,932 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {highlight} from 'chrome://resources/js/search_highlight_utils.js';
import {MatchPosition} from './history_cluster_types.mojom-webui.js';
/**
* Populates `container` with the highlighted `text` based on the mojom provided
* `match_positions`. This function takes care of converting from the mojom
* format to the format expected by search_highlight_utils.
*/
export function insertHighlightedTextWithMatchesIntoElement(
container: HTMLElement, text: string, matches: MatchPosition[]) {
container.textContent = '';
const node = document.createTextNode(text);
container.appendChild(node);
const ranges = [];
for (const match of matches) {
ranges.push({
start: match.begin,
length: match.end - match.begin,
});
}
if (ranges.length > 0) {
highlight(node, ranges);
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/utils.ts | TypeScript | unknown | 967 |
<style include="cr-shared-style">
:host {
--cr-localized-link-display: inline;
display: block;
}
:host([link-disabled]) {
cursor: pointer;
opacity: var(--cr-disabled-opacity);
pointer-events: none;
}
a {
display: var(--cr-localized-link-display);
}
a[href] {
color: var(--cr-link-color);
}
/**
* Prevent action-links from being selected to avoid accidental
* selection when trying to click it.
*/
a[is=action-link] {
user-select: none;
}
#container {
display: contents;
}
</style>
<!-- innerHTML is set via setContainerInnerHtml_. -->
<div id="container"></div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/localized_link/localized_link.html | HTML | unknown | 638 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'localized-link' takes a localized string that
* contains up to one anchor tag, and labels the string contained within the
* anchor tag with the entire localized string. The string should not be bound
* by element tags. The string should not contain any elements other than the
* single anchor tagged element that will be aria-labelledby the entire string.
*
* Example: "lorem ipsum <a href="example.com">Learn More</a> dolor sit"
*
* The "Learn More" will be aria-labelledby like so: "lorem ipsum Learn More
* dolor sit". Meanwhile, "Lorem ipsum" and "dolor sit" will be aria-hidden.
*
* This element also supports strings that do not contain anchor tags; in this
* case, the element gracefully falls back to normal text. This can be useful
* when the property is data-bound to a function which sometimes returns a
* string with a link and sometimes returns a normal string.
*/
import '//resources/cr_elements/cr_shared_vars.css.js';
import '//resources/cr_elements/cr_shared_style.css.js';
import {assert, assertNotReached} from '//resources/js/assert_ts.js';
import {sanitizeInnerHtml} from '//resources/js/parse_html_subset.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './localized_link.html.js';
export interface LocalizedLinkElement {
$: {
container: HTMLElement,
};
}
export class LocalizedLinkElement extends PolymerElement {
static get is() {
return 'localized-link';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* The localized string that contains up to one anchor tag, the text
* within which will be aria-labelledby the entire localizedString.
*/
localizedString: String,
/**
* If provided, the URL that the anchor tag will point to. There is no
* need to provide a linkUrl if the URL is embedded in the
* localizedString.
*/
linkUrl: {
type: String,
value: '',
},
/**
* If true, localized link will be disabled.
*/
linkDisabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: 'updateAnchorTagTabIndex_',
},
/**
* localizedString, with aria attributes and the optionally provided link.
*/
containerInnerHTML_: {
type: String,
value: '',
computed: 'getAriaLabelledContent_(localizedString, linkUrl)',
observer: 'setContainerInnerHtml_',
},
};
}
localizedString: string;
linkUrl: string;
linkDisabled: boolean;
private containerInnerHTML_: string;
/**
* Attaches aria attributes and optionally provided link to the provided
* localizedString.
* @return localizedString formatted with additional ids, spans, and an
* aria-labelledby tag
*/
private getAriaLabelledContent_(localizedString: string, linkUrl: string):
string {
const tempEl = document.createElement('div');
tempEl.innerHTML = sanitizeInnerHtml(localizedString, {attrs: ['id']});
const ariaLabelledByIds: string[] = [];
tempEl.childNodes.forEach((node, index) => {
// Text nodes should be aria-hidden and associated with an element id
// that the anchor element can be aria-labelledby.
if (node.nodeType === Node.TEXT_NODE) {
const spanNode = document.createElement('span');
spanNode.textContent = node.textContent;
spanNode.id = `id${index}`;
ariaLabelledByIds.push(spanNode.id);
spanNode.setAttribute('aria-hidden', 'true');
node.replaceWith(spanNode);
return;
}
// The single element node with anchor tags should also be aria-labelledby
// itself in-order with respect to the entire string.
if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'A') {
const element = node as HTMLAnchorElement;
element.id = `id${index}`;
ariaLabelledByIds.push(element.id);
return;
}
// Only text and <a> nodes are allowed.
assertNotReached('localized-link has invalid node types');
});
const anchorTags = tempEl.querySelectorAll('a');
// In the event the provided localizedString contains only text nodes,
// populate the contents with the provided localizedString.
if (anchorTags.length === 0) {
return localizedString;
}
assert(
anchorTags.length === 1,
'localized-link should contain exactly one anchor tag');
const anchorTag = anchorTags[0]!;
anchorTag.setAttribute('aria-labelledby', ariaLabelledByIds.join(' '));
anchorTag.tabIndex = this.linkDisabled ? -1 : 0;
if (linkUrl !== '') {
anchorTag.href = linkUrl;
anchorTag.target = '_blank';
}
return tempEl.innerHTML;
}
private setContainerInnerHtml_() {
this.$.container.innerHTML = sanitizeInnerHtml(this.containerInnerHTML_, {
attrs: [
'aria-hidden',
'aria-labelledby',
'id',
'tabindex',
],
});
const anchorTag = this.shadowRoot!.querySelector('a');
if (anchorTag) {
anchorTag.addEventListener(
'click', (event) => this.onAnchorTagClick_(event));
}
}
private onAnchorTagClick_(event: Event) {
if (this.linkDisabled) {
event.preventDefault();
return;
}
this.dispatchEvent(new CustomEvent(
'link-clicked', {bubbles: true, composed: true, detail: {event}}));
// Stop propagation of the event, since it has already been handled by
// opening the link.
event.stopPropagation();
}
/**
* Removes anchor tag from being targeted by chromeVox when link is
* disabled.
*/
private updateAnchorTagTabIndex_() {
const anchorTag = this.shadowRoot!.querySelector('a');
if (!anchorTag) {
return;
}
anchorTag.tabIndex = this.linkDisabled ? -1 : 0;
}
}
declare global {
interface HTMLElementTagNameMap {
'localized-link': LocalizedLinkElement;
}
}
customElements.define(LocalizedLinkElement.is, LocalizedLinkElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/localized_link/localized_link.ts | TypeScript | unknown | 6,291 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Minimal externs file provided for places in the code that
* still use JavaScript instead of TypeScript.
* @externs
*/
/**
* @constructor
* @extends {HTMLElement}
*/
function LocalizedLinkElement() {}
/** @type {string} */
LocalizedLinkElement.prototype.localizedString;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/localized_link/localized_link_externs.js | JavaScript | unknown | 425 |
<style>
iron-icon {
--iron-icon-height: var(--cr-icon-size);
--iron-icon-width: var(--cr-icon-size);
padding-inline-end: 10px;
}
cr-dialog::part(body-container) {
padding-inline-start: 35px;
}
</style>
<cr-dialog id="dialog" close-text="[[i18n('close')]]" show-on-attach>
<div slot="title">
<iron-icon icon="cr:domain" role="img"
aria-label="[[i18n('controlledSettingPolicy')]]">
</iron-icon>
[[title]]
</div>
<div slot="body">[[body]]</div>
<div slot="button-container">
<cr-button class="action-button" on-click="onOkClick_">
[[i18n('ok')]]
</cr-button>
</div>
</cr-dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/managed_dialog/managed_dialog.html | HTML | unknown | 646 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'managed-dialog' is a dialog that is displayed when a user
* interact with some UI features which are managed by the user's organization.
*/
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import 'chrome://resources/cr_elements/cr_shared_vars.css.js';
import 'chrome://resources/cr_elements/icons.html.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './managed_dialog.html.js';
export interface ManagedDialogElement {
$: {
dialog: CrDialogElement,
};
}
const ManagedDialogElementBase = I18nMixin(PolymerElement);
export class ManagedDialogElement extends ManagedDialogElementBase {
static get is() {
return 'managed-dialog';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/** Managed dialog title text. */
title: String,
/** Managed dialog body text. */
body: String,
};
}
override title: string;
body: string;
private onOkClick_() {
this.$.dialog.close();
}
}
declare global {
interface HTMLElementTagNameMap {
'managed-dialog': ManagedDialogElement;
}
}
customElements.define(ManagedDialogElement.is, ManagedDialogElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/managed_dialog/managed_dialog.ts | TypeScript | unknown | 1,705 |
<style>
:host {
align-items: center;
border-top: 1px solid var(--cr-separator-color);
color: var(--cr-secondary-text-color);
display: none;
/* Should be 13px when <html> font-size is 16px */
font-size: 0.8125rem;
justify-content: center;
padding: 0 24px;
}
:host([is-managed_]) {
display: flex;
}
a[href] {
color: var(--cr-link-color);
}
iron-icon {
align-self: flex-start;
flex-shrink: 0;
height: 20px;
padding-inline-end: var(--managed-footnote-icon-padding, 8px);
width: 20px;
}
</style>
<template is="dom-if" if="[[isManaged_]]">
<iron-icon icon="cr:domain"></iron-icon>
<div id="content"
inner-h-t-m-l="[[getManagementString_(showDeviceInfo)]]">
</div>
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/managed_footnote/managed_footnote.html | HTML | unknown | 886 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Polymer element for indicating that this user is managed by
* their organization. This component uses the |isManaged| boolean in
* loadTimeData, and the |managedByOrg| i18n string.
*
* If |isManaged| is false, this component is hidden. If |isManaged| is true, it
* becomes visible.
*/
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import '//resources/polymer/v3_0/paper-styles/color.js';
import '//resources/cr_elements/icons.html.js';
import '//resources/cr_elements/cr_shared_vars.css.js';
import {I18nMixin} from '//resources/cr_elements/i18n_mixin.js';
import {WebUiListenerMixin} from '//resources/cr_elements/web_ui_listener_mixin.js';
import {loadTimeData} from '//resources/js/load_time_data.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './managed_footnote.html.js';
const ManagedFootnoteElementBase =
I18nMixin(WebUiListenerMixin(PolymerElement));
export class ManagedFootnoteElement extends ManagedFootnoteElementBase {
static get is() {
return 'managed-footnote';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* Whether the user is managed by their organization through enterprise
* policies.
*/
isManaged_: {
reflectToAttribute: true,
type: Boolean,
value() {
return loadTimeData.getBoolean('isManaged');
},
},
/**
* Whether the device should be indicated as managed rather than the
* browser.
*/
showDeviceInfo: {
type: Boolean,
value: false,
},
};
}
private isManaged_: boolean;
showDeviceInfo: boolean;
override ready() {
super.ready();
this.addWebUiListener('is-managed-changed', (managed: boolean) => {
loadTimeData.overrideValues({isManaged: managed});
this.isManaged_ = managed;
});
}
/** @return Message to display to the user. */
private getManagementString_(): TrustedHTML {
// <if expr="chromeos_ash">
if (this.showDeviceInfo) {
return this.i18nAdvanced('deviceManagedByOrg');
}
// </if>
return this.i18nAdvanced('browserManagedByOrg');
}
}
declare global {
interface HTMLElementTagNameMap {
'managed-footnote': ManagedFootnoteElement;
}
}
customElements.define(ManagedFootnoteElement.is, ManagedFootnoteElement);
chrome.send('observeManagedUI');
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/managed_footnote/managed_footnote.ts | TypeScript | unknown | 2,624 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {MostVisitedPageCallbackRouter, MostVisitedPageHandlerFactory, MostVisitedPageHandlerRemote} from './most_visited.mojom-webui.js';
export class MostVisitedBrowserProxy {
handler: MostVisitedPageHandlerRemote;
callbackRouter: MostVisitedPageCallbackRouter;
constructor(
handler: MostVisitedPageHandlerRemote,
callbackRouter: MostVisitedPageCallbackRouter) {
this.handler = handler;
this.callbackRouter = callbackRouter;
}
static getInstance(): MostVisitedBrowserProxy {
if (instance) {
return instance;
}
const callbackRouter = new MostVisitedPageCallbackRouter();
const handler = new MostVisitedPageHandlerRemote();
const factory = MostVisitedPageHandlerFactory.getRemote();
factory.createPageHandler(
callbackRouter.$.bindNewPipeAndPassRemote(),
handler.$.bindNewPipeAndPassReceiver());
instance = new MostVisitedBrowserProxy(handler, callbackRouter);
return instance;
}
static setInstance(obj: MostVisitedBrowserProxy) {
instance = obj;
}
}
let instance: MostVisitedBrowserProxy|null = null;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/most_visited/browser_proxy.ts | TypeScript | unknown | 1,244 |
<style include="cr-hidden-style cr-icons">
:host {
--icon-button-color-active: var(--google-grey-700);
--icon-button-color: var(--google-grey-600);
--icon-size: 48px;
--tile-background-color: rgb(229, 231, 232);
--tile-hover-color: rgba(var(--google-grey-900-rgb), .1);
--tile-size: 112px;
--title-height: 32px;
}
@media (prefers-color-scheme: dark) {
:host {
--tile-background-color: var(--google-grey-100);
}
}
:host([is-dark_]) {
--icon-button-color-active: var(--google-grey-300);
--icon-button-color: white;
--tile-hover-color: rgba(255, 255, 255, .1);
}
#container {
--content-width: calc(var(--column-count) * var(--tile-size)
/* We add an extra pixel because rounding errors on different zooms can
* make the width shorter than it should be. */
+ 1px);
display: flex;
flex-wrap: wrap;
height: calc(var(--row-count) * var(--tile-size));
justify-content: center;
margin-bottom: 8px;
opacity: 0;
overflow: hidden;
padding: 2px; /* Padding added so focus rings are not clipped. */
transition: opacity 300ms ease-in-out;
width: calc(var(--content-width) + 12px);
}
:host([visible_]) #container {
opacity: 1;
}
#addShortcutIcon,
.query-tile-icon {
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 100%;
height: 24px;
width: 24px;
}
#addShortcutIcon {
-webkit-mask-image: url(chrome://resources/images/add.svg);
background-color: var(--google-grey-900);
}
.query-tile-icon {
-webkit-mask-image: url(chrome://resources/images/icon_search.svg);
background-color: var(--google-grey-700);
}
@media (forced-colors: active) {
#addShortcutIcon,
.query-tile-icon {
background-color: ButtonText;
}
}
:host([use-white-tile-icon_]) #addShortcutIcon {
background-color: white;
}
:host([use-white-tile-icon_]) .query-tile-icon {
background-color: var(--google-grey-400);
}
.tile,
#addShortcut {
-webkit-tap-highlight-color: transparent;
align-items: center;
border-radius: 4px;
box-sizing: border-box;
cursor: pointer;
display: flex;
flex-direction: column;
height: var(--tile-size);
opacity: 1;
outline: none;
position: relative;
text-decoration: none;
transition-duration: 300ms;
transition-property: left, top;
transition-timing-function: ease-in-out;
user-select: none;
width: var(--tile-size);
}
.tile {
touch-action: none;
}
:host-context(.focus-outline-visible) .tile:focus,
:host-context(.focus-outline-visible) #addShortcut:focus {
box-shadow: var(--most-visited-focus-shadow);
}
@media (forced-colors: active) {
:host-context(.focus-outline-visible) .tile:focus,
:host-context(.focus-outline-visible) #addShortcut:focus {
/* Use outline instead of box-shadow (which does not work) in Windows
HCM. */
outline: var(--cr-focus-outline-hcm);
}
}
#addShortcut {
background-color: transparent;
border: none;
box-shadow: none;
justify-content: unset;
padding: 0;
}
:host(:not([reordering_])) .tile:hover,
:host(:not([reordering_])) #addShortcut:hover,
.force-hover {
background-color: var(--tile-hover-color);
}
.tile-icon {
align-items: center;
background-color: var(--tile-background-color);
border-radius: 50%;
display: flex;
flex-shrink: 0;
height: var(--icon-size);
justify-content: center;
margin-top: 16px;
width: var(--icon-size);
}
.tile-icon img {
height: 24px;
width: 24px;
}
.tile-title {
align-items: center;
border-radius: calc(var(--title-height) / 2 + 2px);
color: var(--most-visited-text-color);
display: flex;
height: var(--title-height);
line-height: calc(var(--title-height) / 2);
margin-top: 6px;
padding: 2px 8px;
width: 88px;
}
:host([use-title-pill_]) .tile-title {
background-color: white;
color: var(--google-grey-800);
}
.tile-title span {
font-weight: 400;
overflow: hidden;
text-align: center;
text-overflow: ellipsis;
text-shadow: var(--most-visited-text-shadow);
white-space: nowrap;
width: 100%;
}
.tile[query-tile] .tile-title span {
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
display: -webkit-box;
white-space: initial;
}
:host([use-title-pill_]) .tile-title span {
text-shadow: none;
}
.title-rtl {
direction: rtl;
}
.title-ltr {
direction: ltr;
}
.tile.dragging {
background-color: var(--tile-hover-color);
transition-property: none;
z-index: 2;
}
cr-icon-button {
--cr-icon-button-fill-color: var(--icon-button-color);
--cr-icon-button-size: 28px;
--cr-icon-button-transition: none;
margin: 4px 2px;
opacity: 0;
position: absolute;
right: 0;
top: 0;
transition: opacity 100ms ease-in-out;
}
:host-context([dir=rtl]) cr-icon-button {
left: 0;
right: unset;
}
:host(:not([reordering_])) .tile:hover cr-icon-button,
.force-hover cr-icon-button {
opacity: 1;
transition-delay: 400ms;
}
:host(:not([reordering_])) cr-icon-button:active,
:host-context(.focus-outline-visible):host(:not([reordering_]))
cr-icon-button:focus,
:host(:not([reordering_])) cr-icon-button:hover {
--cr-icon-button-fill-color: var(--icon-button-color-active);
opacity: 1;
transition-delay: 0s;
}
</style>
<div id="container" hidden$="[[!visible_]]"
style="--tile-background-color: [[rgbaOrInherit_(theme.backgroundColor)]];
--column-count: [[columnCount_]]; --row-count: [[rowCount_]];">
<dom-repeat id="tiles" items="[[tiles_]]" on-dom-change="onTilesRendered_">
<template>
<a class="tile" href$="[[item.url.url]]" title$="[[item.title]]"
aria-label="[[item.title]]" on-dragstart="onDragStart_"
on-touchstart="onTouchStart_" hidden$="[[isHidden_(index, maxVisibleTiles_)]]"
on-click="onTileClick_" on-keydown="onTileKeyDown_"
query-tile$="[[item.isQueryTile]]">
<cr-icon-button id="actionMenuButton" class="icon-more-vert"
title="[[i18n('moreActions')]]" on-click="onTileActionButtonClick_"
tabindex="0" hidden$="[[!customLinksEnabled_]]"></cr-icon-button>
<cr-icon-button id="removeButton" class="icon-clear"
title="[[i18n('linkRemove')]]" on-click="onTileRemoveButtonClick_"
tabindex="0" hidden$="[[customLinksEnabled_]]"></cr-icon-button>
<div class="tile-icon">
<img src$="[[getFaviconUrl_(item.url)]]" draggable="false"
hidden$="[[item.isQueryTile]]" alt=""></img>
<div class="query-tile-icon" draggable="false"
hidden$="[[!item.isQueryTile]]"></div>
</div>
<div class$="tile-title [[getTileTitleDirectionClass_(item)]]">
<span>[[item.title]]</span>
</div>
</a>
</template>
</dom-repeat>
<cr-button id="addShortcut" tabindex="0" on-click="onAdd_"
hidden$="[[!showAdd_]]" on-keydown="onAddShortcutKeyDown_"
aria-label="[[i18n('addLinkTitle')]]" title="[[i18n('addLinkTitle')]]" noink>
<div class="tile-icon">
<div id="addShortcutIcon" draggable="false"></div>
</div>
<div class="tile-title">
<span>[[i18n('addLinkTitle')]]</span>
</div>
</cr-button>
<cr-dialog id="dialog" on-close="onDialogClose_">
<div slot="title">[[dialogTitle_]]</div>
<div slot="body">
<cr-input id="dialogInputName" label="[[i18n('nameField')]]"
value="{{dialogTileTitle_}}" spellcheck="false" autofocus></cr-input>
<cr-input id="dialogInputUrl" label="[[i18n('urlField')]]"
value="{{dialogTileUrl_}}" invalid="[[dialogTileUrlInvalid_]]"
error-message="[[dialogTileUrlError_]]" spellcheck="false" type="url"
on-blur="onDialogTileUrlBlur_">
</cr-input>
</div>
<div slot="button-container">
<cr-button class="cancel-button" on-click="onDialogCancel_">
[[i18n('linkCancel')]]
</cr-button>
<cr-button class="action-button" on-click="onSave_"
disabled$="[[dialogSaveDisabled_]]">
[[i18n('linkDone')]]
</cr-button>
</div>
</cr-dialog>
<cr-action-menu id="actionMenu">
<button id="actionMenuEdit" class="dropdown-item" on-click="onEdit_">
[[i18n('editLinkTitle')]]
</button>
<button id="actionMenuRemove" class="dropdown-item" on-click="onRemove_">
[[i18n('linkRemove')]]
</button>
</cr-action-menu>
</div>
<cr-toast id="toast" duration="10000">
<div>[[toastContent_]]</div>
<dom-if if="[[showToastButtons_]]">
<template>
<cr-button id="undo" aria-label="[[i18n('undoDescription')]]"
on-click="onUndoClick_">
[[i18n('undo')]]
</cr-button>
<cr-button id="restore"
aria-label$="[[getRestoreButtonText_(customLinksEnabled_)]]"
on-click="onRestoreDefaultsClick_">
[[getRestoreButtonText_(customLinksEnabled_)]]
</cr-button>
</template>
</dom-if>
</cr-toast>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/most_visited/most_visited.html | HTML | unknown | 9,170 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.js';
import 'chrome://resources/cr_elements/cr_icons.css.js';
import 'chrome://resources/cr_elements/cr_input/cr_input.js';
import 'chrome://resources/cr_elements/cr_toast/cr_toast.js';
import 'chrome://resources/cr_elements/cr_hidden_style.css.js';
import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {CrToastElement} from 'chrome://resources/cr_elements/cr_toast/cr_toast.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {assert} from 'chrome://resources/js/assert_ts.js';
import {skColorToRgba} from 'chrome://resources/js/color_utils.js';
import {EventTracker} from 'chrome://resources/js/event_tracker.js';
import {FocusOutlineManager} from 'chrome://resources/js/focus_outline_manager.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {isMac} from 'chrome://resources/js/platform.js';
import {hasKeyModifiers} from 'chrome://resources/js/util_ts.js';
import {TextDirection} from 'chrome://resources/mojo/mojo/public/mojom/base/text_direction.mojom-webui.js';
import {SkColor} from 'chrome://resources/mojo/skia/public/mojom/skcolor.mojom-webui.js';
import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js';
import {DomRepeat, DomRepeatEvent, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {MostVisitedBrowserProxy} from './browser_proxy.js';
import {getTemplate} from './most_visited.html.js';
import {MostVisitedInfo, MostVisitedPageCallbackRouter, MostVisitedPageHandlerRemote, MostVisitedTheme, MostVisitedTile} from './most_visited.mojom-webui.js';
import {MostVisitedWindowProxy} from './window_proxy.js';
function resetTilePosition(tile: HTMLElement) {
tile.style.position = '';
tile.style.left = '';
tile.style.top = '';
}
function setTilePosition(tile: HTMLElement, {x, y}: {x: number, y: number}) {
tile.style.position = 'fixed';
tile.style.left = `${x}px`;
tile.style.top = `${y}px`;
}
function getHitIndex(rects: DOMRect[], x: number, y: number): number {
return rects.findIndex(
r => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom);
}
/**
* Returns null if URL is not valid.
*/
function normalizeUrl(urlString: string): URL|null {
try {
const url = new URL(
urlString.includes('://') ? urlString : `https://${urlString}/`);
if (['http:', 'https:'].includes(url.protocol)) {
return url;
}
} catch (e) {
}
return null;
}
const MostVisitedElementBase = I18nMixin(PolymerElement);
export interface MostVisitedElement {
$: {
actionMenu: CrActionMenuElement,
container: HTMLElement,
dialog: CrDialogElement,
toast: CrToastElement,
addShortcut: HTMLElement,
tiles: DomRepeat,
};
}
export class MostVisitedElement extends MostVisitedElementBase {
static get is() {
return 'cr-most-visited';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
theme: Object,
/**
* If true, renders MV tiles in a single row up to 10 columns wide.
* If false, renders MV tiles in up to 2 rows up to 5 columns wide.
*/
singleRow: {
type: Boolean,
value: false,
observer: 'onSingleRowChange_',
},
/**
* When the tile icon background is dark, the icon color is white for
* contrast. This can be used to determine the color of the tile hover as
* well.
*/
useWhiteTileIcon_: {
type: Boolean,
reflectToAttribute: true,
computed: `computeUseWhiteTileIcon_(theme)`,
},
/**
* If true wraps the tile titles in white pills.
*/
useTitlePill_: {
type: Boolean,
reflectToAttribute: true,
computed: `computeUseTitlePill_(theme)`,
},
columnCount_: {
type: Number,
computed:
`computeColumnCount_(singleRow, tiles_, maxVisibleColumnCount_, maxTiles_)`,
},
rowCount_: {
type: Number,
computed: 'computeRowCount_(singleRow, columnCount_, tiles_)',
},
customLinksEnabled_: {
type: Boolean,
reflectToAttribute: true,
},
dialogTileTitle_: String,
dialogTileUrl_: {
type: String,
observer: 'onDialogTileUrlChange_',
},
dialogTileUrlInvalid_: {
type: Boolean,
value: false,
},
dialogTitle_: String,
dialogSaveDisabled_: {
type: Boolean,
computed: `computeDialogSaveDisabled_(dialogTitle_, dialogTileUrl_,
dialogShortcutAlreadyExists_)`,
},
dialogShortcutAlreadyExists_: {
type: Boolean,
computed: 'computeDialogShortcutAlreadyExists_(tiles_, dialogTileUrl_)',
},
dialogTileUrlError_: {
type: String,
computed: `computeDialogTileUrlError_(dialogTileUrl_,
dialogShortcutAlreadyExists_)`,
},
isDark_: {
type: Boolean,
reflectToAttribute: true,
computed: `computeIsDark_(theme)`,
},
/**
* Used to hide hover style and cr-icon-button of tiles while the tiles
* are being reordered.
*/
reordering_: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
maxTiles_: {
type: Number,
computed: 'computeMaxTiles_(customLinksEnabled_)',
},
maxVisibleTiles_: {
type: Number,
computed: 'computeMaxVisibleTiles_(columnCount_, rowCount_)',
},
showAdd_: {
type: Boolean,
value: false,
computed:
'computeShowAdd_(tiles_, maxVisibleTiles_, customLinksEnabled_)',
},
showToastButtons_: Boolean,
maxVisibleColumnCount_: Number,
tiles_: Array,
toastContent_: String,
visible_: {
type: Boolean,
reflectToAttribute: true,
},
};
}
public theme: MostVisitedTheme|null;
public singleRow: boolean;
private useWhiteTileIcon_: boolean;
private useTitlePill_: boolean;
private columnCount_: number;
private rowCount_: number;
private customLinksEnabled_: boolean;
private dialogTileTitle_: string;
private dialogTileUrl_: string;
private dialogTileUrlInvalid_: boolean;
private dialogTitle_: string;
private dialogSaveDisabled_: boolean;
private dialogShortcutAlreadyExists_: boolean;
private dialogTileUrlError_: string;
private isDark_: boolean;
private reordering_: boolean;
private maxTiles_: number;
private maxVisibleTiles_: number;
private showAdd_: boolean;
private showToastButtons_: boolean;
private maxVisibleColumnCount_: number;
private tiles_: MostVisitedTile[];
private toastContent_: string;
private visible_: boolean;
private adding_: boolean = false;
private callbackRouter_: MostVisitedPageCallbackRouter;
private pageHandler_: MostVisitedPageHandlerRemote;
private windowProxy_: MostVisitedWindowProxy;
private setMostVisitedInfoListenerId_: number|null = null;
private actionMenuTargetIndex_: number = -1;
private dragOffset_: {x: number, y: number}|null;
private tileRects_: DOMRect[] = [];
private isRtl_: boolean;
private mediaEventTracker_: EventTracker;
private eventTracker_: EventTracker;
private boundOnDocumentKeyDown_: (e: KeyboardEvent) => void;
private get tileElements_() {
return Array.from(
this.shadowRoot!.querySelectorAll<HTMLElement>('.tile:not([hidden])'));
}
// Suppress TypeScript's error TS2376 to intentionally allow calling
// performance.mark() before calling super().
// @ts-ignore
constructor() {
performance.mark('most-visited-creation-start');
super();
this.callbackRouter_ = MostVisitedBrowserProxy.getInstance().callbackRouter;
this.pageHandler_ = MostVisitedBrowserProxy.getInstance().handler;
this.windowProxy_ = MostVisitedWindowProxy.getInstance();
/**
* This is the position of the mouse with respect to the top-left corner
* of the tile being dragged.
*/
this.dragOffset_ = null;
this.mediaEventTracker_ = new EventTracker();
this.eventTracker_ = new EventTracker();
}
override connectedCallback() {
super.connectedCallback();
this.isRtl_ = window.getComputedStyle(this)['direction'] === 'rtl';
this.onSingleRowChange_();
this.setMostVisitedInfoListenerId_ =
this.callbackRouter_.setMostVisitedInfo.addListener(
(info: MostVisitedInfo) => {
performance.measure(
'most-visited-mojo', 'most-visited-mojo-start');
this.visible_ = info.visible;
this.customLinksEnabled_ = info.customLinksEnabled;
assert(this.maxTiles_);
this.tiles_ = info.tiles.slice(0, this.maxTiles_);
});
performance.mark('most-visited-mojo-start');
this.eventTracker_.add(document, 'visibilitychange', () => {
// This updates the most visited tiles every time the NTP tab gets
// activated.
if (document.visibilityState === 'visible') {
this.pageHandler_.updateMostVisitedInfo();
}
});
this.pageHandler_.updateMostVisitedInfo();
FocusOutlineManager.forDocument(document);
}
override disconnectedCallback() {
super.disconnectedCallback();
this.mediaEventTracker_.removeAll();
this.eventTracker_.removeAll();
this.ownerDocument.removeEventListener(
'keydown', this.boundOnDocumentKeyDown_);
}
override ready() {
super.ready();
this.boundOnDocumentKeyDown_ = e => this.onDocumentKeyDown_(e);
this.ownerDocument.addEventListener(
'keydown', this.boundOnDocumentKeyDown_);
performance.measure('most-visited-creation', 'most-visited-creation-start');
}
private rgbaOrInherit_(skColor: SkColor|null): string {
return skColor ? skColorToRgba(skColor) : 'inherit';
}
private clearForceHover_() {
const forceHover = this.shadowRoot!.querySelector('.force-hover');
if (forceHover) {
forceHover.classList.remove('force-hover');
}
}
private computeColumnCount_(): number {
const shortcutCount = this.tiles_ ? this.tiles_.length : 0;
const canShowAdd = this.maxTiles_ > shortcutCount;
const tileCount =
Math.min(this.maxTiles_, shortcutCount + (canShowAdd ? 1 : 0));
const columnCount = tileCount <= this.maxVisibleColumnCount_ ?
tileCount :
Math.min(
this.maxVisibleColumnCount_,
Math.ceil(tileCount / (this.singleRow ? 1 : 2)));
return columnCount || 3;
}
private computeRowCount_(): number {
if (this.columnCount_ === 0) {
return 0;
}
if (this.singleRow) {
return 1;
}
const shortcutCount = this.tiles_ ? this.tiles_.length : 0;
return this.columnCount_ <= shortcutCount ? 2 : 1;
}
private computeMaxTiles_(): number {
return this.customLinksEnabled_ ? 10 : 8;
}
private computeMaxVisibleTiles_(): number {
return this.columnCount_ * this.rowCount_;
}
private computeShowAdd_(): boolean {
return this.customLinksEnabled_ && this.tiles_ &&
this.tiles_.length < this.maxVisibleTiles_;
}
private computeDialogSaveDisabled_(): boolean {
return !this.dialogTileUrl_.trim() ||
normalizeUrl(this.dialogTileUrl_) === null ||
this.dialogShortcutAlreadyExists_;
}
private computeDialogShortcutAlreadyExists_(): boolean {
const dialogTileHref = (normalizeUrl(this.dialogTileUrl_) || {}).href;
if (!dialogTileHref) {
return false;
}
return (this.tiles_ || []).some(({url: {url}}, index) => {
if (index === this.actionMenuTargetIndex_) {
return false;
}
const otherUrl = normalizeUrl(url);
return otherUrl && otherUrl.href === dialogTileHref;
});
}
private computeDialogTileUrlError_(): string {
return loadTimeData.getString(
this.dialogShortcutAlreadyExists_ ? 'shortcutAlreadyExists' :
'invalidUrl');
}
private computeIsDark_(): boolean {
return this.theme ? this.theme.isDark : false;
}
private computeUseWhiteTileIcon_(): boolean {
return this.theme ? this.theme.useWhiteTileIcon : false;
}
private computeUseTitlePill_(): boolean {
return this.theme ? this.theme.useTitlePill : false;
}
/**
* If a pointer is over a tile rect that is different from the one being
* dragged, the dragging tile is moved to the new position. The reordering
* is done in the DOM and the by the |reorderMostVisitedTile()| call. This is
* done to prevent flicking between the time when the tiles are moved back to
* their original positions (by removing position absolute) and when the
* tiles are updated via a |setMostVisitedTiles()| call.
*
* |reordering_| is not set to false when the tiles are reordered. The callers
* will need to set it to false. This is necessary to handle a mouse drag
* issue.
*/
private dragEnd_(x: number, y: number) {
if (!this.customLinksEnabled_) {
this.reordering_ = false;
return;
}
this.dragOffset_ = null;
const dragElement =
this.shadowRoot!.querySelector<HTMLElement>('.tile.dragging');
if (!dragElement) {
this.reordering_ = false;
return;
}
const dragIndex = (this.$.tiles.modelForElement(dragElement) as unknown as {
index: number,
}).index;
dragElement.classList.remove('dragging');
this.tileElements_.forEach(el => resetTilePosition(el));
resetTilePosition(this.$.addShortcut);
const dropIndex = getHitIndex(this.tileRects_, x, y);
if (dragIndex !== dropIndex && dropIndex > -1) {
const [draggingTile] = this.tiles_.splice(dragIndex, 1);
this.tiles_.splice(dropIndex, 0, draggingTile);
this.notifySplices('tiles_', [
{
index: dragIndex,
removed: [draggingTile],
addedCount: 0,
object: this.tiles_,
type: 'splice',
},
{
index: dropIndex,
removed: [],
addedCount: 1,
object: this.tiles_,
type: 'splice',
},
]);
this.pageHandler_.reorderMostVisitedTile(draggingTile.url, dropIndex);
}
}
/**
* The positions of the tiles are updated based on the location of the
* pointer.
*/
private dragOver_(x: number, y: number) {
const dragElement =
this.shadowRoot!.querySelector<HTMLElement>('.tile.dragging');
if (!dragElement) {
this.reordering_ = false;
return;
}
const dragIndex = (this.$.tiles.modelForElement(dragElement) as unknown as {
index: number,
}).index;
setTilePosition(dragElement, {
x: x - this.dragOffset_!.x,
y: y - this.dragOffset_!.y,
});
const dropIndex = getHitIndex(this.tileRects_, x, y);
this.tileElements_.forEach((element, i) => {
let positionIndex;
if (i === dragIndex) {
return;
} else if (dropIndex === -1) {
positionIndex = i;
} else if (dragIndex < dropIndex && dragIndex <= i && i <= dropIndex) {
positionIndex = i - 1;
} else if (dragIndex > dropIndex && dragIndex >= i && i >= dropIndex) {
positionIndex = i + 1;
} else {
positionIndex = i;
}
setTilePosition(element, this.tileRects_[positionIndex]);
});
}
/**
* Sets up tile reordering for both drag and touch events. This method stores
* the following to be used in |dragOver_()| and |dragEnd_()|.
* |dragOffset_|: This is the mouse/touch offset with respect to the
* top/left corner of the tile being dragged. It is used to update the
* dragging tile location during the drag.
* |reordering_|: This is property/attribute used to hide the hover style
* and cr-icon-button of the tiles while they are being reordered.
* |tileRects_|: This is the rects of the tiles before the drag start. It is
* to determine which tile the pointer is over while dragging.
*/
private dragStart_(dragElement: HTMLElement, x: number, y: number) {
// Need to clear the tile that has a forced hover style for when the drag
// started without moving the mouse after the last drag/drop.
this.clearForceHover_();
dragElement.classList.add('dragging');
const dragElementRect = dragElement.getBoundingClientRect();
this.dragOffset_ = {
x: x - dragElementRect.x,
y: y - dragElementRect.y,
};
const tileElements = this.tileElements_;
// Get all the rects first before setting the absolute positions.
this.tileRects_ = tileElements.map(t => t.getBoundingClientRect());
if (this.showAdd_) {
const element = this.$.addShortcut;
setTilePosition(element, element.getBoundingClientRect());
}
tileElements.forEach((tile, i) => {
setTilePosition(tile, this.tileRects_[i]);
});
this.reordering_ = true;
}
private getFaviconUrl_(url: Url): string {
const faviconUrl = new URL('chrome://favicon2/');
faviconUrl.searchParams.set('size', '24');
faviconUrl.searchParams.set('scaleFactor', '1x');
faviconUrl.searchParams.set('showFallbackMonogram', '');
faviconUrl.searchParams.set('pageUrl', url.url);
return faviconUrl.href;
}
private getRestoreButtonText_(): string {
return loadTimeData.getString(
this.customLinksEnabled_ ? 'restoreDefaultLinks' :
'restoreThumbnailsShort');
}
private getTileTitleDirectionClass_(tile: MostVisitedTile): string {
return tile.titleDirection === TextDirection.RIGHT_TO_LEFT ? 'title-rtl' :
'title-ltr';
}
private isHidden_(index: number): boolean {
return index >= this.maxVisibleTiles_;
}
private onSingleRowChange_() {
if (!this.isConnected) {
return;
}
this.mediaEventTracker_.removeAll();
const queryLists: MediaQueryList[] = [];
const updateCount = () => {
const index = queryLists.findIndex(listener => listener.matches);
this.maxVisibleColumnCount_ =
3 + (index > -1 ? queryLists.length - index : 0);
};
const maxColumnCount = this.singleRow ? 10 : 5;
for (let i = maxColumnCount; i >= 4; i--) {
const query = `(min-width: ${112 * (i + 1)}px)`;
const queryList = this.windowProxy_.matchMedia(query);
this.mediaEventTracker_.add(queryList, 'change', updateCount);
queryLists.push(queryList);
}
updateCount();
}
private onAdd_() {
this.dialogTitle_ = loadTimeData.getString('addLinkTitle');
this.dialogTileTitle_ = '';
this.dialogTileUrl_ = '';
this.dialogTileUrlInvalid_ = false;
this.adding_ = true;
this.$.dialog.showModal();
}
private onAddShortcutKeyDown_(e: KeyboardEvent) {
if (hasKeyModifiers(e)) {
return;
}
if (!this.tiles_ || this.tiles_.length === 0) {
return;
}
const backKey = this.isRtl_ ? 'ArrowRight' : 'ArrowLeft';
if (e.key === backKey || e.key === 'ArrowUp') {
this.tileFocus_(this.tiles_.length - 1);
}
}
private onDialogCancel_() {
this.actionMenuTargetIndex_ = -1;
this.$.dialog.cancel();
}
private onDialogClose_() {
this.dialogTileUrl_ = '';
if (this.adding_) {
this.$.addShortcut.focus();
}
this.adding_ = false;
}
private onDialogTileUrlBlur_() {
if (this.dialogTileUrl_.length > 0 &&
(normalizeUrl(this.dialogTileUrl_) === null ||
this.dialogShortcutAlreadyExists_)) {
this.dialogTileUrlInvalid_ = true;
}
}
private onDialogTileUrlChange_() {
this.dialogTileUrlInvalid_ = false;
}
private onDocumentKeyDown_(e: KeyboardEvent) {
if (e.altKey || e.shiftKey) {
return;
}
const modifier = isMac ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;
if (modifier && e.key === 'z') {
e.preventDefault();
this.onUndoClick_();
}
}
private onDragStart_(e: DragEvent) {
if (!this.customLinksEnabled_) {
return;
}
// |dataTransfer| is null in tests.
if (e.dataTransfer) {
// Remove the ghost image that appears when dragging.
e.dataTransfer.setDragImage(new Image(), 0, 0);
}
this.dragStart_(e.target as HTMLElement, e.x, e.y);
const dragOver = (e: DragEvent) => {
e.preventDefault();
e.dataTransfer!.dropEffect = 'move';
this.dragOver_(e.x, e.y);
};
this.ownerDocument.addEventListener('dragover', dragOver);
this.ownerDocument.addEventListener('dragend', e => {
this.ownerDocument.removeEventListener('dragover', dragOver);
this.dragEnd_(e.x, e.y);
const dropIndex = getHitIndex(this.tileRects_, e.x, e.y);
if (dropIndex !== -1) {
this.tileElements_[dropIndex].classList.add('force-hover');
}
this.addEventListener('pointermove', () => {
this.clearForceHover_();
// When |reordering_| is true, the normal hover style is not shown.
// After a drop, the element that has hover is not correct. It will be
// after the mouse moves.
this.reordering_ = false;
}, {once: true});
}, {once: true});
}
private onEdit_() {
this.$.actionMenu.close();
this.dialogTitle_ = loadTimeData.getString('editLinkTitle');
const tile = this.tiles_[this.actionMenuTargetIndex_];
this.dialogTileTitle_ = tile.title;
this.dialogTileUrl_ = tile.url.url;
this.dialogTileUrlInvalid_ = false;
this.$.dialog.showModal();
}
private onRestoreDefaultsClick_() {
if (!this.$.toast.open || !this.showToastButtons_) {
return;
}
this.$.toast.hide();
this.pageHandler_.restoreMostVisitedDefaults();
}
private async onRemove_() {
this.$.actionMenu.close();
await this.tileRemove_(this.actionMenuTargetIndex_);
this.actionMenuTargetIndex_ = -1;
}
private async onSave_() {
const newUrl = {url: normalizeUrl(this.dialogTileUrl_)!.href};
this.$.dialog.close();
let newTitle = this.dialogTileTitle_.trim();
if (newTitle.length === 0) {
newTitle = this.dialogTileUrl_;
}
if (this.adding_) {
const {success} =
await this.pageHandler_.addMostVisitedTile(newUrl, newTitle);
this.toast_(success ? 'linkAddedMsg' : 'linkCantCreate', success);
} else {
const {url, title} = this.tiles_[this.actionMenuTargetIndex_];
if (url.url !== newUrl.url || title !== newTitle) {
const {success} = await this.pageHandler_.updateMostVisitedTile(
url, newUrl, newTitle);
this.toast_(success ? 'linkEditedMsg' : 'linkCantEdit', success);
}
this.actionMenuTargetIndex_ = -1;
}
}
private onTileActionButtonClick_(e: DomRepeatEvent<MostVisitedTile>) {
e.preventDefault();
this.actionMenuTargetIndex_ = e.model.index;
this.$.actionMenu.showAt(e.target as HTMLElement);
}
private onTileRemoveButtonClick_(e: DomRepeatEvent<MostVisitedTile>) {
e.preventDefault();
this.tileRemove_(e.model.index);
}
private onTileClick_(e: DomRepeatEvent<MostVisitedTile, MouseEvent>) {
if (e.defaultPrevented) {
// Ignore previousely handled events.
return;
}
if (loadTimeData.getBoolean('handleMostVisitedNavigationExplicitly')) {
e.preventDefault(); // Prevents default browser action (navigation).
}
this.pageHandler_.onMostVisitedTileNavigation(
e.model.item, e.model.index, e.button || 0, e.altKey, e.ctrlKey,
e.metaKey, e.shiftKey);
}
private onTileKeyDown_(e: DomRepeatEvent<MostVisitedTile, KeyboardEvent>) {
if (hasKeyModifiers(e)) {
return;
}
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight' &&
e.key !== 'ArrowUp' && e.key !== 'ArrowDown' && e.key !== 'Delete') {
return;
}
const index = e.model.index;
if (e.key === 'Delete') {
this.tileRemove_(index);
return;
}
const advanceKey = this.isRtl_ ? 'ArrowLeft' : 'ArrowRight';
const delta = (e.key === advanceKey || e.key === 'ArrowDown') ? 1 : -1;
this.tileFocus_(Math.max(0, index + delta));
}
private onUndoClick_() {
if (!this.$.toast.open || !this.showToastButtons_) {
return;
}
this.$.toast.hide();
this.pageHandler_.undoMostVisitedTileAction();
}
private onTouchStart_(e: TouchEvent) {
if (this.reordering_ || !this.customLinksEnabled_) {
return;
}
const tileElement =
(e.composedPath() as HTMLElement[])
.find(el => el.classList && el.classList.contains('tile'));
if (!tileElement) {
return;
}
const {clientX, clientY} = e.changedTouches[0];
this.dragStart_(tileElement, clientX, clientY);
const touchMove = (e: TouchEvent) => {
const {clientX, clientY} = e.changedTouches[0];
this.dragOver_(clientX, clientY);
};
const touchEnd = (e: TouchEvent) => {
this.ownerDocument.removeEventListener('touchmove', touchMove);
tileElement.removeEventListener('touchend', touchEnd);
tileElement.removeEventListener('touchcancel', touchEnd);
const {clientX, clientY} = e.changedTouches[0];
this.dragEnd_(clientX, clientY);
this.reordering_ = false;
};
this.ownerDocument.addEventListener('touchmove', touchMove);
tileElement.addEventListener('touchend', touchEnd, {once: true});
tileElement.addEventListener('touchcancel', touchEnd, {once: true});
}
private tileFocus_(index: number) {
if (index < 0) {
return;
}
const tileElements = this.tileElements_;
if (index < tileElements.length) {
tileElements[index].focus();
} else if (this.showAdd_ && index === tileElements.length) {
this.$.addShortcut.focus();
}
}
private toast_(msgId: string, showButtons: boolean) {
this.toastContent_ = loadTimeData.getString(msgId);
this.showToastButtons_ = showButtons;
this.$.toast.show();
}
private tileRemove_(index: number) {
const {url, isQueryTile} = this.tiles_[index];
this.pageHandler_.deleteMostVisitedTile(url);
// Do not show the toast buttons when a query tile is removed unless it is a
// custom link. Removal is not reversible for non custom link query tiles.
this.toast_(
'linkRemovedMsg',
/* showButtons= */ this.customLinksEnabled_ || !isQueryTile);
this.tileFocus_(index);
}
private onTilesRendered_() {
performance.measure('most-visited-rendered');
assert(this.maxVisibleTiles_);
this.pageHandler_.onMostVisitedTilesRendered(
this.tiles_.slice(0, this.maxVisibleTiles_), this.windowProxy_.now());
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-most-visited': MostVisitedElement;
}
}
customElements.define(MostVisitedElement.is, MostVisitedElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/most_visited/most_visited.ts | TypeScript | unknown | 27,503 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Abstracts built-in JS functions in order to mock in tests.
*/
export class MostVisitedWindowProxy {
matchMedia(query: string): MediaQueryList {
return window.matchMedia(query);
}
now(): number {
return Date.now();
}
static getInstance(): MostVisitedWindowProxy {
return instance || (instance = new MostVisitedWindowProxy());
}
static setInstance(obj: MostVisitedWindowProxy) {
instance = obj;
}
}
let instance: MostVisitedWindowProxy|null = null;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/most_visited/window_proxy.ts | TypeScript | unknown | 635 |
<style import="cr-shared-style">
:host {
--action-height: 32px;
border: solid 1px var(--google-grey-400);
border-radius: calc(var(--action-height) / 2);
display: flex;
height: var(--action-height);
min-width: 0;
outline: none;
padding-inline-end: 16px;
padding-inline-start: 12px;
}
.contents {
align-items: center;
display: flex;
min-width: 0;
}
#action-icon {
flex-shrink: 0;
height: var(--cr-icon-size);
width: var(--cr-icon-size);
}
#text {
overflow: hidden;
padding-inline-start: 8px;
text-overflow: ellipsis;
white-space: nowrap;
}
:host(:hover) {
background-color: var(--action-bg-hovered,
rgba(var(--google-grey-900-rgb), .1));
}
:host-context(.focus-outline-visible):host(:focus) {
border: solid 1px transparent;
box-shadow: inset 0 0 0 2px var(--google-blue-600);
}
</style>
<div class="contents" title="[[tooltip_]]">
<img id="action-icon" src$="[[action.iconUrl]]">
<div id="text" inner-h-t-m-l="[[hintHtml_]]"></div>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_action.html | HTML | unknown | 1,086 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '//resources/cr_elements/cr_shared_style.css.js';
import {sanitizeInnerHtml} from '//resources/js/parse_html_subset.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {Action} from './omnibox.mojom-webui.js';
import {getTemplate} from './realbox_action.html.js';
import {decodeString16} from './utils.js';
// Displays an action associated with AutocompleteMatch (i.e. Clear
// Browsing History, etc.)
class RealboxActionElement extends PolymerElement {
static get is() {
return 'cr-realbox-action';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
//========================================================================
// Public properties
//========================================================================
action: {
type: Object,
},
/**
* Index of the match in the autocomplete result. Used to inform embedder
* of events such as click, keyboard events etc.
*/
matchIndex: {
type: Number,
value: -1,
},
//========================================================================
// Private properties
//========================================================================
/** Element's 'aria-label' attribute. */
ariaLabel: {
type: String,
computed: `computeAriaLabel_(action)`,
reflectToAttribute: true,
},
/** Rendered hint from action. */
hintHtml_: {
type: String,
computed: `computeHintHtml_(action)`,
},
/** Rendered tooltip from action. */
tooltip_: {
type: String,
computed: `computeTooltip_(action)`,
},
};
}
action: Action;
matchIndex: number;
override ariaLabel: string;
private hintHtml_: TrustedHTML;
private tooltip_: string;
//============================================================================
// Helpers
//============================================================================
private computeAriaLabel_(): string {
if (this.action.a11yLabel) {
return decodeString16(this.action.a11yLabel);
}
return '';
}
private computeHintHtml_(): TrustedHTML {
if (this.action.hint) {
return sanitizeInnerHtml(decodeString16(this.action.hint));
}
return window.trustedTypes!.emptyHTML;
}
private computeTooltip_(): string {
if (this.action.suggestionContents) {
return decodeString16(this.action.suggestionContents);
}
return '';
}
}
customElements.define(RealboxActionElement.is, RealboxActionElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_action.ts | TypeScript | unknown | 2,820 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {PageCallbackRouter, PageHandler, PageHandlerInterface} from './omnibox.mojom-webui.js';
/**
* @fileoverview This file provides a singleton class that exposes the Mojo
* handler interface used for bidirectional communication between the
* <ntp-realbox> or the <cr-realbox-dropdown> and the browser.
*/
let instance: RealboxBrowserProxy|null = null;
export class RealboxBrowserProxy {
static getInstance(): RealboxBrowserProxy {
return instance || (instance = new RealboxBrowserProxy());
}
static setInstance(newInstance: RealboxBrowserProxy) {
instance = newInstance;
}
handler: PageHandlerInterface;
callbackRouter: PageCallbackRouter;
constructor() {
this.handler = PageHandler.getRemote();
this.callbackRouter = new PageCallbackRouter();
this.handler.setPage(this.callbackRouter.$.bindNewPipeAndPassRemote());
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_browser_proxy.ts | TypeScript | unknown | 1,015 |
<style include="cr-icons realbox-dropdown-shared-style">
:host {
user-select: none;
}
#content {
background-color: var(--color-realbox-results-background);
border-radius: calc(0.25 * var(--cr-realbox-height));
box-shadow: var(--cr-realbox-shadow);
display: flex;
gap: 16px;
margin-bottom: 8px;
overflow: hidden;
padding-bottom: 8px;
padding-top: var(--cr-realbox-height);
}
:host([round-corners]) #content {
border-radius: calc(0.5 * var(--cr-realbox-height));
padding-bottom: 18px;
}
@media (forced-colors: active) {
#content {
border: 1px solid ActiveBorder;
}
}
.matches {
display: contents;
}
cr-realbox-match {
color: var(--color-realbox-results-foreground);
}
.header {
align-items: center;
box-sizing: border-box;
cursor: pointer;
display: flex;
font-size: inherit;
font-weight: inherit;
/* To mirror match typical row height of items in vertical list. */
height: 44px;
margin-block-end: 0;
margin-block-start: 0;
outline: none;
padding-bottom: 6px;
padding-inline-end: 16px;
padding-inline-start: 12px;
padding-top: 6px;
}
.header .text {
color: var(--color-realbox-results-foreground-dimmed);
font-size: .875em;
font-weight: 500;
overflow: hidden;
padding-inline-end: 6px;
padding-inline-start: 6px;
text-overflow: ellipsis;
white-space: nowrap;
}
.header:focus-within:not(:focus) cr-icon-button {
--cr-icon-button-fill-color:
var(--color-realbox-results-icon-selected);
}
cr-realbox-match:-webkit-any(:hover, :focus-within, [selected]) {
background-color:
var(--color-realbox-results-background-hovered);
}
@media (forced-colors: active) {
cr-realbox-match:-webkit-any(:hover, :focus-within, [selected]) {
background-color: Highlight;
}
}
.primary-side {
flex: 1;
min-width: 0;
}
.secondary-side {
display: var(--cr-realbox-secondary-side-display, none);
min-width: 0;
padding-block-end: 8px;
padding-inline-end: 16px;
width: 314px;
}
.secondary-side .header {
padding-inline-end: 0;
padding-inline-start: 0;
}
.secondary-side .matches {
display: flex;
gap: 4px;
}
</style>
<div id="content">
<template is="dom-repeat"
items="[[sideTypes_(showSecondarySide_)]]"
as="side">
<div class$="[[classForSide_(side)]]">
<template is="dom-repeat" items="[[groupIdsForSide_(side, result.matches.*)]]"
as="groupId">
<template is="dom-if" if="[[hasHeaderForGroup_(groupId)]]">
<!-- Header cannot be tabbed into but gets focus when clicked. This stops
the dropdown from losing focus and closing as a result. -->
<h3 class="header" data-id$="[[groupId]]" tabindex="-1"
on-focusin="onHeaderFocusin_" on-click="onHeaderClick_"
aria-hidden="true">
<span class="text">[[headerForGroup_(groupId)]]</span>
<cr-icon-button class$="action-icon [[toggleButtonIconForGroup_(groupId, hiddenGroupIds_.*)]]"
title="[[toggleButtonTitleForGroup_(groupId, hiddenGroupIds_.*)]]"
aria-label$="[[toggleButtonA11yLabelForGroup_(groupId, hiddenGroupIds_.*)]]"
on-mousedown="onToggleButtonMouseDown_">
</cr-icon-button>
</h3>
</template>
<div class="matches">
<template is="dom-repeat"
items="[[matchesForGroup_(groupId, result.matches.*, hiddenGroupIds_.*)]]"
as="match" on-dom-change="onResultRepaint_">
<cr-realbox-match tabindex="0" role="option" match="[[match]]"
match-index="[[matchIndex_(match)]]" side-type="[[side]]"
selected$="[[isSelected_(match, selectedMatchIndex)]]">
</cr-realbox-match>
</template>
</div>
</template>
</div>
</template>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_dropdown.html | HTML | unknown | 3,994 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './realbox_match.js';
import './realbox_dropdown_shared_style.css.js';
import '//resources/polymer/v3_0/iron-selector/iron-selector.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.js';
import '//resources/cr_elements/cr_icons.css.js';
import {loadTimeData} from '//resources/js/load_time_data.js';
import {MetricsReporterImpl} from '//resources/js/metrics_reporter/metrics_reporter.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {AutocompleteMatch, AutocompleteResult, PageHandlerInterface, SideType} from './omnibox.mojom-webui.js';
import {RealboxBrowserProxy} from './realbox_browser_proxy.js';
import {getTemplate} from './realbox_dropdown.html.js';
import {RealboxMatchElement} from './realbox_match.js';
import {decodeString16, sideTypeToClass} from './utils.js';
// The '%' operator in JS returns negative numbers. This workaround avoids that.
const remainder = (lhs: number, rhs: number) => ((lhs % rhs) + rhs) % rhs;
const CHAR_TYPED_TO_PAINT = 'Realbox.CharTypedToRepaintLatency.ToPaint';
const RESULT_CHANGED_TO_PAINT = 'Realbox.ResultChangedToRepaintLatency.ToPaint';
// A dropdown element that contains autocomplete matches. Provides an API for
// the embedder (i.e., <ntp-realbox>) to change the selection.
export class RealboxDropdownElement extends PolymerElement {
static get is() {
return 'cr-realbox-dropdown';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
//========================================================================
// Public properties
//========================================================================
/**
* Whether the secondary side can be shown based on the feature state and
* the width available to the dropdown.
*/
canShowSecondarySide: {
type: Boolean,
value: false,
},
/**
* Whether the secondary side was at any point available to be shown.
*/
hadSecondarySide: {
type: Boolean,
value: false,
notify: true,
},
/*
* Whether the secondary side is currently available to be shown.
*/
hasSecondarySide: {
type: Boolean,
computed: `computeHasSecondarySide_(result)`,
notify: true,
},
result: {
type: Object,
},
/** Whether the dropdown should have rounded corners. */
roundCorners: {
type: Boolean,
value: () => loadTimeData.getBoolean('roundCorners'),
reflectToAttribute: true,
},
/** Index of the selected match. */
selectedMatchIndex: {
type: Number,
value: -1,
notify: true,
},
/**
* Computed value for whether or not the dropdown should show the
* secondary side. This depends on whether the parent has set
* `canShowSecondarySide` to true and whether there are visible primary
* matches.
*/
showSecondarySide_: {
type: Boolean,
value: false,
computed: 'computeShowSecondarySide_(' +
'canShowSecondarySide, result.matches.*, hiddenGroupIds_.*)',
},
//========================================================================
// Private properties
//========================================================================
/** The list of suggestion group IDs whose matches should be hidden. */
hiddenGroupIds_: {
type: Array,
computed: `computeHiddenGroupIds_(result)`,
},
/** The list of selectable match elements. */
selectableMatchElements_: {
type: Array,
value: () => [],
},
};
}
canShowSecondarySide: boolean;
hadSecondarySide: boolean;
hasSecondarySide: boolean;
result: AutocompleteResult;
roundCorners: boolean;
selectedMatchIndex: number;
private hiddenGroupIds_: number[];
private selectableMatchElements_: RealboxMatchElement[];
private showSecondarySide_: boolean;
private pageHandler_: PageHandlerInterface;
constructor() {
super();
this.pageHandler_ = RealboxBrowserProxy.getInstance().handler;
}
//============================================================================
// Public methods
//============================================================================
/** Filters out secondary matches, if any, unless they can be shown. */
get selectableMatchElements() {
return this.selectableMatchElements_.filter(
matchEl => matchEl.sideType === SideType.kDefaultPrimary ||
this.showSecondarySide_);
}
/** Unselects the currently selected match, if any. */
unselect() {
this.selectedMatchIndex = -1;
}
/** Focuses the selected match, if any. */
focusSelected() {
this.selectableMatchElements[this.selectedMatchIndex]?.focus();
}
/** Selects the first match. */
selectFirst() {
this.selectedMatchIndex = 0;
}
/** Selects the match at the given index. */
selectIndex(index: number) {
this.selectedMatchIndex = index;
}
/**
* Selects the previous match with respect to the currently selected one.
* Selects the last match if the first one or no match is currently selected.
*/
selectPrevious() {
// The value of -1 for |this.selectedMatchIndex| indicates no selection.
// Therefore subtract one from the maximum of its value and 0.
const previous = Math.max(this.selectedMatchIndex, 0) - 1;
this.selectedMatchIndex =
remainder(previous, this.selectableMatchElements.length);
}
/** Selects the last match. */
selectLast() {
this.selectedMatchIndex = this.selectableMatchElements.length - 1;
}
/**
* Selects the next match with respect to the currently selected one.
* Selects the first match if the last one or no match is currently selected.
*/
selectNext() {
const next = this.selectedMatchIndex + 1;
this.selectedMatchIndex =
remainder(next, this.selectableMatchElements.length);
}
//============================================================================
// Event handlers
//============================================================================
private onHeaderClick_(e: Event) {
const groupId =
Number.parseInt((e.currentTarget as HTMLElement).dataset['id']!, 10);
// Tell the backend to toggle visibility of the given suggestion group ID.
this.pageHandler_.toggleSuggestionGroupIdVisibility(groupId);
// Hide/Show matches with the given suggestion group ID.
const index = this.hiddenGroupIds_.indexOf(groupId);
if (index === -1) {
this.push('hiddenGroupIds_', groupId);
} else {
this.splice('hiddenGroupIds_', index, 1);
}
}
private onHeaderFocusin_() {
this.dispatchEvent(new CustomEvent('header-focusin', {
bubbles: true,
composed: true,
}));
}
private onResultRepaint_() {
const metricsReporter = MetricsReporterImpl.getInstance();
metricsReporter.measure('CharTyped')
.then(duration => {
metricsReporter.umaReportTime(CHAR_TYPED_TO_PAINT, duration);
})
.then(() => {
metricsReporter.clearMark('CharTyped');
})
.catch(() => {}); // Fail silently if 'CharTyped' is not marked.
metricsReporter.measure('ResultChanged')
.then(duration => {
metricsReporter.umaReportTime(RESULT_CHANGED_TO_PAINT, duration);
})
.then(() => {
metricsReporter.clearMark('ResultChanged');
})
.catch(() => {}); // Fail silently if 'ResultChanged' is not marked.
// Update the list of selectable match elements.
this.selectableMatchElements_ =
[...this.shadowRoot!.querySelectorAll('cr-realbox-match')];
}
private onToggleButtonMouseDown_(e: Event) {
e.preventDefault(); // Prevents default browser action (focus).
}
//============================================================================
// Helpers
//============================================================================
private classForSide_(side: SideType): string {
return sideTypeToClass(side);
}
private computeHasSecondarySide_(): boolean {
const hasSecondarySide =
!!this.groupIdsForSide_(SideType.kSecondary).length;
if (!this.hadSecondarySide) {
this.hadSecondarySide = hasSecondarySide;
}
return hasSecondarySide;
}
private computeHiddenGroupIds_(): number[] {
return Object.keys(this.result?.suggestionGroupsMap ?? {})
.map(groupId => Number.parseInt(groupId, 10))
.filter(groupId => this.result.suggestionGroupsMap[groupId].hidden);
}
private isSelected_(match: AutocompleteMatch): boolean {
return this.matchIndex_(match) === this.selectedMatchIndex;
}
/**
* @returns The unique suggestion group IDs that belong to the given side type
* while preserving the order in which they appear in the list of matches.
*/
private groupIdsForSide_(side: SideType): number[] {
return [...new Set<number>(
this.result?.matches?.map(match => match.suggestionGroupId)
.filter(groupId => this.sideTypeForGroup_(groupId) === side))];
}
/**
* @returns Whether matches with the given suggestion group ID should be
* hidden.
*/
private groupIsHidden_(groupId: number): boolean {
return this.hiddenGroupIds_.indexOf(groupId) !== -1;
}
/**
* @returns Whether the given suggestion group ID has a header.
*/
private hasHeaderForGroup_(groupId: number): boolean {
return !!this.headerForGroup_(groupId);
}
/**
* @returns The header for the given suggestion group ID, if any.
*/
private headerForGroup_(groupId: number): string {
return this.result?.suggestionGroupsMap[groupId] ?
decodeString16(this.result.suggestionGroupsMap[groupId].header) :
'';
}
/**
* @returns Index of the match in the autocomplete result. Passed to the match
* so it knows its position in the list of matches.
*/
private matchIndex_(match: AutocompleteMatch): number {
return this.result?.matches?.indexOf(match) ?? -1;
}
/**
* @returns The list of visible matches that belong to the given suggestion
* group ID.
*/
private matchesForGroup_(groupId: number): AutocompleteMatch[] {
return this.groupIsHidden_(groupId) ?
[] :
(this.result?.matches ??
[]).filter(match => match.suggestionGroupId === groupId);
}
/**
* @returns The list of side types to show.
*/
private sideTypes_(): SideType[] {
return this.showSecondarySide_ ?
[SideType.kDefaultPrimary, SideType.kSecondary] :
[SideType.kDefaultPrimary];
}
/**
* @returns The side type for the given suggestion group ID.
*/
private sideTypeForGroup_(groupId: number): SideType {
return this.result?.suggestionGroupsMap[groupId]?.sideType ??
SideType.kDefaultPrimary;
}
/**
* @returns A11y label for suggestion group show/hide toggle button.
*/
private toggleButtonA11yLabelForGroup_(groupId: number): string {
if (!this.hasHeaderForGroup_(groupId)) {
return '';
}
return !this.groupIsHidden_(groupId) ?
decodeString16(
this.result.suggestionGroupsMap[groupId].hideGroupA11yLabel) :
decodeString16(
this.result.suggestionGroupsMap[groupId].showGroupA11yLabel);
}
/**
* @returns Icon name for suggestion group show/hide toggle button.
*/
private toggleButtonIconForGroup_(groupId: number): string {
return this.groupIsHidden_(groupId) ? 'icon-expand-more' :
'icon-expand-less';
}
/**
* @returns Tooltip for suggestion group show/hide toggle button.
*/
private toggleButtonTitleForGroup_(groupId: number): string {
return loadTimeData.getString(
this.groupIsHidden_(groupId) ? 'showSuggestions' : 'hideSuggestions');
}
private computeShowSecondarySide_(): boolean {
if (!this.canShowSecondarySide) {
// Parent prohibits showing secondary side.
return false;
}
if (!this.hiddenGroupIds_) {
// Not ready yet as dropdown has received results but has not yet
// determined which groups are hidden.
return true;
}
// Only show secondary side if there are primary matches visible.
const primaryGroupIds = this.groupIdsForSide_(SideType.kDefaultPrimary);
return primaryGroupIds.some((groupId) => {
return this.matchesForGroup_(groupId).length > 0;
});
}
}
declare global {
interface HTMLElementTagNameMap {
'ntp-realbox-dropdown': RealboxDropdownElement;
}
}
customElements.define(RealboxDropdownElement.is, RealboxDropdownElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_dropdown.ts | TypeScript | unknown | 12,971 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #css_wrapper_metadata_end */
.action-icon {
--cr-icon-button-active-background-color:
var(--color-new-tab-page-active-background);
--cr-icon-button-fill-color: var(--color-realbox-results-icon);
--cr-icon-button-focus-outline-color:
var(--color-realbox-results-icon-focused-outline);
--cr-icon-button-hover-background-color:
var(--color-realbox-results-control-background-hovered);
--cr-icon-button-icon-size: 16px;
--cr-icon-button-margin-end: 0;
--cr-icon-button-margin-start: 0;
--cr-icon-button-size: 24px;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_dropdown_shared_style.css | CSS | unknown | 744 |
<style>
:host {
align-items: center;
display: flex;
flex-shrink: 0;
justify-content: center;
width: 32px;
}
#container {
align-items: center;
aspect-ratio: 1 / 1;
border-radius: var(--cr-realbox-icon-border-radius, 8px);
display: flex;
justify-content: center;
overflow: hidden;
position: relative;
width: 100%;
}
/* Entities may feature a dominant color background until image loads. */
:host-context(cr-realbox-match[has-image]) #container {
background-color: var(--cr-realbox-icon-container-bg-color,
var(--container-bg-color));
}
/* Calculator answer and suggestion answer icons feature a blue background. */
:host-context(cr-realbox-match[is-rich-suggestion]:not([has-image])) #container {
background-color: var(--google-blue-600);
border-radius: 50%;
height: 24px;
width: 24px;
}
#image {
display: none;
height: 100%;
object-fit: contain;
width: 100%;
}
:host-context(cr-realbox-match[has-image]) #image {
display: initial;
}
:host([is-answer]) #image {
max-height: 24px;
max-width: 24px;
}
#imageOverlay {
display: none;
}
/* Put a black scrim over the image for entity suggestions in case the images
* have a background color that matches the background color of the dropdown.
* This makes it clearer where the boundary of the image is. */
:host-context(cr-realbox-match[is-entity-suggestion][has-image])
#imageOverlay {
background: black;
display: block;
inset: 0;
opacity: .05;
position: absolute;
}
#icon {
-webkit-mask-position: center;
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 16px;
background-color: var(--color-realbox-search-icon-background);
background-position: center center;
background-repeat: no-repeat;
background-size: 16px;
height: 24px;
width: 24px;
}
:host-context(cr-realbox-match[has-image]) #icon {
display: none;
}
:host-context(cr-realbox-match[is-rich-suggestion]) #icon {
background-color: white;
}
:host([in-searchbox][background-image*='//resources/cr_components/omnibox/icons/google_g.svg']) #icon {
background-size: 24px;
}
:host([in-searchbox][mask-image*='//resources/images/icon_search.svg']) #icon {
-webkit-mask-size: 20px; /* Loupe in realbox is larger than in matches. */
}
</style>
<div id="container" style="--container-bg-color:
[[containerBgColor_(match.imageDominantColor, imageLoading_)]];">
<img id="image" src="[[imageSrc_]]" on-load="onImageLoad_"></img>
<div id="imageOverlay"></div>
<!--Note: Do not remove the '$' in '$=' below, otherwise the 'style' attribute
is erroneously removed by the HTML minifier. -->
<div id="icon" style$="[[iconStyle_]]"></div>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_icon.html | HTML | unknown | 2,819 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {getFaviconForPageURL} from '//resources/js/icon.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {AutocompleteMatch} from './omnibox.mojom-webui.js';
import {getTemplate} from './realbox_icon.html.js';
const DOCUMENT_MATCH_TYPE: string = 'document';
const HISTORY_CLUSTER_MATCH_TYPE: string = 'history-cluster';
export interface RealboxIconElement {
$: {
container: HTMLElement,
icon: HTMLElement,
image: HTMLImageElement,
};
}
// The LHS icon. Used on autocomplete matches as well as the realbox input to
// render icons, favicons, and entity images.
export class RealboxIconElement extends PolymerElement {
static get is() {
return 'cr-realbox-icon';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
//========================================================================
// Public properties
//========================================================================
/** Used as a background image on #icon if non-empty. */
backgroundImage: {
type: String,
computed: `computeBackgroundImage_(match.*)`,
reflectToAttribute: true,
},
/**
* The default icon to show when no match is selected and/or for
* non-navigation matches. Only set in the context of the realbox input.
*/
defaultIcon: {
type: String,
value: '',
},
/**
* Whether icon is in searchbox or not. Used to prevent
* the match icon of rich suggestions from showing in the context of the
* realbox input.
*/
inSearchbox: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/**
* Whether icon belongs to an answer or not. Used to prevent
* the match image from taking size of container.
*/
isAnswer: {
type: Boolean,
computed: `computeIsAnswer_(match)`,
reflectToAttribute: true,
},
/** Used as a mask image on #icon if |backgroundImage| is empty. */
maskImage: {
type: String,
computed: `computeMaskImage_(match)`,
reflectToAttribute: true,
},
match: {
type: Object,
},
//========================================================================
// Private properties
//========================================================================
iconStyle_: {
type: String,
computed: `computeIconStyle_(backgroundImage, maskImage)`,
},
imageSrc_: {
type: String,
computed: `computeImageSrc_(match.imageUrl, match)`,
observer: 'onImageSrcChanged_',
},
/**
* Flag indicating whether or not an image is loading. This is used to
* show a placeholder color while the image is loading.
*/
imageLoading_: {
type: Boolean,
value: false,
},
};
}
backgroundImage: string;
defaultIcon: string;
inSearchbox: boolean;
isAnswer: boolean;
maskImage: string;
match: AutocompleteMatch;
private iconStyle_: string;
private imageSrc_: string;
private imageLoading_: boolean;
//============================================================================
// Helpers
//============================================================================
private computeBackgroundImage_(): string {
if (this.match && !this.match.isSearchType) {
if (this.match.type !== DOCUMENT_MATCH_TYPE &&
this.match.type !== HISTORY_CLUSTER_MATCH_TYPE) {
return getFaviconForPageURL(
this.match.destinationUrl.url, /* isSyncedUrlForHistoryUi= */ false,
/* remoteIconUrlForUma= */ '', /* size= */ 32,
/* forceLightMode= */ true);
}
if (this.match.type === DOCUMENT_MATCH_TYPE) {
return `url(${this.match.iconUrl})`;
}
}
if (this.defaultIcon ===
'//resources/cr_components/omnibox/icons/google_g.svg') {
// The google_g.svg is a fully colored icon, so it needs to be displayed
// as a background image as mask images will mask the colors.
return `url(${this.defaultIcon})`;
}
return '';
}
private computeIsAnswer_(): boolean {
return this.match && !!this.match.answer;
}
private computeMaskImage_(): string {
if (this.match && (!this.match.isRichSuggestion || !this.inSearchbox)) {
return `url(${this.match.iconUrl})`;
} else {
return `url(${this.defaultIcon})`;
}
}
private computeIconStyle_(): string {
// Use a background image if applicable. Otherwise use a mask image.
if (this.backgroundImage) {
return `background-image: ${this.backgroundImage};` +
`background-color: transparent;`;
} else {
return `-webkit-mask-image: ${this.maskImage};`;
}
}
private computeImageSrc_(): string {
const imageUrl = this.match?.imageUrl;
if (!imageUrl) {
return '';
}
if (imageUrl.startsWith('data:image/')) {
// Zero-prefix matches come with the data URI content in |match.imageUrl|.
return imageUrl;
}
return `//image?staticEncode=true&encodeType=webp&url=${imageUrl}`;
}
private containerBgColor_(imageDominantColor: string, imageLoading: boolean):
string {
// If the match has an image dominant color, show that color in place of the
// image until it loads. This helps the image appear to load more smoothly.
return (imageLoading && imageDominantColor) ?
// .25 opacity matching c/b/u/views/omnibox/omnibox_match_cell_view.cc.
`${imageDominantColor}40` :
'transparent';
}
private onImageSrcChanged_() {
// If imageSrc_ changes to a new truthy value, a new image is being loaded.
this.imageLoading_ = !!this.imageSrc_;
}
private onImageLoad_() {
this.imageLoading_ = false;
}
}
customElements.define(RealboxIconElement.is, RealboxIconElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_icon.ts | TypeScript | unknown | 6,176 |
<style include="cr-hidden-style cr-icons realbox-dropdown-shared-style">
:host {
display: block;
outline: none;
}
#action {
margin-inline-start: 40px; /* icon width + text padding */
}
.container {
align-items: center;
cursor: default;
display: flex;
overflow: hidden;
padding-bottom: 6px;
padding-inline-end: 16px;
padding-inline-start: 12px;
padding-top: 6px;
position: relative;
}
.container + .container {
padding-bottom: 12px;
padding-top: 0;
}
#contents,
#description {
overflow: hidden;
text-overflow: ellipsis;
}
#ellipsis {
inset-inline-end: 0;
position: absolute;
}
#focus-indicator {
background-color: var(--google-blue-600);
border-radius: 3px;
display: none;
height: 100%;
margin-inline-start: -15px; /* -1 * (.container padding + width / 2) */
position: absolute;
width: 6px;
}
/* TODO(crbug.com/1430996): Add focus indicator for secondary results. */
:host(:is(:focus-visible, [selected]:not(:focus-within)):not(
[side-type-class_='secondary-side'])) #focus-indicator {
display: block;
}
#prefix {
opacity: 0;
}
#separator {
white-space: pre;
}
#tail-suggest-prefix {
position: relative;
}
#text-container {
align-items: center;
display: flex;
flex-grow: 1;
overflow: hidden;
padding-inline-end: 8px;
padding-inline-start: 8px;
white-space: nowrap;
}
:host([is-rich-suggestion]) #text-container {
align-items: flex-start;
flex-direction: column;
}
:host([is-rich-suggestion]) #separator {
display: none;
}
:host([is-rich-suggestion]) #contents,
:host([is-rich-suggestion]) #description {
width: 100%;
}
/* Deemphasizes description for entities with images. */
:host([is-entity-suggestion][has-image]) #description {
font-size: .875em;
}
.match {
font-weight: 600;
}
/* Uses a dimmed color for description for entities. */
:host([is-entity-suggestion]) #description,
.dim {
color: var(--color-realbox-results-foreground-dimmed);
}
/* Uses a dimmed color for description for entities. */
:host-context(cr-realbox-match:-webkit-any(:focus-within, [selected])):host([is-entity-suggestion]) #description,
:host-context(cr-realbox-match:-webkit-any(:focus-within, [selected])) .dim {
color: var(--color-realbox-results-dim-selected);
}
.url {
color: var(--color-realbox-results-url);
}
:host-context(cr-realbox-match:-webkit-any(:focus-within, [selected])) .url {
color: var(--color-realbox-results-url-selected);
}
#remove {
margin-inline-end: 1px;
opacity: 0; /* Hides the button while keeping it in tab order. */
}
:host-context(cr-realbox-match:hover) #remove {
opacity: 1;
}
:host-context(cr-realbox-match:-webkit-any(:focus-within, [selected])) #remove {
--cr-icon-button-fill-color:
var(--color-realbox-results-icon-selected);
opacity: 1;
}
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image]) {
border-radius: 16px;
}
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image])
.container {
box-sizing: border-box;
flex-direction: column;
padding: 6px;
padding-block-end: 16px;
width: 102px;
}
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image])
.focus-indicator {
display: none;
}
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image])
#icon {
--cr-realbox-icon-border-radius: 12px;
/* Disable placeholder dominant color as the images are large and the
* placeholder color looks like a flash of unstyled content. */
--cr-realbox-icon-container-bg-color: transparent;
height: 90px;
margin-block-end: 8px;
width: 90px;
}
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image])
#text-container {
padding: 0;
white-space: normal;
width: 100%;
}
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image])
#contents,
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image])
#description {
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
display: -webkit-box;
font-weight: 400;
overflow: hidden;
}
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image])
#contents {
font-size: 13px;
line-height: 20px;
margin-block-end: 4px;
}
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image])
#description {
font-size: 12px;
line-height: 16px;
}
:host([side-type-class_='secondary-side'][is-entity-suggestion][has-image])
#remove {
display: none;
}
</style>
<div class="container" aria-hidden="true">
<div id="focus-indicator"></div>
<cr-realbox-icon id="icon" match="[[match]]"></cr-realbox-icon>
<div id="text-container">
<span id="tail-suggest-prefix" hidden$="[[!tailSuggestPrefix_]]">
<span id="prefix">[[tailSuggestPrefix_]]</span>
<!-- This is equivalent to AutocompleteMatch::kEllipsis which is
prepended to the match content in other surfaces-->
<span id="ellipsis">... </span>
</span>
<span id="contents" inner-h-t-m-l="[[contentsHtml_]]"></span>
<span id="separator" class="dim">[[separatorText_]]</span>
<span id="description" inner-h-t-m-l="[[descriptionHtml_]]"></span>
</div>
<cr-icon-button id="remove" class="action-icon icon-clear"
aria-label="[[removeButtonAriaLabel_]]"
on-click="onRemoveButtonClick_" on-mousedown="onRemoveButtonMouseDown_"
title="[[removeButtonTitle_]]" hidden$="[[!match.supportsDeletion]]"
tabindex="2">
</cr-icon-button>
</div>
<template is="dom-if" if="[[actionIsVisible_]]">
<div class="container" aria-hidden="true">
<cr-realbox-action id="action" action="[[match.action]]"
tabindex="1" on-click="onActionClick_"
on-keydown="onActionKeyDown_">
</cr-realbox-action>
</div>
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_match.html | HTML | unknown | 6,119 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './realbox_icon.js';
import './realbox_action.js';
import './realbox_dropdown_shared_style.css.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.js';
import '//resources/cr_elements/cr_icons.css.js';
import '//resources/cr_elements/cr_hidden_style.css.js';
import {loadTimeData} from '//resources/js/load_time_data.js';
import {sanitizeInnerHtml} from '//resources/js/parse_html_subset.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {ACMatchClassification, AutocompleteMatch, NavigationPredictor, PageHandlerInterface, SideType} from './omnibox.mojom-webui.js';
import {RealboxBrowserProxy} from './realbox_browser_proxy.js';
import {RealboxIconElement} from './realbox_icon.js';
import {getTemplate} from './realbox_match.html.js';
import {decodeString16, mojoTimeTicks, sideTypeToClass} from './utils.js';
// clang-format off
/**
* Bitmap used to decode the value of ACMatchClassification style
* field.
* See components/omnibox/browser/autocomplete_match.h.
*/
enum AcMatchClassificationStyle {
NONE = 0,
URL = 1 << 0, // A URL.
MATCH = 1 << 1, // A match for the user's search term.
DIM = 1 << 2, // A "helper text".
}
// clang-format on
const ENTITY_MATCH_TYPE: string = 'search-suggest-entity';
export interface RealboxMatchElement {
$: {
icon: RealboxIconElement,
contents: HTMLElement,
description: HTMLElement,
remove: HTMLElement,
separator: HTMLElement,
'focus-indicator': HTMLElement,
};
}
// Displays an autocomplete match similar to those in the Omnibox.
export class RealboxMatchElement extends PolymerElement {
static get is() {
return 'cr-realbox-match';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
//========================================================================
// Public properties
//========================================================================
/** Element's 'aria-label' attribute. */
ariaLabel: {
type: String,
computed: `computeAriaLabel_(match.a11yLabel)`,
reflectToAttribute: true,
},
/**
* Whether the match features an image (as opposed to an icon or favicon).
*/
hasImage: {
type: Boolean,
computed: `computeHasImage_(match)`,
reflectToAttribute: true,
},
/**
* Whether the match is an entity suggestion (with or without an image).
*/
isEntitySuggestion: {
type: Boolean,
computed: `computeIsEntitySuggestion_(match)`,
reflectToAttribute: true,
},
/**
* Whether the match should be rendered in a two-row layout. Currently
* limited to matches that feature an image, calculator, and answers.
*/
isRichSuggestion: {
type: Boolean,
computed: `computeIsRichSuggestion_(match)`,
reflectToAttribute: true,
},
match: Object,
/**
* Index of the match in the autocomplete result. Used to inform embedder
* of events such as deletion, click, etc.
*/
matchIndex: {
type: Number,
value: -1,
},
sideType: Number,
/** String representation of `sideType` to use in CSS. */
sideTypeClass_: {
type: String,
computed: 'computeSideTypeClass_(sideType)',
reflectToAttribute: true,
},
//========================================================================
// Private properties
//========================================================================
actionIsVisible_: {
type: Boolean,
computed: `computeActionIsVisible_(match)`,
},
/** Rendered match contents based on autocomplete provided styling. */
contentsHtml_: {
type: String,
computed: `computeContentsHtml_(match)`,
},
/** Rendered match description based on autocomplete provided styling. */
descriptionHtml_: {
type: String,
computed: `computeDescriptionHtml_(match)`,
},
/** Remove button's 'aria-label' attribute. */
removeButtonAriaLabel_: {
type: String,
computed: `computeRemoveButtonAriaLabel_(match.removeButtonA11yLabel)`,
},
removeButtonTitle_: {
type: String,
value: () => loadTimeData.getString('removeSuggestion'),
},
/** Used to separate the contents from the description. */
separatorText_: {
type: String,
computed: `computeSeparatorText_(match)`,
},
/** Rendered tail suggest common prefix. */
tailSuggestPrefix_: {
type: String,
computed: `computeTailSuggestPrefix_(match)`,
},
};
}
override ariaLabel: string;
hasImage: boolean;
match: AutocompleteMatch;
matchIndex: number;
sideType: SideType;
private actionIsVisible_: boolean;
private contentsHtml_: TrustedHTML;
private descriptionHtml_: TrustedHTML;
private removeButtonAriaLabel_: string;
private removeButtonTitle_: string;
private separatorText_: string;
private sideTypeClass_: string;
private tailSuggestPrefix_: string;
private pageHandler_: PageHandlerInterface;
constructor() {
super();
this.pageHandler_ = RealboxBrowserProxy.getInstance().handler;
}
override ready() {
super.ready();
this.addEventListener('click', (event) => this.onMatchClick_(event));
this.addEventListener('focusin', () => this.onMatchFocusin_());
this.addEventListener('mousedown', () => this.onMatchMouseDown_());
}
//============================================================================
// Event handlers
//============================================================================
/**
* containing index of the match that was removed as well as modifier key
* presses.
*/
private executeAction_(e: MouseEvent|KeyboardEvent) {
this.pageHandler_.executeAction(
this.matchIndex, this.match.destinationUrl, mojoTimeTicks(Date.now()),
(e as MouseEvent).button || 0, e.altKey, e.ctrlKey, e.metaKey,
e.shiftKey);
}
private onActionClick_(e: MouseEvent|KeyboardEvent) {
this.executeAction_(e);
e.preventDefault(); // Prevents default browser action (navigation).
e.stopPropagation(); // Prevents <iron-selector> from selecting the match.
}
private onActionKeyDown_(e: KeyboardEvent) {
if (e.key && (e.key === 'Enter' || e.key === ' ')) {
this.onActionClick_(e);
}
}
private onMatchClick_(e: MouseEvent) {
if (e.button > 1) {
// Only handle main (generally left) and middle button presses.
return;
}
this.dispatchEvent(new CustomEvent('match-click', {
bubbles: true,
composed: true,
detail: {index: this.matchIndex, event: e},
}));
e.preventDefault(); // Prevents default browser action (navigation).
e.stopPropagation(); // Prevents <iron-selector> from selecting the match.
}
private onMatchFocusin_() {
this.dispatchEvent(new CustomEvent('match-focusin', {
bubbles: true,
composed: true,
detail: this.matchIndex,
}));
}
private onMatchMouseDown_() {
this.pageHandler_.onNavigationLikely(
this.matchIndex, this.match.destinationUrl,
NavigationPredictor.kMouseDown);
}
private onRemoveButtonClick_(e: MouseEvent) {
if (e.button !== 0) {
// Only handle main (generally left) button presses.
return;
}
this.dispatchEvent(new CustomEvent('match-remove', {
bubbles: true,
composed: true,
detail: this.matchIndex,
}));
e.preventDefault(); // Prevents default browser action (navigation).
e.stopPropagation(); // Prevents <iron-selector> from selecting the match.
}
private onRemoveButtonMouseDown_(e: Event) {
e.preventDefault(); // Prevents default browser action (focus).
}
//============================================================================
// Helpers
//============================================================================
private computeAriaLabel_(): string {
if (!this.match) {
return '';
}
return decodeString16(this.match.a11yLabel);
}
private sanitizeInnerHtml_(html: string): TrustedHTML {
return sanitizeInnerHtml(html, {attrs: ['class']});
}
private computeContentsHtml_(): TrustedHTML {
if (!this.match) {
return window.trustedTypes!.emptyHTML;
}
const match = this.match;
// `match.answer.firstLine` is generated by appending an optional additional
// text from the answer's first line to `match.contents`, making the latter
// a prefix of the former. Thus `match.answer.firstLine` can be rendered
// using the markup in `match.contentsClass` which contains positions in
// `match.contents` and the markup to be applied to those positions.
// See //chrome/browser/ui/webui/realbox/realbox_handler.cc
const matchContents =
match.answer ? match.answer.firstLine : match.contents;
return match.swapContentsAndDescription ?
this.sanitizeInnerHtml_(
this.renderTextWithClassifications_(
decodeString16(match.description), match.descriptionClass)
.innerHTML) :
this.sanitizeInnerHtml_(
this.renderTextWithClassifications_(
decodeString16(matchContents), match.contentsClass)
.innerHTML);
}
private computeDescriptionHtml_(): TrustedHTML {
if (!this.match) {
return window.trustedTypes!.emptyHTML;
}
const match = this.match;
if (match.answer) {
return this.sanitizeInnerHtml_(decodeString16(match.answer.secondLine));
}
return match.swapContentsAndDescription ?
this.sanitizeInnerHtml_(
this.renderTextWithClassifications_(
decodeString16(match.contents), match.contentsClass)
.innerHTML) :
this.sanitizeInnerHtml_(
this.renderTextWithClassifications_(
decodeString16(match.description), match.descriptionClass)
.innerHTML);
}
private computeTailSuggestPrefix_(): string {
if (!this.match || !this.match.tailSuggestCommonPrefix) {
return '';
}
const prefix = decodeString16(this.match.tailSuggestCommonPrefix);
// Replace last space with non breaking space since spans collapse
// trailing white spaces and the prefix always ends with a white space.
if (prefix.slice(-1) === ' ') {
return prefix.slice(0, -1) + '\u00A0';
}
return prefix;
}
private computeHasImage_(): boolean {
return this.match && !!this.match.imageUrl;
}
private computeIsEntitySuggestion_(): boolean {
return this.match && this.match.type === ENTITY_MATCH_TYPE;
}
private computeIsRichSuggestion_(): boolean {
return this.match && this.match.isRichSuggestion;
}
private computeActionIsVisible_(): boolean {
return this.match && !!this.match.action;
}
private computeRemoveButtonAriaLabel_(): string {
if (!this.match) {
return '';
}
return decodeString16(this.match.removeButtonA11yLabel);
}
private computeSeparatorText_(): string {
return this.match && decodeString16(this.match.description) ?
loadTimeData.getString('realboxSeparator') :
'';
}
private computeSideTypeClass_(): string {
return sideTypeToClass(this.sideType);
}
/**
* Decodes the AcMatchClassificationStyle enteries encoded in the given
* ACMatchClassification style field, maps each entry to a CSS
* class and returns them.
*/
private convertClassificationStyleToCssClasses_(style: number): string[] {
const classes = [];
if (style & AcMatchClassificationStyle.DIM) {
classes.push('dim');
}
if (style & AcMatchClassificationStyle.MATCH) {
classes.push('match');
}
if (style & AcMatchClassificationStyle.URL) {
classes.push('url');
}
return classes;
}
private createSpanWithClasses_(text: string, classes: string[]): Element {
const span = document.createElement('span');
if (classes.length) {
span.classList.add(...classes);
}
span.textContent = text;
return span;
}
/**
* Renders |text| based on the given ACMatchClassification(s)
* Each classification contains an 'offset' and an encoded list of styles for
* styling a substring starting with the 'offset' and ending with the next.
* @return A <span> with <span> children for each styled substring.
*/
private renderTextWithClassifications_(
text: string, classifications: ACMatchClassification[]): Element {
return classifications
.map(({offset, style}, index) => {
const next = classifications[index + 1] || {offset: text.length};
const subText = text.substring(offset, next.offset);
const classes = this.convertClassificationStyleToCssClasses_(style);
return this.createSpanWithClasses_(subText, classes);
})
.reduce((container, currentElement) => {
container.appendChild(currentElement);
return container;
}, document.createElement('span'));
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-realbox-match': RealboxMatchElement;
}
}
customElements.define(RealboxMatchElement.is, RealboxMatchElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/realbox_match.ts | TypeScript | unknown | 13,624 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assertNotReached} from '//resources/js/assert_ts.js';
import {String16} from '//resources/mojo/mojo/public/mojom/base/string16.mojom-webui.js';
import {TimeTicks} from '//resources/mojo/mojo/public/mojom/base/time.mojom-webui.js';
import {SideType} from './omnibox.mojom-webui.js';
/** Converts a String16 to a JavaScript String. */
export function decodeString16(str: String16|null): string {
return str ? str.data.map(ch => String.fromCodePoint(ch)).join('') : '';
}
/** Converts a JavaScript String to a String16. */
export function mojoString16(str: string): String16 {
const array = new Array(str.length);
for (let i = 0; i < str.length; ++i) {
array[i] = str.charCodeAt(i);
}
return {data: array};
}
/**
* Converts a time ticks in milliseconds to TimeTicks.
* @param timeTicks time ticks in milliseconds
*/
export function mojoTimeTicks(timeTicks: number): TimeTicks {
return {internalValue: BigInt(Math.floor(timeTicks * 1000))};
}
/** Converts a side type to a string to be used in CSS. */
export function sideTypeToClass(sideType: SideType): string {
switch (sideType) {
case SideType.kDefaultPrimary:
return 'primary-side';
case SideType.kSecondary:
return 'secondary-side';
default:
assertNotReached('Unexpected side type');
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/omnibox/utils.ts | TypeScript | unknown | 1,450 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview The browser proxy used to access `PageImageService` from WebUI.
*/
import {PageImageServiceHandler, PageImageServiceHandlerRemote} from './page_image_service.mojom-webui.js';
export class PageImageServiceBrowserProxy {
handler: PageImageServiceHandlerRemote;
constructor(handler: PageImageServiceHandlerRemote) {
this.handler = handler;
}
static getInstance(): PageImageServiceBrowserProxy {
return instance ||
(instance = new PageImageServiceBrowserProxy(
PageImageServiceHandler.getRemote()));
}
static setInstance(obj: PageImageServiceBrowserProxy) {
instance = obj;
}
}
let instance: PageImageServiceBrowserProxy|null = null;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/page_image_service/browser_proxy.ts | TypeScript | unknown | 849 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/** @fileoverview Utility functions to help use prefs in Polymer controls. */
import {assertNotReached} from 'chrome://resources/js/assert_ts.js';
/**
* Converts a string value to a type corresponding to the given preference.
*/
export function stringToPrefValue(
value: string, pref: chrome.settingsPrivate.PrefObject):
(boolean|number|string|undefined) {
switch (pref.type) {
case chrome.settingsPrivate.PrefType.BOOLEAN:
return value === 'true';
case chrome.settingsPrivate.PrefType.NUMBER:
const n = parseFloat(value);
if (isNaN(n)) {
console.error(
'Argument to stringToPrefValue for number pref ' +
'was unparsable: ' + value);
return undefined;
}
return n;
case chrome.settingsPrivate.PrefType.STRING:
case chrome.settingsPrivate.PrefType.URL:
return value;
default:
assertNotReached('No conversion from string to ' + pref.type + ' pref');
}
}
/**
* Returns the value of the pref as a string.
*/
export function prefToString(pref: chrome.settingsPrivate.PrefObject): string {
switch (pref.type) {
case chrome.settingsPrivate.PrefType.BOOLEAN:
case chrome.settingsPrivate.PrefType.NUMBER:
return pref.value.toString();
case chrome.settingsPrivate.PrefType.STRING:
case chrome.settingsPrivate.PrefType.URL:
return pref.value;
default:
assertNotReached('No conversion from ' + pref.type + ' pref to string');
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/settings_prefs/pref_util.ts | TypeScript | unknown | 1,624 |
/* Copyright 2015 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/**
* @fileoverview
* 'settings-prefs' exposes a singleton model of Chrome settings and
* preferences, which listens to changes to Chrome prefs allowed in
* chrome.settingsPrivate. When changing prefs in this element's 'prefs'
* property via the UI, the singleton model tries to set those preferences in
* Chrome. Whether or not the calls to settingsPrivate.setPref succeed, 'prefs'
* is eventually consistent with the Chrome pref store.
*/
import {assert} from '//resources/js/assert_ts.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CrSettingsPrefs} from './prefs_types.js';
/**
* Checks whether two values are recursively equal. Only compares serializable
* data (primitives, serializable arrays and serializable objects).
* @param val1 Value to compare.
* @param val2 Value to compare with val1.
* @return Whether the values are recursively equal.
*/
function deepEqual(val1: any, val2: any): boolean {
if (val1 === val2) {
return true;
}
if (Array.isArray(val1) || Array.isArray(val2)) {
if (!Array.isArray(val1) || !Array.isArray(val2)) {
return false;
}
return arraysEqual(val1, val2);
}
if (val1 instanceof Object && val2 instanceof Object) {
return objectsEqual(val1, val2);
}
return false;
}
/**
* @return Whether the arrays are recursively equal.
*/
function arraysEqual(arr1: any[], arr2: any[]): boolean {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (!deepEqual(arr1[i], arr2[i])) {
return false;
}
}
return true;
}
/**
* @return Whether the objects are recursively equal.
*/
function objectsEqual(
obj1: {[key: string]: any}, obj2: {[key: string]: any}): boolean {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (let i = 0; i < keys1.length; i++) {
const key = keys1[i];
if (!deepEqual(obj1[key], obj2[key])) {
return false;
}
}
return true;
}
/**
* Returns a recursive copy of the value.
* @param val Value to copy. Should be a primitive or only contain
* serializable data (primitives, serializable arrays and
* serializable objects).
* @return A deep copy of the value.
*/
function deepCopy(val: any): any {
if (!(val instanceof Object)) {
return val;
}
return Array.isArray(val) ? deepCopyArray(val) : deepCopyObject(val);
}
/**
* @return Deep copy of the array.
*/
function deepCopyArray(arr: any[]): any[] {
const copy = [];
for (let i = 0; i < arr.length; i++) {
copy.push(deepCopy(arr[i]));
}
return copy;
}
/**
* @return Deep copy of the object.
*/
function deepCopyObject(obj: {[key: string]: any}): {[key: string]: any} {
const copy: {[key: string]: any} = {};
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
copy[key] = deepCopy(obj[key]);
}
return copy;
}
export class SettingsPrefsElement extends PolymerElement {
static get is() {
return 'settings-prefs';
}
static get properties() {
return {
/**
* Object containing all preferences, for use by Polymer controls.
*/
prefs: {
type: Object,
notify: true,
},
/**
* Map of pref keys to values representing the state of the Chrome
* pref store as of the last update from the API.
*/
lastPrefValues_: {
type: Object,
value() {
return {};
},
},
};
}
static get observers() {
return [
'prefsChanged_(prefs.*)',
];
}
prefs: {[key: string]: any}|undefined;
private lastPrefValues_: {[key: string]: any};
private settingsApi_: typeof chrome.settingsPrivate = chrome.settingsPrivate;
private initialized_: boolean = false;
private boundPrefsChanged_:
(prefs: chrome.settingsPrivate.PrefObject[]) => void;
constructor() {
super();
if (!CrSettingsPrefs.deferInitialization) {
this.initialize();
}
}
override disconnectedCallback() {
super.disconnectedCallback();
CrSettingsPrefs.resetForTesting();
}
/**
* @param settingsApi SettingsPrivate implementation to use
* (chrome.settingsPrivate by default).
*/
initialize(settingsApi?: typeof chrome.settingsPrivate) {
// Only initialize once (or after resetForTesting() is called).
if (this.initialized_) {
return;
}
this.initialized_ = true;
if (settingsApi) {
this.settingsApi_ = settingsApi;
}
this.boundPrefsChanged_ = this.onSettingsPrivatePrefsChanged_.bind(this);
this.settingsApi_.onPrefsChanged.addListener(this.boundPrefsChanged_);
this.settingsApi_.getAllPrefs().then((prefs) => {
this.updatePrefs_(prefs);
CrSettingsPrefs.setInitialized();
});
}
private prefsChanged_(e: {path: string}) {
// |prefs| can be directly set or unset in tests.
if (!CrSettingsPrefs.isInitialized || e.path === 'prefs') {
return;
}
const key = this.getPrefKeyFromPath_(e.path);
const prefStoreValue = this.lastPrefValues_[key];
const prefObj = this.get(key, this.prefs);
// If settingsPrivate already has this value, ignore it. (Otherwise,
// a change event from settingsPrivate could make us call
// settingsPrivate.setPref and potentially trigger an IPC loop.)
if (!deepEqual(prefStoreValue, prefObj.value)) {
// <if expr="chromeos_ash">
this.dispatchEvent(new CustomEvent('user-action-setting-change', {
bubbles: true,
composed: true,
detail: {prefKey: key, prefValue: prefObj.value},
}));
// </if>
this.settingsApi_
.setPref(
key, prefObj.value,
/* pageId */ '')
.then(success => {
if (!success) {
this.refresh(key);
}
});
}
}
/**
* Called when prefs in the underlying Chrome pref store are changed.
*/
private onSettingsPrivatePrefsChanged_(
prefs: chrome.settingsPrivate.PrefObject[]) {
if (CrSettingsPrefs.isInitialized) {
this.updatePrefs_(prefs);
}
}
/**
* Get the current pref value from chrome.settingsPrivate to ensure the UI
* stays up to date.
*/
refresh(key: string) {
this.settingsApi_.getPref(key).then(pref => {
this.updatePrefs_([pref]);
});
}
/**
* Builds an object structure for the provided |path| within |prefsObject|,
* ensuring that names that already exist are not overwritten. For example:
* "a.b.c" -> a = {};a.b={};a.b.c={};
* @param path Path to the new pref value.
* @param value The value to expose at the end of the path.
* @param prefsObject The prefs object to add the path to.
*/
private updatePrefPath_(
path: string, value: any, prefsObject: {[key: string]: any}) {
const parts = path.split('.');
let cur = prefsObject;
for (let part; parts.length && (part = parts.shift());) {
if (!parts.length) {
// last part, set the value.
cur[part] = value;
} else if (part in cur) {
cur = cur[part];
} else {
cur = cur[part] = {};
}
}
}
/**
* Updates the prefs model with the given prefs.
*/
private updatePrefs_(newPrefs: chrome.settingsPrivate.PrefObject[]) {
// Use the existing prefs object or create it.
const prefs = this.prefs || {};
newPrefs.forEach((newPrefObj) => {
// Use the PrefObject from settingsPrivate to create a copy in
// lastPrefValues_ at the pref's key.
this.lastPrefValues_[newPrefObj.key] = deepCopy(newPrefObj.value);
if (!deepEqual(this.get(newPrefObj.key, prefs), newPrefObj)) {
// Add the pref to |prefs|.
this.updatePrefPath_(newPrefObj.key, newPrefObj, prefs);
// If this.prefs already exists, notify listeners of the change.
if (prefs === this.prefs) {
this.notifyPath('prefs.' + newPrefObj.key, newPrefObj);
}
}
});
if (!this.prefs) {
this.prefs = prefs;
}
}
/**
* Given a 'property-changed' path, returns the key of the preference the
* path refers to. E.g., if the path of the changed property is
* 'prefs.search.suggest_enabled.value', the key of the pref that changed is
* 'search.suggest_enabled'.
*/
private getPrefKeyFromPath_(path: string): string {
// Skip the first token, which refers to the member variable (this.prefs).
const parts = path.split('.');
assert(parts.shift() === 'prefs', 'Path doesn\'t begin with \'prefs\'');
for (let i = 1; i <= parts.length; i++) {
const key = parts.slice(0, i).join('.');
// The lastPrefValues_ keys match the pref keys.
if (this.lastPrefValues_.hasOwnProperty(key)) {
return key;
}
}
return '';
}
/**
* Resets the element so it can be re-initialized with a new prefs state.
*/
resetForTesting() {
if (!this.initialized_) {
return;
}
this.prefs = undefined;
this.lastPrefValues_ = {};
this.initialized_ = false;
// Remove the listener added in initialize().
this.settingsApi_.onPrefsChanged.removeListener(this.boundPrefsChanged_);
this.settingsApi_ = chrome.settingsPrivate;
}
}
declare global {
interface HTMLElementTagNameMap {
'settings-prefs': SettingsPrefsElement;
}
}
customElements.define(SettingsPrefsElement.is, SettingsPrefsElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/settings_prefs/prefs.ts | TypeScript | unknown | 9,671 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Common prefs behavior.
*/
// clang-format off
import {assert} from 'chrome://resources/js/assert_ts.js';
import {dedupingMixin, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
// clang-format on
type Constructor<T> = new (...args: any[]) => T;
export const PrefsMixin = dedupingMixin(
<T extends Constructor<PolymerElement>>(superClass: T): T&
Constructor<PrefsMixinInterface> => {
class PrefsMixin extends superClass implements PrefsMixinInterface {
static get properties() {
return {
/** Preferences state. */
prefs: {
type: Object,
notify: true,
},
};
}
prefs: any;
/**
* Gets the pref at the given prefPath. Throws if the pref is not found.
*/
getPref(prefPath: string) {
const pref = this.get(prefPath, this.prefs);
assert(typeof pref !== 'undefined', 'Pref is missing: ' + prefPath);
return pref;
}
/**
* Sets the value of the pref at the given prefPath. Throws if the pref
* is not found.
*/
setPrefValue(prefPath: string, value: any) {
this.getPref(prefPath); // Ensures we throw if the pref is not found.
this.set('prefs.' + prefPath + '.value', value);
}
/**
* Appends the item to the pref list at the given key if the item is not
* already in the list. Asserts if the pref itself is not found or is
* not an Array type.
*/
appendPrefListItem(key: string, item: any) {
const pref = this.getPref(key);
assert(pref && pref.type === chrome.settingsPrivate.PrefType.LIST);
if (pref.value.indexOf(item) === -1) {
this.push('prefs.' + key + '.value', item);
}
}
/**
* Updates the item in the pref list to the new value. Asserts if the
* pref itself is not found or is not an Array type.
*/
updatePrefListItem(key: string, item: any, newItem: any) {
const pref = this.getPref(key);
assert(pref && pref.type === chrome.settingsPrivate.PrefType.LIST);
const index = pref.value.indexOf(item);
if (index !== -1) {
this.set(`prefs.${key}.value.${index}`, newItem);
}
}
/**
* Deletes the given item from the pref at the given key if the item is
* found. Asserts if the pref itself is not found or is not an Array
* type.
*/
deletePrefListItem(key: string, item: any) {
assert(
this.getPref(key).type === chrome.settingsPrivate.PrefType.LIST);
const index = this.getPref(key).value.indexOf(item);
if (index !== -1) {
this.splice(`prefs.${key}.value`, index, 1);
}
}
}
return PrefsMixin;
});
export interface PrefsMixinInterface {
prefs: any;
getPref<T = any>(prefPath: string): chrome.settingsPrivate.PrefObject<T>;
setPrefValue(prefPath: string, value: any): void;
appendPrefListItem(key: string, item: any): void;
updatePrefListItem(key: string, item: any, new_item: any): void;
deletePrefListItem(key: string, item: any): void;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/settings_prefs/prefs_mixin.ts | TypeScript | unknown | 3,490 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Global state for prefs initialization status.
*/
import {PromiseResolver} from 'chrome://resources/js/promise_resolver.js';
class CrSettingsPrefsInternal {
isInitialized: boolean = false;
deferInitialization: boolean;
private initializedResolver_: PromiseResolver<void> = new PromiseResolver();
constructor() {
/**
* Whether to defer initialization. Used in testing to prevent premature
* initialization when intending to fake the settings API.
*/
this.deferInitialization = false;
}
get initialized(): Promise<void> {
return this.initializedResolver_.promise;
}
/** Resolves the |initialized| promise. */
setInitialized() {
this.isInitialized = true;
this.initializedResolver_.resolve();
}
/** Restores state for testing. */
resetForTesting() {
this.isInitialized = false;
this.initializedResolver_ = new PromiseResolver();
}
}
export const CrSettingsPrefs: CrSettingsPrefsInternal =
new CrSettingsPrefsInternal();
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/settings_prefs/prefs_types.ts | TypeScript | unknown | 1,162 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #import=./cr_shared_vars.css.js
* #import=//resources/polymer/v3_0/paper-styles/color.js
* #css_wrapper_metadata_end */
[is='action-link'] {
cursor: pointer;
display: inline-block;
text-decoration: underline;
}
[is='action-link'],
[is='action-link']:active,
[is='action-link']:hover,
[is='action-link']:visited {
color: var(--cr-link-color);
}
[is='action-link'][disabled] {
color: var(--paper-grey-600); /* TODO(dbeam): update for dark mode. */
cursor: default;
opacity: 0.65;
pointer-events: none;
}
[is='action-link'].no-outline {
outline: none;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/action_link.css | CSS | unknown | 772 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #scheme=relative
* #css_wrapper_metadata_end */
/* Style Module that defines color overrides for cr-elements on Chrome OS.
This file plumbs semantic colors from cros_styles.css into cr-elements.
To get Chrome OS System Colors, an element must:
- be beneath a <html> element with a "cros" attribute
- have a <style include="cros-color-overrides"> module in its style module list
- import the following URL in JS/TS
//resources/cr_elements/chromeos/cros_color_overrides.css.js
*/
:host-context([cros]) a:not(.item)[href] {
color: var(--cros-link-color);
}
:host-context([cros]) cr-button[has-prefix-icon_],
:host-context([cros]) cr-button[has-suffix-icon_] {
--iron-icon-fill-color: currentColor;
}
:host-context([cros]) cr-dialog::part(dialog) {
--cr-dialog-background-color: var(--cros-bg-color-elevation-3);
background-image: none;
box-shadow: var(--cros-elevation-3-shadow);
}
:host-context([cros]) cr-radio-button {
--cr-radio-button-checked-color: var(--cros-radio-button-color);
--cr-radio-button-checked-ripple-color:
var(--cros-radio-button-ripple-color);
--cr-radio-button-unchecked-color:
var(--cros-radio-button-color-unchecked);
--cr-radio-button-unchecked-ripple-color:
var(--cros-radio-button-ripple-color-unchecked);
}
:host-context([cros]) cr-toast {
--cr-toast-background-color: var(--cros-toast-background-color);
--cr-toast-background: var(--cros-toast-background-color);
--cr-toast-text-color: var(--cros-toast-text-color);
--iron-icon-fill-color: var(--cros-toast-icon-color);
}
:host-context([cros]) cr-toast .error-message {
color: var(--cros-toast-text-color);
}
:host-context([cros]) cr-toggle {
--cr-toggle-checked-bar-color: var(--cros-switch-track-color-active);
/* |--cros-switch-track-color-active| already includes opacity. */
--cr-toggle-checked-bar-opacity: 100%;
--cr-toggle-checked-button-color: var(--cros-switch-knob-color-active);
--cr-toggle-checked-ripple-color: var(--cros-focus-aura-color);
--cr-toggle-unchecked-bar-color: var(--cros-switch-track-color-inactive);
--cr-toggle-unchecked-button-color: var(--cros-switch-knob-color-inactive);
--cr-toggle-unchecked-ripple-color: var(--cros-ripple-color);
--cr-toggle-box-shadow: var(--cros-elevation-1-shadow);
--cr-toggle-ripple-diameter: 32px;
}
:host-context([cros]) cr-toggle:focus {
--cr-toggle-ripple-ring: 2px solid var(--cros-focus-ring-color);
}
:host-context([cros]) .primary-toggle {
color: var(--cros-text-color-secondary);
}
:host-context([cros]) .primary-toggle[checked] {
color: var(--cros-text-color-prominent);
}
:host-context([cros]) paper-spinner-lite {
--paper-spinner-color: var(--cros-icon-color-prominent);
}
:host-context([cros]) cr-tooltip-icon {
--cr-link-color: var(--cros-tooltip-link-color);
}
/** Jelly-specific styles below */
/** General color overrides */
:host-context(body.jelly-enabled) {
/* TODO(b/266837484) --cros-* values will be updated globally. Remove these
definitions after the swap. */
--cros-button-label-color-primary: var(--cros-sys-on_primary);
--cros-link-color: var(--cros-sys-primary);
--cros-separator-color: var(--cros-sys-separator);
--cros-tab-slider-track-color: var(--cros-sys-surface_variant, 80%);
--cr-form-field-label-color: var(--cros-sys-on_surface);
--cr-link-color: var(--cros-sys-primary);
--cr-primary-text-color: var(--cros-sys-on_surface);
--cr-secondary-text-color: var(--cros-sys-secondary);
}
/* Button */
:host-context(body.jelly-enabled) cr-button {
/* Default button colors */
--text-color: var(--cros-sys-on_primary_container);
--ink-color: var(--cros-sys-ripple_primary);
--iron-icon-fill-color: currentColor;
--hover-bg-color: var(--cros-sys-hover_on_subtle);
--ripple-opacity: .1;
/* Action button colors */
--bg-action: var(--cros-sys-primary);
--ink-color-action: var(--cros-sys-ripple_primary);
--text-color-action: var(--cros-sys-on_primary);
--hover-bg-action: var(--cros-sys-hover_on_prominent);
--ripple-opacity-action: 1;
/* Disabled button colors */
--disabled-bg: var(--cros-sys-disabled_container);
--disabled-bg-action: var(--cros-sys-disabled_container);
--disabled-text-color: var(--cros-sys-disabled);
background-color: var(--cros-sys-primary_container);
border: none;
}
:host-context(body.jelly-enabled) cr-button:hover::part(hoverBackground) {
background-color: var(--hover-bg-color);
display: block;
}
:host-context(body.jelly-enabled) cr-button.action-button {
background-color: var(--bg-action);
}
:host-context(body.jelly-enabled)
cr-button.action-button:hover::part(hoverBackground) {
background-color: var(--hover-bg-action);
}
:host-context(body.jelly-enabled) cr-button[disabled] {
background-color: var(--cros-sys-disabled_container);
}
:host-context(body.jelly-enabled):host-context(.focus-outline-visible)
cr-button:focus {
box-shadow: none;
outline: 2px solid var(--cros-sys-focus_ring);
}
/* Checkbox */
:host-context(body.jelly-enabled) cr-checkbox {
--cr-checkbox-checked-box-color: var(--cros-sys-primary);
--cr-checkbox-ripple-checked-color: var(--cros-sys-ripple_primary);
--cr-checkbox-checked-ripple-opacity: 1;
--cr-checkbox-mark-color: var(--cros-sys-inverse_on_surface);
--cr-checkbox-ripple-unchecked-color: var(--cros-sys-ripple_primary);
--cr-checkbox-unchecked-box-color: var(--cros-sys-on_surface);
--cr-checkbox-unchecked-ripple-opacity: 1;
}
/* Dialog */
:host-context(body.jelly-enabled) cr-dialog::part(dialog) {
--cr-dialog-background-color: var(--cros-sys-base_elevated);
background-image: none;
/* TODO(b/266837484) Replace with cros.sys.app-elevation3 when available */
box-shadow: 0 0 12px 0 var(--cros-sys-shadow);
}
/* Icon button */
:host-context(body.jelly-enabled) cr-icon-button,
:host-context(body.jelly-enabled) cr-link-row::part(icon),
:host-context(body.jelly-enabled) cr-expand-button::part(icon) {
--cr-icon-button-fill-color: var(--cros-sys-secondary);
}
/* Input and Textarea */
:host-context(body.jelly-enabled) cr-input,
:host-context(body.jelly-enabled) cr-search-field::part(searchInput),
:host-context(body.jelly-enabled) cr-textarea {
--cr-input-background-color: var(--cros-sys-input_field_on_base);
--cr-input-error-color: var(--cros-sys-error);
--cr-input-focus-color: var(--cros-sys-primary);
--cr-input-placeholder-color: var(--cros-sys-secondary);
}
/* md-select */
:host-context(body.jelly-enabled) .md-select {
--md-select-bg-color: var(--cros-sys-input_field_on_base);
--md-select-focus-shadow-color: var(--cros-sys-primary);
--md-select-option-bg-color: var(--cros-sys-base_elevated);
--md-select-text-color: var(--cros-sys-on_surface);
}
/* Radio button */
:host-context(body.jelly-enabled),
:host-context(body.jelly-enabled) cr-radio-button {
--cr-radio-button-checked-color: var(--cros-sys-primary);
--cr-radio-button-checked-ripple-color: var(--cros-sys-ripple_primary);
--cr-radio-button-unchecked-color: var(--cros-sys-on_surface);
--cr-radio-button-unchecked-ripple-color:
var(--cros-sys-ripple_neutral_on_subtle);
}
:host-context(body.jelly-enabled) cr-card-radio-button {
--cr-card-background-color: var(--cros-sys-app_base);
--cr-checked-color: var(--cros-sys-primary);
--cr-radio-button-checked-ripple-color: var(--cros-sys-ripple_primary);
--hover-bg-color: var(--cros-sys-hover_on_subtle);
}
/* Search field */
:host-context(body.jelly-enabled) cr-search-field {
--cr-search-field-clear-icon-fill: var(--cros-sys-primary);
--cr-search-field-clear-icon-margin-end: 6px;
--cr-search-field-input-border-bottom: none;
--cr-search-field-input-padding-start: 8px;
--cr-search-field-input-underline-border-radius: 4px;
--cr-search-field-search-icon-display: none;
--cr-search-field-search-icon-fill: var(--cros-sys-primary);
--cr-search-field-search-icon-inline-display: block;
--cr-search-field-search-icon-inline-margin-start: 6px;
border-radius: 4px;
}
/* Slider */
:host-context(body.jelly-enabled) cr-slider {
--cr-slider-active-color: var(--cros-sys-primary);
--cr-slider-container-color: var(--cros-sys-primary_container);
--cr-slider-container-disabled-color: var(--cros-sys-disabled_container);
--cr-slider-disabled-color: var(--cros-sys-disabled);
--cr-slider-knob-active-color: var(--cros-sys-primary);
--cr-slider-knob-disabled-color: var(--cros-sys-disabled);
--cr-slider-marker-active-color: var(--cros-sys-primary_container);
--cr-slider-marker-color: var(--cros-sys-primary);
--cr-slider-marker-disabled-color: var(--cros-sys-disabled);
--cr-slider-ripple-color: var(--cros-sys-hover_on_prominent);
}
:host-context(body.jelly-enabled) cr-slider:not([disabled])::part(knob) {
background-color: var(--cros-sys-primary);
}
:host-context(body.jelly-enabled) cr-slider[disabled]::part(knob) {
border: none;
}
:host-context(body.jelly-enabled) cr-slider::part(label) {
background: var(--cros-sys-primary);
color: var(--cros-sys-on_primary);
}
/* Tabs */
:host-context(body.jelly-enabled) cr-tabs {
--cr-tabs-selected-color: var(--cros-sys-primary);
}
/* Toggle */
:host-context(body.jelly-enabled) cr-toggle {
--cr-toggle-checked-bar-color: var(--cros-sys-primary_container);
--cr-toggle-checked-bar-opacity: 100%;
--cr-toggle-checked-button-color: var(--cros-sys-primary);
--cr-toggle-checked-ripple-color: var(--cros-sys-hover_on_prominent);
--cr-toggle-unchecked-bar-color: var(--cros-sys-secondary);
--cr-toggle-unchecked-button-color: var(--cros-sys-on_secondary);
--cr-toggle-unchecked-ripple-color: var(--cros-sys-hover_on_prominent);
/* TODO(b/266837484) Replace with cros.sys.app-elevation1 when available */
--cr-toggle-box-shadow: var(--cros-elevation-1-shadow);
--cr-toggle-ripple-diameter: 32px;
}
:host-context(body.jelly-enabled) cr-toggle:focus {
--cr-toggle-ripple-ring: 2px solid var(--cros-sys-focus_ring);
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/chromeos/cros_color_overrides.css | CSS | unknown | 10,131 |
<style>
:host {
clip: rect(0 0 0 0);
height: 1px;
overflow: hidden;
position: fixed;
width: 1px;
}
</style>
<div id="messages" role="alert" aria-live="polite" aria-relevant="additions">
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_a11y_announcer/cr_a11y_announcer.html | HTML | unknown | 218 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert} from '//resources/js/assert_ts.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_a11y_announcer.html.js';
/**
* The CrA11yAnnouncerElement is a visually hidden element that reads out
* messages to a screen reader. This is preferred over IronA11yAnnouncer.
* @fileoverview
*/
type CrA11yAnnouncerMessagesSentEvent = CustomEvent<{
messages: string[],
}>;
declare global {
interface HTMLElementEventMap {
'cr-a11y-announcer-messages-sent': CrA11yAnnouncerMessagesSentEvent;
}
}
/**
* 150ms seems to be around the minimum time required for screen readers to
* read out consecutively queued messages.
*/
export const TIMEOUT_MS: number = 150;
/**
* A map of an HTML element to its corresponding CrA11yAnnouncerElement. There
* may be multiple CrA11yAnnouncerElements on a page, especially for cases in
* which the DocumentElement's CrA11yAnnouncerElement becomes hidden or
* deactivated (eg. when a modal dialog causes the CrA11yAnnouncerElement to
* become inaccessible).
*/
const instances: Map<HTMLElement, CrA11yAnnouncerElement> = new Map();
export function getInstance(container: HTMLElement = document.body):
CrA11yAnnouncerElement {
if (instances.has(container)) {
return instances.get(container)!;
}
assert(container.isConnected);
const instance = new CrA11yAnnouncerElement();
container.appendChild(instance);
instances.set(container, instance);
return instance;
}
export class CrA11yAnnouncerElement extends PolymerElement {
static get is() {
return 'cr-a11y-announcer';
}
static get template() {
return getTemplate();
}
private currentTimeout_: number|null = null;
private messages_: string[] = [];
override disconnectedCallback() {
super.disconnectedCallback();
if (this.currentTimeout_ !== null) {
clearTimeout(this.currentTimeout_);
this.currentTimeout_ = null;
}
for (const [parent, instance] of instances) {
if (instance === this) {
instances.delete(parent);
break;
}
}
}
announce(message: string) {
if (this.currentTimeout_ !== null) {
clearTimeout(this.currentTimeout_);
this.currentTimeout_ = null;
}
this.messages_.push(message);
this.currentTimeout_ = setTimeout(() => {
const messagesDiv = this.shadowRoot!.querySelector('#messages')!;
messagesDiv.innerHTML = window.trustedTypes!.emptyHTML;
// <if expr="is_macosx">
// VoiceOver on Mac does not seem to consistently read out the contents of
// a static alert element. Toggling the role of alert seems to force VO
// to consistently read out the messages.
messagesDiv.removeAttribute('role');
messagesDiv.setAttribute('role', 'alert');
// </if>
for (const message of this.messages_) {
const div = document.createElement('div');
div.textContent = message;
messagesDiv.appendChild(div);
}
// Dispatch a custom event to allow consumers to know when certain alerts
// have been sent to the screen reader.
this.dispatchEvent(new CustomEvent(
'cr-a11y-announcer-messages-sent',
{bubbles: true, detail: {messages: this.messages_.slice()}}));
this.messages_.length = 0;
this.currentTimeout_ = null;
}, TIMEOUT_MS);
}
}
customElements.define(CrA11yAnnouncerElement.is, CrA11yAnnouncerElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_a11y_announcer/cr_a11y_announcer.ts | TypeScript | unknown | 3,613 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @constructor
* @extends {HTMLElement}
*/
function CrA11yAnnouncerElement() {}
/** @param {string} message */
CrA11yAnnouncerElement.prototype.announce = function(message) {};
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_a11y_announcer/cr_a11y_announcer_externs.js | JavaScript | unknown | 329 |
<style>
:host dialog {
background-color: var(--cr-menu-background-color);
border: none;
border-radius: 4px;
box-shadow: var(--cr-menu-shadow);
margin: 0;
min-width: 128px;
outline: none;
padding: 0;
position: absolute;
}
@media (forced-colors: active) {
:host dialog {
/* Use border instead of box-shadow (which does not work) in Windows
HCM. */
border: var(--cr-border-hcm);
}
}
:host dialog::backdrop {
background-color: transparent;
}
:host ::slotted(.dropdown-item) {
-webkit-tap-highlight-color: transparent;
background: none;
border: none;
border-radius: 0;
box-sizing: border-box;
color: var(--cr-primary-text-color);
font: inherit;
min-height: 32px;
padding: 8px 24px;
text-align: start;
user-select: none;
width: 100%;
}
:host ::slotted(.dropdown-item:not([hidden])) {
align-items: center;
display: flex;
}
:host ::slotted(.dropdown-item[disabled]) {
opacity: var(--cr-action-menu-disabled-item-opacity, 0.65);
}
:host ::slotted(.dropdown-item:not([disabled])) {
cursor: pointer;
}
:host ::slotted(.dropdown-item:focus) {
background-color: var(--cr-menu-background-focus-color);
outline: none;
}
@media (forced-colors: active) {
:host ::slotted(.dropdown-item:focus) {
/* Use outline instead of background-color (which does not work) in
Windows HCM. */
outline: var(--cr-focus-outline-hcm);
}
}
.item-wrapper {
background: var(--cr-menu-background-sheen);
outline: none;
padding: 8px 0;
}
</style>
<dialog id="dialog" part="dialog" on-close="onNativeDialogClose_"
role="application" aria-roledescription$="[[roleDescription]]">
<div id="wrapper" class="item-wrapper" role="menu" tabindex="-1"
aria-label$="[[accessibilityLabel]]">
<slot id="contentNode"></slot>
</div>
</dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.html | HTML | unknown | 2,217 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../cr_shared_vars.css.js';
import {assert} from '//resources/js/assert_ts.js';
import {FocusOutlineManager} from '//resources/js/focus_outline_manager.js';
import {FocusRow} from '//resources/js/focus_row.js';
import {focusWithoutInk} from '//resources/js/focus_without_ink.js';
import {isMac, isWindows} from '//resources/js/platform.js';
import {getDeepActiveElement} from '//resources/js/util_ts.js';
import {FlattenedNodesObserver, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_action_menu.html.js';
interface ShowAtConfig {
top?: number;
left?: number;
width?: number;
height?: number;
anchorAlignmentX?: number;
anchorAlignmentY?: number;
minX?: number;
minY?: number;
maxX?: number;
maxY?: number;
noOffset?: boolean;
}
export interface ShowAtPositionConfig {
top: number;
left: number;
width?: number;
height?: number;
anchorAlignmentX?: number;
anchorAlignmentY?: number;
minX?: number;
minY?: number;
maxX?: number;
maxY?: number;
}
export enum AnchorAlignment {
BEFORE_START = -2,
AFTER_START = -1,
CENTER = 0,
BEFORE_END = 1,
AFTER_END = 2,
}
const DROPDOWN_ITEM_CLASS: string = 'dropdown-item';
const SELECTABLE_DROPDOWN_ITEM_QUERY: string =
`.${DROPDOWN_ITEM_CLASS}:not([hidden]):not([disabled])`;
const AFTER_END_OFFSET: number = 10;
/**
* Returns the point to start along the X or Y axis given a start and end
* point to anchor to, the length of the target and the direction to anchor
* in. If honoring the anchor would force the menu outside of min/max, this
* will ignore the anchor position and try to keep the menu within min/max.
*/
function getStartPointWithAnchor(
start: number, end: number, menuLength: number,
anchorAlignment: AnchorAlignment, min: number, max: number): number {
let startPoint = 0;
switch (anchorAlignment) {
case AnchorAlignment.BEFORE_START:
startPoint = -menuLength;
break;
case AnchorAlignment.AFTER_START:
startPoint = start;
break;
case AnchorAlignment.CENTER:
startPoint = (start + end - menuLength) / 2;
break;
case AnchorAlignment.BEFORE_END:
startPoint = end - menuLength;
break;
case AnchorAlignment.AFTER_END:
startPoint = end;
break;
}
if (startPoint + menuLength > max) {
startPoint = end - menuLength;
}
if (startPoint < min) {
startPoint = start;
}
startPoint = Math.max(min, Math.min(startPoint, max - menuLength));
return startPoint;
}
function getDefaultShowConfig(): ShowAtPositionConfig {
return {
top: 0,
left: 0,
height: 0,
width: 0,
anchorAlignmentX: AnchorAlignment.AFTER_START,
anchorAlignmentY: AnchorAlignment.AFTER_START,
minX: 0,
minY: 0,
maxX: 0,
maxY: 0,
};
}
export interface CrActionMenuElement {
$: {
contentNode: HTMLSlotElement,
dialog: HTMLDialogElement,
wrapper: HTMLElement,
};
}
export class CrActionMenuElement extends PolymerElement {
static get is() {
return 'cr-action-menu';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
// Accessibility text of the menu. Should be something along the lines of
// "actions", or "more actions".
accessibilityLabel: String,
// Setting this flag will make the menu listen for content size changes
// and reposition to its anchor accordingly.
autoReposition: {
type: Boolean,
value: false,
},
open: {
type: Boolean,
notify: true,
value: false,
},
// Descriptor of the menu. Should be something along the lines of "menu"
roleDescription: String,
};
}
accessibilityLabel: string;
autoReposition: boolean;
open: boolean;
roleDescription: string;
private boundClose_: (() => void)|null = null;
private contentObserver_: FlattenedNodesObserver|null = null;
private resizeObserver_: ResizeObserver|null = null;
private hasMousemoveListener_: boolean = false;
private anchorElement_: HTMLElement|null = null;
private lastConfig_: ShowAtPositionConfig|null = null;
override ready() {
super.ready();
this.addEventListener('keydown', this.onKeyDown_.bind(this));
this.addEventListener('mouseover', this.onMouseover_);
this.addEventListener('click', this.onClick_);
}
override disconnectedCallback() {
super.disconnectedCallback();
this.removeListeners_();
}
private fire_(eventName: string, detail?: any) {
this.dispatchEvent(
new CustomEvent(eventName, {bubbles: true, composed: true, detail}));
}
/**
* Exposing internal <dialog> elements for tests.
*/
getDialog(): HTMLDialogElement {
return this.$.dialog;
}
private removeListeners_() {
window.removeEventListener('resize', this.boundClose_!);
window.removeEventListener('popstate', this.boundClose_!);
if (this.contentObserver_) {
this.contentObserver_.disconnect();
this.contentObserver_ = null;
}
if (this.resizeObserver_) {
this.resizeObserver_.disconnect();
this.resizeObserver_ = null;
}
}
private onNativeDialogClose_(e: Event) {
// Ignore any 'close' events not fired directly by the <dialog> element.
if (e.target !== this.$.dialog) {
return;
}
// Catch and re-fire the 'close' event such that it bubbles across Shadow
// DOM v1.
this.fire_('close');
}
private onClick_(e: Event) {
if (e.target === this) {
this.close();
e.stopPropagation();
}
}
private onKeyDown_(e: KeyboardEvent) {
e.stopPropagation();
if (e.key === 'Tab' || e.key === 'Escape') {
this.close();
if (e.key === 'Tab') {
this.fire_('tabkeyclose', {shiftKey: e.shiftKey});
}
e.preventDefault();
return;
}
if (e.key !== 'Enter' && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') {
return;
}
const options = Array.from(
this.querySelectorAll<HTMLElement>(SELECTABLE_DROPDOWN_ITEM_QUERY));
if (options.length === 0) {
return;
}
const focused = getDeepActiveElement();
const index = options.findIndex(
option => FocusRow.getFocusableElement(option) === focused);
if (e.key === 'Enter') {
// If a menu item has focus, don't change focus or close menu on 'Enter'.
if (index !== -1) {
return;
}
if (isWindows || isMac) {
this.close();
e.preventDefault();
return;
}
}
e.preventDefault();
this.updateFocus_(options, index, e.key !== 'ArrowUp');
if (!this.hasMousemoveListener_) {
this.hasMousemoveListener_ = true;
this.addEventListener('mousemove', e => {
this.onMouseover_(e);
this.hasMousemoveListener_ = false;
}, {once: true});
}
}
private onMouseover_(e: Event) {
const item =
(e.composedPath() as HTMLElement[])
.find(
el => el.matches && el.matches(SELECTABLE_DROPDOWN_ITEM_QUERY));
(item || this.$.wrapper).focus();
}
private updateFocus_(
options: HTMLElement[], focusedIndex: number, next: boolean) {
const numOptions = options.length;
assert(numOptions > 0);
let index;
if (focusedIndex === -1) {
index = next ? 0 : numOptions - 1;
} else {
const delta = next ? 1 : -1;
index = (numOptions + focusedIndex + delta) % numOptions;
}
options[index]!.focus();
}
close() {
// Removing 'resize' and 'popstate' listeners when dialog is closed.
this.removeListeners_();
this.$.dialog.close();
this.open = false;
if (this.anchorElement_) {
assert(this.anchorElement_);
focusWithoutInk(this.anchorElement_);
this.anchorElement_ = null;
}
if (this.lastConfig_) {
this.lastConfig_ = null;
}
}
/**
* Shows the menu anchored to the given element.
*/
showAt(anchorElement: HTMLElement, config?: ShowAtConfig) {
this.anchorElement_ = anchorElement;
// Scroll the anchor element into view so that the bounding rect will be
// accurate for where the menu should be shown.
this.anchorElement_.scrollIntoViewIfNeeded();
const rect = this.anchorElement_!.getBoundingClientRect();
let height = rect.height;
if (config && !config.noOffset &&
config.anchorAlignmentY === AnchorAlignment.AFTER_END) {
// When an action menu is positioned after the end of an element, the
// action menu can appear too far away from the anchor element, typically
// because anchors tend to have padding. So we offset the height a bit
// so the menu shows up slightly closer to the content of anchor.
height -= AFTER_END_OFFSET;
}
this.showAtPosition(Object.assign(
{
top: rect.top,
left: rect.left,
height: height,
width: rect.width,
// Default to anchoring towards the left.
anchorAlignmentX: AnchorAlignment.BEFORE_END,
},
config));
this.$.wrapper.focus();
}
/**
* Shows the menu anchored to the given box. The anchor alignment is
* specified as an X and Y alignment which represents a point in the anchor
* where the menu will align to, which can have the menu either before or
* after the given point in each axis. Center alignment places the center of
* the menu in line with the center of the anchor. Coordinates are relative to
* the top-left of the viewport.
*
* y-start
* _____________
* | |
* | |
* | CENTER |
* x-start | x | x-end
* | |
* |anchor box |
* |___________|
*
* y-end
*
* For example, aligning the menu to the inside of the top-right edge of
* the anchor, extending towards the bottom-left would use a alignment of
* (BEFORE_END, AFTER_START), whereas centering the menu below the bottom
* edge of the anchor would use (CENTER, AFTER_END).
*/
showAtPosition(config: ShowAtPositionConfig) {
// Save the scroll position of the viewport.
const doc = document.scrollingElement!;
const scrollLeft = doc.scrollLeft;
const scrollTop = doc.scrollTop;
// Reset position so that layout isn't affected by the previous position,
// and so that the dialog is positioned at the top-start corner of the
// document.
this.resetStyle_();
this.$.dialog.showModal();
this.open = true;
config.top += scrollTop;
config.left += scrollLeft;
this.positionDialog_(Object.assign(
{
minX: scrollLeft,
minY: scrollTop,
maxX: scrollLeft + doc.clientWidth,
maxY: scrollTop + doc.clientHeight,
},
config));
// Restore the scroll position.
doc.scrollTop = scrollTop;
doc.scrollLeft = scrollLeft;
this.addListeners_();
// Focus the first selectable item.
const openedByKey = FocusOutlineManager.forDocument(document).visible;
if (openedByKey) {
const firstSelectableItem =
this.querySelector<HTMLElement>(SELECTABLE_DROPDOWN_ITEM_QUERY);
if (firstSelectableItem) {
requestAnimationFrame(() => {
// Wait for the next animation frame for the dialog to become visible.
firstSelectableItem.focus();
});
}
}
}
private resetStyle_() {
this.$.dialog.style.left = '';
this.$.dialog.style.right = '';
this.$.dialog.style.top = '0';
}
/**
* Position the dialog using the coordinates in config. Coordinates are
* relative to the top-left of the viewport when scrolled to (0, 0).
*/
private positionDialog_(config: ShowAtPositionConfig) {
this.lastConfig_ = config;
const c = Object.assign(getDefaultShowConfig(), config);
const top = c.top;
const left = c.left;
const bottom = top + c.height!;
const right = left + c.width!;
// Flip the X anchor in RTL.
const rtl = getComputedStyle(this).direction === 'rtl';
if (rtl) {
c.anchorAlignmentX! *= -1;
}
const offsetWidth = this.$.dialog.offsetWidth;
const menuLeft = getStartPointWithAnchor(
left, right, offsetWidth, c.anchorAlignmentX!, c.minX!, c.maxX!);
if (rtl) {
const menuRight =
document.scrollingElement!.clientWidth - menuLeft - offsetWidth;
this.$.dialog.style.right = menuRight + 'px';
} else {
this.$.dialog.style.left = menuLeft + 'px';
}
const menuTop = getStartPointWithAnchor(
top, bottom, this.$.dialog.offsetHeight, c.anchorAlignmentY!, c.minY!,
c.maxY!);
this.$.dialog.style.top = menuTop + 'px';
}
private addListeners_() {
this.boundClose_ = this.boundClose_ || (() => {
if (this.$.dialog.open) {
this.close();
}
});
window.addEventListener('resize', this.boundClose_);
window.addEventListener('popstate', this.boundClose_);
this.contentObserver_ = new FlattenedNodesObserver(
this.$.contentNode, (info: {addedNodes: Element[]}) => {
info.addedNodes.forEach(node => {
if (node.classList &&
node.classList.contains(DROPDOWN_ITEM_CLASS) &&
!node.getAttribute('role')) {
node.setAttribute('role', 'menuitem');
}
});
});
if (this.autoReposition) {
this.resizeObserver_ = new ResizeObserver(() => {
if (this.lastConfig_) {
this.positionDialog_(this.lastConfig_);
this.fire_('cr-action-menu-repositioned'); // For easier testing.
}
});
this.resizeObserver_.observe(this.$.dialog);
}
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-action-menu': CrActionMenuElement;
}
}
customElements.define(CrActionMenuElement.is, CrActionMenuElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.ts | TypeScript | unknown | 14,206 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Minimal externs file provided for places in the code that
* still use JavaScript instead of TypeScript.
* @externs
*/
/**
* @typedef {{
* top: (number|undefined),
* left: (number|undefined),
* width: (number|undefined),
* height: (number|undefined),
* anchorAlignmentX: (number|undefined),
* anchorAlignmentY: (number|undefined),
* minX: (number|undefined),
* minY: (number|undefined),
* maxX: (number|undefined),
* maxY: (number|undefined),
* noOffset: (boolean|undefined),
* }}
*/
let ShowAtConfig;
/**
* @constructor
* @extends {HTMLElement}
*/
function CrActionMenuElement() {}
/** @type {boolean} */
CrActionMenuElement.prototype.open;
/** @return {!HTMLDialogElement} */
CrActionMenuElement.prototype.getDialog = function() {};
/**
* @param {!HTMLElement} anchorElement
* @param {ShowAtConfig=} config
*/
CrActionMenuElement.prototype.showAt = function(anchorElement, config) {};
CrActionMenuElement.prototype.close = function() {};
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu_externs.js | JavaScript | unknown | 1,137 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #import=./cr_shared_vars.css.js
* #css_wrapper_metadata_end */
:host {
align-items: center;
align-self: stretch;
display: flex;
margin: 0;
outline: none;
}
/* [effectively-disabled_] is a private attribute to allow custom elements
* to toggle the attribute based on state, such as whether or not the
* internal control element is disabled, without affecting any public
* attributes or properties. */
:host(:not([effectively-disabled_])) {
cursor: pointer;
}
:host(:not([no-hover], [effectively-disabled_]):hover) {
background-color: var(--cr-hover-background-color);
}
:host(:not([no-hover], [effectively-disabled_]):active) {
background-color: var(--cr-active-background-color);
}
/* Do not show hover or active states for cr-icon-buttons that are
* embedded within the row to avoid showing multiple layers of
* backgrounds. */
:host(:not([no-hover], [effectively-disabled_])) cr-icon-button {
--cr-icon-button-hover-background-color: transparent;
--cr-icon-button-active-background-color: transparent;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_actionable_row_style.css | CSS | unknown | 1,233 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview <cr-auto-img> is a specialized <img> that facilitates embedding
* images into WebUIs via its auto-src attribute. <cr-auto-img> automatically
* determines if the image is local (e.g. data: or chrome://) or external (e.g.
* https://), and embeds the image directly or via the chrome://image data
* source accordingly. Usage:
*
* 1. In C++ register |SanitizedImageSource| for your WebUI.
*
* 2. In HTML instantiate
*
* <img is="cr-auto-img" auto-src="https://foo.com/bar.png">
*
* If your image URL points to Google Photos storage, meaning it needs an
* auth token, you can use the is-google-photos attribute as follows:
*
* <img is="cr-auto-img" auto-src="https://foo.com/bar.png"
* is-google-photos>
*
* If you want the image to reset to an empty state when auto-src changes
* and the new image is still loading, set the clear-src attribute:
*
* <img is="cr-auto-img" auto-src="[[calculateSrc()]]" clear-src>
*
* If you want your image to be always encoded as a static image (even if
* the source image is animated), set the static-encode attribute:
*
* <img is="cr-auto-img" auto-src="https://foo.com/bar.png"
* static-encode>
*
* Static images are encoded as PNG by default. If you want your image to
* be encoded as a Webp image, set the encode-type attribute to "webp".
*
* <img is="cr-auto-img" auto-src="https://foo.com/bar.png"
* static-encode encode-type="webp">
*
* NOTE: Since <cr-auto-img> may use the chrome://image data source some images
* may be transcoded to PNG.
*/
const AUTO_SRC: string = 'auto-src';
const CLEAR_SRC: string = 'clear-src';
const IS_GOOGLE_PHOTOS: string = 'is-google-photos';
const STATIC_ENCODE: string = 'static-encode';
const ENCODE_TYPE: string = 'encode-type';
export class CrAutoImgElement extends HTMLImageElement {
static get observedAttributes() {
return [AUTO_SRC, IS_GOOGLE_PHOTOS, STATIC_ENCODE, ENCODE_TYPE];
}
attributeChangedCallback(
name: string, oldValue: string|null, newValue: string|null) {
if (name !== AUTO_SRC && name !== IS_GOOGLE_PHOTOS &&
name !== STATIC_ENCODE && name !== ENCODE_TYPE) {
return;
}
// Changes to |IS_GOOGLE_PHOTOS| are only interesting when the attribute is
// being added or removed.
if (name === IS_GOOGLE_PHOTOS &&
((oldValue === null) === (newValue === null))) {
return;
}
if (this.hasAttribute(CLEAR_SRC)) {
// Remove the src attribute so that the old image is not shown while the
// new one is loading.
this.removeAttribute('src');
}
let url = null;
try {
url = new URL(this.getAttribute(AUTO_SRC) || '');
} catch (_) {
}
if (!url || url.protocol === 'chrome-untrusted:') {
// Loading chrome-untrusted:// directly kills the renderer process.
// Loading chrome-untrusted:// via the chrome://image data source
// results in a broken image.
this.removeAttribute('src');
return;
}
if (url.protocol === 'data:' || url.protocol === 'chrome:') {
this.src = url.href;
return;
}
if (!this.hasAttribute(IS_GOOGLE_PHOTOS) &&
!this.hasAttribute(STATIC_ENCODE) && !this.hasAttribute(ENCODE_TYPE)) {
this.src = 'chrome://image?' + url.href;
return;
}
this.src = `chrome://image?url=${encodeURIComponent(url.href)}`;
if (this.hasAttribute(IS_GOOGLE_PHOTOS)) {
this.src += `&isGooglePhotos=true`;
}
if (this.hasAttribute(STATIC_ENCODE)) {
this.src += `&staticEncode=true`;
}
if (this.hasAttribute(ENCODE_TYPE)) {
this.src += `&encodeType=${this.getAttribute(ENCODE_TYPE)}`;
}
}
set autoSrc(src: string) {
this.setAttribute(AUTO_SRC, src);
}
get autoSrc(): string {
return this.getAttribute(AUTO_SRC) || '';
}
set clearSrc(_: string) {
this.setAttribute(CLEAR_SRC, '');
}
get clearSrc(): string {
return this.getAttribute(CLEAR_SRC) || '';
}
set isGooglePhotos(enabled: boolean) {
if (enabled) {
this.setAttribute(IS_GOOGLE_PHOTOS, '');
} else {
this.removeAttribute(IS_GOOGLE_PHOTOS);
}
}
get isGooglePhotos(): boolean {
return this.hasAttribute(IS_GOOGLE_PHOTOS);
}
set staticEncode(enabled: boolean) {
if (enabled) {
this.setAttribute(STATIC_ENCODE, '');
} else {
this.removeAttribute(STATIC_ENCODE);
}
}
get staticEncode(): boolean {
return this.hasAttribute(STATIC_ENCODE);
}
set encodeType(type: string) {
if (type) {
this.setAttribute(ENCODE_TYPE, type);
} else {
this.removeAttribute(ENCODE_TYPE);
}
}
get encodeType(): string {
return this.getAttribute(ENCODE_TYPE) || '';
}
}
customElements.define('cr-auto-img', CrAutoImgElement, {extends: 'img'});
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_auto_img/cr_auto_img.ts | TypeScript | unknown | 5,039 |
<style include="cr-hidden-style">
:host {
--active-shadow-rgb: var(--google-grey-800-rgb);
--active-shadow-action-rgb: var(--google-blue-500-rgb);
--bg-action: var(--google-blue-600);
--border-color: var(--google-grey-300);
--disabled-bg-action: var(--google-grey-100);
--disabled-bg: white;
--disabled-border-color: var(--google-grey-100);
--disabled-text-color: var(--google-grey-600);
--focus-shadow-color: rgba(var(--google-blue-600-rgb), .4);
--hover-bg-action: rgba(var(--google-blue-600-rgb), .9);
--hover-bg-color: rgba(var(--google-blue-500-rgb), .04);
--hover-border-color: var(--google-blue-100);
--hover-shadow-action-rgb: var(--google-blue-500-rgb);
--ink-color-action: white;
/* Blue-ish color used either as a background or as a text color,
* depending on the type of button. */
--ink-color: var(--google-blue-600);
--ripple-opacity-action: .32;
--ripple-opacity: .1;
--text-color-action: white;
--text-color: var(--google-blue-600);
}
@media (prefers-color-scheme: dark) {
:host {
/* Only in dark. */
--active-bg: black linear-gradient(rgba(255, 255, 255, .06),
rgba(255, 255, 255, .06));
--active-shadow-rgb: 0, 0, 0;
--active-shadow-action-rgb: var(--google-blue-500-rgb);
--bg-action: var(--google-blue-300);
--border-color: var(--google-grey-700);
--disabled-bg-action: var(--google-grey-800);
/* TODO(dbeam): get --disabled-bg from Namrata. */
--disabled-bg: transparent;
--disabled-border-color: var(--google-grey-800);
--disabled-text-color: var(--google-grey-500);
--focus-shadow-color: rgba(var(--google-blue-300-rgb), .5);
--hover-bg-action: var(--bg-action)
linear-gradient(rgba(0, 0, 0, .08), rgba(0, 0, 0, .08));
--hover-bg-color: rgba(var(--google-blue-300-rgb), .08);
--ink-color-action: black;
--ink-color: var(--google-blue-300);
--ripple-opacity-action: .16;
--ripple-opacity: .16;
--text-color-action: var(--google-grey-900);
--text-color: var(--google-blue-300);
}
}
:host {
--paper-ripple-opacity: var(--ripple-opacity);
-webkit-tap-highlight-color: transparent;
align-items: center;
border: 1px solid var(--border-color);
border-radius: 4px;
box-sizing: border-box;
color: var(--text-color);
cursor: pointer;
display: inline-flex;
flex-shrink: 0;
font-weight: 500;
height: var(--cr-button-height);
justify-content: center;
min-width: 5.14em;
outline-width: 0;
overflow: hidden;
padding: 8px 16px;
position: relative;
user-select: none;
}
:host-context([chrome-refresh-2023]):host {
/* Default button colors. */
--border-color: var(--color-button-border,
var(--cr-fallback-color-primary-container));
--text-color: var(--color-button-foreground,
var(--cr-fallback-color-primary));
--hover-bg-color: transparent;
--hover-border-color: var(--border-color);
--active-bg: transparent;
--active-shadow: none;
--ink-color: var(--cr-active-background-color);
--ripple-opacity: 1;
/* Disabled default button colors. */
--disabled-border-color: var(--color-button-border-disabled,
rgba(var(--cr-fallback-color-on-surface-rgb), .12));
--disabled-text-color: var(--color-button-foreground-disabled,
rgba(var(--cr-fallback-color-on-surface-rgb),
var(--cr-disabled-opacity)));
/* Action button colors. */
--bg-action: var(--color-button-background-prominent,
var(--cr-fallback-color-primary));
--text-color-action: var(--color-button-foreground-prominent,
var(--cr-fallback-color-on-primary));
--hover-bg-action: var(--bg-action);
--active-shadow-action: none;
--ink-color-action: var(--cr-active-background-color);
--ripple-opacity-action: 1;
/* Disabled action button colors. */
--disabled-bg-action: var(--color-button-background-prominent-disabled,
rgba(var(--cr-fallback-color-on-surface-rgb), .12));
background: transparent;
border-radius: 100px;
line-height: 20px;
}
:host([has-prefix-icon_]),
:host([has-suffix-icon_]) {
--iron-icon-height: 16px;
--iron-icon-width: 16px;
gap: 8px;
padding: 8px;
}
:host-context([chrome-refresh-2023]):host([has-prefix-icon_]),
:host-context([chrome-refresh-2023]):host([has-suffix-icon_]) {
--iron-icon-height: 20px;
--iron-icon-width: 20px;
--icon-block-padding-large: 16px;
--icon-block-padding-small: 12px;
padding-block-end: 8px;
padding-block-start: 8px;
}
:host-context([chrome-refresh-2023]):host([has-prefix-icon_]) {
padding-inline-end: var(--icon-block-padding-large);
padding-inline-start: var(--icon-block-padding-small);
}
:host-context([chrome-refresh-2023]):host([has-suffix-icon_]) {
padding-inline-end: var(--icon-block-padding-small);
padding-inline-start: var(--icon-block-padding-large);
}
:host-context(.focus-outline-visible):host(:focus) {
box-shadow: 0 0 0 2px var(--focus-shadow-color);
}
@media (forced-colors: active) {
:host-context(.focus-outline-visible):host(:focus) {
/* Use outline instead of box-shadow (which does not work) in Windows
HCM. */
outline: var(--cr-focus-outline-hcm);
}
}
:host-context([chrome-refresh-2023].focus-outline-visible):host(:focus) {
border-color: transparent;
box-shadow: none;
outline: 2px solid var(--cr-focus-outline-color);
}
:host(:active) {
background: var(--active-bg);
box-shadow: var(--active-shadow,
0 1px 2px 0 rgba(var(--active-shadow-rgb), .3),
0 3px 6px 2px rgba(var(--active-shadow-rgb), .15));
}
:host(:hover) {
background-color: var(--hover-bg-color);
}
@media (prefers-color-scheme: light) {
:host(:hover) {
border-color: var(--hover-border-color);
}
}
#background {
border: 2px solid transparent;
border-radius: inherit;
inset: 0;
pointer-events: none;
position: absolute;
z-index: 0;
}
:host-context([chrome-refresh-2023]):host(:hover) #background {
background-color: var(--hover-bg-color);
}
:host-context([chrome-refresh-2023].focus-outline-visible):host(:focus)
#background {
background-clip: padding-box;
}
:host-context([chrome-refresh-2023]):host(.action-button) #background {
background-color: var(--bg-action);
}
:host-context([chrome-refresh-2023]):host([disabled]) #background {
background-color: var(--disabled-bg);
}
:host-context([chrome-refresh-2023]):host(.action-button[disabled])
#background {
background-color: var(--disabled-bg-action);
}
:host-context([chrome-refresh-2023]):host(.tonal-button) #background,
:host-context([chrome-refresh-2023]):host(.floating-button) #background {
background-color: var(--color-button-background-tonal,
var(--cr-fallback-color-secondary-container));
}
:host-context([chrome-refresh-2023]):host([disabled].tonal-button)
#background,
:host-context([chrome-refresh-2023]):host([disabled].floating-button)
#background {
background-color: var(--color-button-background-tonal-disabled,
rgba(var(--cr-fallback-color-on-surface-rgb), .12));
}
#content {
display: contents;
}
:host-context([chrome-refresh-2023]) #content {
display: inline;
z-index: 2;
}
:host-context([chrome-refresh-2023]) ::slotted(*) {
z-index: 2;
}
#hoverBackground {
content: '';
display: none;
inset: 0;
pointer-events: none;
position: absolute;
z-index: 1;
}
:host-context([chrome-refresh-2023]):host(:hover) #hoverBackground {
background: var(--cr-hover-background-color);
display: block;
}
:host(.action-button) {
--ink-color: var(--ink-color-action);
--paper-ripple-opacity: var(--ripple-opacity-action);
background-color: var(--bg-action);
border: none;
color: var(--text-color-action);
}
:host-context([chrome-refresh-2023]):host(.action-button) {
background-color: transparent;
}
:host(.action-button:active) {
box-shadow: var(--active-shadow-action,
0 1px 2px 0 rgba(var(--active-shadow-action-rgb), .3),
0 3px 6px 2px rgba(var(--active-shadow-action-rgb), .15));
}
:host(.action-button:hover) {
background: var(--hover-bg-action);
}
@media (prefers-color-scheme: light) {
:host(.action-button:not(:active):hover) {
box-shadow:
0 1px 2px 0 rgba(var(--hover-shadow-action-rgb), .3),
0 1px 3px 1px rgba(var(--hover-shadow-action-rgb), .15);
}
:host-context([chrome-refresh-2023]):host(
.action-button:not(:active):hover) {
box-shadow: none;
}
}
:host([disabled]) {
background-color: var(--disabled-bg);
border-color: var(--disabled-border-color);
color: var(--disabled-text-color);
cursor: auto;
pointer-events: none;
}
:host(.action-button[disabled]) {
background-color: var(--disabled-bg-action);
border-color: transparent;
}
/* cancel-button is meant to be used within a cr-dialog */
:host(.cancel-button) {
margin-inline-end: 8px;
}
:host(.action-button),
:host(.cancel-button) {
line-height: 154%;
}
:host-context([chrome-refresh-2023]):host(.tonal-button),
:host-context([chrome-refresh-2023]):host(.floating-button) {
border: none;
color: var(--color-button-foreground-tonal,
var(--cr-fallback-color-on-secondary-container));
}
:host-context([chrome-refresh-2023]):host(.tonal-button[disabled]),
:host-context([chrome-refresh-2023]):host(.floating-button[disabled]) {
border: none;
color: var(--disabled-text-color);
}
:host-context([chrome-refresh-2023]):host(.floating-button) {
border-radius: 8px;
height: 40px;
}
paper-ripple {
color: var(--ink-color);
height: var(--paper-ripple-height);
/* Fallback to 0 to match the values in paper-ripple.html. Falls back
* to null without this. */
left: var(--paper-ripple-left, 0);
top: var(--paper-ripple-top, 0);
width: var(--paper-ripple-width);
}
:host-context([chrome-refresh-2023]) paper-ripple {
z-index: 1;
}
</style>
<div id="background"></div>
<slot id="prefixIcon" name="prefix-icon"
on-slotchange="onPrefixIconSlotChanged_">
</slot>
<span id="content"><slot></slot></span>
<slot id="suffixIcon" name="suffix-icon"
on-slotchange="onSuffixIconSlotChanged_">
</slot>
<div id="hoverBackground" part="hoverBackground"></div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_button/cr_button.html | HTML | unknown | 11,888 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'cr-button' is a button which displays slotted elements. It can
* be interacted with like a normal button using click as well as space and
* enter to effectively click the button and fire a 'click' event. It can also
* style an icon inside of the button with the [has-icon] attribute.
*/
import '//resources/polymer/v3_0/paper-styles/color.js';
import '../cr_hidden_style.css.js';
import '../cr_shared_vars.css.js';
import {FocusOutlineManager} from '//resources/js/focus_outline_manager.js';
import {PaperRippleBehavior} from '//resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js';
import {mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_button.html.js';
export interface CrButtonElement {
$: {
prefixIcon: HTMLSlotElement,
suffixIcon: HTMLSlotElement,
};
}
const CrButtonElementBase =
mixinBehaviors([PaperRippleBehavior], PolymerElement) as {
new (): PolymerElement & PaperRippleBehavior,
};
export class CrButtonElement extends CrButtonElementBase {
static get is() {
return 'cr-button';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: 'disabledChanged_',
},
/**
* Use this property in order to configure the "tabindex" attribute.
*/
customTabIndex: {
type: Number,
observer: 'applyTabIndex_',
},
/**
* Flag used for formatting ripples on circle shaped cr-buttons.
* @private
*/
circleRipple: {
type: Boolean,
value: false,
},
hasPrefixIcon_: {
type: Boolean,
reflectToAttribute: true,
value: false,
},
hasSuffixIcon_: {
type: Boolean,
reflectToAttribute: true,
value: false,
},
};
}
disabled: boolean;
customTabIndex: number;
circleRipple: boolean;
private hasPrefixIcon_: boolean;
private hasSuffixIcon_: boolean;
/**
* It is possible to activate a tab when the space key is pressed down. When
* this element has focus, the keyup event for the space key should not
* perform a 'click'. |spaceKeyDown_| tracks when a space pressed and
* handled by this element. Space keyup will only result in a 'click' when
* |spaceKeyDown_| is true. |spaceKeyDown_| is set to false when element
* loses focus.
*/
private spaceKeyDown_: boolean = false;
private timeoutIds_: Set<number> = new Set();
constructor() {
super();
this.addEventListener('blur', this.onBlur_.bind(this));
// Must be added in constructor so that stopImmediatePropagation() works as
// expected.
this.addEventListener('click', this.onClick_.bind(this));
this.addEventListener('keydown', this.onKeyDown_.bind(this));
this.addEventListener('keyup', this.onKeyUp_.bind(this));
this.addEventListener('pointerdown', this.onPointerDown_.bind(this));
}
override ready() {
super.ready();
if (!this.hasAttribute('role')) {
this.setAttribute('role', 'button');
}
if (!this.hasAttribute('tabindex')) {
this.setAttribute('tabindex', '0');
}
if (!this.hasAttribute('aria-disabled')) {
this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false');
}
FocusOutlineManager.forDocument(document);
}
override disconnectedCallback() {
super.disconnectedCallback();
this.timeoutIds_.forEach(clearTimeout);
this.timeoutIds_.clear();
}
private setTimeout_(fn: () => void, delay?: number) {
if (!this.isConnected) {
return;
}
const id = setTimeout(() => {
this.timeoutIds_.delete(id);
fn();
}, delay);
this.timeoutIds_.add(id);
}
private disabledChanged_(newValue: boolean, oldValue: boolean|undefined) {
if (!newValue && oldValue === undefined) {
return;
}
if (this.disabled) {
this.blur();
}
this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false');
this.applyTabIndex_();
}
/**
* Updates the tabindex HTML attribute to the actual value.
*/
private applyTabIndex_() {
let value = this.customTabIndex;
if (value === undefined) {
value = this.disabled ? -1 : 0;
}
this.setAttribute('tabindex', value.toString());
}
private onBlur_() {
this.spaceKeyDown_ = false;
}
private onClick_(e: Event) {
if (this.disabled) {
e.stopImmediatePropagation();
}
}
private onPrefixIconSlotChanged_() {
this.hasPrefixIcon_ = this.$.prefixIcon.assignedElements().length > 0;
}
private onSuffixIconSlotChanged_() {
this.hasSuffixIcon_ = this.$.suffixIcon.assignedElements().length > 0;
}
private onKeyDown_(e: KeyboardEvent) {
if (e.key !== ' ' && e.key !== 'Enter') {
return;
}
e.preventDefault();
e.stopPropagation();
if (e.repeat) {
return;
}
this.getRipple().uiDownAction();
if (e.key === 'Enter') {
this.click();
// Delay was chosen manually as a good time period for the ripple to be
// visible.
this.setTimeout_(() => this.getRipple().uiUpAction(), 100);
} else if (e.key === ' ') {
this.spaceKeyDown_ = true;
}
}
private onKeyUp_(e: KeyboardEvent) {
if (e.key !== ' ' && e.key !== 'Enter') {
return;
}
e.preventDefault();
e.stopPropagation();
if (this.spaceKeyDown_ && e.key === ' ') {
this.spaceKeyDown_ = false;
this.click();
this.getRipple().uiUpAction();
}
}
private onPointerDown_() {
this.ensureRipple();
}
/**
* Customize the element's ripple. Overriding the '_createRipple' function
* from PaperRippleBehavior.
*/
/* eslint-disable-next-line @typescript-eslint/naming-convention */
override _createRipple() {
const ripple = super._createRipple();
if (this.circleRipple) {
ripple.setAttribute('center', '');
ripple.classList.add('circle');
}
return ripple;
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-button': CrButtonElement;
}
}
customElements.define(CrButtonElement.is, CrButtonElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_button/cr_button.ts | TypeScript | unknown | 6,449 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Minimal externs file provided for places in the code that
* still use JavaScript instead of TypeScript.
* @externs
*/
/**
* @constructor
* @extends {HTMLElement}
*/
function CrButtonElement() {}
/** @type {boolean} */
CrButtonElement.prototype.disabled;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_button/cr_button_externs.js | JavaScript | unknown | 409 |
<style>
:host {
-webkit-tap-highlight-color: transparent;
align-items: center;
cursor: pointer;
display: flex;
outline: none;
user-select: none;
/* Sizes. */
--cr-checkbox-border-size: 2px;
--cr-checkbox-size: 16px;
--cr-checkbox-ripple-size: 40px;
/* Derived sizes (offsets). */
--cr-checkbox-ripple-offset: calc(var(--cr-checkbox-size)/2 -
var(--cr-checkbox-ripple-size)/2 - var(--cr-checkbox-border-size));
/* --cr-checked-color automatically flips for light/dark mode. */
--cr-checkbox-checked-box-color: var(--cr-checked-color);
--cr-checkbox-ripple-checked-color: var(--cr-checked-color);
/* Light mode colors. */
--cr-checkbox-checked-ripple-opacity: .2;
--cr-checkbox-mark-color: white;
--cr-checkbox-ripple-unchecked-color: var(--google-grey-900);
--cr-checkbox-unchecked-box-color: var(--google-grey-700);
--cr-checkbox-unchecked-ripple-opacity: .15;
}
@media (prefers-color-scheme: dark) {
:host {
/* Dark mode colors. */
--cr-checkbox-checked-ripple-opacity: .4;
--cr-checkbox-mark-color: var(--google-grey-900);
--cr-checkbox-ripple-unchecked-color: var(--google-grey-500);
--cr-checkbox-unchecked-box-color: var(--google-grey-500);
--cr-checkbox-unchecked-ripple-opacity: .4;
}
}
:host-context([chrome-refresh-2023]):host {
--cr-checkbox-ripple-size: 32px;
--cr-checkbox-checked-box-color: var(--color-checkbox-foreground-checked,
var(--cr-fallback-color-primary));
--cr-checkbox-unchecked-box-color: var(--color-checkbox-foreground-unchecked,
var(--cr-fallback-color-outline));
--cr-checkbox-ripple-checked-color: var(--cr-active-background-color);
--cr-checkbox-ripple-unchecked-color: var(--cr-active-background-color);
--cr-checkbox-ripple-offset: 50%;
--cr-checkbox-ripple-opacity: 1;
}
:host([disabled]) {
cursor: initial;
opacity: var(--cr-disabled-opacity);
pointer-events: none;
}
:host-context([chrome-refresh-2023]):host([disabled]) {
opacity: 1;
--cr-checkbox-checked-box-color: var(--color-checkbox-background-disabled,
rgba(var(--cr-fallback-color-on-surface-rgb), .12));
--cr-checkbox-unchecked-box-color: var(--color-checkbox-background-disabled,
rgba(var(--cr-fallback-color-on-surface-rgb), .12));
--cr-checkbox-mark-color: var(--color-checkbox-foreground-disabled,
rgba(var(--cr-fallback-color-on-surface-rgb), var(--cr-disabled-opacity)));
}
#checkbox {
background: none;
border: var(--cr-checkbox-border-size) solid
var(--cr-checkbox-unchecked-box-color);
border-radius: 2px;
box-sizing: border-box;
cursor: pointer;
display: block;
flex-shrink: 0;
height: var(--cr-checkbox-size);
margin: 0;
outline: none;
padding: 0;
position: relative;
transform: none; /* Checkboxes shouldn't flip even in RTL. */
width: var(--cr-checkbox-size);
}
:host-context([chrome-refresh-2023]):host([disabled][checked]) #checkbox {
border-color: transparent;
}
:host-context([chrome-refresh-2023]) #hover-layer {
display: none;
}
:host-context([chrome-refresh-2023]) #checkbox:hover #hover-layer {
background-color: var(--cr-hover-background-color);
border-radius: 50%;
display: block;
height: 32px;
left: 50%;
overflow: hidden;
pointer-events: none;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
width: 32px;
}
@media (forced-colors: active) {
/* paper-ripple is not showing in Windows HCM. Use outline instead. */
:host(:focus) #checkbox {
outline: var(--cr-focus-outline-hcm);
}
}
:host-context([chrome-refresh-2023]) #checkbox:focus-visible {
border: none;
outline: 2px solid var(--cr-focus-outline-color);
}
#checkmark {
display: block;
/* Automatically adjust color of the checkmark SVG in forced colors mode.
* Otherwise, this property defaults to preserve-parent-color.
* https://www.w3.org/TR/css-color-adjust-1/#forced-color-adjust-prop */
forced-color-adjust: auto;
position: relative;
transform: scale(0);
z-index: 1;
}
#checkmark path {
fill: var(--cr-checkbox-mark-color);
}
:host([checked]) #checkmark {
transform: scale(1);
/* Only animate when showing checkmark. */
transition: transform 140ms ease-out;
}
:host([checked]) #checkbox {
background: var(--cr-checkbox-checked-box-background-color,
var(--cr-checkbox-checked-box-color));
border-color: var(--cr-checkbox-checked-box-color);
}
:host-context([chrome-refresh-2023]):host([checked]) #checkbox:focus-visible {
background-clip: padding-box;
border: 2px solid transparent;
}
paper-ripple {
--paper-ripple-opacity: var(--cr-checkbox-ripple-opacity,
var(--cr-checkbox-unchecked-ripple-opacity));
color: var(--cr-checkbox-ripple-unchecked-color);
height: var(--cr-checkbox-ripple-size);
left: var(--cr-checkbox-ripple-offset);
outline: var(--cr-checkbox-ripple-ring, none);
pointer-events: none;
top: var(--cr-checkbox-ripple-offset);
transition: color linear 80ms;
width: var(--cr-checkbox-ripple-size);
}
:host([checked]) paper-ripple {
--paper-ripple-opacity: var(--cr-checkbox-ripple-opacity,
var(--cr-checkbox-checked-ripple-opacity));
color: var(--cr-checkbox-ripple-checked-color);
}
:host-context([dir=rtl]) paper-ripple {
left: auto;
right: var(--cr-checkbox-ripple-offset);
}
:host-context([chrome-refresh-2023]) paper-ripple {
transform: translate(-50%, -50%);
}
#label-container {
color: var(--cr-checkbox-label-color, var(--cr-primary-text-color));
padding-inline-start: var(--cr-checkbox-label-padding-start, 20px);
white-space: normal;
}
:host(.label-first) #label-container {
order: -1;
padding-inline-end: var(--cr-checkbox-label-padding-end, 20px);
padding-inline-start: 0;
}
:host(.no-label) #label-container {
display: none;
}
/* Hidden from UI, but not screen readers. */
#ariaDescription {
height: 0;
overflow: hidden;
width: 0;
}
</style>
<div id="checkbox" tabindex$="[[tabIndex]]" role="checkbox"
on-keydown="onKeyDown_" on-keyup="onKeyUp_" aria-disabled="false"
aria-checked="false" aria-labelledby="label-container"
aria-describedby="ariaDescription">
<!-- Inline SVG paints faster than loading it from a separate file. -->
<svg id="checkmark" width="12" height="12" viewBox="0 0 12 12"
fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="m10.192 2.121-6.01 6.01-2.121-2.12L1 7.07l2.121 2.121.707.707.354.354 7.071-7.071-1.06-1.06Z">
</svg>
<div id="hover-layer"></div>
</div>
<div id="label-container" aria-hidden="true" part="label-container">
<slot></slot>
</div>
<div id="ariaDescription" aria-hidden="true">[[ariaDescription]]</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_checkbox/cr_checkbox.html | HTML | unknown | 7,797 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'cr-checkbox' is a component similar to native checkbox. It
* fires a 'change' event *only* when its state changes as a result of a user
* interaction. By default it assumes there will be child(ren) passed in to be
* used as labels. If no label will be provided, a .no-label class should be
* added to hide the spacing between the checkbox and the label container.
*
* If a label is provided, it will be shown by default after the checkbox. A
* .label-first CSS class can be added to show the label before the checkbox.
*
* List of customizable styles:
* --cr-checkbox-border-size
* --cr-checkbox-checked-box-background-color
* --cr-checkbox-checked-box-color
* --cr-checkbox-label-color
* --cr-checkbox-label-padding-start
* --cr-checkbox-mark-color
* --cr-checkbox-ripple-checked-color
* --cr-checkbox-ripple-size
* --cr-checkbox-ripple-unchecked-color
* --cr-checkbox-size
* --cr-checkbox-unchecked-box-color
*/
import '//resources/polymer/v3_0/paper-styles/color.js';
import '../cr_shared_vars.css.js';
import {PaperRippleBehavior} from '//resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js';
import {mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_checkbox.html.js';
const CrCheckboxElementBase =
mixinBehaviors([PaperRippleBehavior], PolymerElement) as
{new (): PolymerElement & PaperRippleBehavior};
export interface CrCheckboxElement {
$: {
checkbox: HTMLElement,
};
}
export class CrCheckboxElement extends CrCheckboxElementBase {
static get is() {
return 'cr-checkbox';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
checked: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: 'checkedChanged_',
notify: true,
},
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: 'disabledChanged_',
},
ariaDescription: String,
tabIndex: {
type: Number,
value: 0,
observer: 'onTabIndexChanged_',
},
};
}
checked: boolean;
disabled: boolean;
ariaDescription: string;
override tabIndex: number;
/* eslint-disable-next-line @typescript-eslint/naming-convention */
override _rippleContainer: Element;
override ready() {
super.ready();
this.removeAttribute('unresolved');
this.addEventListener('click', this.onClick_.bind(this));
this.addEventListener('pointerup', this.hideRipple_.bind(this));
if (document.documentElement.hasAttribute('chrome-refresh-2023')) {
this.addEventListener('pointerdown', this.showRipple_.bind(this));
this.addEventListener('pointerleave', this.hideRipple_.bind(this));
} else {
this.addEventListener('blur', this.hideRipple_.bind(this));
this.addEventListener('focus', this.showRipple_.bind(this));
}
}
override focus() {
this.$.checkbox.focus();
}
getFocusableElement(): HTMLElement {
return this.$.checkbox;
}
private checkedChanged_() {
this.$.checkbox.setAttribute(
'aria-checked', this.checked ? 'true' : 'false');
}
private disabledChanged_(_current: boolean, previous: boolean) {
if (previous === undefined && !this.disabled) {
return;
}
this.tabIndex = this.disabled ? -1 : 0;
this.$.checkbox.setAttribute(
'aria-disabled', this.disabled ? 'true' : 'false');
}
private showRipple_() {
if (this.noink) {
return;
}
this.getRipple().showAndHoldDown();
}
private hideRipple_() {
this.getRipple().clear();
}
private onClick_(e: Event) {
if (this.disabled || (e.target as HTMLElement).tagName === 'A') {
return;
}
// Prevent |click| event from bubbling. It can cause parents of this
// elements to erroneously re-toggle this control.
e.stopPropagation();
e.preventDefault();
this.checked = !this.checked;
this.dispatchEvent(new CustomEvent(
'change', {bubbles: true, composed: true, detail: this.checked}));
}
private onKeyDown_(e: KeyboardEvent) {
if (e.key !== ' ' && e.key !== 'Enter') {
return;
}
e.preventDefault();
e.stopPropagation();
if (e.repeat) {
return;
}
if (e.key === 'Enter') {
this.click();
}
}
private onKeyUp_(e: KeyboardEvent) {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
e.stopPropagation();
}
if (e.key === ' ') {
this.click();
}
}
private onTabIndexChanged_() {
// :host shouldn't have a tabindex because it's set on #checkbox.
this.removeAttribute('tabindex');
}
// Overridden from PaperRippleBehavior
/* eslint-disable-next-line @typescript-eslint/naming-convention */
override _createRipple() {
this._rippleContainer = this.$.checkbox;
const ripple = super._createRipple();
ripple.id = 'ink';
ripple.setAttribute('recenters', '');
ripple.classList.add('circle', 'toggle-ink');
return ripple;
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-checkbox': CrCheckboxElement;
}
}
customElements.define(CrCheckboxElement.is, CrCheckboxElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_checkbox/cr_checkbox.ts | TypeScript | unknown | 5,456 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview CrContainerShadowMixin holds logic for showing a drop shadow
* near the top of a container element, when the content has scrolled.
*
* Elements using this mixin are expected to define a #container element,
* which is the element being scrolled. If the #container element has a
* show-bottom-shadow attribute, a drop shadow will also be shown near the
* bottom of the container element, when there is additional content to scroll
* to. Examples:
*
* For both top and bottom shadows:
* <div id="container" show-bottom-shadow>...</div>
*
* For top shadow only:
* <div id="container">...</div>
*
* The mixin will take care of inserting an element with ID
* 'cr-container-shadow-top' which holds the drop shadow effect, and,
* optionally, an element with ID 'cr-container-shadow-bottom' which holds the
* same effect. A 'has-shadow' CSS class is automatically added to/removed from
* both elements while scrolling, as necessary. Note that the show-bottom-shadow
* attribute is inspected only during attached(), and any changes to it that
* occur after that point will not be respected.
*
* Clients should either use the existing shared styling in
* cr_shared_style.css, '#cr-container-shadow-[top/bottom]' and
* '#cr-container-shadow-[top/bottom].has-shadow', or define their own styles.
*/
import {assert} from '//resources/js/assert_ts.js';
import {dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
export enum CrContainerShadowSide {
TOP = 'top',
BOTTOM = 'bottom',
}
type Constructor<T> = new (...args: any[]) => T;
export const CrContainerShadowMixin = dedupingMixin(
<T extends Constructor<PolymerElement>>(superClass: T): T&
Constructor<CrContainerShadowMixinInterface> => {
class CrContainerShadowMixin extends superClass implements
CrContainerShadowMixinInterface {
private intersectionObserver_: IntersectionObserver|null = null;
private dropShadows_: Map<CrContainerShadowSide, HTMLDivElement> =
new Map();
private intersectionProbes_:
Map<CrContainerShadowSide, HTMLDivElement> = new Map();
private sides_: CrContainerShadowSide[]|null = null;
override connectedCallback() {
super.connectedCallback();
const hasBottomShadow =
this.getContainer_().hasAttribute('show-bottom-shadow');
this.sides_ = hasBottomShadow ?
[CrContainerShadowSide.TOP, CrContainerShadowSide.BOTTOM] :
[CrContainerShadowSide.TOP];
this.sides_!.forEach(side => {
// The element holding the drop shadow effect to be shown.
const shadow = document.createElement('div');
shadow.id = `cr-container-shadow-${side}`;
shadow.classList.add('cr-container-shadow');
this.dropShadows_.set(side, shadow);
this.intersectionProbes_.set(side, document.createElement('div'));
});
this.getContainer_().parentNode!.insertBefore(
this.dropShadows_.get(CrContainerShadowSide.TOP)!,
this.getContainer_());
this.getContainer_().prepend(
this.intersectionProbes_.get(CrContainerShadowSide.TOP)!);
if (hasBottomShadow) {
this.getContainer_().parentNode!.insertBefore(
this.dropShadows_.get(CrContainerShadowSide.BOTTOM)!,
this.getContainer_().nextSibling);
this.getContainer_().append(
this.intersectionProbes_.get(CrContainerShadowSide.BOTTOM)!);
}
this.enableShadowBehavior(true);
}
override disconnectedCallback() {
super.disconnectedCallback();
this.enableShadowBehavior(false);
}
private getContainer_(): HTMLElement {
return this.shadowRoot!.querySelector('#container')!;
}
private getIntersectionObserver_(): IntersectionObserver {
const callback = (entries: IntersectionObserverEntry[]) => {
// In some rare cases, there could be more than one entry per
// observed element, in which case the last entry's result
// stands.
for (const entry of entries) {
const target = entry.target;
this.sides_!.forEach(side => {
if (target === this.intersectionProbes_.get(side)) {
this.dropShadows_.get(side)!.classList.toggle(
'has-shadow', entry.intersectionRatio === 0);
}
});
}
};
return new IntersectionObserver(
callback, {root: this.getContainer_(), threshold: 0});
}
/**
* @param enable Whether to enable the mixin or disable it.
* This function does nothing if the mixin is already in the
* requested state.
*/
enableShadowBehavior(enable: boolean) {
// Behavior is already enabled/disabled. Return early.
if (enable === !!this.intersectionObserver_) {
return;
}
if (!enable) {
this.intersectionObserver_!.disconnect();
this.intersectionObserver_ = null;
return;
}
this.intersectionObserver_ = this.getIntersectionObserver_();
// Need to register the observer within a setTimeout() callback,
// otherwise the drop shadow flashes once on startup, because of the
// DOM modifications earlier in this function causing a relayout.
window.setTimeout(() => {
if (this.intersectionObserver_) {
// In case this is already detached.
this.intersectionProbes_.forEach(probe => {
this.intersectionObserver_!.observe(probe);
});
}
});
}
/**
* Shows the shadows. The shadow mixin must be disabled before
* calling this method, otherwise the intersection observer might
* show the shadows again.
*/
showDropShadows() {
assert(!this.intersectionObserver_);
assert(this.sides_);
for (const side of this.sides_) {
this.dropShadows_.get(side)!.classList.toggle('has-shadow', true);
}
}
}
return CrContainerShadowMixin;
});
export interface CrContainerShadowMixinInterface {
enableShadowBehavior(enable: boolean): void;
showDropShadows(): void;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_container_shadow_mixin.ts | TypeScript | unknown | 6,707 |
<style include="cr-hidden-style cr-icons">
dialog {
--scroll-border-color: var(--paper-grey-300);
--scroll-border: 1px solid var(--scroll-border-color);
background-color: var(--cr-dialog-background-color, white);
border: 0;
border-radius: 8px;
bottom: 50%;
box-shadow: 0 0 16px rgba(0, 0, 0, 0.12),
0 16px 16px rgba(0, 0, 0, 0.24);
color: inherit;
max-height: initial;
max-width: initial;
overflow-y: hidden;
padding: 0;
position: absolute;
top: 50%;
width: var(--cr-dialog-width, 512px);
}
@media (prefers-color-scheme: dark) {
dialog {
--scroll-border-color: var(--google-grey-700);
background-color: var(--cr-dialog-background-color,
var(--google-grey-900));
/* Note: the colors in linear-gradient() are intentionally the same to
* add a 4% white layer on top of the fully opaque background-color. */
background-image: linear-gradient(rgba(255, 255, 255, .04),
rgba(255, 255, 255, .04));
}
}
@media (forced-colors: active) {
dialog {
/* Use border instead of box-shadow (which does not work) in Windows
HCM. */
border: var(--cr-border-hcm);
}
}
dialog[open] #content-wrapper {
/* Keep max-height within viewport, and flex content accordingly. */
display: flex;
flex-direction: column;
max-height: 100vh;
overflow: auto;
}
/* When needing to flex, force .body-container alone to shrink. */
.top-container,
:host ::slotted([slot=button-container]),
:host ::slotted([slot=footer]) {
flex-shrink: 0;
}
dialog::backdrop {
background-color: rgba(0, 0, 0, 0.6);
bottom: 0;
left: 0;
position: fixed;
right: 0;
top: 0;
}
:host ::slotted([slot=body]) {
color: var(--cr-secondary-text-color);
padding: 0 var(--cr-dialog-body-padding-horizontal, 20px);
}
:host ::slotted([slot=title]) {
color: var(--cr-primary-text-color);
flex: 1;
font-family: var(--cr-dialog-font-family, inherit);
font-size: var(--cr-dialog-title-font-size, calc(15 / 13 * 100%));
line-height: 1;
padding-bottom: var(--cr-dialog-title-slot-padding-bottom, 16px);
padding-inline-end: var(--cr-dialog-title-slot-padding-end, 20px);
padding-inline-start: var(--cr-dialog-title-slot-padding-start, 20px);
padding-top: var(--cr-dialog-title-slot-padding-top, 20px);
}
:host ::slotted([slot=button-container]) {
display: flex;
justify-content: flex-end;
padding-bottom: var(--cr-dialog-button-container-padding-bottom, 16px);
padding-inline-end: var(--cr-dialog-button-container-padding-horizontal, 16px);
padding-inline-start: var(--cr-dialog-button-container-padding-horizontal, 16px);
padding-top: 24px;
}
:host ::slotted([slot=footer]) {
border-bottom-left-radius: inherit;
border-bottom-right-radius: inherit;
border-top: 1px solid #dbdbdb;
margin: 0;
padding: 16px 20px;
}
:host([hide-backdrop]) dialog::backdrop {
opacity: 0;
}
@media (prefers-color-scheme: dark) {
:host ::slotted([slot=footer]) {
border-top-color: var(--cr-separator-color);
}
}
.body-container {
box-sizing: border-box;
display: flex;
flex-direction: column;
min-height: 1.375rem; /* Minimum reasonably usable height. */
overflow: auto;
}
:host {
--transparent-border: 1px solid transparent;
}
/* Cr Dialog uses borders instead of box-shadows. */
#cr-container-shadow-top {
border-bottom: var(--cr-dialog-body-border-top,
var(--transparent-border));
}
#cr-container-shadow-bottom {
border-bottom: var(--cr-dialog-body-border-bottom,
var(--transparent-border));
}
#cr-container-shadow-top.has-shadow,
#cr-container-shadow-bottom.has-shadow {
border-bottom: var(--scroll-border);
}
.top-container {
align-items: flex-start;
display: flex;
min-height: var(--cr-dialog-top-container-min-height, 31px);
}
.title-container {
display: flex;
flex: 1;
font-size: inherit;
font-weight: inherit;
margin: 0;
outline: none;
}
#close {
align-self: flex-start;
margin-inline-end: 4px;
margin-top: 4px;
}
</style>
<dialog id="dialog" on-close="onNativeDialogClose_"
on-cancel="onNativeDialogCancel_" part="dialog"
aria-labelledby="title" aria-describedby="container">
<!-- This wrapper is necessary, such that the "pulse" animation is not
erroneously played when the user clicks on the outer-most scrollbar. -->
<div id="content-wrapper" part="wrapper">
<div class="top-container">
<h2 id="title" class="title-container" tabindex="-1">
<slot name="title"></slot>
</h2>
<cr-icon-button id="close" class="icon-clear"
hidden$="[[!showCloseButton]]" aria-label$="[[closeText]]"
on-click="cancel" on-keypress="onCloseKeypress_">
</cr-icon-button>
</div>
<slot name="header"></slot>
<div class="body-container" id="container" show-bottom-shadow
part="body-container">
<slot name="body"></slot>
</div>
<slot name="button-container"></slot>
<slot name="footer"></slot>
</div>
</dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html | HTML | unknown | 5,911 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'cr-dialog' is a component for showing a modal dialog. If the
* dialog is closed via close(), a 'close' event is fired. If the dialog is
* canceled via cancel(), a 'cancel' event is fired followed by a 'close' event.
*
* Additionally clients can get a reference to the internal native <dialog> via
* calling getNative() and inspecting the |returnValue| property inside
* the 'close' event listener to determine whether it was canceled or just
* closed, where a truthy value means success, and a falsy value means it was
* canceled.
*
* Note that <cr-dialog> wrapper itself always has 0x0 dimensions, and
* specifying width/height on <cr-dialog> directly will have no effect on the
* internal native <dialog>. Instead use cr-dialog::part(dialog) to specify
* width/height (as well as other available mixins to style other parts of the
* dialog contents).
*/
import '../cr_icon_button/cr_icon_button.js';
import '../cr_icons.css.js';
import '../cr_hidden_style.css.js';
import '../cr_shared_vars.css.js';
import {assert} from '//resources/js/assert_ts.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CrContainerShadowMixin} from '../cr_container_shadow_mixin.js';
import {CrIconButtonElement} from '../cr_icon_button/cr_icon_button.js';
import {CrInputElement} from '../cr_input/cr_input.js';
import {getTemplate} from './cr_dialog.html.js';
const CrDialogElementBase = CrContainerShadowMixin(PolymerElement);
export interface CrDialogElement {
$: {
close: CrIconButtonElement,
dialog: HTMLDialogElement,
};
}
export class CrDialogElement extends CrDialogElementBase {
static get is() {
return 'cr-dialog';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
open: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/**
* Alt-text for the dialog close button.
*/
closeText: String,
/**
* True if the dialog should remain open on 'popstate' events. This is
* used for navigable dialogs that have their separate navigation handling
* code.
*/
ignorePopstate: {
type: Boolean,
value: false,
},
/**
* True if the dialog should ignore 'Enter' keypresses.
*/
ignoreEnterKey: {
type: Boolean,
value: false,
},
/**
* True if the dialog should consume 'keydown' events. If ignoreEnterKey
* is true, 'Enter' key won't be consumed.
*/
consumeKeydownEvent: {
type: Boolean,
value: false,
},
/**
* True if the dialog should not be able to be cancelled, which will
* prevent 'Escape' key presses from closing the dialog.
*/
noCancel: {
type: Boolean,
value: false,
},
// True if dialog should show the 'X' close button.
showCloseButton: {
type: Boolean,
value: false,
},
showOnAttach: {
type: Boolean,
value: false,
},
};
}
closeText: string;
consumeKeydownEvent: boolean;
ignoreEnterKey: boolean;
ignorePopstate: boolean;
noCancel: boolean;
open: boolean;
showCloseButton: boolean;
showOnAttach: boolean;
private intersectionObserver_: IntersectionObserver|null = null;
private mutationObserver_: MutationObserver|null = null;
private boundKeydown_: ((e: KeyboardEvent) => void)|null = null;
override ready() {
super.ready();
// If the active history entry changes (i.e. user clicks back button),
// all open dialogs should be cancelled.
window.addEventListener('popstate', () => {
if (!this.ignorePopstate && this.$.dialog.open) {
this.cancel();
}
});
if (!this.ignoreEnterKey) {
this.addEventListener('keypress', this.onKeypress_.bind(this));
}
this.addEventListener('pointerdown', e => this.onPointerdown_(e));
}
override connectedCallback() {
super.connectedCallback();
const mutationObserverCallback = () => {
if (this.$.dialog.open) {
this.enableShadowBehavior(true);
this.addKeydownListener_();
} else {
this.enableShadowBehavior(false);
this.removeKeydownListener_();
}
};
this.mutationObserver_ = new MutationObserver(mutationObserverCallback);
this.mutationObserver_.observe(this.$.dialog, {
attributes: true,
attributeFilter: ['open'],
});
// In some cases dialog already has the 'open' attribute by this point.
mutationObserverCallback();
if (this.showOnAttach) {
this.showModal();
}
}
override disconnectedCallback() {
super.disconnectedCallback();
this.removeKeydownListener_();
if (this.mutationObserver_) {
this.mutationObserver_.disconnect();
this.mutationObserver_ = null;
}
}
private addKeydownListener_() {
if (!this.consumeKeydownEvent) {
return;
}
this.boundKeydown_ = this.boundKeydown_ || this.onKeydown_.bind(this);
this.addEventListener('keydown', this.boundKeydown_);
// Sometimes <body> is key event's target and in that case the event
// will bypass cr-dialog. We should consume those events too in order to
// behave modally. This prevents accidentally triggering keyboard commands.
document.body.addEventListener('keydown', this.boundKeydown_);
}
private removeKeydownListener_() {
if (!this.boundKeydown_) {
return;
}
this.removeEventListener('keydown', this.boundKeydown_);
document.body.removeEventListener('keydown', this.boundKeydown_);
this.boundKeydown_ = null;
}
showModal() {
this.$.dialog.showModal();
assert(this.$.dialog.open);
this.open = true;
this.dispatchEvent(
new CustomEvent('cr-dialog-open', {bubbles: true, composed: true}));
}
cancel() {
this.dispatchEvent(
new CustomEvent('cancel', {bubbles: true, composed: true}));
this.$.dialog.close();
assert(!this.$.dialog.open);
this.open = false;
}
close() {
this.$.dialog.close('success');
assert(!this.$.dialog.open);
this.open = false;
}
/**
* Set the title of the dialog for a11y reader.
* @param title Title of the dialog.
*/
setTitleAriaLabel(title: string) {
this.$.dialog.removeAttribute('aria-labelledby');
this.$.dialog.setAttribute('aria-label', title);
}
private onCloseKeypress_(e: Event) {
// Because the dialog may have a default Enter key handler, prevent
// keypress events from bubbling up from this element.
e.stopPropagation();
}
private onNativeDialogClose_(e: Event) {
// Ignore any 'close' events not fired directly by the <dialog> element.
if (e.target !== this.getNative()) {
return;
}
// Catch and re-fire the 'close' event such that it bubbles across Shadow
// DOM v1.
this.dispatchEvent(
new CustomEvent('close', {bubbles: true, composed: true}));
}
private onNativeDialogCancel_(e: Event) {
// Ignore any 'cancel' events not fired directly by the <dialog> element.
if (e.target !== this.getNative()) {
return;
}
if (this.noCancel) {
e.preventDefault();
return;
}
// When the dialog is dismissed using the 'Esc' key, need to manually update
// the |open| property (since close() is not called).
this.open = false;
// Catch and re-fire the native 'cancel' event such that it bubbles across
// Shadow DOM v1.
this.dispatchEvent(
new CustomEvent('cancel', {bubbles: true, composed: true}));
}
/**
* Expose the inner native <dialog> for some rare cases where it needs to be
* directly accessed (for example to programmatically setheight/width, which
* would not work on the wrapper).
*/
getNative(): HTMLDialogElement {
return this.$.dialog;
}
private onKeypress_(e: KeyboardEvent) {
if (e.key !== 'Enter') {
return;
}
// Accept Enter keys from either the dialog itself, or a child cr-input,
// considering that the event may have been retargeted, for example if the
// cr-input is nested inside another element. Also exclude inputs of type
// 'search', since hitting 'Enter' on a search field most likely intends to
// trigger searching.
const accept = e.target === this ||
e.composedPath().some(
el => (el as HTMLElement).tagName === 'CR-INPUT' &&
(el as CrInputElement).type !== 'search');
if (!accept) {
return;
}
const actionButton = this.querySelector<HTMLElement>(
'.action-button:not([disabled]):not([hidden])');
if (actionButton) {
actionButton.click();
e.preventDefault();
}
}
private onKeydown_(e: KeyboardEvent) {
assert(this.consumeKeydownEvent);
if (!this.getNative().open) {
return;
}
if (this.ignoreEnterKey && e.key === 'Enter') {
return;
}
// Stop propagation to behave modally.
e.stopPropagation();
}
private onPointerdown_(e: PointerEvent) {
// Only show pulse animation if user left-clicked outside of the dialog
// contents.
if (e.button !== 0 ||
(e.composedPath()[0]! as HTMLElement).tagName !== 'DIALOG') {
return;
}
this.$.dialog.animate(
[
{transform: 'scale(1)', offset: 0},
{transform: 'scale(1.02)', offset: 0.4},
{transform: 'scale(1.02)', offset: 0.6},
{transform: 'scale(1)', offset: 1},
],
{
duration: 180,
easing: 'ease-in-out',
iterations: 1,
});
// Prevent any text from being selected within the dialog when clicking in
// the backdrop area.
e.preventDefault();
}
override focus() {
const titleContainer =
this.shadowRoot!.querySelector<HTMLElement>('.title-container');
assert(titleContainer);
titleContainer.focus();
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-dialog': CrDialogElement;
}
}
customElements.define(CrDialogElement.is, CrDialogElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_dialog/cr_dialog.ts | TypeScript | unknown | 10,325 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Minimal externs file provided for places in the code that
* still use JavaScript instead of TypeScript.
* @externs
*/
/**
* @constructor
* @extends {HTMLElement}
*/
function CrDialogElement() {}
/** @type {boolean} */
CrDialogElement.prototype.open;
CrDialogElement.prototype.showModal = function() {};
CrDialogElement.prototype.cancel = function() {};
CrDialogElement.prototype.close = function() {};
/** @return {HTMLDialogElement} */
CrDialogElement.prototype.getNative = function() {};
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_dialog/cr_dialog_externs.js | JavaScript | unknown | 649 |
<style>
:host dialog {
--drawer-width: 256px;
--transition-timing: 200ms ease;
background-color: var(--cr-drawer-background-color, #fff);
border: none;
bottom: 0;
left: calc(-1 * var(--drawer-width));
margin: 0;
max-height: initial;
max-width: initial;
overflow: hidden;
padding: 0;
position: absolute;
top: 0;
transition: left var(--transition-timing);
width: var(--drawer-width);
}
@media (prefers-color-scheme: dark) {
:host dialog {
background: var(--cr-drawer-background-color, var(--google-grey-900))
linear-gradient(rgba(255, 255, 255, .04), rgba(255, 255, 255, .04));
}
}
:host dialog,
#container {
height: 100%;
word-break: break-word;
}
:host([show_]) dialog {
left: 0;
}
:host([align=rtl]) dialog {
left: auto;
right: calc(-1 * var(--drawer-width));
transition: right var(--transition-timing);
}
:host([show_][align=rtl]) dialog {
right: 0;
}
:host dialog::backdrop {
background: rgba(0, 0, 0, 0.5);
bottom: 0;
left: 0;
opacity: 0;
position: absolute;
right: 0;
top: 0;
transition: opacity var(--transition-timing);
}
:host([show_]) dialog::backdrop {
opacity: 1;
}
.drawer-header {
align-items: center;
border-bottom: var(--cr-separator-line);
color: var(--cr-drawer-header-color, inherit);
display: flex;
font-size: 123.08%; /* go to 16px from 13px */
font-weight: var(--cr-drawer-header-font-weight, inherit);
min-height: 56px;
padding-inline-start: var(--cr-drawer-header-padding, 24px);
}
@media (prefers-color-scheme: dark) {
.drawer-header {
color: var(--cr-primary-text-color);
}
}
#heading {
outline: none;
}
:host ::slotted([slot='body']) {
height: calc(100% - 56px);
overflow: auto;
}
picture {
margin-inline-end: 16px;
}
picture,
#product-logo {
height: 24px;
width: 24px;
}
</style>
<dialog id="dialog" on-cancel="onDialogCancel_" on-click="onDialogTap_"
on-close="onDialogClose_">
<div id="container" on-click="onContainerTap_">
<div class="drawer-header">
<slot name="header-icon">
<picture>
<source media="(prefers-color-scheme: dark)"
srcset="//resources/images/chrome_logo_dark.svg">
<img id="product-logo"
srcset="chrome://theme/current-channel-logo@1x 1x,
chrome://theme/current-channel-logo@2x 2x"
role="presentation">
</picture>
</slot>
<div id="heading" tabindex="-1">[[heading]]</div>
</div>
<slot name="body"></slot>
</div>
</dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_drawer/cr_drawer.html | HTML | unknown | 3,112 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../cr_shared_vars.css.js';
import {assertNotReached} from '//resources/js/assert_ts.js';
import {listenOnce} from '//resources/js/util_ts.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_drawer.html.js';
export interface CrDrawerElement {
$: {
dialog: HTMLDialogElement,
};
}
export class CrDrawerElement extends PolymerElement {
static get is() {
return 'cr-drawer';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
heading: String,
show_: {
type: Boolean,
reflectToAttribute: true,
},
/** The alignment of the drawer on the screen ('ltr' or 'rtl'). */
align: {
type: String,
value: 'ltr',
reflectToAttribute: true,
},
};
}
heading: string;
align: 'ltr'|'rtl';
private show_: boolean;
private fire_(eventName: string, detail?: any) {
this.dispatchEvent(
new CustomEvent(eventName, {bubbles: true, composed: true, detail}));
}
get open(): boolean {
return this.$.dialog.open;
}
set open(_value: boolean) {
assertNotReached('Cannot set |open|.');
}
/** Toggles the drawer open and close. */
toggle() {
if (this.open) {
this.cancel();
} else {
this.openDrawer();
}
}
/** Shows drawer and slides it into view. */
openDrawer() {
if (this.open) {
return;
}
this.$.dialog.showModal();
this.show_ = true;
this.fire_('cr-drawer-opening');
listenOnce(this.$.dialog, 'transitionend', () => {
this.fire_('cr-drawer-opened');
});
}
/**
* Slides the drawer away, then closes it after the transition has ended. It
* is up to the owner of this component to differentiate between close and
* cancel.
*/
private dismiss_(cancel: boolean) {
if (!this.open) {
return;
}
this.show_ = false;
listenOnce(this.$.dialog, 'transitionend', () => {
this.$.dialog.close(cancel ? 'canceled' : 'closed');
});
}
cancel() {
this.dismiss_(true);
}
close() {
this.dismiss_(false);
}
wasCanceled(): boolean {
return !this.open && this.$.dialog.returnValue === 'canceled';
}
/**
* Stop propagation of a tap event inside the container. This will allow
* |onDialogTap_| to only be called when clicked outside the container.
*/
private onContainerTap_(event: Event) {
event.stopPropagation();
}
/**
* Close the dialog when tapped outside the container.
*/
private onDialogTap_() {
this.cancel();
}
/**
* Overrides the default cancel machanism to allow for a close animation.
*/
private onDialogCancel_(event: Event) {
event.preventDefault();
this.cancel();
}
private onDialogClose_() {
// Catch and re-fire the 'close' event such that it bubbles across Shadow
// DOM v1.
this.fire_('close');
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-drawer': CrDrawerElement;
}
}
customElements.define(CrDrawerElement.is, CrDrawerElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_drawer/cr_drawer.ts | TypeScript | unknown | 3,269 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Minimal externs file provided for places in the code that
* still use JavaScript instead of TypeScript.
* @externs
*/
/**
* @constructor
* @extends {HTMLElement}
*/
function CrDrawerElement() {}
CrDrawerElement.prototype.cancel = function() {};
CrDrawerElement.prototype.openDrawer = function() {};
CrDrawerElement.prototype.wasCanceled = function() {};
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_drawer/cr_drawer_externs.js | JavaScript | unknown | 509 |
<style include="cr-actionable-row-style">
:host([disabled]) {
opacity: 0.65;
pointer-events: none;
}
:host([disabled]) cr-icon-button {
display: var(--cr-expand-button-disabled-display, initial);
}
#label {
flex: 1;
padding: var(--cr-section-vertical-padding) 0;
}
cr-icon-button {
--cr-icon-button-icon-size: var(--cr-expand-button-icon-size, 20px);
--cr-icon-button-size: var(--cr-expand-button-size, 36px);
}
</style>
<div id="label" aria-hidden="true"><slot></slot></div>
<cr-icon-button id="icon" aria-labelledby="label" disabled="[[disabled]]"
tabindex="[[tabIndex]]" part="icon"></cr-icon-button>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_expand_button/cr_expand_button.html | HTML | unknown | 736 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* 'cr-expand-button' is a chrome-specific wrapper around a button that toggles
* between an opened (expanded) and closed state.
*/
import '../cr_actionable_row_style.css.js';
import '../cr_icon_button/cr_icon_button.js';
import '../cr_shared_vars.css.js';
import '../icons.html.js';
import {focusWithoutInk} from '//resources/js/focus_without_ink.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CrIconButtonElement} from '../cr_icon_button/cr_icon_button.js';
import {getTemplate} from './cr_expand_button.html.js';
export interface CrExpandButtonElement {
$: {
icon: CrIconButtonElement,
};
}
export class CrExpandButtonElement extends PolymerElement {
static get is() {
return 'cr-expand-button';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* If true, the button is in the expanded state and will show the icon
* specified in the `collapseIcon` property. If false, the button shows
* the icon specified in the `expandIcon` property.
*/
expanded: {
type: Boolean,
value: false,
notify: true,
observer: 'onExpandedChange_',
},
/**
* If true, the button will be disabled and grayed out.
*/
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/** A11y text descriptor for this control. */
ariaLabel: {
type: String,
observer: 'onAriaLabelChange_',
},
tabIndex: {
type: Number,
value: 0,
},
expandIcon: {
type: String,
value: 'cr:expand-more',
observer: 'onIconChange_',
},
collapseIcon: {
type: String,
value: 'cr:expand-less',
observer: 'onIconChange_',
},
expandTitle: String,
collapseTitle: String,
tooltipText_: {
type: String,
computed: 'computeTooltipText_(expandTitle, collapseTitle, expanded)',
observer: 'onTooltipTextChange_',
},
};
}
expanded: boolean;
disabled: boolean;
expandIcon: string;
collapseIcon: string;
expandTitle: string;
collapseTitle: string;
private tooltipText_: string;
static get observers() {
return ['updateAriaExpanded_(disabled, expanded)'];
}
override ready() {
super.ready();
this.addEventListener('click', this.toggleExpand_);
}
private computeTooltipText_(): string {
return this.expanded ? this.collapseTitle : this.expandTitle;
}
private onTooltipTextChange_() {
this.title = this.tooltipText_;
}
override focus() {
this.$.icon.focus();
}
private onAriaLabelChange_() {
if (this.ariaLabel) {
this.$.icon.removeAttribute('aria-labelledby');
this.$.icon.setAttribute('aria-label', this.ariaLabel);
} else {
this.$.icon.removeAttribute('aria-label');
this.$.icon.setAttribute('aria-labelledby', 'label');
}
}
private onExpandedChange_() {
this.updateIcon_();
}
private onIconChange_() {
this.updateIcon_();
}
private updateIcon_() {
this.$.icon.ironIcon = this.expanded ? this.collapseIcon : this.expandIcon;
}
private toggleExpand_(event: Event) {
// Prevent |click| event from bubbling. It can cause parents of this
// elements to erroneously re-toggle this control.
event.stopPropagation();
event.preventDefault();
this.scrollIntoViewIfNeeded();
this.expanded = !this.expanded;
focusWithoutInk(this.$.icon);
}
private updateAriaExpanded_() {
if (this.disabled) {
this.$.icon.removeAttribute('aria-expanded');
} else {
this.$.icon.setAttribute(
'aria-expanded', this.expanded ? 'true' : 'false');
}
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-expand-button': CrExpandButtonElement;
}
}
customElements.define(CrExpandButtonElement.is, CrExpandButtonElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_expand_button/cr_expand_button.ts | TypeScript | unknown | 4,175 |
<style>
:host {
user-select: none;
}
.translucent {
opacity: 0.3;
}
#canvasDiv {
height: 240px;
overflow: hidden;
position: relative;
width: 460px;
}
cr-lottie {
display: inline-block;
position: absolute;
}
#fingerprintScanned {
position: absolute;
}
</style>
<div id="canvasDiv">
<canvas id="canvas" height="240" width="460"></canvas>
<iron-media-query query="(prefers-color-scheme: dark)"
query-matches="{{isDarkModeActive_}}">
</iron-media-query>
<cr-lottie id="scanningAnimation" aria-hidden="true"
autoplay="[[autoplay]]">
</cr-lottie>
<iron-icon id="fingerprintScanned" hidden></iron-icon>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_fingerprint/cr_fingerprint_progress_arc.html | HTML | unknown | 813 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import '//resources/polymer/v3_0/iron-media-query/iron-media-query.js';
import './cr_fingerprint_icons.html.js';
import '../cr_lottie/cr_lottie.js';
import {assert} from '//resources/js/assert_ts.js';
import {IronIconElement} from '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CrLottieElement} from '../cr_lottie/cr_lottie.js';
import {getTemplate} from './cr_fingerprint_progress_arc.html.js';
/**
* The dark-mode fingerprint icon displayed temporarily each time a user scans
* their fingerprint and persistently once the enrollment process is complete.
*/
export const FINGERPRINT_SCANNED_ICON_DARK: string =
'cr-fingerprint-icon:fingerprint-scanned-dark';
/**
* The light-mode fingerprint icon displayed temporarily each time a user scans
* their fingerprint and persistently once the enrollment process is complete.
*/
export const FINGERPRINT_SCANNED_ICON_LIGHT: string =
'cr-fingerprint-icon:fingerprint-scanned-light';
export const FINGERPRINT_CHECK_DARK_URL: string =
'chrome://theme/IDR_FINGERPRINT_COMPLETE_CHECK_DARK';
export const FINGERPRINT_CHECK_LIGHT_URL: string =
'chrome://theme/IDR_FINGERPRINT_COMPLETE_CHECK_LIGHT';
/**
* The dark-mode color of the progress circle background: Google Grey 700.
*/
export const PROGRESS_CIRCLE_BACKGROUND_COLOR_DARK: string =
'rgba(95, 99, 104, 1.0)';
/**
* The light-mode color of the progress circle background: Google Grey 200.
*/
export const PROGRESS_CIRCLE_BACKGROUND_COLOR_LIGHT: string =
'rgba(232, 234, 237, 1.0)';
/**
* The dark-mode color of the setup progress arc: Google Blue 400.
*/
export const PROGRESS_CIRCLE_FILL_COLOR_DARK: string =
'rgba(102, 157, 246, 1.0)';
/**
* The light-mode color of the setup progress arc: Google Blue 500.
*/
export const PROGRESS_CIRCLE_FILL_COLOR_LIGHT: string =
'rgba(66, 133, 244, 1.0)';
/**
* The time in milliseconds of the animation updates.
*/
const ANIMATE_TICKS_MS: number = 20;
/**
* The duration in milliseconds of the animation of the progress circle when the
* user is touching the scanner.
*/
const ANIMATE_DURATION_MS: number = 200;
/**
* The radius of the add fingerprint progress circle.
*/
const DEFAULT_PROGRESS_CIRCLE_RADIUS: number = 114;
/**
* The default height of the icon located in the center of the fingerprint
* progress circle.
*/
const ICON_HEIGHT: number = 118;
/**
* The default width of the icon located in the center of the fingerprint
* progress circle.
*/
const ICON_WIDTH: number = 106;
/**
* The default size of the check mark located in the bottom-right corner of the
* fingerprint progress circle.
*/
const CHECK_MARK_SIZE: number = 53;
/**
* The time in milliseconds of the fingerprint scan success timeout.
*/
const FINGERPRINT_SCAN_SUCCESS_MS: number = 500;
/**
* The thickness of the fingerprint progress circle.
*/
const PROGRESS_CIRCLE_STROKE_WIDTH: number = 4;
export interface CrFingerprintProgressArcElement {
$: {
canvas: HTMLCanvasElement,
fingerprintScanned: IronIconElement,
scanningAnimation: CrLottieElement,
};
}
export class CrFingerprintProgressArcElement extends PolymerElement {
static get is() {
return 'cr-fingerprint-progress-arc';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* Radius of the fingerprint progress circle being displayed.
*/
circleRadius: {
type: Number,
value: DEFAULT_PROGRESS_CIRCLE_RADIUS,
},
/**
* Whether lottie animation should be autoplayed.
*/
autoplay: {
type: Boolean,
value: false,
},
/**
* Scale factor based the configured radius (circleRadius) vs the default
* radius (DEFAULT_PROGRESS_CIRCLE_RADIUS).
* This will affect the size of icons and check mark.
*/
scale_: {
type: Number,
value: 1.0,
},
/**
* Whether fingerprint enrollment is complete.
*/
isComplete_: Boolean,
/**
* Whether the fingerprint progress page is being rendered in dark mode.
*/
isDarkModeActive_: {
type: Boolean,
value: false,
observer: 'onDarkModeChanged_',
},
};
}
circleRadius: number;
autoplay: boolean;
private scale_: number;
private isComplete_: boolean;
private isDarkModeActive_: boolean;
// Animation ID for the fingerprint progress circle.
private progressAnimationIntervalId_: number|undefined = undefined;
// Percentage of the enrollment process completed as of the last update.
private progressPercentDrawn_: number = 0;
// Timer ID for fingerprint scan success update.
private updateTimerId_: number|undefined = undefined;
/**
* Updates the current state to account for whether dark mode is enabled.
*/
private onDarkModeChanged_() {
this.clearCanvas_();
this.drawProgressCircle_(this.progressPercentDrawn_);
this.updateAnimationAsset_();
this.updateIconAsset_();
}
override connectedCallback() {
super.connectedCallback();
this.scale_ = this.circleRadius / DEFAULT_PROGRESS_CIRCLE_RADIUS;
this.updateIconAsset_();
this.updateImages_();
}
/**
* Reset the element to initial state, when the enrollment just starts.
*/
reset() {
this.cancelAnimations_();
this.clearCanvas_();
this.isComplete_ = false;
// Draw an empty background for the progress circle.
this.drawProgressCircle_(/** currentPercent = */ 0);
this.$.fingerprintScanned.hidden = true;
const scanningAnimation = this.$.scanningAnimation;
scanningAnimation.singleLoop = false;
scanningAnimation.classList.add('translucent');
this.updateAnimationAsset_();
this.resizeAndCenterIcon_(scanningAnimation);
scanningAnimation.hidden = false;
}
/**
* Animates the progress circle. Animates an arc that starts at the top of
* the circle to prevPercentComplete, to an arc that starts at the top of the
* circle to currPercentComplete.
* @param prevPercentComplete The previous progress indicates the start angle
* of the arc we want to draw.
* @param currPercentComplete The current progress indicates the end angle of
* the arc we want to draw.
* @param isComplete Indicate whether enrollment is complete.
*/
setProgress(
prevPercentComplete: number, currPercentComplete: number,
isComplete: boolean) {
if (this.isComplete_) {
return;
}
this.isComplete_ = isComplete;
this.cancelAnimations_();
let nextPercentToDraw = prevPercentComplete;
const endPercent = isComplete ? 100 : Math.min(100, currPercentComplete);
// The value by which to update the progress percent each tick.
const step = (endPercent - prevPercentComplete) /
(ANIMATE_DURATION_MS / ANIMATE_TICKS_MS);
// Function that is called every tick of the interval, draws the arc a bit
// closer to the final destination each tick, until it reaches the final
// destination.
const doAnimate = () => {
if (nextPercentToDraw >= endPercent) {
if (this.progressAnimationIntervalId_) {
clearInterval(this.progressAnimationIntervalId_);
this.progressAnimationIntervalId_ = undefined;
}
nextPercentToDraw = endPercent;
}
this.clearCanvas_();
this.drawProgressCircle_(nextPercentToDraw);
if (!this.progressAnimationIntervalId_) {
this.dispatchEvent(new CustomEvent(
'cr-fingerprint-progress-arc-drawn',
{bubbles: true, composed: true}));
}
nextPercentToDraw += step;
};
this.progressAnimationIntervalId_ =
setInterval(doAnimate, ANIMATE_TICKS_MS);
if (isComplete) {
this.animateScanComplete_();
} else {
this.animateScanProgress_();
}
}
/**
* Controls the animation based on the value of |shouldPlay|.
* @param shouldPlay Will play the animation if true else pauses it.
*/
setPlay(shouldPlay: boolean) {
this.$.scanningAnimation.setPlay(shouldPlay);
}
isComplete(): boolean {
return this.isComplete_;
}
/**
* Draws an arc on the canvas element around the center with radius
* |circleRadius|.
* @param startAngle The start angle of the arc we want to draw.
* @param endAngle The end angle of the arc we want to draw.
* @param color The color of the arc we want to draw. The string is
* in the format rgba(r',g',b',a'). r', g', b' are values from [0-255]
* and a' is a value from [0-1].
*/
private drawArc_(startAngle: number, endAngle: number, color: string) {
const c = this.$.canvas;
const ctx = c.getContext('2d');
assert(!!ctx);
ctx.beginPath();
ctx.arc(c.width / 2, c.height / 2, this.circleRadius, startAngle, endAngle);
ctx.lineWidth = PROGRESS_CIRCLE_STROKE_WIDTH;
ctx.strokeStyle = color;
ctx.stroke();
}
/**
* Draws a circle on the canvas element around the center with radius
* |circleRadius|. The first |currentPercent| of the circle, starting at the
* top, is drawn with |PROGRESS_CIRCLE_FILL_COLOR|; the remainder of the
* circle is drawn |PROGRESS_CIRCLE_BACKGROUND_COLOR|.
* @param currentPercent A value from [0-100] indicating the
* percentage of progress to display.
*/
private drawProgressCircle_(currentPercent: number) {
// Angles on HTML canvases start at 0 radians on the positive x-axis and
// increase in the clockwise direction. We want to start at the top of the
// circle, which is 3pi/2.
const start = 3 * Math.PI / 2;
const currentAngle = 2 * Math.PI * currentPercent / 100;
// Drawing two arcs to form a circle gives a nicer look than drawing an arc
// on top of a circle (i.e., compared to drawing a full background circle
// first). If |currentAngle| is 0, draw from 3pi/2 to 7pi/2 explicitly;
// otherwise, the regular draw from |start| + |currentAngle| to |start|
// will do nothing.
this.drawArc_(
start, start + currentAngle,
this.isDarkModeActive_ ? PROGRESS_CIRCLE_FILL_COLOR_DARK :
PROGRESS_CIRCLE_FILL_COLOR_LIGHT);
this.drawArc_(
start + currentAngle, currentAngle <= 0 ? 7 * Math.PI / 2 : start,
this.isDarkModeActive_ ? PROGRESS_CIRCLE_BACKGROUND_COLOR_DARK :
PROGRESS_CIRCLE_BACKGROUND_COLOR_LIGHT);
this.progressPercentDrawn_ = currentPercent;
}
/**
* Updates the lottie animation taking into account the current state and
* whether dark mode is enabled.
*/
private updateAnimationAsset_() {
const scanningAnimation = this.$.scanningAnimation;
if (this.isComplete_) {
scanningAnimation.animationUrl = this.isDarkModeActive_ ?
FINGERPRINT_CHECK_DARK_URL :
FINGERPRINT_CHECK_LIGHT_URL;
return;
}
scanningAnimation.animationUrl = this.isDarkModeActive_ ?
'chrome://theme/IDR_FINGERPRINT_ICON_ANIMATION_DARK' :
'chrome://theme/IDR_FINGERPRINT_ICON_ANIMATION_LIGHT';
}
/**
* Updates the fingerprint-scanned icon based on whether dark mode is enabled.
*/
private updateIconAsset_() {
this.$.fingerprintScanned.icon = this.isDarkModeActive_ ?
FINGERPRINT_SCANNED_ICON_DARK :
FINGERPRINT_SCANNED_ICON_LIGHT;
}
/*
* Cleans up any pending animation update created by setInterval().
*/
private cancelAnimations_() {
this.progressPercentDrawn_ = 0;
if (this.progressAnimationIntervalId_) {
clearInterval(this.progressAnimationIntervalId_);
this.progressAnimationIntervalId_ = undefined;
}
if (this.updateTimerId_) {
window.clearTimeout(this.updateTimerId_);
this.updateTimerId_ = undefined;
}
}
/**
* Show animation for enrollment completion.
*/
private animateScanComplete_() {
const scanningAnimation = this.$.scanningAnimation;
scanningAnimation.singleLoop = true;
scanningAnimation.autoplay = true;
scanningAnimation.classList.remove('translucent');
this.updateAnimationAsset_();
this.resizeCheckMark_(scanningAnimation);
this.$.fingerprintScanned.hidden = false;
}
/**
* Show animation for enrollment in progress.
*/
private animateScanProgress_() {
this.$.fingerprintScanned.hidden = false;
this.$.scanningAnimation.hidden = true;
this.updateTimerId_ = window.setTimeout(() => {
this.$.scanningAnimation.hidden = false;
this.$.fingerprintScanned.hidden = true;
}, FINGERPRINT_SCAN_SUCCESS_MS);
}
/**
* Clear the canvas of any renderings.
*/
private clearCanvas_() {
const c = this.$.canvas;
const ctx = c.getContext('2d');
assert(!!ctx);
ctx.clearRect(0, 0, c.width, c.height);
}
/**
* Update the size and position of the animation images.
*/
private updateImages_() {
this.resizeAndCenterIcon_(this.$.scanningAnimation);
this.resizeAndCenterIcon_(this.$.fingerprintScanned);
}
/**
* Resize the icon based on the scale and place it in the center of the
* fingerprint progress circle.
*/
private resizeAndCenterIcon_(target: HTMLElement) {
// Resize icon based on the default width/height and scale.
target.style.width = ICON_WIDTH * this.scale_ + 'px';
target.style.height = ICON_HEIGHT * this.scale_ + 'px';
// Place in the center of the canvas.
const left = this.$.canvas.width / 2 - ICON_WIDTH * this.scale_ / 2;
const top = this.$.canvas.height / 2 - ICON_HEIGHT * this.scale_ / 2;
target.style.left = left + 'px';
target.style.top = top + 'px';
}
/**
* Resize the check mark based on the scale and place it in the bottom-right
* corner of the fingerprint progress circle.
*/
private resizeCheckMark_(target: HTMLElement) {
// Resize check mark based on the default size and scale.
target.style.width = CHECK_MARK_SIZE * this.scale_ + 'px';
target.style.height = CHECK_MARK_SIZE * this.scale_ + 'px';
// Place it in the bottom-right corner of the fingerprint progress circle.
const top = this.$.canvas.height / 2 + this.circleRadius -
CHECK_MARK_SIZE * this.scale_;
const left = this.$.canvas.width / 2 + this.circleRadius -
CHECK_MARK_SIZE * this.scale_;
target.style.left = left + 'px';
target.style.top = top + 'px';
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-fingerprint-progress-arc': CrFingerprintProgressArcElement;
}
}
customElements.define(
CrFingerprintProgressArcElement.is, CrFingerprintProgressArcElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_fingerprint/cr_fingerprint_progress_arc.ts | TypeScript | unknown | 14,918 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Minimal externs file provided for places in the code that
* still use JavaScript instead of TypeScript.
* @externs
*/
/**
* @constructor
* @extends {HTMLElement}
*/
function CrFingerprintProgressArcElement() {}
/**
* @param {number} prevPercentComplete
* @param {number} currPercentComplete
* @param {boolean} isComplete
*/
CrFingerprintProgressArcElement.prototype.setProgress = function(
prevPercentComplete, currPercentComplete, isComplete) {};
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_fingerprint/cr_fingerprint_progress_arc_externs.js | JavaScript | unknown | 611 |
<style>
:host {
--cr-grid-gap: 0px;
--cr-column-width: auto;
--cr-grid-width: fit-content;
}
#grid {
display: grid;
grid-gap: var(--cr-grid-gap);
grid-template-columns: repeat(var(--cr-grid-columns), var(--cr-column-width));
width: var(--cr-grid-width);
}
::slotted(*) {
align-self: center;
justify-self: center;
}
</style>
<div id="grid" on-keydown="onKeyDown_">
<slot id="items"></slot>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_grid/cr_grid.html | HTML | unknown | 448 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_grid.html.js';
// Displays children in a two-dimensional grid and supports focusing children
// with arrow keys.
export interface CrGridElement {
$: {
items: HTMLSlotElement,
};
}
export class CrGridElement extends PolymerElement {
static get is() {
return 'cr-grid';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
columns: {
type: Number,
observer: 'onColumnsChange_',
},
disableArrowNavigation: Boolean,
};
}
disableArrowNavigation: boolean = false;
columns: number = 1;
private onColumnsChange_() {
this.updateStyles({'--cr-grid-columns': this.columns});
}
private onKeyDown_(e: KeyboardEvent) {
if (!this.disableArrowNavigation &&
['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
e.preventDefault();
const items =
(this.$.items.assignedElements() as HTMLElement[]).filter(el => {
return !!(
el.offsetWidth || el.offsetHeight ||
el.getClientRects().length);
});
const currentIndex = items.indexOf(e.target as HTMLElement);
const isRtl = window.getComputedStyle(this)['direction'] === 'rtl';
const bottomRowColumns = items.length % this.columns;
const direction = ['ArrowRight', 'ArrowDown'].includes(e.key) ? 1 : -1;
const inEdgeRow = direction === 1 ?
currentIndex >= items.length - bottomRowColumns :
currentIndex < this.columns;
let delta = 0;
switch (e.key) {
case 'ArrowLeft':
case 'ArrowRight':
delta = direction * (isRtl ? -1 : 1);
break;
case 'ArrowUp':
case 'ArrowDown':
delta = direction * (inEdgeRow ? bottomRowColumns : this.columns);
break;
}
// Handle cases where we move to an empty space in a non-full bottom row
// and have to jump to the next row.
if (e.key === 'ArrowUp' && inEdgeRow &&
currentIndex >= bottomRowColumns) {
delta -= this.columns;
} else if (
e.key === 'ArrowDown' && !inEdgeRow &&
currentIndex + delta >= items.length) {
delta += bottomRowColumns;
}
const newIndex = (items.length + currentIndex + delta) % items.length;
items[newIndex]!.focus();
}
if (['Enter', ' '].includes(e.key)) {
e.preventDefault();
e.stopPropagation();
(e.target as HTMLElement).click();
}
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-grid': CrGridElement;
}
}
customElements.define(CrGridElement.is, CrGridElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_grid/cr_grid.ts | TypeScript | unknown | 2,921 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #scheme=relative
* #css_wrapper_metadata_end */
/* Included here so we don't have to include "iron-positioning" in every
* stylesheet. See crbug.com/498405. */
[hidden],
:host([hidden]) {
display: none !important;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_hidden_style.css | CSS | unknown | 417 |
<style>
:host {
--cr-icon-button-fill-color: var(--google-grey-700);
--cr-icon-button-icon-start-offset: 0;
--cr-icon-button-icon-size: 20px;
--cr-icon-button-size: 36px;
--cr-icon-button-height: var(--cr-icon-button-size);
--cr-icon-button-transition: 150ms ease-in-out;
--cr-icon-button-width: var(--cr-icon-button-size);
/* Copied from paper-fab.html. Prevents square touch highlight. */
-webkit-tap-highlight-color: transparent;
border-radius: 50%;
color: var(--cr-icon-button-stroke-color,
var(--cr-icon-button-fill-color));
cursor: pointer;
display: inline-flex;
flex-shrink: 0;
height: var(--cr-icon-button-height);
margin-inline-end: var(--cr-icon-button-margin-end,
var(--cr-icon-ripple-margin));
margin-inline-start: var(--cr-icon-button-margin-start);
outline: none;
overflow: hidden;
user-select: none;
vertical-align: middle;
width: var(--cr-icon-button-width);
}
:host-context([chrome-refresh-2023]):host {
--cr-icon-button-fill-color: currentColor;
--cr-icon-button-size: 32px;
position: relative;
}
:host(:hover) {
background-color: var(--cr-icon-button-hover-background-color,
var(--cr-hover-background-color));
}
:host(:focus-visible:focus) {
box-shadow: inset 0 0 0 2px var(--cr-icon-button-focus-outline-color,
var(--cr-focus-outline-color));
}
@media (forced-colors: active) {
:host(:focus-visible:focus) {
/* Use outline instead of box-shadow (which does not work) in Windows
HCM. */
outline: var(--cr-focus-outline-hcm);
}
}
:host-context(html:not([chrome-refresh-2023])) :host(:active) {
background-color: var(--cr-icon-button-active-background-color,
var(--cr-active-background-color));
}
paper-ripple {
display: none;
}
:host-context([chrome-refresh-2023]) paper-ripple {
--paper-ripple-opacity: 1;
color: var(--cr-active-background-color);
display: block;
}
:host([disabled]) {
cursor: initial;
opacity: var(--cr-disabled-opacity);
pointer-events: none;
}
:host(.no-overlap) {
--cr-icon-button-margin-end: 0;
--cr-icon-button-margin-start: 0;
}
:host-context([dir=rtl]):host(:not([dir=ltr]):not([multiple-icons_])) {
transform: scaleX(-1); /* Invert X: flip on the Y axis (aka mirror). */
}
:host-context([dir=rtl]):host(:not([dir=ltr])[multiple-icons_])
iron-icon {
transform: scaleX(-1); /* Invert X: flip on the Y axis (aka mirror). */
}
:host(:not([iron-icon])) #maskedImage {
-webkit-mask-image: var(--cr-icon-image);
-webkit-mask-position: center;
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: var(--cr-icon-button-icon-size);
-webkit-transform: var(--cr-icon-image-transform, none);
background-color: var(--cr-icon-button-fill-color);
height: 100%;
transition: background-color var(--cr-icon-button-transition);
width: 100%;
}
@media (forced-colors: active) {
:host(:not([iron-icon])) #maskedImage {
background-color: ButtonText;
}
}
#icon {
align-items: center;
border-radius: 4px;
display: flex;
height: 100%;
justify-content: center;
padding-inline-start: var(--cr-icon-button-icon-start-offset);
/* The |_rippleContainer| must be position relative. */
position: relative;
width: 100%;
}
iron-icon {
--iron-icon-fill-color: var(--cr-icon-button-fill-color);
--iron-icon-stroke-color: var(--cr-icon-button-stroke-color, none);
--iron-icon-height: var(--cr-icon-button-icon-size);
--iron-icon-width: var(--cr-icon-button-icon-size);
transition: fill var(--cr-icon-button-transition),
stroke var(--cr-icon-button-transition);
}
@media (prefers-color-scheme: dark) {
:host {
--cr-icon-button-fill-color: var(--google-grey-500);
}
}
</style>
<div id="icon">
<div id="maskedImage"></div>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_icon_button/cr_icon_button.html | HTML | unknown | 4,454 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'cr-icon-button' is a button which displays an icon with a
* ripple. It can be interacted with like a normal button using click as well as
* space and enter to effectively click the button and fire a 'click' event.
*
* There are two sources to icons, cr-icons and iron-iconset-svg. The cr-icon's
* are defined as background images with a reference to a resource file
* associated with a CSS class name. The iron-icon's are defined as inline SVG's
* under a key that is stored in a global map that is accessible to the
* iron-icon element.
*
* Example of using a cr-icon:
* <link rel="import" href="chrome://resources/cr_elements/cr_icons.css.html">
* <dom-module id="module">
* <template>
* <style includes="cr-icons"></style>
* <cr-icon-button class="icon-class-name"></cr-icon-button>
* </template>
* </dom-module>
*
* In general when an icon is specified using a class, the expectation is the
* class will set an image to the --cr-icon-image variable.
*
* Example of using an iron-icon:
* In the TS file:
* import 'chrome://resources/cr_elements/icons.html.js';
*
* In the HTML template file:
* <cr-icon-button iron-icon="cr:icon-key"></cr-icon-button>
*
* The color of the icon can be overridden using CSS variables. When using
* iron-icon both the fill and stroke can be overridden the variables:
* --cr-icon-button-fill-color
* --cr-icon-button-stroke-color
*
* When not using iron-icon (ie. specifying --cr-icon-image), the icons support
* one color and the 'stroke' variables are ignored.
*
* When using iron-icon's, more than one icon can be specified by setting
* the |ironIcon| property to a comma-delimited list of keys.
*/
import '../cr_shared_vars.css.js';
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import {PaperRippleBehavior} from '//resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js';
import {mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_icon_button.html.js';
export interface CrIconButtonElement {
$: {
icon: HTMLElement,
};
}
const CrIconbuttonElementBase =
mixinBehaviors([PaperRippleBehavior], PolymerElement) as {
new (): PolymerElement & PaperRippleBehavior,
};
export class CrIconButtonElement extends CrIconbuttonElementBase {
static get is() {
return 'cr-icon-button';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: 'disabledChanged_',
},
/**
* Use this property in order to configure the "tabindex" attribute.
*/
customTabIndex: {
type: Number,
observer: 'applyTabIndex_',
},
ironIcon: {
type: String,
observer: 'onIronIconChanged_',
reflectToAttribute: true,
},
multipleIcons_: {
type: Boolean,
reflectToAttribute: true,
},
};
}
disabled: boolean;
customTabIndex: number;
ironIcon: string;
private multipleIcons_: boolean;
/**
* It is possible to activate a tab when the space key is pressed down. When
* this element has focus, the keyup event for the space key should not
* perform a 'click'. |spaceKeyDown_| tracks when a space pressed and
* handled by this element. Space keyup will only result in a 'click' when
* |spaceKeyDown_| is true. |spaceKeyDown_| is set to false when element
* loses focus.
*/
private spaceKeyDown_: boolean = false;
constructor() {
super();
this.addEventListener('blur', this.onBlur_.bind(this));
this.addEventListener('click', this.onClick_.bind(this));
this.addEventListener('keydown', this.onKeyDown_.bind(this));
this.addEventListener('keyup', this.onKeyUp_.bind(this));
if (document.documentElement.hasAttribute('chrome-refresh-2023')) {
this.addEventListener('pointerdown', this.onPointerDown_.bind(this));
}
}
override ready() {
super.ready();
this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false');
if (!this.hasAttribute('role')) {
this.setAttribute('role', 'button');
}
if (!this.hasAttribute('tabindex')) {
this.setAttribute('tabindex', '0');
}
}
toggleClass(className: string) {
this.classList.toggle(className);
}
private disabledChanged_(newValue: boolean, oldValue?: boolean) {
if (!newValue && oldValue === undefined) {
return;
}
if (this.disabled) {
this.blur();
}
this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false');
this.applyTabIndex_();
}
/**
* Updates the tabindex HTML attribute to the actual value.
*/
private applyTabIndex_() {
let value = this.customTabIndex;
if (value === undefined) {
value = this.disabled ? -1 : 0;
}
this.setAttribute('tabindex', value.toString());
}
private onBlur_() {
this.spaceKeyDown_ = false;
}
private onClick_(e: Event) {
if (this.disabled) {
e.stopImmediatePropagation();
}
}
private onIronIconChanged_() {
this.shadowRoot!.querySelectorAll('iron-icon').forEach(el => el.remove());
if (!this.ironIcon) {
return;
}
const icons = (this.ironIcon || '').split(',');
this.multipleIcons_ = icons.length > 1;
icons.forEach(icon => {
const ironIcon = document.createElement('iron-icon');
ironIcon.icon = icon;
this.$.icon.appendChild(ironIcon);
if (ironIcon.shadowRoot) {
ironIcon.shadowRoot.querySelectorAll('svg, img')
.forEach(child => child.setAttribute('role', 'none'));
}
});
}
private onKeyDown_(e: KeyboardEvent) {
if (e.key !== ' ' && e.key !== 'Enter') {
return;
}
e.preventDefault();
e.stopPropagation();
if (e.repeat) {
return;
}
if (e.key === 'Enter') {
this.click();
} else if (e.key === ' ') {
this.spaceKeyDown_ = true;
}
}
private onKeyUp_(e: KeyboardEvent) {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
e.stopPropagation();
}
if (this.spaceKeyDown_ && e.key === ' ') {
this.spaceKeyDown_ = false;
this.click();
}
}
private onPointerDown_() {
this.ensureRipple();
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-icon-button': CrIconButtonElement;
}
}
customElements.define(CrIconButtonElement.is, CrIconButtonElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_icon_button/cr_icon_button.ts | TypeScript | unknown | 6,716 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #scheme=relative
* #css_wrapper_metadata_end */
.icon-arrow-back {
--cr-icon-image: url(chrome://resources/images/icon_arrow_back.svg);
}
.icon-arrow-dropdown {
--cr-icon-image: url(chrome://resources/images/icon_arrow_dropdown.svg);
}
.icon-cancel {
--cr-icon-image: url(chrome://resources/images/icon_cancel.svg);
}
.icon-clear {
--cr-icon-image: url(chrome://resources/images/icon_clear.svg);
}
.icon-copy-content {
--cr-icon-image: url(chrome://resources/images/icon_copy_content.svg);
}
.icon-delete-gray {
--cr-icon-image: url(chrome://resources/images/icon_delete_gray.svg);
}
.icon-edit {
--cr-icon-image: url(chrome://resources/images/icon_edit.svg);
}
.icon-file {
--cr-icon-image: url(chrome://resources/images/icon_filetype_generic.svg);
}
.icon-folder-open {
--cr-icon-image: url(chrome://resources/images/icon_folder_open.svg);
}
.icon-picture-delete {
--cr-icon-image: url(chrome://resources/images/icon_picture_delete.svg);
}
.icon-expand-less {
--cr-icon-image: url(chrome://resources/images/icon_expand_less.svg);
}
.icon-expand-more {
--cr-icon-image: url(chrome://resources/images/icon_expand_more.svg);
}
.icon-external {
--cr-icon-image: url(chrome://resources/images/open_in_new.svg);
}
.icon-more-vert {
--cr-icon-image: url(chrome://resources/images/icon_more_vert.svg);
}
.icon-refresh {
--cr-icon-image: url(chrome://resources/images/icon_refresh.svg);
}
.icon-search {
--cr-icon-image: url(chrome://resources/images/icon_search.svg);
}
.icon-settings {
--cr-icon-image: url(chrome://resources/images/icon_settings.svg);
}
.icon-visibility {
--cr-icon-image: url(chrome://resources/images/icon_visibility.svg);
}
.icon-visibility-off {
--cr-icon-image: url(chrome://resources/images/icon_visibility_off.svg);
}
.subpage-arrow {
--cr-icon-image: url(chrome://resources/images/arrow_right.svg);
}
.cr-icon {
-webkit-mask-image: var(--cr-icon-image);
-webkit-mask-position: center;
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: var(--cr-icon-size);
background-color: var(--cr-icon-color, var(--google-grey-700));
flex-shrink: 0;
height: var(--cr-icon-ripple-size);
margin-inline-end: var(--cr-icon-ripple-margin);
margin-inline-start: var(--cr-icon-button-margin-start);
user-select: none;
width: var(--cr-icon-ripple-size);
}
:host-context([dir=rtl]) .cr-icon {
transform: scaleX(-1); /* Invert X: flip on the Y axis (aka mirror). */
}
.cr-icon.no-overlap {
margin-inline-end: 0;
margin-inline-start: 0;
}
@media (prefers-color-scheme: dark) {
.cr-icon {
background-color: var(--cr-icon-color, var(--google-grey-500));
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_icons.css | CSS | unknown | 2,851 |
<style include="cr-hidden-style cr-input-style cr-shared-style">
/*
A 'suffix' element will be outside the underlined space, while a
'inline-prefix' and 'inline-suffix' elements will be inside the
underlined space by default.
Regarding cr-input's width:
When there's no element in the 'inline-prefix', 'inline-suffix' or
'suffix' slot, setting the width of cr-input as follows will work as
expected:
cr-input {
width: 200px;
}
However, when there's an element in the 'suffix', 'inline-suffix' and/or
'inline-prefix' slot, setting the 'width' will dictate the total width
of the input field *plus* the 'inline-prefix', 'inline-suffix' and
'suffix' elements. To set the width of the input field +
'inline-prefix' + 'inline-suffix' when a 'suffix' is present,
use --cr-input-width.
cr-input {
--cr-input-width: 200px;
}
*/
/* Disabled status should not impact suffix slot. */
:host([disabled]) :-webkit-any(#label, #error, #input-container) {
opacity: var(--cr-disabled-opacity);
pointer-events: none;
}
/* Margin between <input> and <cr-button> in the 'suffix' slot */
:host ::slotted(cr-button[slot=suffix]) {
margin-inline-start: var(--cr-button-edge-spacing) !important;
}
:host([invalid]) #label {
color: var(--cr-input-error-color);
}
#input {
border-bottom: var(--cr-input-border-bottom, none);
letter-spacing: var(--cr-input-letter-spacing);
}
:host-context([chrome-refresh-2023]) #input-container {
border: var(--cr-input-border, none);
}
#input::placeholder {
color: var(--cr-input-placeholder-color, var(--cr-secondary-text-color));
letter-spacing: var(--cr-input-placeholder-letter-spacing);
}
:host([invalid]) #input {
caret-color: var(--cr-input-error-color);
}
:host([readonly]) #input {
opacity: var(--cr-input-readonly-opacity, 0.6);
}
:host([invalid]) #underline {
border-color: var(--cr-input-error-color);
}
/* Error styling below. */
#error {
/* Defaults to "display: block" and "visibility:hidden" to allocate
space for error message, such that the page does not shift when
error appears. For cr-inputs that can't be invalid, but are in a
form with cr-inputs that can be invalid, this space is also desired
in order to have consistent spacing.
If spacing is not needed, apply "--cr-input-error-display: none".
When grouping cr-inputs horizontally, it might be helpful to set
--cr-input-error-white-space to "nowrap" and set a fixed width for
each cr-input so that a long error label does not shift the inputs
forward. */
color: var(--cr-input-error-color);
display: var(--cr-input-error-display, block);
font-size: var(--cr-form-field-label-font-size);
height: var(--cr-form-field-label-height);
line-height: var(--cr-form-field-label-line-height);
margin: 8px 0;
visibility: hidden;
white-space: var(--cr-input-error-white-space);
}
:host([invalid]) #error {
visibility: visible;
}
#row-container,
#inner-input-container {
align-items: center;
display: flex;
/* This will spread the input field and the suffix apart only if the
host element width is intentionally set to something large. */
justify-content: space-between;
position: relative;
}
#input[type='search']::-webkit-search-cancel-button {
display: none;
}
:host-context([dir=rtl]) #input[type=url] {
text-align: right; /* csschecker-disable-line left-right */
}
#input[type=url] {
direction: ltr;
}
</style>
<div id="label" class="cr-form-field-label" hidden="[[!label]]"
aria-hidden="true">
[[label]]
</div>
<div id="row-container" part="row-container">
<div id="input-container">
<div id="inner-input-container">
<slot name="inline-prefix"></slot>
<!-- Only attributes that are named inconsistently between html and js
need to use attr$="", such as |readonly| vs .readOnly. -->
<input id="input" disabled="[[disabled]]" autofocus="[[autofocus]]"
value="{{value::input}}" tabindex$="[[inputTabindex]]"
type="[[type]]"
readonly$="[[readonly]]" maxlength$="[[maxlength]]"
pattern$="[[pattern]]" required="[[required]]"
minlength$="[[minlength]]" inputmode$="[[inputmode]]"
aria-description$="[[ariaDescription]]"
aria-label$="[[getAriaLabel_(ariaLabel, label, placeholder)]]"
aria-invalid$="[[getAriaInvalid_(invalid)]]"
max="[[max]]" min="[[min]]" on-focus="onInputFocus_"
on-blur="onInputBlur_" on-change="onInputChange_"
part="input"
autocomplete="off">
<slot name="inline-suffix"></slot>
</div>
<div id="underline"></div>
</div>
<slot name="suffix"></slot>
</div>
<div id="error" aria-live="assertive">[[displayErrorMessage_]]</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_input/cr_input.html | HTML | unknown | 5,478 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '//resources/polymer/v3_0/paper-styles/color.js';
import '../cr_hidden_style.css.js';
import '../cr_shared_style.css.js';
import '../cr_shared_vars.css.js';
import './cr_input_style.css.js';
import {assert} from '//resources/js/assert_ts.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_input.html.js';
/**
* Input types supported by cr-input.
*/
const SUPPORTED_INPUT_TYPES: Set<string> = new Set([
'number',
'password',
'search',
'text',
'url',
]);
/**
* @fileoverview 'cr-input' is a component similar to native input.
*
* Native input attributes that are currently supported by cr-inputs are:
* autofocus
* disabled
* max (only applicable when type="number")
* min (only applicable when type="number")
* maxlength
* minlength
* pattern
* placeholder
* readonly
* required
* tabindex (set through input-tabindex)
* type (see |SUPPORTED_INPUT_TYPES| above)
* value
*
* Additional attributes that you can use with cr-input:
* label
* auto-validate - triggers validation based on |pattern| and |required|,
* whenever |value| changes.
* error-message - message displayed under the input when |invalid| is true.
* invalid
*
* You may pass an element into cr-input via [slot="suffix"] to be vertically
* center-aligned with the input field, regardless of position of the label and
* error-message. Example:
* <cr-input>
* <cr-button slot="suffix"></cr-button>
* </cr-input>
*/
export interface CrInputElement {
$: {
error: HTMLElement,
label: HTMLElement,
input: HTMLInputElement,
underline: HTMLElement,
};
}
export class CrInputElement extends PolymerElement {
static get is() {
return 'cr-input';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
ariaDescription: {
type: String,
},
ariaLabel: {
type: String,
value: '',
},
autofocus: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
autoValidate: Boolean,
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
errorMessage: {
type: String,
value: '',
observer: 'onInvalidOrErrorMessageChanged_',
},
displayErrorMessage_: {
type: String,
value: '',
},
/**
* This is strictly used internally for styling, do not attempt to use
* this to set focus.
*/
focused_: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
invalid: {
type: Boolean,
value: false,
notify: true,
reflectToAttribute: true,
observer: 'onInvalidOrErrorMessageChanged_',
},
max: {
type: Number,
reflectToAttribute: true,
},
min: {
type: Number,
reflectToAttribute: true,
},
maxlength: {
type: Number,
reflectToAttribute: true,
},
minlength: {
type: Number,
reflectToAttribute: true,
},
pattern: {
type: String,
reflectToAttribute: true,
},
inputmode: String,
label: {
type: String,
value: '',
},
placeholder: {
type: String,
value: null,
observer: 'placeholderChanged_',
},
readonly: {
type: Boolean,
reflectToAttribute: true,
},
required: {
type: Boolean,
reflectToAttribute: true,
},
inputTabindex: {
type: Number,
value: 0,
observer: 'onInputTabindexChanged_',
},
type: {
type: String,
value: 'text',
observer: 'onTypeChanged_',
},
value: {
type: String,
value: '',
notify: true,
observer: 'onValueChanged_',
},
};
}
ariaDescription: string|undefined;
autoFocus: boolean;
autoValidate: boolean;
disabled: boolean;
errorMessage: string;
inputmode: string;
inputTabindex: number;
invalid: boolean;
label: string;
max: number;
min: number;
maxlength: number;
minlength: number;
pattern: string;
placeholder: string|null;
readonly: boolean;
required: boolean;
type: string;
value: string;
private displayErrorMessage_: string;
private focused_: boolean;
override ready() {
super.ready();
// Use inputTabindex instead.
assert(!this.hasAttribute('tabindex'));
}
private onInputTabindexChanged_() {
// CrInput only supports 0 or -1 values for the input's tabindex to allow
// having the input in tab order or not. Values greater than 0 will not work
// as the shadow root encapsulates tabindices.
assert(this.inputTabindex === 0 || this.inputTabindex === -1);
}
private onTypeChanged_() {
// Check that the 'type' is one of the supported types.
assert(SUPPORTED_INPUT_TYPES.has(this.type));
}
get inputElement(): HTMLInputElement {
return this.$.input;
}
/**
* Returns the aria label to be used with the input element.
*/
private getAriaLabel_(ariaLabel: string, label: string, placeholder: string):
string {
return ariaLabel || label || placeholder;
}
/**
* Returns 'true' or 'false' as a string for the aria-invalid attribute.
*/
private getAriaInvalid_(invalid: boolean): string {
return invalid ? 'true' : 'false';
}
private onInvalidOrErrorMessageChanged_() {
this.displayErrorMessage_ = this.invalid ? this.errorMessage : '';
// On VoiceOver role="alert" is not consistently announced when its content
// changes. Adding and removing the |role| attribute every time there
// is an error, triggers VoiceOver to consistently announce.
const ERROR_ID = 'error';
const errorElement =
this.shadowRoot!.querySelector<HTMLElement>(`#${ERROR_ID}`);
assert(errorElement);
if (this.invalid) {
errorElement.setAttribute('role', 'alert');
this.inputElement.setAttribute('aria-errormessage', ERROR_ID);
} else {
errorElement.removeAttribute('role');
this.inputElement.removeAttribute('aria-errormessage');
}
}
/**
* This is necessary instead of doing <input placeholder="[[placeholder]]">
* because if this.placeholder is set to a truthy value then removed, it
* would show "null" as placeholder.
*/
private placeholderChanged_() {
if (this.placeholder || this.placeholder === '') {
this.inputElement.setAttribute('placeholder', this.placeholder);
} else {
this.inputElement.removeAttribute('placeholder');
}
}
override focus() {
this.focusInput();
}
/**
* Focuses the input element.
* TODO(crbug.com/882612): Replace this with focus() after resolving the text
* selection issue described in onFocus_().
* @return Whether the <input> element was focused.
*/
focusInput(): boolean {
if (this.shadowRoot!.activeElement === this.inputElement) {
return false;
}
this.inputElement.focus();
return true;
}
private onValueChanged_(newValue: string, oldValue: string) {
if (!newValue && !oldValue) {
return;
}
if (this.autoValidate) {
this.validate();
}
}
/**
* 'change' event fires when <input> value changes and user presses 'Enter'.
* This function helps propagate it to host since change events don't
* propagate across Shadow DOM boundary by default.
*/
private onInputChange_(e: Event) {
this.dispatchEvent(new CustomEvent(
'change', {bubbles: true, composed: true, detail: {sourceEvent: e}}));
}
private onInputFocus_() {
this.focused_ = true;
}
private onInputBlur_() {
this.focused_ = false;
}
/**
* Selects the text within the input. If no parameters are passed, it will
* select the entire string. Either no params or both params should be passed.
* Publicly, this function should be used instead of inputElement.select() or
* manipulating inputElement.selectionStart/selectionEnd because the order of
* execution between focus() and select() is sensitive.
*/
select(start?: number, end?: number) {
this.inputElement.focus();
if (start !== undefined && end !== undefined) {
this.inputElement.setSelectionRange(start, end);
} else {
// Can't just pass one param.
assert(start === undefined && end === undefined);
this.inputElement.select();
}
}
validate(): boolean {
this.invalid = !this.inputElement.checkValidity();
return !this.invalid;
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-input': CrInputElement;
}
}
customElements.define(CrInputElement.is, CrInputElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_input/cr_input.ts | TypeScript | unknown | 9,045 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Minimal externs file provided for places in the code that
* still use JavaScript instead of TypeScript.
* @externs
*/
/**
* @constructor
* @extends {HTMLElement}
*/
function CrInputElement() {}
/** @type {string} */
CrInputElement.prototype.ariaLabel;
/** @type {boolean} */
CrInputElement.prototype.invalid;
/** @type {number} */
CrInputElement.prototype.maxlength;
/** @type {string} */
CrInputElement.prototype.value;
/** @type {!HTMLInputElement} */
CrInputElement.prototype.inputElement;
CrInputElement.prototype.focusInput = function() {};
/**
* @param {number=} start
* @param {number=} end
*/
CrInputElement.prototype.select = function(start, end) {};
/** @return {boolean} */
CrInputElement.prototype.validate = function() {};
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_input/cr_input_externs.js | JavaScript | unknown | 901 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #import=../cr_shared_vars.css.js
* #css_wrapper_metadata_end */
:host {
--cr-input-background-color: var(--google-grey-100);
--cr-input-color: var(--cr-primary-text-color);
--cr-input-error-color: var(--google-red-600);
--cr-input-focus-color: var(--google-blue-600);
display: block;
/* Avoid showing outline when focus() programmatically called multiple
times in a row. */
outline: none;
}
@media (prefers-color-scheme: dark) {
:host {
--cr-input-background-color: rgba(0, 0, 0, .3);
--cr-input-error-color: var(--google-red-300);
--cr-input-focus-color: var(--google-blue-300);
}
}
:host([focused_]:not([readonly]):not([invalid])) #label {
color: var(--cr-input-focus-color);
}
/* Input styling below. */
#input-container {
border-radius: var(--cr-input-border-radius, 4px);
overflow: hidden;
position: relative;
width: var(--cr-input-width, 100%);
}
#inner-input-container {
background-color: var(--cr-input-background-color);
box-sizing: border-box;
padding: 0;
}
#input {
-webkit-appearance: none;
/* Transparent, #inner-input-container will apply background. */
background-color: transparent;
border: none;
box-sizing: border-box;
caret-color: var(--cr-input-focus-color);
color: var(--cr-input-color);
font-family: inherit;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
min-height: var(--cr-input-min-height, auto);
outline: none;
/**
* When using mixins, avoid using padding shorthand. Using both the
* shorthand and top/bottom/start/end can lead to style override issues.
* This is only noticable when the |optimize_webui=true| build argument
* is used.
*
* See https://crbug.com/846254 and associated CL for more information.
*/
padding-bottom: var(--cr-input-padding-bottom, 6px);
padding-inline-end: var(--cr-input-padding-end, 8px);
padding-inline-start: var(--cr-input-padding-start, 8px);
padding-top: var(--cr-input-padding-top, 6px);
text-align: inherit;
text-overflow: ellipsis;
width: 100%;
}
/* Underline styling below. */
#underline {
border-bottom: 2px solid var(--cr-input-focus-color);
border-radius: var(--cr-input-underline-border-radius, 0);
bottom: 0;
box-sizing: border-box;
display: var(--cr-input-underline-display);
height: var(--cr-input-underline-height, 0);
left: 0;
margin: auto;
opacity: 0;
position: absolute;
right: 0;
transition: opacity 120ms ease-out, width 0s linear 180ms;
width: 0;
}
:host([invalid]) #underline,
:host([force-underline]) #underline,
:host([focused_]) #underline {
opacity: 1;
transition: opacity 120ms ease-in, width 180ms ease-out;
width: 100%;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_input/cr_input_style.css | CSS | unknown | 3,391 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* cr-lazy-render is a simple variant of dom-if designed for lazy rendering
* of elements that are accessed imperatively.
* Usage:
* <cr-lazy-render id="menu">
* <template>
* <heavy-menu></heavy-menu>
* </template>
* </cr-lazy-render>
*
* this.$.menu.get().show();
*/
import {assert} from '//resources/js/assert_ts.js';
import {html, PolymerElement, TemplateInstanceBase, templatize} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
export class CrLazyRenderElement<T extends HTMLElement> extends PolymerElement {
static get is() {
return 'cr-lazy-render';
}
static get template() {
return html`<slot></slot>`;
}
private child_: T|null = null;
private instance_: TemplateInstanceBase|null = null;
/**
* Stamp the template into the DOM tree synchronously
* @return Child element which has been stamped into the DOM tree.
*/
override get(): T {
if (!this.child_) {
this.render_();
}
assert(this.child_);
return this.child_;
}
/**
* @return The element contained in the template, if it has
* already been stamped.
*/
getIfExists(): (T|null) {
return this.child_;
}
private render_() {
const template =
(this.shadowRoot!.querySelector('slot')!.assignedNodes({flatten: true})
.filter(n => n.nodeType === Node.ELEMENT_NODE)[0]) as
HTMLTemplateElement;
const TemplateClass = templatize(template, this, {
mutableData: false,
forwardHostProp: this._forwardHostPropV2,
});
const parentNode = this.parentNode;
if (parentNode && !this.child_) {
this.instance_ = new TemplateClass();
this.child_ = this.instance_.root.firstElementChild as T;
parentNode.insertBefore(this.instance_.root, this);
}
}
/* eslint-disable-next-line @typescript-eslint/naming-convention */
_forwardHostPropV2(prop: string, value: object) {
if (this.instance_) {
this.instance_.forwardHostProp(prop, value);
}
}
}
customElements.define(CrLazyRenderElement.is, CrLazyRenderElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_lazy_render/cr_lazy_render.ts | TypeScript | unknown | 2,249 |
<style include="cr-actionable-row-style cr-shared-style cr-hidden-style">
:host {
box-sizing: border-box;
flex: 1;
font-family: inherit;
font-size: 100%; /* Specifically for Mac OSX, harmless elsewhere. */
line-height: 154%; /* 20px. */
min-height: var(--cr-section-min-height);
padding: 0;
}
:host(:not([embedded])) {
padding: 0 var(--cr-section-padding);
}
#startIcon {
--iron-icon-fill-color: var(--cr-link-row-start-icon-color,
var(--google-grey-700));
display: flex;
flex-shrink: 0;
padding-inline-end: var(--cr-icon-button-margin-start);
width: var(--cr-link-row-icon-width, var(--cr-icon-size));
}
@media (prefers-color-scheme: dark) {
#startIcon {
--iron-icon-fill-color: var(--cr-link-row-start-icon-color,
var(--google-grey-500));
}
}
#labelWrapper {
flex: 1;
flex-basis: 0.000000001px;
padding-bottom: var(--cr-section-vertical-padding);
padding-top: var(--cr-section-vertical-padding);
text-align: start;
}
#label,
#subLabel {
display: flex;
}
#buttonAriaDescription {
clip: rect(0,0,0,0);
display: block;
position: fixed;
}
</style>
<iron-icon id="startIcon" icon="[[startIcon]]" hidden="[[!startIcon]]"
aria-hidden="true">
</iron-icon>
<div id="labelWrapper" hidden="[[hideLabelWrapper_]]">
<div id="label" aria-hidden="[[!ariaShowLabel]]">
[[label]]
<slot name="label"></slot>
</div>
<div id="subLabel" class="cr-secondary-text"
aria-hidden="[[!ariaShowSublabel]]">
[[subLabel]]
<slot name="sub-label"></slot>
</div>
</div>
<slot></slot>
<div id="buttonAriaDescription" aria-hidden="true">
[[computeButtonAriaDescription_(external, buttonAriaDescription)]]
</div>
<cr-icon-button id="icon" iron-icon="[[getIcon_(external)]]" role="link"
part="icon" aria-roledescription$="[[roleDescription]]"
aria-describedby="buttonAriaDescription"
aria-labelledby="label subLabel" disabled="[[disabled]]">
</cr-icon-button>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_link_row/cr_link_row.html | HTML | unknown | 2,031 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* A link row is a UI element similar to a button, though usually wider than a
* button (taking up the whole 'row'). The name link comes from the intended use
* of this element to take the user to another page in the app or to an external
* page (somewhat like an HTML link).
*/
import '../cr_actionable_row_style.css.js';
import '../cr_icon_button/cr_icon_button.js';
import '../cr_hidden_style.css.js';
import '../icons.html.js';
import '../cr_shared_style.css.js';
import '../cr_shared_vars.css.js';
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import {loadTimeData} from '//resources/js/load_time_data.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CrIconButtonElement} from '../cr_icon_button/cr_icon_button.js';
import {getTemplate} from './cr_link_row.html.js';
export interface CrLinkRowElement {
$: {
icon: CrIconButtonElement,
buttonAriaDescription: HTMLElement,
};
}
export class CrLinkRowElement extends PolymerElement {
static get is() {
return 'cr-link-row';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
ariaShowLabel: {
type: Boolean,
reflectToAttribute: true,
value: false,
},
ariaShowSublabel: {
type: Boolean,
reflectToAttribute: true,
value: false,
},
startIcon: {
type: String,
value: '',
},
label: {
type: String,
value: '',
},
subLabel: {
type: String,
/* Value used for noSubLabel attribute. */
value: '',
},
disabled: {
type: Boolean,
reflectToAttribute: true,
},
external: {
type: Boolean,
value: false,
},
usingSlottedLabel: {
type: Boolean,
value: false,
},
roleDescription: String,
buttonAriaDescription: String,
hideLabelWrapper_: {
type: Boolean,
computed: 'computeHideLabelWrapper_(label, usingSlottedLabel)',
},
};
}
ariaShowLabel: boolean;
ariaShowSublabel: boolean;
startIcon: string;
label: string;
subLabel: string;
disabled: boolean;
external: boolean;
usingSlottedLabel: boolean;
roleDescription: string;
buttonAriaDescription: string;
private hideLabelWrapper_: boolean;
override focus() {
this.$.icon.focus();
}
private computeHideLabelWrapper_(): boolean {
return !(this.label || this.usingSlottedLabel);
}
private getIcon_(): string {
return this.external ? 'cr:open-in-new' : 'cr:arrow-right';
}
private computeButtonAriaDescription_(
external: boolean, buttonAriaDescription?: string): string {
return buttonAriaDescription ??
(external ? loadTimeData.getString('opensInNewTab') : '');
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-link-row': CrLinkRowElement;
}
}
customElements.define(CrLinkRowElement.is, CrLinkRowElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_link_row/cr_link_row.ts | TypeScript | unknown | 3,188 |
<style>
canvas {
height: 100%;
width: 100%;
}
</style>
<canvas id="canvas" hidden="[[hidden]]"></canvas>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_lottie/cr_lottie.html | HTML | unknown | 145 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'cr-lottie' is a wrapper around the player for lottie
* animations. Since the player runs on a worker thread, 'cr-lottie' requires
* the document CSP to be set to "worker-src blob: chrome://resources 'self';".
*
* For documents that have TrustedTypes CSP checks enabled, it also requires the
* document CSP to be set to "trusted-types lottie-worker-script-loader;".
*
* Fires a 'cr-lottie-initialized' event when the animation was successfully
* initialized.
* Fires a 'cr-lottie-playing' event when the animation starts playing.
* Fires a 'cr-lottie-paused' event when the animation has paused.
* Fires a 'cr-lottie-stopped' event when animation has stopped.
* Fires a 'cr-lottie-resized' event when the canvas the animation is being
* drawn on is resized.
*/
import {assert, assertNotReached} from '//resources/js/assert_ts.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_lottie.html.js';
let workerLoaderPolicy: TrustedTypePolicy|null = null;
function getLottieWorkerURL(): TrustedScriptURL {
if (workerLoaderPolicy === null) {
workerLoaderPolicy =
window.trustedTypes!.createPolicy('lottie-worker-script-loader', {
createScriptURL: (_ignore: string) => {
const script =
`import 'chrome://resources/lottie/lottie_worker.min.js';`;
// CORS blocks loading worker script from a different origin, even
// if chrome://resources/ is added in the 'worker-src' CSP header.
// (see https://crbug.com/1385477). Loading scripts as blob and then
// instantiating it as web worker is possible.
const blob = new Blob([script], {type: 'text/javascript'});
return URL.createObjectURL(blob);
},
createHTML: () => assertNotReached(),
createScript: () => assertNotReached(),
});
}
return workerLoaderPolicy.createScriptURL('');
}
interface MessageData {
animationData: object|null|string;
drawSize: {width: number, height: number};
params: {loop: boolean, autoplay: boolean};
canvas?: OffscreenCanvas;
}
interface CanvasElementWithOffscreen extends HTMLCanvasElement {
transferControlToOffscreen: () => OffscreenCanvas;
}
export interface CrLottieElement {
$: {
canvas: CanvasElementWithOffscreen,
};
}
export class CrLottieElement extends PolymerElement {
static get is() {
return 'cr-lottie';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
animationUrl: {
type: String,
value: '',
observer: 'animationUrlChanged_',
},
autoplay: {
type: Boolean,
value: false,
},
hidden: {
type: Boolean,
value: false,
},
singleLoop: {
type: Boolean,
value: false,
},
};
}
animationUrl: string;
autoplay: boolean;
override hidden: boolean;
singleLoop: boolean;
private canvasElement_: CanvasElementWithOffscreen|null = null;
private isAnimationLoaded_: boolean = false;
private offscreenCanvas_: OffscreenCanvas|null = null;
/** Whether the canvas has been transferred to the worker thread. */
private hasTransferredCanvas_: boolean = false;
private resizeObserver_: ResizeObserver|null = null;
/**
* The last state that was explicitly set via setPlay.
* In case setPlay() is invoked before the animation is initialized, the
* state is stored in this variable. Once the animation initializes, the
* state is sent to the worker.
*/
private playState_: boolean = false;
/**
* Whether the Worker needs to receive new size
* information about the canvas. This is necessary for the corner case
* when the size information is received when the animation is still being
* loaded into the worker.
*/
private workerNeedsSizeUpdate_: boolean = false;
/**
* Whether the Worker needs to receive new control
* information about its desired state. This is necessary for the corner
* case when the control information is received when the animation is still
* being loaded into the worker.
*/
private workerNeedsPlayControlUpdate_: boolean = false;
private worker_: Worker|null = null;
/** The current in-flight request. */
private xhr_: XMLHttpRequest|null = null;
override connectedCallback() {
super.connectedCallback();
this.worker_ =
new Worker(getLottieWorkerURL() as unknown as URL, {type: 'module'});
this.worker_.onmessage = this.onMessage_.bind(this);
this.initialize_();
}
override disconnectedCallback() {
super.disconnectedCallback();
if (this.resizeObserver_) {
this.resizeObserver_.disconnect();
}
if (this.worker_) {
this.worker_.terminate();
this.worker_ = null;
}
if (this.xhr_) {
this.xhr_.abort();
this.xhr_ = null;
}
}
/**
* Controls the animation based on the value of |shouldPlay|. If the
* animation is being loaded into the worker when this method is invoked,
* the action will be postponed to when the animation is fully loaded.
* @param shouldPlay True for play, false for pause.
*/
setPlay(shouldPlay: boolean) {
this.playState_ = shouldPlay;
if (this.isAnimationLoaded_) {
this.sendPlayControlInformationToWorker_();
} else {
this.workerNeedsPlayControlUpdate_ = true;
}
}
/**
* Sends control (play/pause) information to the worker.
*/
private sendPlayControlInformationToWorker_() {
assert(this.worker_);
this.worker_.postMessage({control: {play: this.playState_}});
}
/**
* Initializes all the members of this polymer element.
*/
private initialize_() {
// Generate an offscreen canvas.
this.canvasElement_ = this.$.canvas;
this.offscreenCanvas_ = this.canvasElement_.transferControlToOffscreen();
this.resizeObserver_ =
new ResizeObserver(this.onCanvasElementResized_.bind(this));
this.resizeObserver_.observe(this.canvasElement_);
if (this.isAnimationLoaded_) {
return;
}
// Open animation file and start playing the animation.
this.sendXmlHttpRequest_(
this.animationUrl, 'json', this.initAnimation_.bind(this));
}
/**
* Updates the animation that is being displayed.
*/
private animationUrlChanged_() {
if (!this.worker_) {
// The worker hasn't loaded yet. We will load the new animation once the
// worker loads.
return;
}
if (this.xhr_) {
// There is an in-flight request to load the previous animation. Abort it
// before loading a new image.
this.xhr_.abort();
this.xhr_ = null;
}
if (this.isAnimationLoaded_) {
this.worker_.postMessage({control: {stop: true}});
this.isAnimationLoaded_ = false;
}
this.sendXmlHttpRequest_(
this.animationUrl, 'json', this.initAnimation_.bind(this));
}
/**
* Computes the draw buffer size for the canvas. This ensures that the
* rasterization is crisp and sharp rather than blurry.
* @return Size of the canvas draw buffer
*/
private getCanvasDrawBufferSize_(): {width: number, height: number} {
const canvasElement = this.$.canvas;
const devicePixelRatio = window.devicePixelRatio;
const clientRect = canvasElement.getBoundingClientRect();
const drawSize = {
width: clientRect.width * devicePixelRatio,
height: clientRect.height * devicePixelRatio,
};
return drawSize;
}
/**
* Returns true if the |maybeValidUrl| provided is safe to use in an
* XMLHTTPRequest.
* @param maybeValidUrl The url string to check for validity.
*/
private isValidUrl_(maybeValidUrl: string): boolean {
const url = new URL(maybeValidUrl, document.location.href);
return url.protocol === 'chrome:' ||
(url.protocol === 'data:' &&
url.pathname.startsWith('application/json;'));
}
/**
* Sends an XMLHTTPRequest to load a resource and runs the callback on
* getting a successful response.
* @param url The URL to load the resource.
* @param responseType The type of response the request would
* give on success.
* @param successCallback The callback to run
* when a successful response is received.
*/
private sendXmlHttpRequest_(
url: string, responseType: XMLHttpRequestResponseType,
successCallback: (p: object|null|Blob|MediaSource) => void) {
assert(this.isValidUrl_(url), 'Invalid scheme or data url used.');
assert(!this.xhr_);
this.xhr_ = new XMLHttpRequest();
this.xhr_!.open('GET', url, true);
this.xhr_!.responseType = responseType;
this.xhr_!.send();
this.xhr_!.onreadystatechange = () => {
assert(this.xhr_);
if (this.xhr_.readyState === 4 && this.xhr_.status === 200) {
// |successCallback| might trigger another xhr, so we set to null before
// calling it.
const response = this.xhr_.response;
this.xhr_ = null;
successCallback(response);
}
};
}
/**
* Handles the canvas element resize event. If the animation isn't fully
* loaded, the canvas size is sent later, once the loading is done.
*/
private onCanvasElementResized_() {
if (this.isAnimationLoaded_) {
this.sendCanvasSizeToWorker_();
} else {
// Mark a size update as necessary once the animation is loaded.
this.workerNeedsSizeUpdate_ = true;
}
}
/**
* This informs the offscreen canvas worker of the current canvas size.
*/
private sendCanvasSizeToWorker_() {
assert(this.worker_);
this.worker_.postMessage({drawSize: this.getCanvasDrawBufferSize_()});
}
/**
* Initializes the the animation on the web worker with the data provided.
* @param animationData The animation that will be played.
*/
private initAnimation_(animationData: object|null|string) {
const message: MessageData = {
animationData,
drawSize: this.getCanvasDrawBufferSize_(),
params: {loop: !this.singleLoop, autoplay: this.autoplay},
};
assert(this.worker_);
if (!this.hasTransferredCanvas_) {
message.canvas = this.offscreenCanvas_!;
this.hasTransferredCanvas_ = true;
this.worker_.postMessage(
message, [this.offscreenCanvas_! as unknown as Transferable]);
} else {
this.worker_.postMessage(message);
}
}
private fire_(eventName: string, eventData?: number) {
this.dispatchEvent(new CustomEvent(
eventName, {bubbles: true, composed: true, detail: eventData}));
}
/**
* Handles the messages sent from the web worker to its parent thread.
* @param event Event sent by the web worker.
*/
private onMessage_(event: MessageEvent) {
if (event.data.name === 'initialized' && event.data.success) {
this.isAnimationLoaded_ = true;
this.sendPendingInfo_();
this.fire_('cr-lottie-initialized');
} else if (event.data.name === 'playing') {
this.fire_('cr-lottie-playing');
} else if (event.data.name === 'paused') {
this.fire_('cr-lottie-paused');
} else if (event.data.name === 'stopped') {
this.fire_('cr-lottie-stopped');
} else if (event.data.name === 'resized') {
this.fire_('cr-lottie-resized', event.data.size);
}
}
/**
* Called once the animation is fully loaded into the worker. Sends any
* size or control information that may have arrived while the animation
* was not yet fully loaded.
*/
private sendPendingInfo_() {
if (this.workerNeedsSizeUpdate_) {
this.workerNeedsSizeUpdate_ = false;
this.sendCanvasSizeToWorker_();
}
if (this.workerNeedsPlayControlUpdate_) {
this.workerNeedsPlayControlUpdate_ = false;
this.sendPlayControlInformationToWorker_();
}
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-lottie': CrLottieElement;
}
}
customElements.define(CrLottieElement.is, CrLottieElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_lottie/cr_lottie.ts | TypeScript | unknown | 12,188 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Minimal externs file provided for places in the code that
* still use JavaScript instead of TypeScript.
* @externs
*/
/**
* @constructor
* @extends {HTMLElement}
*/
function CrLottieElement() {}
/** @param {boolean} shouldPlay */
CrLottieElement.prototype.setPlay = function(shouldPlay) {};
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_lottie/cr_lottie_externs.js | JavaScript | unknown | 446 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert} from '//resources/js/assert_ts.js';
import {FocusOutlineManager} from '//resources/js/focus_outline_manager.js';
import {IronSelectableBehavior} from '//resources/polymer/v3_0/iron-selector/iron-selectable.js';
import {mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
const CrMenuSelectorBase =
mixinBehaviors([IronSelectableBehavior], PolymerElement) as
{new (): PolymerElement & IronSelectableBehavior};
export class CrMenuSelector extends CrMenuSelectorBase {
static get is() {
return 'cr-menu-selector';
}
private focusOutlineManager_: FocusOutlineManager;
override connectedCallback() {
super.connectedCallback();
this.focusOutlineManager_ = FocusOutlineManager.forDocument(document);
}
override ready() {
super.ready();
this.setAttribute('role', 'menu');
this.addEventListener('focusin', this.onFocusin_.bind(this));
this.addEventListener('keydown', this.onKeydown_.bind(this));
this.addEventListener(
'iron-deselect',
e => this.onIronDeselected_(e as CustomEvent<{item: HTMLElement}>));
this.addEventListener(
'iron-select',
e => this.onIronSelected_(e as CustomEvent<{item: HTMLElement}>));
}
private getAllFocusableItems_(): HTMLElement[] {
// Note that this is different from IronSelectableBehavior's items property
// as some items are focusable and actionable but not selectable (eg. an
// external link).
return Array.from(
this.querySelectorAll('[role=menuitem]:not([disabled]):not([hidden])'));
}
private onFocusin_(e: FocusEvent) {
// If the focus was moved by keyboard and is coming in from a relatedTarget
// that is not within this menu, move the focus to the first menu item. This
// ensures that the first menu item is always the first focused item when
// focusing into the menu. A null relatedTarget means the focus was moved
// from outside the WebContents.
const focusMovedWithKeyboard = this.focusOutlineManager_.visible;
const focusMovedFromOutside = e.relatedTarget === null ||
!this.contains(e.relatedTarget as HTMLElement);
if (focusMovedWithKeyboard && focusMovedFromOutside) {
this.getAllFocusableItems_()[0]!.focus();
}
}
private onIronDeselected_(e: CustomEvent<{item: HTMLElement}>) {
e.detail.item.removeAttribute('aria-current');
}
private onIronSelected_(e: CustomEvent<{item: HTMLElement}>) {
e.detail.item.setAttribute('aria-current', 'page');
}
private onKeydown_(event: KeyboardEvent) {
const items = this.getAllFocusableItems_();
assert(items.length >= 1);
const currentFocusedIndex =
items.indexOf(this.querySelector<HTMLElement>(':focus')!);
let newFocusedIndex = currentFocusedIndex;
switch (event.key) {
case 'Tab':
if (event.shiftKey) {
// If pressing Shift+Tab, immediately focus the first element so that
// when the event is finished processing, the browser automatically
// focuses the previous focusable element outside of the menu.
items[0]!.focus();
} else {
// If pressing Tab, immediately focus the last element so that when
// the event is finished processing, the browser automatically focuses
// the next focusable element outside of the menu.
items[items.length - 1]!.focus({preventScroll: true});
}
return;
case 'ArrowDown':
newFocusedIndex = (currentFocusedIndex + 1) % items.length;
break;
case 'ArrowUp':
newFocusedIndex =
(currentFocusedIndex + items.length - 1) % items.length;
break;
case 'Home':
newFocusedIndex = 0;
break;
case 'End':
newFocusedIndex = items.length - 1;
break;
}
if (newFocusedIndex === currentFocusedIndex) {
return;
}
event.preventDefault();
items[newFocusedIndex]!.focus();
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-menu-selector': CrMenuSelector;
}
}
customElements.define(CrMenuSelector.is, CrMenuSelector);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_menu_selector/cr_menu_selector.ts | TypeScript | unknown | 4,311 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #import=./cr_shared_vars.css.js
* #css_wrapper_metadata_end */
.cr-nav-menu-item {
--iron-icon-fill-color: var(--google-grey-700);
/* Sizes icons for iron-icons. */
--iron-icon-height: 20px;
--iron-icon-width: 20px;
/* Sizes icons for cr-icons. */
--cr-icon-ripple-size: 20px;
align-items: center;
border-end-end-radius: 100px;
border-start-end-radius: 100px;
box-sizing: border-box;
color: var(--google-grey-900);
display: flex;
font-size: 14px;
font-weight: 500;
line-height: 14px;
margin-inline-end: 2px;
margin-inline-start: 1px;
min-height: 40px;
overflow: hidden;
padding-block-end: 10px;
padding-block-start: 10px;
padding-inline-start: 23px;
position: relative;
text-decoration: none;
}
:host-context(cr-drawer) .cr-nav-menu-item {
margin-inline-end: 8px;
}
.cr-nav-menu-item:hover {
background: var(--google-grey-200);
}
.cr-nav-menu-item[selected] {
--iron-icon-fill-color: var(--google-blue-600);
background: var(--google-blue-50);
color: var(--google-blue-700);
}
@media (prefers-color-scheme: dark) {
.cr-nav-menu-item {
--iron-icon-fill-color: var(--google-grey-500);
color: white;
}
.cr-nav-menu-item:hover {
--iron-icon-fill-color: white;
background: var(--google-grey-800);
}
.cr-nav-menu-item[selected] {
--iron-icon-fill-color: black;
background: var(--google-blue-300);
color: var(--google-grey-900);
}
}
.cr-nav-menu-item:focus {
outline: auto 5px -webkit-focus-ring-color;
/**
* A non-zero z-index to force the outline to appear above the fill
* background of selected item.
*/
z-index: 1;
}
.cr-nav-menu-item:focus:not([selected]):not(:hover) {
background: transparent; /* Override iron-list selectable item CSS. */
}
.cr-nav-menu-item iron-icon {
margin-inline-end: 20px;
pointer-events: none;
vertical-align: top;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_nav_menu_item_style.css | CSS | unknown | 2,069 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #import=./cr_shared_vars.css.js
* #css_wrapper_metadata_end */
/* Common CSS properties for WebUI pages, such as an entire page or a standalone
* dialog. The CSS here is in its own file so that the properties can be
* imported independently and applied directly to the :host element without
* having to import other shared CSS. */
:host {
color: var(--cr-primary-text-color);
line-height: 154%; /* Apply 20px default line-height to all text. */
overflow: hidden; /* Prevent double scroll bar bugs. */
user-select: text;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_page_host_style.css | CSS | unknown | 732 |
<style include="cr-shared-style">
:host {
--avatar-size: 96px;
--avatar-spacing: 24px;
/* Size of the outline for the selected avatar. This variable can be
* modified when using the component with different sizes.
*/
--selected-border: 4px;
display: inline-flex;
}
#avatar-grid .avatar-container {
height: var(--avatar-size);
margin: calc(var(--avatar-spacing) / 2);
position: relative;
width: var(--avatar-size);
}
#avatar-grid .avatar {
--avatar-focus-color: var(--google-grey-700);
--avatar-gap-color: white;
--avatar-gap-width: 2px;
--avatar-selected-color: rgba(var(--google-blue-600-rgb), 0.4);
background-position: center;
background-repeat: no-repeat;
border: 1px solid var(--paper-grey-300);
border-radius: 100%;
display: flex;
height: var(--avatar-size);
min-width: 0;
padding: 0;
transition: none !important; /* Polymer's :host([animated]) rule. */
width: var(--avatar-size);
}
#avatar-grid .iron-selected .avatar {
--avatar-outline-color: var(--avatar-selected-color);
--avatar-outline-width: var(--selected-border);
outline: var(--avatar-outline-width) solid var(--avatar-outline-color);
}
.checkmark {
--checkmark-size: 21px;
--iron-icon-fill-color: white;
background-color: var(--google-blue-600);
border-radius: 100%;
height: var(--checkmark-size);
inset-inline-end: 0;
padding: 1px;
position: absolute;
top: 0;
visibility: hidden;
width: var(--checkmark-size);
}
.iron-selected .checkmark {
visibility: visible;
}
@media (prefers-color-scheme: dark) {
#avatar-grid .avatar {
--avatar-focus-color: var(--google-grey-500);
--avatar-gap-color: var(--google-grey-800);
}
.checkmark {
--iron-icon-fill-color: var(--google-grey-900);
background-color: var(--google-blue-300);
}
}
:host-context(.focus-outline-visible) #avatar-grid
.avatar-container:not(.iron-selected) .avatar:focus {
--avatar-outline-color: var(--avatar-focus-color);
--avatar-outline-width: 1px;
}
cr-button {
background-size: var(--avatar-size);
}
paper-tooltip {
--paper-tooltip-delay-in: 100ms;
--paper-tooltip-duration-in: 100ms;
--paper-tooltip-duration-out: 100ms;
--paper-tooltip-min-width: none;
}
</style>
<cr-profile-avatar-selector-grid id="avatar-grid" role="radiogroup"
ignore-modified-key-events="[[ignoreModifiedKeyEvents]]">
<template is="dom-repeat" items="[[avatars]]">
<div class$=
"avatar-container [[getSelectedClass_(item, selectedAvatar)]]">
<cr-button id="[[getAvatarId_(index)]]" aria-label="[[item.label]]"
tabindex$="[[getTabIndex_(index, item, tabFocusableAvatar_)]]"
class="avatar" on-click="onAvatarTap_" role="radio"
style$="background-image: [[getIconImageSet_(item.url)]]"
aria-checked$="[[getCheckedAttribute_(item, selectedAvatar)]]">
</cr-button>
<iron-icon icon="cr:check" class="checkmark"></iron-icon>
</div>
<paper-tooltip for="[[getAvatarId_(index)]]"
offset="0" fit-to-visible-bounds>
[[item.label]]
</paper-tooltip>
</template>
</cr-profile-avatar-selector-grid>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector.html | HTML | unknown | 3,666 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'cr-profile-avatar-selector' is an element that displays
* profile avatar icons and allows an avatar to be selected.
*/
import '../cr_button/cr_button.js';
import '../cr_shared_vars.css.js';
import '../cr_shared_style.css.js';
import '//resources/polymer/v3_0/paper-styles/color.js';
import '//resources/polymer/v3_0/paper-tooltip/paper-tooltip.js';
import './cr_profile_avatar_selector_grid.js';
import {assert} from '//resources/js/assert_ts.js';
import {getImage} from '//resources/js/icon.js';
import {DomRepeatEvent, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_profile_avatar_selector.html.js';
export interface AvatarIcon {
url: string;
label: string;
index: number;
isGaiaAvatar: boolean;
selected: boolean;
}
export class CrProfileAvatarSelectorElement extends PolymerElement {
static get is() {
return 'cr-profile-avatar-selector';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* The list of profile avatar URLs and labels.
*/
avatars: {
type: Array,
value() {
return [];
},
},
/**
* The currently selected profile avatar icon, if any.
*/
selectedAvatar: {
type: Object,
notify: true,
},
ignoreModifiedKeyEvents: {
type: Boolean,
value: false,
},
/**
* The currently selected profile avatar icon index, or '-1' if none is
* selected.
*/
tabFocusableAvatar_: {
type: Number,
computed: 'computeTabFocusableAvatar_(avatars, selectedAvatar)',
},
};
}
avatars: AvatarIcon[];
selectedAvatar: AvatarIcon|null;
ignoreModifiedKeyEvents: boolean;
private tabFocusableAvatar_: number;
private getAvatarId_(index: number): string {
return 'avatarId' + index;
}
private getTabIndex_(index: number, item: AvatarIcon): string {
if (item.index === this.tabFocusableAvatar_) {
return '0';
}
// If no avatar is selected, focus the first element of the grid on 'tab'.
if (this.tabFocusableAvatar_ === -1 && index === 0) {
return '0';
}
return '-1';
}
private computeTabFocusableAvatar_(): number {
const selectedAvatar =
this.avatars.find(avatar => this.isAvatarSelected(avatar));
return selectedAvatar ? selectedAvatar.index : -1;
}
private getSelectedClass_(avatarItem: AvatarIcon): string {
// TODO(dpapad): Rename 'iron-selected' to 'selected' now that this CSS
// class is not assigned by any iron-* behavior.
return this.isAvatarSelected(avatarItem) ? 'iron-selected' : '';
}
private getCheckedAttribute_(avatarItem: AvatarIcon): string {
return this.isAvatarSelected(avatarItem) ? 'true' : 'false';
}
private isAvatarSelected(avatarItem: AvatarIcon): boolean {
return !!avatarItem &&
(avatarItem.selected ||
(!!this.selectedAvatar &&
this.selectedAvatar.index === avatarItem.index));
}
/**
* @return A CSS image-set for multiple scale factors.
*/
private getIconImageSet_(iconUrl: string): string {
return getImage(iconUrl);
}
private onAvatarTap_(e: DomRepeatEvent<AvatarIcon>) {
// |selectedAvatar| is set to pass back selection to the owner of this
// component.
this.selectedAvatar = e.model.item;
// Autoscroll to selected avatar if it is not completely visible.
const avatarList =
this.shadowRoot!.querySelectorAll<HTMLElement>('.avatar-container');
assert(avatarList.length > 0);
const selectedAvatarElement = avatarList[e.model.index];
assert(selectedAvatarElement!.classList.contains('iron-selected'));
selectedAvatarElement!.scrollIntoViewIfNeeded();
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-profile-avatar-selector': CrProfileAvatarSelectorElement;
}
}
customElements.define(
CrProfileAvatarSelectorElement.is, CrProfileAvatarSelectorElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector.ts | TypeScript | unknown | 4,217 |
<style>
:host {
display: inline-flex;
flex-wrap: wrap;
margin: calc(var(--avatar-spacing) / -2);
}
</style>
<slot></slot>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector_grid.html | HTML | unknown | 170 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'cr-profile-avatar-selector-grid' is an accessible control for
* profile avatar icons that allows keyboard navigation with all arrow keys.
*/
import {assert} from '//resources/js/assert_ts.js';
import {hasKeyModifiers} from '//resources/js/util_ts.js';
import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_profile_avatar_selector_grid.html.js';
export class CrProfileAvatarSelectorGridElement extends PolymerElement {
static get is() {
return 'cr-profile-avatar-selector-grid';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
ignoreModifiedKeyEvents: {
type: Boolean,
value: false,
},
};
}
ignoreModifiedKeyEvents: boolean;
override ready() {
super.ready();
this.addEventListener('keydown', this.onKeyDown_.bind(this));
}
private onKeyDown_(e: KeyboardEvent) {
const items = this.querySelectorAll<HTMLElement>('.avatar');
switch (e.key) {
case 'ArrowDown':
case 'ArrowUp':
this.moveFocusRow_(items, e.key);
e.preventDefault();
return;
case 'ArrowLeft':
case 'ArrowRight':
// Ignores keys likely to be browse shortcuts (like Alt+Left for back).
if (this.ignoreModifiedKeyEvents && hasKeyModifiers(e)) {
return;
}
this.moveFocusRow_(items, e.key);
e.preventDefault();
return;
}
}
/**
* Moves focus up/down/left/right according to the given direction. Wraps
* around as necessary.
*/
private moveFocusRow_(
items: NodeListOf<HTMLElement>,
direction: 'ArrowDown'|'ArrowRight'|'ArrowUp'|'ArrowLeft') {
let offset =
(direction === 'ArrowDown' || direction === 'ArrowRight') ? 1 : -1;
const style = getComputedStyle(this);
const avatarSpacing =
parseInt(style.getPropertyValue('--avatar-spacing'), 10);
const avatarSize = parseInt(style.getPropertyValue('--avatar-size'), 10);
const rowSize = Math.floor(this.clientWidth / (avatarSpacing + avatarSize));
const rows = Math.ceil(items.length / rowSize);
const gridSize = rows * rowSize;
const focusIndex = Array.prototype.slice.call(items).findIndex(item => {
return (this.parentNode as ShadowRoot).activeElement === item;
});
let nextItem = null;
if (direction === 'ArrowDown' || direction === 'ArrowUp') {
for (let i = offset; Math.abs(i) <= rows; i += offset) {
nextItem = items[(focusIndex + i * rowSize + gridSize) % gridSize];
if (nextItem) {
break;
}
// This codepath can be hit when |gridSize| is larger than
// |items.length|, which means that there are empty grid spots at the
// end.
}
} else {
if (style.direction === 'rtl') {
offset *= -1;
}
let nextIndex = (focusIndex + offset) % items.length;
if (nextIndex < 0) {
nextIndex = items.length - 1;
}
nextItem = items[nextIndex];
}
nextItem!.focus();
assert((this.parentNode as ShadowRoot).activeElement === nextItem);
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-profile-avatar-selector-grid': CrProfileAvatarSelectorGridElement;
}
}
customElements.define(
CrProfileAvatarSelectorGridElement.is, CrProfileAvatarSelectorGridElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector_grid.ts | TypeScript | unknown | 3,571 |
<style include="cr-radio-button-style">
:host {
background-color: var(--cr-card-background-color);
border-radius: 8px;
box-shadow: var(--cr-elevation-1);
margin: var(--cr-card-radio-button-margin, 8px);
width: var(--cr-card-radio-button-width, 200px);
--focus-shadow-color: rgba(var(--google-blue-600-rgb), .4);
--hover-bg-color: rgba(var(--google-blue-500-rgb), .04);
}
@media (prefers-color-scheme: dark) {
:host {
--focus-shadow-color: rgba(var(--google-blue-300-rgb), .5);
--hover-bg-color: rgba(var(--google-blue-300-rgb), .08);
}
}
/* Overwrite paper-ripple defined in cr-radio-button-style
* to ensure it extends to the entire button. */
.disc-wrapper,
paper-ripple {
border-radius: inherit; /* Defined in :host above. */
}
paper-ripple {
height: var(--paper-ripple-height);
/* Fallback to 0 to match the values in paper-ripple.html. Falls back
* to auto without this. */
left: var(--paper-ripple-left, 0);
top: var(--paper-ripple-top, 0);
width: var(--paper-ripple-width);
}
#button {
height: var(--cr-card-radio-button-height, auto);
padding: var(--cr-card-radio-button-padding, 24px);
position: relative;
width: 100%;
}
:host-context(.focus-outline-visible) #button:focus {
box-shadow: 0 0 0 2px var(--focus-shadow-color);
}
#button:hover {
background-color: var(--hover-bg-color);
}
#checkMark {
fill: var(--cr-checked-color);
left: var(--cr-card-radio-button-checkmark-left, auto);
position: absolute;
right: var(--cr-card-radio-button-checkmark-right, var(--cr-button-edge-spacing));
top: var(--cr-card-radio-button-checkmark-top, var(--cr-button-edge-spacing));
}
:host-context([dir=rtl]) #checkMark {
left: var(--cr-card-radio-button-checkmark-right,
var(--cr-button-edge-spacing));
right: var(--cr-card-radio-button-checkmark-left, auto);
}
:host(:not([checked])) #checkMark {
display: none;
}
#slottedContent {
padding: var(--cr-card-radio-button-slotted-content-padding);
}
</style>
<div id="button" role="radio"
aria-checked$="[[getAriaChecked_(checked)]]"
aria-describedby="slotted-content"
aria-disabled$="[[getAriaDisabled_(disabled)]]"
class="disc-wrapper"
tabindex$="[[buttonTabIndex_]]"
aria-labelledby="slotted-content"
on-keydown="onInputKeydown_">
<iron-icon id="checkMark" icon="cr:check-circle"></iron-icon>
<span id="slottedContent">
<slot></slot>
</span>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_radio_button/cr_card_radio_button.html | HTML | unknown | 2,840 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* 'cr-card-radio-button' is a radio button in the style of a card. A checkmark
* is displayed in the upper right hand corner if the radio button is selected.
*/
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import './cr_radio_button_style.css.js';
import '../cr_shared_vars.css.js';
import '../icons.html.js';
import {PaperRippleBehavior} from '//resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js';
import {mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_card_radio_button.html.js';
import {CrRadioButtonMixin, CrRadioButtonMixinInterface} from './cr_radio_button_mixin.js';
const CrCardRadioButtonElementBase =
mixinBehaviors([PaperRippleBehavior], CrRadioButtonMixin(PolymerElement)) as
{
new (): PolymerElement & CrRadioButtonMixinInterface &
PaperRippleBehavior,
};
export interface CrCardRadioButtonElement {
$: {
button: HTMLElement,
};
}
export class CrCardRadioButtonElement extends CrCardRadioButtonElementBase {
static get is() {
return 'cr-card-radio-button';
}
static get template() {
return getTemplate();
}
// Overridden from CrRadioButtonMixin
override getPaperRipple() {
return this.getRipple();
}
// Overridden from PaperRippleBehavior
/* eslint-disable-next-line @typescript-eslint/naming-convention */
override _createRipple() {
this._rippleContainer = this.shadowRoot!.querySelector('.disc-wrapper');
const ripple = super._createRipple();
ripple.id = 'ink';
ripple.setAttribute('recenters', '');
ripple.classList.add('circle', 'toggle-ink');
return ripple;
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-card-radio-button': CrCardRadioButtonElement;
}
}
customElements.define(CrCardRadioButtonElement.is, CrCardRadioButtonElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_radio_button/cr_card_radio_button.ts | TypeScript | unknown | 2,050 |
<style include="cr-radio-button-style cr-hidden-style"></style>
<div aria-checked$="[[getAriaChecked_(checked)]]"
aria-describedby="slotted-content"
aria-disabled$="[[getAriaDisabled_(disabled)]]"
aria-labelledby="label"
class="disc-wrapper"
id="button"
role="radio"
tabindex$="[[buttonTabIndex_]]"
on-keydown="onInputKeydown_">
<div class="disc-border"></div>
<div class="disc"></div>
<div id="overlay"></div>
</div>
<div id="labelWrapper">
<span id="label" hidden$="[[!label]]" aria-hidden="true">[[label]]</span>
<span id="slotted-content">
<slot></slot>
</span>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_radio_button/cr_radio_button.html | HTML | unknown | 703 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '//resources/polymer/v3_0/paper-styles/color.js';
import '../cr_hidden_style.css.js';
import '../cr_shared_vars.css.js';
import './cr_radio_button_style.css.js';
import {PaperRippleBehavior} from '//resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js';
import {mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './cr_radio_button.html.js';
import {CrRadioButtonMixin, CrRadioButtonMixinInterface} from './cr_radio_button_mixin.js';
const CrRadioButtonElementBase = mixinBehaviors(
[PaperRippleBehavior],
CrRadioButtonMixin(PolymerElement)) as {
new (): PolymerElement & CrRadioButtonMixinInterface & PaperRippleBehavior,
};
export interface CrRadioButtonElement {
$: {
button: HTMLElement,
};
}
export class CrRadioButtonElement extends CrRadioButtonElementBase {
static get is() {
return 'cr-radio-button';
}
static get template() {
return getTemplate();
}
// Overridden from CrRadioButtonMixin
override getPaperRipple() {
return this.getRipple();
}
// Overridden from PaperRippleBehavior
/* eslint-disable-next-line @typescript-eslint/naming-convention */
override _createRipple() {
this._rippleContainer = this.shadowRoot!.querySelector('.disc-wrapper');
const ripple = super._createRipple();
ripple.id = 'ink';
ripple.setAttribute('recenters', '');
ripple.classList.add('circle', 'toggle-ink');
return ripple;
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-radio-button': CrRadioButtonElement;
}
}
customElements.define(CrRadioButtonElement.is, CrRadioButtonElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_radio_button/cr_radio_button.ts | TypeScript | unknown | 1,879 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Minimal externs file provided for places in the code that
* still use JavaScript instead of TypeScript.
* @externs
*/
/** @interface */
class CrRadioButtonMixinInterface {
constructor() {
/** @type {boolean} */
this.checked;
/** @type {boolean} */
this.disabled;
/** @type {boolean} */
this.focusabled;
/** @type {string} */
this.name;
}
/** @return {HTMLElement} */
getPaperRipple() {}
}
/**
* @constructor
* @extends {HTMLElement}
* @implements {CrRadioButtonMixinInterface}
*/
function CrRadioButtonElement() {}
/**
* @constructor
* @extends {HTMLElement}
* @implements {CrRadioButtonMixinInterface}
*/
function CrCardRadioButtonElement() {}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_radio_button/cr_radio_button_externs.js | JavaScript | unknown | 850 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Mixin for cr-radio-button-like elements.
*/
// clang-format off
import {dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {assert, assertNotReached} from '//resources/js/assert_ts.js';
interface PaperRippleElement {
clear(): void;
showAndHoldDown(): void;
}
type Constructor<T> = new (...args: any[]) => T;
export const CrRadioButtonMixin = dedupingMixin(
<T extends Constructor<PolymerElement>>(superClass: T): T&
Constructor<CrRadioButtonMixinInterface> => {
class CrRadioButtonMixin extends superClass implements
CrRadioButtonMixinInterface {
static get properties() {
return {
checked: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
notify: true,
},
/**
* Whether the radio button should be focusable or not. Toggling
* this property sets the corresponding tabindex of the button
* itself as well as any links in the button description.
*/
focusable: {
type: Boolean,
value: false,
observer: 'onFocusableChanged_',
},
hideLabelText: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
label: {
type: String,
value: '', // Allows hidden$= binding to run without being set.
},
name: {
type: String,
notify: true,
reflectToAttribute: true,
},
/**
* Holds the tabIndex for the radio button.
*/
buttonTabIndex_: {
type: Number,
computed: 'getTabIndex_(focusable)',
},
};
}
checked: boolean;
disabled: boolean;
focusable: boolean;
hideLabelText: boolean;
label: string;
name: string;
private buttonTabIndex_: number;
override connectedCallback() {
super.connectedCallback();
this.addEventListener('blur', this.hideRipple_.bind(this));
if (!document.documentElement.hasAttribute('chrome-refresh-2023')) {
this.addEventListener('focus', this.onFocus_.bind(this));
}
this.addEventListener('up', this.hideRipple_.bind(this));
}
override focus() {
const button = this.shadowRoot!.querySelector<HTMLElement>('#button');
assert(button);
button.focus();
}
getPaperRipple(): PaperRippleElement {
assertNotReached();
}
private onFocus_() {
this.getPaperRipple().showAndHoldDown();
}
private hideRipple_() {
this.getPaperRipple().clear();
}
private onFocusableChanged_() {
const links = this.querySelectorAll('a');
links.forEach((link) => {
// Remove the tab stop on any links when the row is unchecked.
// Since the row is not tabbable, any links within the row
// should not be either.
link.tabIndex = this.checked ? 0 : -1;
});
}
private getAriaChecked_(): string {
return this.checked ? 'true' : 'false';
}
private getAriaDisabled_(): string {
return this.disabled ? 'true' : 'false';
}
private getTabIndex_(): number {
return this.focusable ? 0 : -1;
}
/**
* When shift-tab is pressed, first bring the focus to the host
* element. This accomplishes 2 things:
* 1) Host doesn't get focused when the browser moves the focus
* backward.
* 2) focus now escaped the shadow-dom of this element, so that
* it'll correctly obey non-zero tabindex ordering of the
* containing document.
*/
private onInputKeydown_(e: KeyboardEvent) {
if (e.shiftKey && e.key === 'Tab') {
this.focus();
}
}
}
return CrRadioButtonMixin;
});
export interface CrRadioButtonMixinInterface {
checked: boolean;
disabled: boolean;
focusable: boolean;
hideLabelText: boolean;
label: string;
name: string;
getPaperRipple(): PaperRippleElement;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_radio_button/cr_radio_button_mixin.ts | TypeScript | unknown | 4,743 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #import=../cr_shared_vars.css.js
* #import=../cr_shared_vars.css.js
* #css_wrapper_metadata_end */
/* Common radio-button styling for Material Design WebUI. */
:host {
--cr-radio-button-checked-color: var(--google-blue-600);
--cr-radio-button-checked-ripple-color:
rgba(var(--google-blue-600-rgb), .2);
--cr-radio-button-ink-size: 40px;
--cr-radio-button-size: 16px;
--cr-radio-button-unchecked-color: var(--google-grey-700);
--cr-radio-button-unchecked-ripple-color:
rgba(var(--google-grey-600-rgb), .15);
--ink-to-circle: calc((var(--cr-radio-button-ink-size) -
var(--cr-radio-button-size)) / 2);
align-items: center;
display: flex;
flex-shrink: 0;
outline: none;
}
@media (prefers-color-scheme: dark) {
:host {
--cr-radio-button-checked-color: var(--google-blue-300);
--cr-radio-button-checked-ripple-color:
rgba(var(--google-blue-300-rgb), .4);
--cr-radio-button-unchecked-color: var(--google-grey-500);
--cr-radio-button-unchecked-ripple-color:
rgba(var(--google-grey-300-rgb), .4);
}
}
:host-context([chrome-refresh-2023]):host {
--cr-radio-button-ink-size: 32px;
--cr-radio-button-checked-color:
var(--color-radio-button-foreground-checked,
var(--cr-fallback-color-primary));
--cr-radio-button-checked-ripple-color:
var(--cr-active-background-color);
--cr-radio-button-unchecked-color:
var(--color-radio-button-foreground-unchecked,
var(--cr-fallback-color-outline));
--cr-radio-button-unchecked-ripple-color:
var(--cr-active-background-color);
}
@media (forced-colors: active) {
:host {
--cr-radio-button-checked-color: SelectedItem;
}
}
:host([disabled]) {
opacity: var(--cr-disabled-opacity);
/* Disable pointer events for this whole element, as outer on-click gets
* triggered when clicking anywhere in :host. */
pointer-events: none;
}
:host-context([chrome-refresh-2023]):host([disabled]) {
opacity: 1;
--cr-radio-button-checked-color: var(--color-radio-foreground-disabled,
rgba(var(--cr-fallback-color-on-surface-rgb), .12));
--cr-radio-button-unchecked-color:
var(--color-radio-foreground-disabled,
rgba(var(--cr-fallback-color-on-surface-rgb), .12));
}
:host(:not([disabled])) {
cursor: pointer;
}
#labelWrapper {
flex: 1;
margin-inline-start: var(--cr-radio-button-label-spacing, 20px);
}
:host-context([chrome-refresh-2023]):host([disabled]) #labelWrapper {
opacity: var(--cr-disabled-opacity);
}
#label {
color: inherit;
}
/* Visually hide the label but allow the screen reader to pick it up. */
:host([hide-label-text]) #label {
clip: rect(0,0,0,0);
display: block;
position: fixed;
}
.disc-border,
.disc,
.disc-wrapper,
paper-ripple {
border-radius: 50%;
}
.disc-wrapper {
height: var(--cr-radio-button-size);
margin-block-start: var(--cr-radio-button-disc-margin-block-start, 0);
position: relative;
width: var(--cr-radio-button-size);
}
.disc-border,
.disc {
box-sizing: border-box;
height: var(--cr-radio-button-size);
width: var(--cr-radio-button-size);
}
.disc-border {
border: 2px solid var(--cr-radio-button-unchecked-color);
}
:host([checked]) .disc-border {
border-color: var(--cr-radio-button-checked-color);
}
#button:focus {
outline: none;
}
.disc {
background-color: transparent;
position: absolute;
top: 0;
transform: scale(0);
transition: border-color 200ms, transform 200ms;
}
:host([checked]) .disc {
background-color: var(--cr-radio-button-checked-color);
transform: scale(0.5);
}
:host-context([chrome-refresh-2023]) #overlay {
border-radius: 50%;
box-sizing: border-box;
display: none;
height: var(--cr-radio-button-ink-size);
left: 50%;
pointer-events: none;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
width: var(--cr-radio-button-ink-size);
}
:host-context([chrome-refresh-2023]) #button:hover #overlay {
background-color: var(--cr-hover-background-color);
display: block;
}
:host-context([chrome-refresh-2023]) #button:focus-visible #overlay {
border: 2px solid var(--cr-focus-outline-color);
display: block;
}
paper-ripple {
--paper-ripple-opacity: 1; /* Opacity in each color's alpha. */
color: var(--cr-radio-button-unchecked-ripple-color);
height: var(--cr-radio-button-ink-size);
left: calc(-1 * var(--ink-to-circle));
pointer-events: none;
position: absolute;
top: calc(-1 * var(--ink-to-circle));
transition: color linear 80ms;
width: var(--cr-radio-button-ink-size);
}
:host-context([dir=rtl]) paper-ripple {
left: auto;
right: calc(-1 * var(--ink-to-circle));
}
:host([checked]) paper-ripple {
color: var(--cr-radio-button-checked-ripple-color);
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_elements/cr_radio_button/cr_radio_button_style.css | CSS | unknown | 5,865 |